UNPKG

1.31 MBJavaScriptView Raw
1/**
2 * @license Angular v8.2.14
3 * (c) 2010-2019 Google LLC. https://angular.io/
4 * License: MIT
5 */
6
7import { __assign, __spread, __extends, __values, __read } from 'tslib';
8
9/**
10 * @license
11 * Copyright Google Inc. All Rights Reserved.
12 *
13 * Use of this source code is governed by an MIT-style license that can be
14 * found in the LICENSE file at https://angular.io/license
15 */
16var TagContentType;
17(function (TagContentType) {
18 TagContentType[TagContentType["RAW_TEXT"] = 0] = "RAW_TEXT";
19 TagContentType[TagContentType["ESCAPABLE_RAW_TEXT"] = 1] = "ESCAPABLE_RAW_TEXT";
20 TagContentType[TagContentType["PARSABLE_DATA"] = 2] = "PARSABLE_DATA";
21})(TagContentType || (TagContentType = {}));
22function splitNsName(elementName) {
23 if (elementName[0] != ':') {
24 return [null, elementName];
25 }
26 var colonIndex = elementName.indexOf(':', 1);
27 if (colonIndex == -1) {
28 throw new Error("Unsupported format \"" + elementName + "\" expecting \":namespace:name\"");
29 }
30 return [elementName.slice(1, colonIndex), elementName.slice(colonIndex + 1)];
31}
32// `<ng-container>` tags work the same regardless the namespace
33function isNgContainer(tagName) {
34 return splitNsName(tagName)[1] === 'ng-container';
35}
36// `<ng-content>` tags work the same regardless the namespace
37function isNgContent(tagName) {
38 return splitNsName(tagName)[1] === 'ng-content';
39}
40// `<ng-template>` tags work the same regardless the namespace
41function isNgTemplate(tagName) {
42 return splitNsName(tagName)[1] === 'ng-template';
43}
44function getNsPrefix(fullName) {
45 return fullName === null ? null : splitNsName(fullName)[0];
46}
47function mergeNsAndName(prefix, localName) {
48 return prefix ? ":" + prefix + ":" + localName : localName;
49}
50// see http://www.w3.org/TR/html51/syntax.html#named-character-references
51// see https://html.spec.whatwg.org/multipage/entities.json
52// This list is not exhaustive to keep the compiler footprint low.
53// The `&#123;` / `&#x1ab;` syntax should be used when the named character reference does not
54// exist.
55var NAMED_ENTITIES = {
56 'Aacute': '\u00C1',
57 'aacute': '\u00E1',
58 'Acirc': '\u00C2',
59 'acirc': '\u00E2',
60 'acute': '\u00B4',
61 'AElig': '\u00C6',
62 'aelig': '\u00E6',
63 'Agrave': '\u00C0',
64 'agrave': '\u00E0',
65 'alefsym': '\u2135',
66 'Alpha': '\u0391',
67 'alpha': '\u03B1',
68 'amp': '&',
69 'and': '\u2227',
70 'ang': '\u2220',
71 'apos': '\u0027',
72 'Aring': '\u00C5',
73 'aring': '\u00E5',
74 'asymp': '\u2248',
75 'Atilde': '\u00C3',
76 'atilde': '\u00E3',
77 'Auml': '\u00C4',
78 'auml': '\u00E4',
79 'bdquo': '\u201E',
80 'Beta': '\u0392',
81 'beta': '\u03B2',
82 'brvbar': '\u00A6',
83 'bull': '\u2022',
84 'cap': '\u2229',
85 'Ccedil': '\u00C7',
86 'ccedil': '\u00E7',
87 'cedil': '\u00B8',
88 'cent': '\u00A2',
89 'Chi': '\u03A7',
90 'chi': '\u03C7',
91 'circ': '\u02C6',
92 'clubs': '\u2663',
93 'cong': '\u2245',
94 'copy': '\u00A9',
95 'crarr': '\u21B5',
96 'cup': '\u222A',
97 'curren': '\u00A4',
98 'dagger': '\u2020',
99 'Dagger': '\u2021',
100 'darr': '\u2193',
101 'dArr': '\u21D3',
102 'deg': '\u00B0',
103 'Delta': '\u0394',
104 'delta': '\u03B4',
105 'diams': '\u2666',
106 'divide': '\u00F7',
107 'Eacute': '\u00C9',
108 'eacute': '\u00E9',
109 'Ecirc': '\u00CA',
110 'ecirc': '\u00EA',
111 'Egrave': '\u00C8',
112 'egrave': '\u00E8',
113 'empty': '\u2205',
114 'emsp': '\u2003',
115 'ensp': '\u2002',
116 'Epsilon': '\u0395',
117 'epsilon': '\u03B5',
118 'equiv': '\u2261',
119 'Eta': '\u0397',
120 'eta': '\u03B7',
121 'ETH': '\u00D0',
122 'eth': '\u00F0',
123 'Euml': '\u00CB',
124 'euml': '\u00EB',
125 'euro': '\u20AC',
126 'exist': '\u2203',
127 'fnof': '\u0192',
128 'forall': '\u2200',
129 'frac12': '\u00BD',
130 'frac14': '\u00BC',
131 'frac34': '\u00BE',
132 'frasl': '\u2044',
133 'Gamma': '\u0393',
134 'gamma': '\u03B3',
135 'ge': '\u2265',
136 'gt': '>',
137 'harr': '\u2194',
138 'hArr': '\u21D4',
139 'hearts': '\u2665',
140 'hellip': '\u2026',
141 'Iacute': '\u00CD',
142 'iacute': '\u00ED',
143 'Icirc': '\u00CE',
144 'icirc': '\u00EE',
145 'iexcl': '\u00A1',
146 'Igrave': '\u00CC',
147 'igrave': '\u00EC',
148 'image': '\u2111',
149 'infin': '\u221E',
150 'int': '\u222B',
151 'Iota': '\u0399',
152 'iota': '\u03B9',
153 'iquest': '\u00BF',
154 'isin': '\u2208',
155 'Iuml': '\u00CF',
156 'iuml': '\u00EF',
157 'Kappa': '\u039A',
158 'kappa': '\u03BA',
159 'Lambda': '\u039B',
160 'lambda': '\u03BB',
161 'lang': '\u27E8',
162 'laquo': '\u00AB',
163 'larr': '\u2190',
164 'lArr': '\u21D0',
165 'lceil': '\u2308',
166 'ldquo': '\u201C',
167 'le': '\u2264',
168 'lfloor': '\u230A',
169 'lowast': '\u2217',
170 'loz': '\u25CA',
171 'lrm': '\u200E',
172 'lsaquo': '\u2039',
173 'lsquo': '\u2018',
174 'lt': '<',
175 'macr': '\u00AF',
176 'mdash': '\u2014',
177 'micro': '\u00B5',
178 'middot': '\u00B7',
179 'minus': '\u2212',
180 'Mu': '\u039C',
181 'mu': '\u03BC',
182 'nabla': '\u2207',
183 'nbsp': '\u00A0',
184 'ndash': '\u2013',
185 'ne': '\u2260',
186 'ni': '\u220B',
187 'not': '\u00AC',
188 'notin': '\u2209',
189 'nsub': '\u2284',
190 'Ntilde': '\u00D1',
191 'ntilde': '\u00F1',
192 'Nu': '\u039D',
193 'nu': '\u03BD',
194 'Oacute': '\u00D3',
195 'oacute': '\u00F3',
196 'Ocirc': '\u00D4',
197 'ocirc': '\u00F4',
198 'OElig': '\u0152',
199 'oelig': '\u0153',
200 'Ograve': '\u00D2',
201 'ograve': '\u00F2',
202 'oline': '\u203E',
203 'Omega': '\u03A9',
204 'omega': '\u03C9',
205 'Omicron': '\u039F',
206 'omicron': '\u03BF',
207 'oplus': '\u2295',
208 'or': '\u2228',
209 'ordf': '\u00AA',
210 'ordm': '\u00BA',
211 'Oslash': '\u00D8',
212 'oslash': '\u00F8',
213 'Otilde': '\u00D5',
214 'otilde': '\u00F5',
215 'otimes': '\u2297',
216 'Ouml': '\u00D6',
217 'ouml': '\u00F6',
218 'para': '\u00B6',
219 'permil': '\u2030',
220 'perp': '\u22A5',
221 'Phi': '\u03A6',
222 'phi': '\u03C6',
223 'Pi': '\u03A0',
224 'pi': '\u03C0',
225 'piv': '\u03D6',
226 'plusmn': '\u00B1',
227 'pound': '\u00A3',
228 'prime': '\u2032',
229 'Prime': '\u2033',
230 'prod': '\u220F',
231 'prop': '\u221D',
232 'Psi': '\u03A8',
233 'psi': '\u03C8',
234 'quot': '\u0022',
235 'radic': '\u221A',
236 'rang': '\u27E9',
237 'raquo': '\u00BB',
238 'rarr': '\u2192',
239 'rArr': '\u21D2',
240 'rceil': '\u2309',
241 'rdquo': '\u201D',
242 'real': '\u211C',
243 'reg': '\u00AE',
244 'rfloor': '\u230B',
245 'Rho': '\u03A1',
246 'rho': '\u03C1',
247 'rlm': '\u200F',
248 'rsaquo': '\u203A',
249 'rsquo': '\u2019',
250 'sbquo': '\u201A',
251 'Scaron': '\u0160',
252 'scaron': '\u0161',
253 'sdot': '\u22C5',
254 'sect': '\u00A7',
255 'shy': '\u00AD',
256 'Sigma': '\u03A3',
257 'sigma': '\u03C3',
258 'sigmaf': '\u03C2',
259 'sim': '\u223C',
260 'spades': '\u2660',
261 'sub': '\u2282',
262 'sube': '\u2286',
263 'sum': '\u2211',
264 'sup': '\u2283',
265 'sup1': '\u00B9',
266 'sup2': '\u00B2',
267 'sup3': '\u00B3',
268 'supe': '\u2287',
269 'szlig': '\u00DF',
270 'Tau': '\u03A4',
271 'tau': '\u03C4',
272 'there4': '\u2234',
273 'Theta': '\u0398',
274 'theta': '\u03B8',
275 'thetasym': '\u03D1',
276 'thinsp': '\u2009',
277 'THORN': '\u00DE',
278 'thorn': '\u00FE',
279 'tilde': '\u02DC',
280 'times': '\u00D7',
281 'trade': '\u2122',
282 'Uacute': '\u00DA',
283 'uacute': '\u00FA',
284 'uarr': '\u2191',
285 'uArr': '\u21D1',
286 'Ucirc': '\u00DB',
287 'ucirc': '\u00FB',
288 'Ugrave': '\u00D9',
289 'ugrave': '\u00F9',
290 'uml': '\u00A8',
291 'upsih': '\u03D2',
292 'Upsilon': '\u03A5',
293 'upsilon': '\u03C5',
294 'Uuml': '\u00DC',
295 'uuml': '\u00FC',
296 'weierp': '\u2118',
297 'Xi': '\u039E',
298 'xi': '\u03BE',
299 'Yacute': '\u00DD',
300 'yacute': '\u00FD',
301 'yen': '\u00A5',
302 'yuml': '\u00FF',
303 'Yuml': '\u0178',
304 'Zeta': '\u0396',
305 'zeta': '\u03B6',
306 'zwj': '\u200D',
307 'zwnj': '\u200C',
308};
309// The &ngsp; pseudo-entity is denoting a space. see:
310// https://github.com/dart-lang/angular/blob/0bb611387d29d65b5af7f9d2515ab571fd3fbee4/_tests/test/compiler/preserve_whitespace_test.dart
311var NGSP_UNICODE = '\uE500';
312NAMED_ENTITIES['ngsp'] = NGSP_UNICODE;
313
314/**
315 * @license
316 * Copyright Google Inc. All Rights Reserved.
317 *
318 * Use of this source code is governed by an MIT-style license that can be
319 * found in the LICENSE file at https://angular.io/license
320 */
321var HtmlTagDefinition = /** @class */ (function () {
322 function HtmlTagDefinition(_a) {
323 var _this = this;
324 var _b = _a === void 0 ? {} : _a, closedByChildren = _b.closedByChildren, implicitNamespacePrefix = _b.implicitNamespacePrefix, _c = _b.contentType, contentType = _c === void 0 ? TagContentType.PARSABLE_DATA : _c, _d = _b.closedByParent, closedByParent = _d === void 0 ? false : _d, _e = _b.isVoid, isVoid = _e === void 0 ? false : _e, _f = _b.ignoreFirstLf, ignoreFirstLf = _f === void 0 ? false : _f;
325 this.closedByChildren = {};
326 this.closedByParent = false;
327 this.canSelfClose = false;
328 if (closedByChildren && closedByChildren.length > 0) {
329 closedByChildren.forEach(function (tagName) { return _this.closedByChildren[tagName] = true; });
330 }
331 this.isVoid = isVoid;
332 this.closedByParent = closedByParent || isVoid;
333 this.implicitNamespacePrefix = implicitNamespacePrefix || null;
334 this.contentType = contentType;
335 this.ignoreFirstLf = ignoreFirstLf;
336 }
337 HtmlTagDefinition.prototype.isClosedByChild = function (name) {
338 return this.isVoid || name.toLowerCase() in this.closedByChildren;
339 };
340 return HtmlTagDefinition;
341}());
342var _DEFAULT_TAG_DEFINITION;
343// see http://www.w3.org/TR/html51/syntax.html#optional-tags
344// This implementation does not fully conform to the HTML5 spec.
345var TAG_DEFINITIONS;
346function getHtmlTagDefinition(tagName) {
347 if (!TAG_DEFINITIONS) {
348 _DEFAULT_TAG_DEFINITION = new HtmlTagDefinition();
349 TAG_DEFINITIONS = {
350 'base': new HtmlTagDefinition({ isVoid: true }),
351 'meta': new HtmlTagDefinition({ isVoid: true }),
352 'area': new HtmlTagDefinition({ isVoid: true }),
353 'embed': new HtmlTagDefinition({ isVoid: true }),
354 'link': new HtmlTagDefinition({ isVoid: true }),
355 'img': new HtmlTagDefinition({ isVoid: true }),
356 'input': new HtmlTagDefinition({ isVoid: true }),
357 'param': new HtmlTagDefinition({ isVoid: true }),
358 'hr': new HtmlTagDefinition({ isVoid: true }),
359 'br': new HtmlTagDefinition({ isVoid: true }),
360 'source': new HtmlTagDefinition({ isVoid: true }),
361 'track': new HtmlTagDefinition({ isVoid: true }),
362 'wbr': new HtmlTagDefinition({ isVoid: true }),
363 'p': new HtmlTagDefinition({
364 closedByChildren: [
365 'address', 'article', 'aside', 'blockquote', 'div', 'dl', 'fieldset',
366 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5',
367 'h6', 'header', 'hgroup', 'hr', 'main', 'nav', 'ol',
368 'p', 'pre', 'section', 'table', 'ul'
369 ],
370 closedByParent: true
371 }),
372 'thead': new HtmlTagDefinition({ closedByChildren: ['tbody', 'tfoot'] }),
373 'tbody': new HtmlTagDefinition({ closedByChildren: ['tbody', 'tfoot'], closedByParent: true }),
374 'tfoot': new HtmlTagDefinition({ closedByChildren: ['tbody'], closedByParent: true }),
375 'tr': new HtmlTagDefinition({ closedByChildren: ['tr'], closedByParent: true }),
376 'td': new HtmlTagDefinition({ closedByChildren: ['td', 'th'], closedByParent: true }),
377 'th': new HtmlTagDefinition({ closedByChildren: ['td', 'th'], closedByParent: true }),
378 'col': new HtmlTagDefinition({ isVoid: true }),
379 'svg': new HtmlTagDefinition({ implicitNamespacePrefix: 'svg' }),
380 'math': new HtmlTagDefinition({ implicitNamespacePrefix: 'math' }),
381 'li': new HtmlTagDefinition({ closedByChildren: ['li'], closedByParent: true }),
382 'dt': new HtmlTagDefinition({ closedByChildren: ['dt', 'dd'] }),
383 'dd': new HtmlTagDefinition({ closedByChildren: ['dt', 'dd'], closedByParent: true }),
384 'rb': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }),
385 'rt': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }),
386 'rtc': new HtmlTagDefinition({ closedByChildren: ['rb', 'rtc', 'rp'], closedByParent: true }),
387 'rp': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }),
388 'optgroup': new HtmlTagDefinition({ closedByChildren: ['optgroup'], closedByParent: true }),
389 'option': new HtmlTagDefinition({ closedByChildren: ['option', 'optgroup'], closedByParent: true }),
390 'pre': new HtmlTagDefinition({ ignoreFirstLf: true }),
391 'listing': new HtmlTagDefinition({ ignoreFirstLf: true }),
392 'style': new HtmlTagDefinition({ contentType: TagContentType.RAW_TEXT }),
393 'script': new HtmlTagDefinition({ contentType: TagContentType.RAW_TEXT }),
394 'title': new HtmlTagDefinition({ contentType: TagContentType.ESCAPABLE_RAW_TEXT }),
395 'textarea': new HtmlTagDefinition({ contentType: TagContentType.ESCAPABLE_RAW_TEXT, ignoreFirstLf: true }),
396 };
397 }
398 return TAG_DEFINITIONS[tagName.toLowerCase()] || _DEFAULT_TAG_DEFINITION;
399}
400
401/**
402 * @license
403 * Copyright Google Inc. All Rights Reserved.
404 *
405 * Use of this source code is governed by an MIT-style license that can be
406 * found in the LICENSE file at https://angular.io/license
407 */
408var _SELECTOR_REGEXP = new RegExp('(\\:not\\()|' + //":not("
409 '([-\\w]+)|' + // "tag"
410 '(?:\\.([-\\w]+))|' + // ".class"
411 // "-" should appear first in the regexp below as FF31 parses "[.-\w]" as a range
412 '(?:\\[([-.\\w*]+)(?:=([\"\']?)([^\\]\"\']*)\\5)?\\])|' + // "[name]", "[name=value]",
413 // "[name="value"]",
414 // "[name='value']"
415 '(\\))|' + // ")"
416 '(\\s*,\\s*)', // ","
417'g');
418/**
419 * A css selector contains an element name,
420 * css classes and attribute/value pairs with the purpose
421 * of selecting subsets out of them.
422 */
423var CssSelector = /** @class */ (function () {
424 function CssSelector() {
425 this.element = null;
426 this.classNames = [];
427 /**
428 * The selectors are encoded in pairs where:
429 * - even locations are attribute names
430 * - odd locations are attribute values.
431 *
432 * Example:
433 * Selector: `[key1=value1][key2]` would parse to:
434 * ```
435 * ['key1', 'value1', 'key2', '']
436 * ```
437 */
438 this.attrs = [];
439 this.notSelectors = [];
440 }
441 CssSelector.parse = function (selector) {
442 var results = [];
443 var _addResult = function (res, cssSel) {
444 if (cssSel.notSelectors.length > 0 && !cssSel.element && cssSel.classNames.length == 0 &&
445 cssSel.attrs.length == 0) {
446 cssSel.element = '*';
447 }
448 res.push(cssSel);
449 };
450 var cssSelector = new CssSelector();
451 var match;
452 var current = cssSelector;
453 var inNot = false;
454 _SELECTOR_REGEXP.lastIndex = 0;
455 while (match = _SELECTOR_REGEXP.exec(selector)) {
456 if (match[1]) {
457 if (inNot) {
458 throw new Error('Nesting :not is not allowed in a selector');
459 }
460 inNot = true;
461 current = new CssSelector();
462 cssSelector.notSelectors.push(current);
463 }
464 if (match[2]) {
465 current.setElement(match[2]);
466 }
467 if (match[3]) {
468 current.addClassName(match[3]);
469 }
470 if (match[4]) {
471 current.addAttribute(match[4], match[6]);
472 }
473 if (match[7]) {
474 inNot = false;
475 current = cssSelector;
476 }
477 if (match[8]) {
478 if (inNot) {
479 throw new Error('Multiple selectors in :not are not supported');
480 }
481 _addResult(results, cssSelector);
482 cssSelector = current = new CssSelector();
483 }
484 }
485 _addResult(results, cssSelector);
486 return results;
487 };
488 CssSelector.prototype.isElementSelector = function () {
489 return this.hasElementSelector() && this.classNames.length == 0 && this.attrs.length == 0 &&
490 this.notSelectors.length === 0;
491 };
492 CssSelector.prototype.hasElementSelector = function () { return !!this.element; };
493 CssSelector.prototype.setElement = function (element) {
494 if (element === void 0) { element = null; }
495 this.element = element;
496 };
497 /** Gets a template string for an element that matches the selector. */
498 CssSelector.prototype.getMatchingElementTemplate = function () {
499 var tagName = this.element || 'div';
500 var classAttr = this.classNames.length > 0 ? " class=\"" + this.classNames.join(' ') + "\"" : '';
501 var attrs = '';
502 for (var i = 0; i < this.attrs.length; i += 2) {
503 var attrName = this.attrs[i];
504 var attrValue = this.attrs[i + 1] !== '' ? "=\"" + this.attrs[i + 1] + "\"" : '';
505 attrs += " " + attrName + attrValue;
506 }
507 return getHtmlTagDefinition(tagName).isVoid ? "<" + tagName + classAttr + attrs + "/>" :
508 "<" + tagName + classAttr + attrs + "></" + tagName + ">";
509 };
510 CssSelector.prototype.getAttrs = function () {
511 var result = [];
512 if (this.classNames.length > 0) {
513 result.push('class', this.classNames.join(' '));
514 }
515 return result.concat(this.attrs);
516 };
517 CssSelector.prototype.addAttribute = function (name, value) {
518 if (value === void 0) { value = ''; }
519 this.attrs.push(name, value && value.toLowerCase() || '');
520 };
521 CssSelector.prototype.addClassName = function (name) { this.classNames.push(name.toLowerCase()); };
522 CssSelector.prototype.toString = function () {
523 var res = this.element || '';
524 if (this.classNames) {
525 this.classNames.forEach(function (klass) { return res += "." + klass; });
526 }
527 if (this.attrs) {
528 for (var i = 0; i < this.attrs.length; i += 2) {
529 var name_1 = this.attrs[i];
530 var value = this.attrs[i + 1];
531 res += "[" + name_1 + (value ? '=' + value : '') + "]";
532 }
533 }
534 this.notSelectors.forEach(function (notSelector) { return res += ":not(" + notSelector + ")"; });
535 return res;
536 };
537 return CssSelector;
538}());
539/**
540 * Reads a list of CssSelectors and allows to calculate which ones
541 * are contained in a given CssSelector.
542 */
543var SelectorMatcher = /** @class */ (function () {
544 function SelectorMatcher() {
545 this._elementMap = new Map();
546 this._elementPartialMap = new Map();
547 this._classMap = new Map();
548 this._classPartialMap = new Map();
549 this._attrValueMap = new Map();
550 this._attrValuePartialMap = new Map();
551 this._listContexts = [];
552 }
553 SelectorMatcher.createNotMatcher = function (notSelectors) {
554 var notMatcher = new SelectorMatcher();
555 notMatcher.addSelectables(notSelectors, null);
556 return notMatcher;
557 };
558 SelectorMatcher.prototype.addSelectables = function (cssSelectors, callbackCtxt) {
559 var listContext = null;
560 if (cssSelectors.length > 1) {
561 listContext = new SelectorListContext(cssSelectors);
562 this._listContexts.push(listContext);
563 }
564 for (var i = 0; i < cssSelectors.length; i++) {
565 this._addSelectable(cssSelectors[i], callbackCtxt, listContext);
566 }
567 };
568 /**
569 * Add an object that can be found later on by calling `match`.
570 * @param cssSelector A css selector
571 * @param callbackCtxt An opaque object that will be given to the callback of the `match` function
572 */
573 SelectorMatcher.prototype._addSelectable = function (cssSelector, callbackCtxt, listContext) {
574 var matcher = this;
575 var element = cssSelector.element;
576 var classNames = cssSelector.classNames;
577 var attrs = cssSelector.attrs;
578 var selectable = new SelectorContext(cssSelector, callbackCtxt, listContext);
579 if (element) {
580 var isTerminal = attrs.length === 0 && classNames.length === 0;
581 if (isTerminal) {
582 this._addTerminal(matcher._elementMap, element, selectable);
583 }
584 else {
585 matcher = this._addPartial(matcher._elementPartialMap, element);
586 }
587 }
588 if (classNames) {
589 for (var i = 0; i < classNames.length; i++) {
590 var isTerminal = attrs.length === 0 && i === classNames.length - 1;
591 var className = classNames[i];
592 if (isTerminal) {
593 this._addTerminal(matcher._classMap, className, selectable);
594 }
595 else {
596 matcher = this._addPartial(matcher._classPartialMap, className);
597 }
598 }
599 }
600 if (attrs) {
601 for (var i = 0; i < attrs.length; i += 2) {
602 var isTerminal = i === attrs.length - 2;
603 var name_2 = attrs[i];
604 var value = attrs[i + 1];
605 if (isTerminal) {
606 var terminalMap = matcher._attrValueMap;
607 var terminalValuesMap = terminalMap.get(name_2);
608 if (!terminalValuesMap) {
609 terminalValuesMap = new Map();
610 terminalMap.set(name_2, terminalValuesMap);
611 }
612 this._addTerminal(terminalValuesMap, value, selectable);
613 }
614 else {
615 var partialMap = matcher._attrValuePartialMap;
616 var partialValuesMap = partialMap.get(name_2);
617 if (!partialValuesMap) {
618 partialValuesMap = new Map();
619 partialMap.set(name_2, partialValuesMap);
620 }
621 matcher = this._addPartial(partialValuesMap, value);
622 }
623 }
624 }
625 };
626 SelectorMatcher.prototype._addTerminal = function (map, name, selectable) {
627 var terminalList = map.get(name);
628 if (!terminalList) {
629 terminalList = [];
630 map.set(name, terminalList);
631 }
632 terminalList.push(selectable);
633 };
634 SelectorMatcher.prototype._addPartial = function (map, name) {
635 var matcher = map.get(name);
636 if (!matcher) {
637 matcher = new SelectorMatcher();
638 map.set(name, matcher);
639 }
640 return matcher;
641 };
642 /**
643 * Find the objects that have been added via `addSelectable`
644 * whose css selector is contained in the given css selector.
645 * @param cssSelector A css selector
646 * @param matchedCallback This callback will be called with the object handed into `addSelectable`
647 * @return boolean true if a match was found
648 */
649 SelectorMatcher.prototype.match = function (cssSelector, matchedCallback) {
650 var result = false;
651 var element = cssSelector.element;
652 var classNames = cssSelector.classNames;
653 var attrs = cssSelector.attrs;
654 for (var i = 0; i < this._listContexts.length; i++) {
655 this._listContexts[i].alreadyMatched = false;
656 }
657 result = this._matchTerminal(this._elementMap, element, cssSelector, matchedCallback) || result;
658 result = this._matchPartial(this._elementPartialMap, element, cssSelector, matchedCallback) ||
659 result;
660 if (classNames) {
661 for (var i = 0; i < classNames.length; i++) {
662 var className = classNames[i];
663 result =
664 this._matchTerminal(this._classMap, className, cssSelector, matchedCallback) || result;
665 result =
666 this._matchPartial(this._classPartialMap, className, cssSelector, matchedCallback) ||
667 result;
668 }
669 }
670 if (attrs) {
671 for (var i = 0; i < attrs.length; i += 2) {
672 var name_3 = attrs[i];
673 var value = attrs[i + 1];
674 var terminalValuesMap = this._attrValueMap.get(name_3);
675 if (value) {
676 result =
677 this._matchTerminal(terminalValuesMap, '', cssSelector, matchedCallback) || result;
678 }
679 result =
680 this._matchTerminal(terminalValuesMap, value, cssSelector, matchedCallback) || result;
681 var partialValuesMap = this._attrValuePartialMap.get(name_3);
682 if (value) {
683 result = this._matchPartial(partialValuesMap, '', cssSelector, matchedCallback) || result;
684 }
685 result =
686 this._matchPartial(partialValuesMap, value, cssSelector, matchedCallback) || result;
687 }
688 }
689 return result;
690 };
691 /** @internal */
692 SelectorMatcher.prototype._matchTerminal = function (map, name, cssSelector, matchedCallback) {
693 if (!map || typeof name !== 'string') {
694 return false;
695 }
696 var selectables = map.get(name) || [];
697 var starSelectables = map.get('*');
698 if (starSelectables) {
699 selectables = selectables.concat(starSelectables);
700 }
701 if (selectables.length === 0) {
702 return false;
703 }
704 var selectable;
705 var result = false;
706 for (var i = 0; i < selectables.length; i++) {
707 selectable = selectables[i];
708 result = selectable.finalize(cssSelector, matchedCallback) || result;
709 }
710 return result;
711 };
712 /** @internal */
713 SelectorMatcher.prototype._matchPartial = function (map, name, cssSelector, matchedCallback) {
714 if (!map || typeof name !== 'string') {
715 return false;
716 }
717 var nestedSelector = map.get(name);
718 if (!nestedSelector) {
719 return false;
720 }
721 // TODO(perf): get rid of recursion and measure again
722 // TODO(perf): don't pass the whole selector into the recursion,
723 // but only the not processed parts
724 return nestedSelector.match(cssSelector, matchedCallback);
725 };
726 return SelectorMatcher;
727}());
728var SelectorListContext = /** @class */ (function () {
729 function SelectorListContext(selectors) {
730 this.selectors = selectors;
731 this.alreadyMatched = false;
732 }
733 return SelectorListContext;
734}());
735// Store context to pass back selector and context when a selector is matched
736var SelectorContext = /** @class */ (function () {
737 function SelectorContext(selector, cbContext, listContext) {
738 this.selector = selector;
739 this.cbContext = cbContext;
740 this.listContext = listContext;
741 this.notSelectors = selector.notSelectors;
742 }
743 SelectorContext.prototype.finalize = function (cssSelector, callback) {
744 var result = true;
745 if (this.notSelectors.length > 0 && (!this.listContext || !this.listContext.alreadyMatched)) {
746 var notMatcher = SelectorMatcher.createNotMatcher(this.notSelectors);
747 result = !notMatcher.match(cssSelector, null);
748 }
749 if (result && callback && (!this.listContext || !this.listContext.alreadyMatched)) {
750 if (this.listContext) {
751 this.listContext.alreadyMatched = true;
752 }
753 callback(this.selector, this.cbContext);
754 }
755 return result;
756 };
757 return SelectorContext;
758}());
759
760/**
761 * @license
762 * Copyright Google Inc. All Rights Reserved.
763 *
764 * Use of this source code is governed by an MIT-style license that can be
765 * found in the LICENSE file at https://angular.io/license
766 */
767var createInject = makeMetadataFactory('Inject', function (token) { return ({ token: token }); });
768var createInjectionToken = makeMetadataFactory('InjectionToken', function (desc) { return ({ _desc: desc, ngInjectableDef: undefined }); });
769var createAttribute = makeMetadataFactory('Attribute', function (attributeName) { return ({ attributeName: attributeName }); });
770var createContentChildren = makeMetadataFactory('ContentChildren', function (selector, data) {
771 if (data === void 0) { data = {}; }
772 return (__assign({ selector: selector, first: false, isViewQuery: false, descendants: false }, data));
773});
774var createContentChild = makeMetadataFactory('ContentChild', function (selector, data) {
775 if (data === void 0) { data = {}; }
776 return (__assign({ selector: selector, first: true, isViewQuery: false, descendants: true }, data));
777});
778var createViewChildren = makeMetadataFactory('ViewChildren', function (selector, data) {
779 if (data === void 0) { data = {}; }
780 return (__assign({ selector: selector, first: false, isViewQuery: true, descendants: true }, data));
781});
782var createViewChild = makeMetadataFactory('ViewChild', function (selector, data) {
783 return (__assign({ selector: selector, first: true, isViewQuery: true, descendants: true }, data));
784});
785var createDirective = makeMetadataFactory('Directive', function (dir) {
786 if (dir === void 0) { dir = {}; }
787 return dir;
788});
789var ViewEncapsulation;
790(function (ViewEncapsulation) {
791 ViewEncapsulation[ViewEncapsulation["Emulated"] = 0] = "Emulated";
792 ViewEncapsulation[ViewEncapsulation["Native"] = 1] = "Native";
793 ViewEncapsulation[ViewEncapsulation["None"] = 2] = "None";
794 ViewEncapsulation[ViewEncapsulation["ShadowDom"] = 3] = "ShadowDom";
795})(ViewEncapsulation || (ViewEncapsulation = {}));
796var ChangeDetectionStrategy;
797(function (ChangeDetectionStrategy) {
798 ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush";
799 ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default";
800})(ChangeDetectionStrategy || (ChangeDetectionStrategy = {}));
801var createComponent = makeMetadataFactory('Component', function (c) {
802 if (c === void 0) { c = {}; }
803 return (__assign({ changeDetection: ChangeDetectionStrategy.Default }, c));
804});
805var createPipe = makeMetadataFactory('Pipe', function (p) { return (__assign({ pure: true }, p)); });
806var createInput = makeMetadataFactory('Input', function (bindingPropertyName) { return ({ bindingPropertyName: bindingPropertyName }); });
807var createOutput = makeMetadataFactory('Output', function (bindingPropertyName) { return ({ bindingPropertyName: bindingPropertyName }); });
808var createHostBinding = makeMetadataFactory('HostBinding', function (hostPropertyName) { return ({ hostPropertyName: hostPropertyName }); });
809var createHostListener = makeMetadataFactory('HostListener', function (eventName, args) { return ({ eventName: eventName, args: args }); });
810var createNgModule = makeMetadataFactory('NgModule', function (ngModule) { return ngModule; });
811var createInjectable = makeMetadataFactory('Injectable', function (injectable) {
812 if (injectable === void 0) { injectable = {}; }
813 return injectable;
814});
815var CUSTOM_ELEMENTS_SCHEMA = {
816 name: 'custom-elements'
817};
818var NO_ERRORS_SCHEMA = {
819 name: 'no-errors-schema'
820};
821var createOptional = makeMetadataFactory('Optional');
822var createSelf = makeMetadataFactory('Self');
823var createSkipSelf = makeMetadataFactory('SkipSelf');
824var createHost = makeMetadataFactory('Host');
825var Type = Function;
826var SecurityContext;
827(function (SecurityContext) {
828 SecurityContext[SecurityContext["NONE"] = 0] = "NONE";
829 SecurityContext[SecurityContext["HTML"] = 1] = "HTML";
830 SecurityContext[SecurityContext["STYLE"] = 2] = "STYLE";
831 SecurityContext[SecurityContext["SCRIPT"] = 3] = "SCRIPT";
832 SecurityContext[SecurityContext["URL"] = 4] = "URL";
833 SecurityContext[SecurityContext["RESOURCE_URL"] = 5] = "RESOURCE_URL";
834})(SecurityContext || (SecurityContext = {}));
835var MissingTranslationStrategy;
836(function (MissingTranslationStrategy) {
837 MissingTranslationStrategy[MissingTranslationStrategy["Error"] = 0] = "Error";
838 MissingTranslationStrategy[MissingTranslationStrategy["Warning"] = 1] = "Warning";
839 MissingTranslationStrategy[MissingTranslationStrategy["Ignore"] = 2] = "Ignore";
840})(MissingTranslationStrategy || (MissingTranslationStrategy = {}));
841function makeMetadataFactory(name, props) {
842 // This must be declared as a function, not a fat arrow, so that ES2015 devmode produces code
843 // that works with the static_reflector.ts in the ViewEngine compiler.
844 // In particular, `_registerDecoratorOrConstructor` assumes that the value returned here can be
845 // new'ed.
846 function factory() {
847 var args = [];
848 for (var _i = 0; _i < arguments.length; _i++) {
849 args[_i] = arguments[_i];
850 }
851 var values = props ? props.apply(void 0, __spread(args)) : {};
852 return __assign({ ngMetadataName: name }, values);
853 }
854 factory.isTypeOf = function (obj) { return obj && obj.ngMetadataName === name; };
855 factory.ngMetadataName = name;
856 return factory;
857}
858function parserSelectorToSimpleSelector(selector) {
859 var classes = selector.classNames && selector.classNames.length ? __spread([8 /* CLASS */], selector.classNames) :
860 [];
861 var elementName = selector.element && selector.element !== '*' ? selector.element : '';
862 return __spread([elementName], selector.attrs, classes);
863}
864function parserSelectorToNegativeSelector(selector) {
865 var classes = selector.classNames && selector.classNames.length ? __spread([8 /* CLASS */], selector.classNames) :
866 [];
867 if (selector.element) {
868 return __spread([
869 1 /* NOT */ | 4 /* ELEMENT */, selector.element
870 ], selector.attrs, classes);
871 }
872 else if (selector.attrs.length) {
873 return __spread([1 /* NOT */ | 2 /* ATTRIBUTE */], selector.attrs, classes);
874 }
875 else {
876 return selector.classNames && selector.classNames.length ? __spread([1 /* NOT */ | 8 /* CLASS */], selector.classNames) :
877 [];
878 }
879}
880function parserSelectorToR3Selector(selector) {
881 var positive = parserSelectorToSimpleSelector(selector);
882 var negative = selector.notSelectors && selector.notSelectors.length ?
883 selector.notSelectors.map(function (notSelector) { return parserSelectorToNegativeSelector(notSelector); }) :
884 [];
885 return positive.concat.apply(positive, __spread(negative));
886}
887function parseSelectorToR3Selector(selector) {
888 return selector ? CssSelector.parse(selector).map(parserSelectorToR3Selector) : [];
889}
890
891var core = /*#__PURE__*/Object.freeze({
892 createInject: createInject,
893 createInjectionToken: createInjectionToken,
894 createAttribute: createAttribute,
895 createContentChildren: createContentChildren,
896 createContentChild: createContentChild,
897 createViewChildren: createViewChildren,
898 createViewChild: createViewChild,
899 createDirective: createDirective,
900 get ViewEncapsulation () { return ViewEncapsulation; },
901 get ChangeDetectionStrategy () { return ChangeDetectionStrategy; },
902 createComponent: createComponent,
903 createPipe: createPipe,
904 createInput: createInput,
905 createOutput: createOutput,
906 createHostBinding: createHostBinding,
907 createHostListener: createHostListener,
908 createNgModule: createNgModule,
909 createInjectable: createInjectable,
910 CUSTOM_ELEMENTS_SCHEMA: CUSTOM_ELEMENTS_SCHEMA,
911 NO_ERRORS_SCHEMA: NO_ERRORS_SCHEMA,
912 createOptional: createOptional,
913 createSelf: createSelf,
914 createSkipSelf: createSkipSelf,
915 createHost: createHost,
916 Type: Type,
917 get SecurityContext () { return SecurityContext; },
918 get MissingTranslationStrategy () { return MissingTranslationStrategy; },
919 parseSelectorToR3Selector: parseSelectorToR3Selector
920});
921
922/**
923 * @license
924 * Copyright Google Inc. All Rights Reserved.
925 *
926 * Use of this source code is governed by an MIT-style license that can be
927 * found in the LICENSE file at https://angular.io/license
928 */
929//// Types
930var TypeModifier;
931(function (TypeModifier) {
932 TypeModifier[TypeModifier["Const"] = 0] = "Const";
933})(TypeModifier || (TypeModifier = {}));
934var Type$1 = /** @class */ (function () {
935 function Type(modifiers) {
936 if (modifiers === void 0) { modifiers = null; }
937 this.modifiers = modifiers;
938 if (!modifiers) {
939 this.modifiers = [];
940 }
941 }
942 Type.prototype.hasModifier = function (modifier) { return this.modifiers.indexOf(modifier) !== -1; };
943 return Type;
944}());
945var BuiltinTypeName;
946(function (BuiltinTypeName) {
947 BuiltinTypeName[BuiltinTypeName["Dynamic"] = 0] = "Dynamic";
948 BuiltinTypeName[BuiltinTypeName["Bool"] = 1] = "Bool";
949 BuiltinTypeName[BuiltinTypeName["String"] = 2] = "String";
950 BuiltinTypeName[BuiltinTypeName["Int"] = 3] = "Int";
951 BuiltinTypeName[BuiltinTypeName["Number"] = 4] = "Number";
952 BuiltinTypeName[BuiltinTypeName["Function"] = 5] = "Function";
953 BuiltinTypeName[BuiltinTypeName["Inferred"] = 6] = "Inferred";
954 BuiltinTypeName[BuiltinTypeName["None"] = 7] = "None";
955})(BuiltinTypeName || (BuiltinTypeName = {}));
956var BuiltinType = /** @class */ (function (_super) {
957 __extends(BuiltinType, _super);
958 function BuiltinType(name, modifiers) {
959 if (modifiers === void 0) { modifiers = null; }
960 var _this = _super.call(this, modifiers) || this;
961 _this.name = name;
962 return _this;
963 }
964 BuiltinType.prototype.visitType = function (visitor, context) {
965 return visitor.visitBuiltinType(this, context);
966 };
967 return BuiltinType;
968}(Type$1));
969var ExpressionType = /** @class */ (function (_super) {
970 __extends(ExpressionType, _super);
971 function ExpressionType(value, modifiers, typeParams) {
972 if (modifiers === void 0) { modifiers = null; }
973 if (typeParams === void 0) { typeParams = null; }
974 var _this = _super.call(this, modifiers) || this;
975 _this.value = value;
976 _this.typeParams = typeParams;
977 return _this;
978 }
979 ExpressionType.prototype.visitType = function (visitor, context) {
980 return visitor.visitExpressionType(this, context);
981 };
982 return ExpressionType;
983}(Type$1));
984var ArrayType = /** @class */ (function (_super) {
985 __extends(ArrayType, _super);
986 function ArrayType(of, modifiers) {
987 if (modifiers === void 0) { modifiers = null; }
988 var _this = _super.call(this, modifiers) || this;
989 _this.of = of;
990 return _this;
991 }
992 ArrayType.prototype.visitType = function (visitor, context) {
993 return visitor.visitArrayType(this, context);
994 };
995 return ArrayType;
996}(Type$1));
997var MapType = /** @class */ (function (_super) {
998 __extends(MapType, _super);
999 function MapType(valueType, modifiers) {
1000 if (modifiers === void 0) { modifiers = null; }
1001 var _this = _super.call(this, modifiers) || this;
1002 _this.valueType = valueType || null;
1003 return _this;
1004 }
1005 MapType.prototype.visitType = function (visitor, context) { return visitor.visitMapType(this, context); };
1006 return MapType;
1007}(Type$1));
1008var DYNAMIC_TYPE = new BuiltinType(BuiltinTypeName.Dynamic);
1009var INFERRED_TYPE = new BuiltinType(BuiltinTypeName.Inferred);
1010var BOOL_TYPE = new BuiltinType(BuiltinTypeName.Bool);
1011var INT_TYPE = new BuiltinType(BuiltinTypeName.Int);
1012var NUMBER_TYPE = new BuiltinType(BuiltinTypeName.Number);
1013var STRING_TYPE = new BuiltinType(BuiltinTypeName.String);
1014var FUNCTION_TYPE = new BuiltinType(BuiltinTypeName.Function);
1015var NONE_TYPE = new BuiltinType(BuiltinTypeName.None);
1016///// Expressions
1017var BinaryOperator;
1018(function (BinaryOperator) {
1019 BinaryOperator[BinaryOperator["Equals"] = 0] = "Equals";
1020 BinaryOperator[BinaryOperator["NotEquals"] = 1] = "NotEquals";
1021 BinaryOperator[BinaryOperator["Identical"] = 2] = "Identical";
1022 BinaryOperator[BinaryOperator["NotIdentical"] = 3] = "NotIdentical";
1023 BinaryOperator[BinaryOperator["Minus"] = 4] = "Minus";
1024 BinaryOperator[BinaryOperator["Plus"] = 5] = "Plus";
1025 BinaryOperator[BinaryOperator["Divide"] = 6] = "Divide";
1026 BinaryOperator[BinaryOperator["Multiply"] = 7] = "Multiply";
1027 BinaryOperator[BinaryOperator["Modulo"] = 8] = "Modulo";
1028 BinaryOperator[BinaryOperator["And"] = 9] = "And";
1029 BinaryOperator[BinaryOperator["Or"] = 10] = "Or";
1030 BinaryOperator[BinaryOperator["BitwiseAnd"] = 11] = "BitwiseAnd";
1031 BinaryOperator[BinaryOperator["Lower"] = 12] = "Lower";
1032 BinaryOperator[BinaryOperator["LowerEquals"] = 13] = "LowerEquals";
1033 BinaryOperator[BinaryOperator["Bigger"] = 14] = "Bigger";
1034 BinaryOperator[BinaryOperator["BiggerEquals"] = 15] = "BiggerEquals";
1035})(BinaryOperator || (BinaryOperator = {}));
1036function nullSafeIsEquivalent(base, other) {
1037 if (base == null || other == null) {
1038 return base == other;
1039 }
1040 return base.isEquivalent(other);
1041}
1042function areAllEquivalent(base, other) {
1043 var len = base.length;
1044 if (len !== other.length) {
1045 return false;
1046 }
1047 for (var i = 0; i < len; i++) {
1048 if (!base[i].isEquivalent(other[i])) {
1049 return false;
1050 }
1051 }
1052 return true;
1053}
1054var Expression = /** @class */ (function () {
1055 function Expression(type, sourceSpan) {
1056 this.type = type || null;
1057 this.sourceSpan = sourceSpan || null;
1058 }
1059 Expression.prototype.prop = function (name, sourceSpan) {
1060 return new ReadPropExpr(this, name, null, sourceSpan);
1061 };
1062 Expression.prototype.key = function (index, type, sourceSpan) {
1063 return new ReadKeyExpr(this, index, type, sourceSpan);
1064 };
1065 Expression.prototype.callMethod = function (name, params, sourceSpan) {
1066 return new InvokeMethodExpr(this, name, params, null, sourceSpan);
1067 };
1068 Expression.prototype.callFn = function (params, sourceSpan) {
1069 return new InvokeFunctionExpr(this, params, null, sourceSpan);
1070 };
1071 Expression.prototype.instantiate = function (params, type, sourceSpan) {
1072 return new InstantiateExpr(this, params, type, sourceSpan);
1073 };
1074 Expression.prototype.conditional = function (trueCase, falseCase, sourceSpan) {
1075 if (falseCase === void 0) { falseCase = null; }
1076 return new ConditionalExpr(this, trueCase, falseCase, null, sourceSpan);
1077 };
1078 Expression.prototype.equals = function (rhs, sourceSpan) {
1079 return new BinaryOperatorExpr(BinaryOperator.Equals, this, rhs, null, sourceSpan);
1080 };
1081 Expression.prototype.notEquals = function (rhs, sourceSpan) {
1082 return new BinaryOperatorExpr(BinaryOperator.NotEquals, this, rhs, null, sourceSpan);
1083 };
1084 Expression.prototype.identical = function (rhs, sourceSpan) {
1085 return new BinaryOperatorExpr(BinaryOperator.Identical, this, rhs, null, sourceSpan);
1086 };
1087 Expression.prototype.notIdentical = function (rhs, sourceSpan) {
1088 return new BinaryOperatorExpr(BinaryOperator.NotIdentical, this, rhs, null, sourceSpan);
1089 };
1090 Expression.prototype.minus = function (rhs, sourceSpan) {
1091 return new BinaryOperatorExpr(BinaryOperator.Minus, this, rhs, null, sourceSpan);
1092 };
1093 Expression.prototype.plus = function (rhs, sourceSpan) {
1094 return new BinaryOperatorExpr(BinaryOperator.Plus, this, rhs, null, sourceSpan);
1095 };
1096 Expression.prototype.divide = function (rhs, sourceSpan) {
1097 return new BinaryOperatorExpr(BinaryOperator.Divide, this, rhs, null, sourceSpan);
1098 };
1099 Expression.prototype.multiply = function (rhs, sourceSpan) {
1100 return new BinaryOperatorExpr(BinaryOperator.Multiply, this, rhs, null, sourceSpan);
1101 };
1102 Expression.prototype.modulo = function (rhs, sourceSpan) {
1103 return new BinaryOperatorExpr(BinaryOperator.Modulo, this, rhs, null, sourceSpan);
1104 };
1105 Expression.prototype.and = function (rhs, sourceSpan) {
1106 return new BinaryOperatorExpr(BinaryOperator.And, this, rhs, null, sourceSpan);
1107 };
1108 Expression.prototype.bitwiseAnd = function (rhs, sourceSpan, parens) {
1109 if (parens === void 0) { parens = true; }
1110 return new BinaryOperatorExpr(BinaryOperator.BitwiseAnd, this, rhs, null, sourceSpan, parens);
1111 };
1112 Expression.prototype.or = function (rhs, sourceSpan) {
1113 return new BinaryOperatorExpr(BinaryOperator.Or, this, rhs, null, sourceSpan);
1114 };
1115 Expression.prototype.lower = function (rhs, sourceSpan) {
1116 return new BinaryOperatorExpr(BinaryOperator.Lower, this, rhs, null, sourceSpan);
1117 };
1118 Expression.prototype.lowerEquals = function (rhs, sourceSpan) {
1119 return new BinaryOperatorExpr(BinaryOperator.LowerEquals, this, rhs, null, sourceSpan);
1120 };
1121 Expression.prototype.bigger = function (rhs, sourceSpan) {
1122 return new BinaryOperatorExpr(BinaryOperator.Bigger, this, rhs, null, sourceSpan);
1123 };
1124 Expression.prototype.biggerEquals = function (rhs, sourceSpan) {
1125 return new BinaryOperatorExpr(BinaryOperator.BiggerEquals, this, rhs, null, sourceSpan);
1126 };
1127 Expression.prototype.isBlank = function (sourceSpan) {
1128 // Note: We use equals by purpose here to compare to null and undefined in JS.
1129 // We use the typed null to allow strictNullChecks to narrow types.
1130 return this.equals(TYPED_NULL_EXPR, sourceSpan);
1131 };
1132 Expression.prototype.cast = function (type, sourceSpan) {
1133 return new CastExpr(this, type, sourceSpan);
1134 };
1135 Expression.prototype.toStmt = function () { return new ExpressionStatement(this, null); };
1136 return Expression;
1137}());
1138var BuiltinVar;
1139(function (BuiltinVar) {
1140 BuiltinVar[BuiltinVar["This"] = 0] = "This";
1141 BuiltinVar[BuiltinVar["Super"] = 1] = "Super";
1142 BuiltinVar[BuiltinVar["CatchError"] = 2] = "CatchError";
1143 BuiltinVar[BuiltinVar["CatchStack"] = 3] = "CatchStack";
1144})(BuiltinVar || (BuiltinVar = {}));
1145var ReadVarExpr = /** @class */ (function (_super) {
1146 __extends(ReadVarExpr, _super);
1147 function ReadVarExpr(name, type, sourceSpan) {
1148 var _this = _super.call(this, type, sourceSpan) || this;
1149 if (typeof name === 'string') {
1150 _this.name = name;
1151 _this.builtin = null;
1152 }
1153 else {
1154 _this.name = null;
1155 _this.builtin = name;
1156 }
1157 return _this;
1158 }
1159 ReadVarExpr.prototype.isEquivalent = function (e) {
1160 return e instanceof ReadVarExpr && this.name === e.name && this.builtin === e.builtin;
1161 };
1162 ReadVarExpr.prototype.isConstant = function () { return false; };
1163 ReadVarExpr.prototype.visitExpression = function (visitor, context) {
1164 return visitor.visitReadVarExpr(this, context);
1165 };
1166 ReadVarExpr.prototype.set = function (value) {
1167 if (!this.name) {
1168 throw new Error("Built in variable " + this.builtin + " can not be assigned to.");
1169 }
1170 return new WriteVarExpr(this.name, value, null, this.sourceSpan);
1171 };
1172 return ReadVarExpr;
1173}(Expression));
1174var TypeofExpr = /** @class */ (function (_super) {
1175 __extends(TypeofExpr, _super);
1176 function TypeofExpr(expr, type, sourceSpan) {
1177 var _this = _super.call(this, type, sourceSpan) || this;
1178 _this.expr = expr;
1179 return _this;
1180 }
1181 TypeofExpr.prototype.visitExpression = function (visitor, context) {
1182 return visitor.visitTypeofExpr(this, context);
1183 };
1184 TypeofExpr.prototype.isEquivalent = function (e) {
1185 return e instanceof TypeofExpr && e.expr.isEquivalent(this.expr);
1186 };
1187 TypeofExpr.prototype.isConstant = function () { return this.expr.isConstant(); };
1188 return TypeofExpr;
1189}(Expression));
1190var WrappedNodeExpr = /** @class */ (function (_super) {
1191 __extends(WrappedNodeExpr, _super);
1192 function WrappedNodeExpr(node, type, sourceSpan) {
1193 var _this = _super.call(this, type, sourceSpan) || this;
1194 _this.node = node;
1195 return _this;
1196 }
1197 WrappedNodeExpr.prototype.isEquivalent = function (e) {
1198 return e instanceof WrappedNodeExpr && this.node === e.node;
1199 };
1200 WrappedNodeExpr.prototype.isConstant = function () { return false; };
1201 WrappedNodeExpr.prototype.visitExpression = function (visitor, context) {
1202 return visitor.visitWrappedNodeExpr(this, context);
1203 };
1204 return WrappedNodeExpr;
1205}(Expression));
1206var WriteVarExpr = /** @class */ (function (_super) {
1207 __extends(WriteVarExpr, _super);
1208 function WriteVarExpr(name, value, type, sourceSpan) {
1209 var _this = _super.call(this, type || value.type, sourceSpan) || this;
1210 _this.name = name;
1211 _this.value = value;
1212 return _this;
1213 }
1214 WriteVarExpr.prototype.isEquivalent = function (e) {
1215 return e instanceof WriteVarExpr && this.name === e.name && this.value.isEquivalent(e.value);
1216 };
1217 WriteVarExpr.prototype.isConstant = function () { return false; };
1218 WriteVarExpr.prototype.visitExpression = function (visitor, context) {
1219 return visitor.visitWriteVarExpr(this, context);
1220 };
1221 WriteVarExpr.prototype.toDeclStmt = function (type, modifiers) {
1222 return new DeclareVarStmt(this.name, this.value, type, modifiers, this.sourceSpan);
1223 };
1224 WriteVarExpr.prototype.toConstDecl = function () { return this.toDeclStmt(INFERRED_TYPE, [StmtModifier.Final]); };
1225 return WriteVarExpr;
1226}(Expression));
1227var WriteKeyExpr = /** @class */ (function (_super) {
1228 __extends(WriteKeyExpr, _super);
1229 function WriteKeyExpr(receiver, index, value, type, sourceSpan) {
1230 var _this = _super.call(this, type || value.type, sourceSpan) || this;
1231 _this.receiver = receiver;
1232 _this.index = index;
1233 _this.value = value;
1234 return _this;
1235 }
1236 WriteKeyExpr.prototype.isEquivalent = function (e) {
1237 return e instanceof WriteKeyExpr && this.receiver.isEquivalent(e.receiver) &&
1238 this.index.isEquivalent(e.index) && this.value.isEquivalent(e.value);
1239 };
1240 WriteKeyExpr.prototype.isConstant = function () { return false; };
1241 WriteKeyExpr.prototype.visitExpression = function (visitor, context) {
1242 return visitor.visitWriteKeyExpr(this, context);
1243 };
1244 return WriteKeyExpr;
1245}(Expression));
1246var WritePropExpr = /** @class */ (function (_super) {
1247 __extends(WritePropExpr, _super);
1248 function WritePropExpr(receiver, name, value, type, sourceSpan) {
1249 var _this = _super.call(this, type || value.type, sourceSpan) || this;
1250 _this.receiver = receiver;
1251 _this.name = name;
1252 _this.value = value;
1253 return _this;
1254 }
1255 WritePropExpr.prototype.isEquivalent = function (e) {
1256 return e instanceof WritePropExpr && this.receiver.isEquivalent(e.receiver) &&
1257 this.name === e.name && this.value.isEquivalent(e.value);
1258 };
1259 WritePropExpr.prototype.isConstant = function () { return false; };
1260 WritePropExpr.prototype.visitExpression = function (visitor, context) {
1261 return visitor.visitWritePropExpr(this, context);
1262 };
1263 return WritePropExpr;
1264}(Expression));
1265var BuiltinMethod;
1266(function (BuiltinMethod) {
1267 BuiltinMethod[BuiltinMethod["ConcatArray"] = 0] = "ConcatArray";
1268 BuiltinMethod[BuiltinMethod["SubscribeObservable"] = 1] = "SubscribeObservable";
1269 BuiltinMethod[BuiltinMethod["Bind"] = 2] = "Bind";
1270})(BuiltinMethod || (BuiltinMethod = {}));
1271var InvokeMethodExpr = /** @class */ (function (_super) {
1272 __extends(InvokeMethodExpr, _super);
1273 function InvokeMethodExpr(receiver, method, args, type, sourceSpan) {
1274 var _this = _super.call(this, type, sourceSpan) || this;
1275 _this.receiver = receiver;
1276 _this.args = args;
1277 if (typeof method === 'string') {
1278 _this.name = method;
1279 _this.builtin = null;
1280 }
1281 else {
1282 _this.name = null;
1283 _this.builtin = method;
1284 }
1285 return _this;
1286 }
1287 InvokeMethodExpr.prototype.isEquivalent = function (e) {
1288 return e instanceof InvokeMethodExpr && this.receiver.isEquivalent(e.receiver) &&
1289 this.name === e.name && this.builtin === e.builtin && areAllEquivalent(this.args, e.args);
1290 };
1291 InvokeMethodExpr.prototype.isConstant = function () { return false; };
1292 InvokeMethodExpr.prototype.visitExpression = function (visitor, context) {
1293 return visitor.visitInvokeMethodExpr(this, context);
1294 };
1295 return InvokeMethodExpr;
1296}(Expression));
1297var InvokeFunctionExpr = /** @class */ (function (_super) {
1298 __extends(InvokeFunctionExpr, _super);
1299 function InvokeFunctionExpr(fn, args, type, sourceSpan, pure) {
1300 if (pure === void 0) { pure = false; }
1301 var _this = _super.call(this, type, sourceSpan) || this;
1302 _this.fn = fn;
1303 _this.args = args;
1304 _this.pure = pure;
1305 return _this;
1306 }
1307 InvokeFunctionExpr.prototype.isEquivalent = function (e) {
1308 return e instanceof InvokeFunctionExpr && this.fn.isEquivalent(e.fn) &&
1309 areAllEquivalent(this.args, e.args) && this.pure === e.pure;
1310 };
1311 InvokeFunctionExpr.prototype.isConstant = function () { return false; };
1312 InvokeFunctionExpr.prototype.visitExpression = function (visitor, context) {
1313 return visitor.visitInvokeFunctionExpr(this, context);
1314 };
1315 return InvokeFunctionExpr;
1316}(Expression));
1317var InstantiateExpr = /** @class */ (function (_super) {
1318 __extends(InstantiateExpr, _super);
1319 function InstantiateExpr(classExpr, args, type, sourceSpan) {
1320 var _this = _super.call(this, type, sourceSpan) || this;
1321 _this.classExpr = classExpr;
1322 _this.args = args;
1323 return _this;
1324 }
1325 InstantiateExpr.prototype.isEquivalent = function (e) {
1326 return e instanceof InstantiateExpr && this.classExpr.isEquivalent(e.classExpr) &&
1327 areAllEquivalent(this.args, e.args);
1328 };
1329 InstantiateExpr.prototype.isConstant = function () { return false; };
1330 InstantiateExpr.prototype.visitExpression = function (visitor, context) {
1331 return visitor.visitInstantiateExpr(this, context);
1332 };
1333 return InstantiateExpr;
1334}(Expression));
1335var LiteralExpr = /** @class */ (function (_super) {
1336 __extends(LiteralExpr, _super);
1337 function LiteralExpr(value, type, sourceSpan) {
1338 var _this = _super.call(this, type, sourceSpan) || this;
1339 _this.value = value;
1340 return _this;
1341 }
1342 LiteralExpr.prototype.isEquivalent = function (e) {
1343 return e instanceof LiteralExpr && this.value === e.value;
1344 };
1345 LiteralExpr.prototype.isConstant = function () { return true; };
1346 LiteralExpr.prototype.visitExpression = function (visitor, context) {
1347 return visitor.visitLiteralExpr(this, context);
1348 };
1349 return LiteralExpr;
1350}(Expression));
1351var ExternalExpr = /** @class */ (function (_super) {
1352 __extends(ExternalExpr, _super);
1353 function ExternalExpr(value, type, typeParams, sourceSpan) {
1354 if (typeParams === void 0) { typeParams = null; }
1355 var _this = _super.call(this, type, sourceSpan) || this;
1356 _this.value = value;
1357 _this.typeParams = typeParams;
1358 return _this;
1359 }
1360 ExternalExpr.prototype.isEquivalent = function (e) {
1361 return e instanceof ExternalExpr && this.value.name === e.value.name &&
1362 this.value.moduleName === e.value.moduleName && this.value.runtime === e.value.runtime;
1363 };
1364 ExternalExpr.prototype.isConstant = function () { return false; };
1365 ExternalExpr.prototype.visitExpression = function (visitor, context) {
1366 return visitor.visitExternalExpr(this, context);
1367 };
1368 return ExternalExpr;
1369}(Expression));
1370var ExternalReference = /** @class */ (function () {
1371 function ExternalReference(moduleName, name, runtime) {
1372 this.moduleName = moduleName;
1373 this.name = name;
1374 this.runtime = runtime;
1375 }
1376 return ExternalReference;
1377}());
1378var ConditionalExpr = /** @class */ (function (_super) {
1379 __extends(ConditionalExpr, _super);
1380 function ConditionalExpr(condition, trueCase, falseCase, type, sourceSpan) {
1381 if (falseCase === void 0) { falseCase = null; }
1382 var _this = _super.call(this, type || trueCase.type, sourceSpan) || this;
1383 _this.condition = condition;
1384 _this.falseCase = falseCase;
1385 _this.trueCase = trueCase;
1386 return _this;
1387 }
1388 ConditionalExpr.prototype.isEquivalent = function (e) {
1389 return e instanceof ConditionalExpr && this.condition.isEquivalent(e.condition) &&
1390 this.trueCase.isEquivalent(e.trueCase) && nullSafeIsEquivalent(this.falseCase, e.falseCase);
1391 };
1392 ConditionalExpr.prototype.isConstant = function () { return false; };
1393 ConditionalExpr.prototype.visitExpression = function (visitor, context) {
1394 return visitor.visitConditionalExpr(this, context);
1395 };
1396 return ConditionalExpr;
1397}(Expression));
1398var NotExpr = /** @class */ (function (_super) {
1399 __extends(NotExpr, _super);
1400 function NotExpr(condition, sourceSpan) {
1401 var _this = _super.call(this, BOOL_TYPE, sourceSpan) || this;
1402 _this.condition = condition;
1403 return _this;
1404 }
1405 NotExpr.prototype.isEquivalent = function (e) {
1406 return e instanceof NotExpr && this.condition.isEquivalent(e.condition);
1407 };
1408 NotExpr.prototype.isConstant = function () { return false; };
1409 NotExpr.prototype.visitExpression = function (visitor, context) {
1410 return visitor.visitNotExpr(this, context);
1411 };
1412 return NotExpr;
1413}(Expression));
1414var AssertNotNull = /** @class */ (function (_super) {
1415 __extends(AssertNotNull, _super);
1416 function AssertNotNull(condition, sourceSpan) {
1417 var _this = _super.call(this, condition.type, sourceSpan) || this;
1418 _this.condition = condition;
1419 return _this;
1420 }
1421 AssertNotNull.prototype.isEquivalent = function (e) {
1422 return e instanceof AssertNotNull && this.condition.isEquivalent(e.condition);
1423 };
1424 AssertNotNull.prototype.isConstant = function () { return false; };
1425 AssertNotNull.prototype.visitExpression = function (visitor, context) {
1426 return visitor.visitAssertNotNullExpr(this, context);
1427 };
1428 return AssertNotNull;
1429}(Expression));
1430var CastExpr = /** @class */ (function (_super) {
1431 __extends(CastExpr, _super);
1432 function CastExpr(value, type, sourceSpan) {
1433 var _this = _super.call(this, type, sourceSpan) || this;
1434 _this.value = value;
1435 return _this;
1436 }
1437 CastExpr.prototype.isEquivalent = function (e) {
1438 return e instanceof CastExpr && this.value.isEquivalent(e.value);
1439 };
1440 CastExpr.prototype.isConstant = function () { return false; };
1441 CastExpr.prototype.visitExpression = function (visitor, context) {
1442 return visitor.visitCastExpr(this, context);
1443 };
1444 return CastExpr;
1445}(Expression));
1446var FnParam = /** @class */ (function () {
1447 function FnParam(name, type) {
1448 if (type === void 0) { type = null; }
1449 this.name = name;
1450 this.type = type;
1451 }
1452 FnParam.prototype.isEquivalent = function (param) { return this.name === param.name; };
1453 return FnParam;
1454}());
1455var FunctionExpr = /** @class */ (function (_super) {
1456 __extends(FunctionExpr, _super);
1457 function FunctionExpr(params, statements, type, sourceSpan, name) {
1458 var _this = _super.call(this, type, sourceSpan) || this;
1459 _this.params = params;
1460 _this.statements = statements;
1461 _this.name = name;
1462 return _this;
1463 }
1464 FunctionExpr.prototype.isEquivalent = function (e) {
1465 return e instanceof FunctionExpr && areAllEquivalent(this.params, e.params) &&
1466 areAllEquivalent(this.statements, e.statements);
1467 };
1468 FunctionExpr.prototype.isConstant = function () { return false; };
1469 FunctionExpr.prototype.visitExpression = function (visitor, context) {
1470 return visitor.visitFunctionExpr(this, context);
1471 };
1472 FunctionExpr.prototype.toDeclStmt = function (name, modifiers) {
1473 if (modifiers === void 0) { modifiers = null; }
1474 return new DeclareFunctionStmt(name, this.params, this.statements, this.type, modifiers, this.sourceSpan);
1475 };
1476 return FunctionExpr;
1477}(Expression));
1478var BinaryOperatorExpr = /** @class */ (function (_super) {
1479 __extends(BinaryOperatorExpr, _super);
1480 function BinaryOperatorExpr(operator, lhs, rhs, type, sourceSpan, parens) {
1481 if (parens === void 0) { parens = true; }
1482 var _this = _super.call(this, type || lhs.type, sourceSpan) || this;
1483 _this.operator = operator;
1484 _this.rhs = rhs;
1485 _this.parens = parens;
1486 _this.lhs = lhs;
1487 return _this;
1488 }
1489 BinaryOperatorExpr.prototype.isEquivalent = function (e) {
1490 return e instanceof BinaryOperatorExpr && this.operator === e.operator &&
1491 this.lhs.isEquivalent(e.lhs) && this.rhs.isEquivalent(e.rhs);
1492 };
1493 BinaryOperatorExpr.prototype.isConstant = function () { return false; };
1494 BinaryOperatorExpr.prototype.visitExpression = function (visitor, context) {
1495 return visitor.visitBinaryOperatorExpr(this, context);
1496 };
1497 return BinaryOperatorExpr;
1498}(Expression));
1499var ReadPropExpr = /** @class */ (function (_super) {
1500 __extends(ReadPropExpr, _super);
1501 function ReadPropExpr(receiver, name, type, sourceSpan) {
1502 var _this = _super.call(this, type, sourceSpan) || this;
1503 _this.receiver = receiver;
1504 _this.name = name;
1505 return _this;
1506 }
1507 ReadPropExpr.prototype.isEquivalent = function (e) {
1508 return e instanceof ReadPropExpr && this.receiver.isEquivalent(e.receiver) &&
1509 this.name === e.name;
1510 };
1511 ReadPropExpr.prototype.isConstant = function () { return false; };
1512 ReadPropExpr.prototype.visitExpression = function (visitor, context) {
1513 return visitor.visitReadPropExpr(this, context);
1514 };
1515 ReadPropExpr.prototype.set = function (value) {
1516 return new WritePropExpr(this.receiver, this.name, value, null, this.sourceSpan);
1517 };
1518 return ReadPropExpr;
1519}(Expression));
1520var ReadKeyExpr = /** @class */ (function (_super) {
1521 __extends(ReadKeyExpr, _super);
1522 function ReadKeyExpr(receiver, index, type, sourceSpan) {
1523 var _this = _super.call(this, type, sourceSpan) || this;
1524 _this.receiver = receiver;
1525 _this.index = index;
1526 return _this;
1527 }
1528 ReadKeyExpr.prototype.isEquivalent = function (e) {
1529 return e instanceof ReadKeyExpr && this.receiver.isEquivalent(e.receiver) &&
1530 this.index.isEquivalent(e.index);
1531 };
1532 ReadKeyExpr.prototype.isConstant = function () { return false; };
1533 ReadKeyExpr.prototype.visitExpression = function (visitor, context) {
1534 return visitor.visitReadKeyExpr(this, context);
1535 };
1536 ReadKeyExpr.prototype.set = function (value) {
1537 return new WriteKeyExpr(this.receiver, this.index, value, null, this.sourceSpan);
1538 };
1539 return ReadKeyExpr;
1540}(Expression));
1541var LiteralArrayExpr = /** @class */ (function (_super) {
1542 __extends(LiteralArrayExpr, _super);
1543 function LiteralArrayExpr(entries, type, sourceSpan) {
1544 var _this = _super.call(this, type, sourceSpan) || this;
1545 _this.entries = entries;
1546 return _this;
1547 }
1548 LiteralArrayExpr.prototype.isConstant = function () { return this.entries.every(function (e) { return e.isConstant(); }); };
1549 LiteralArrayExpr.prototype.isEquivalent = function (e) {
1550 return e instanceof LiteralArrayExpr && areAllEquivalent(this.entries, e.entries);
1551 };
1552 LiteralArrayExpr.prototype.visitExpression = function (visitor, context) {
1553 return visitor.visitLiteralArrayExpr(this, context);
1554 };
1555 return LiteralArrayExpr;
1556}(Expression));
1557var LiteralMapEntry = /** @class */ (function () {
1558 function LiteralMapEntry(key, value, quoted) {
1559 this.key = key;
1560 this.value = value;
1561 this.quoted = quoted;
1562 }
1563 LiteralMapEntry.prototype.isEquivalent = function (e) {
1564 return this.key === e.key && this.value.isEquivalent(e.value);
1565 };
1566 return LiteralMapEntry;
1567}());
1568var LiteralMapExpr = /** @class */ (function (_super) {
1569 __extends(LiteralMapExpr, _super);
1570 function LiteralMapExpr(entries, type, sourceSpan) {
1571 var _this = _super.call(this, type, sourceSpan) || this;
1572 _this.entries = entries;
1573 _this.valueType = null;
1574 if (type) {
1575 _this.valueType = type.valueType;
1576 }
1577 return _this;
1578 }
1579 LiteralMapExpr.prototype.isEquivalent = function (e) {
1580 return e instanceof LiteralMapExpr && areAllEquivalent(this.entries, e.entries);
1581 };
1582 LiteralMapExpr.prototype.isConstant = function () { return this.entries.every(function (e) { return e.value.isConstant(); }); };
1583 LiteralMapExpr.prototype.visitExpression = function (visitor, context) {
1584 return visitor.visitLiteralMapExpr(this, context);
1585 };
1586 return LiteralMapExpr;
1587}(Expression));
1588var CommaExpr = /** @class */ (function (_super) {
1589 __extends(CommaExpr, _super);
1590 function CommaExpr(parts, sourceSpan) {
1591 var _this = _super.call(this, parts[parts.length - 1].type, sourceSpan) || this;
1592 _this.parts = parts;
1593 return _this;
1594 }
1595 CommaExpr.prototype.isEquivalent = function (e) {
1596 return e instanceof CommaExpr && areAllEquivalent(this.parts, e.parts);
1597 };
1598 CommaExpr.prototype.isConstant = function () { return false; };
1599 CommaExpr.prototype.visitExpression = function (visitor, context) {
1600 return visitor.visitCommaExpr(this, context);
1601 };
1602 return CommaExpr;
1603}(Expression));
1604var THIS_EXPR = new ReadVarExpr(BuiltinVar.This, null, null);
1605var SUPER_EXPR = new ReadVarExpr(BuiltinVar.Super, null, null);
1606var CATCH_ERROR_VAR = new ReadVarExpr(BuiltinVar.CatchError, null, null);
1607var CATCH_STACK_VAR = new ReadVarExpr(BuiltinVar.CatchStack, null, null);
1608var NULL_EXPR = new LiteralExpr(null, null, null);
1609var TYPED_NULL_EXPR = new LiteralExpr(null, INFERRED_TYPE, null);
1610//// Statements
1611var StmtModifier;
1612(function (StmtModifier) {
1613 StmtModifier[StmtModifier["Final"] = 0] = "Final";
1614 StmtModifier[StmtModifier["Private"] = 1] = "Private";
1615 StmtModifier[StmtModifier["Exported"] = 2] = "Exported";
1616 StmtModifier[StmtModifier["Static"] = 3] = "Static";
1617})(StmtModifier || (StmtModifier = {}));
1618var Statement = /** @class */ (function () {
1619 function Statement(modifiers, sourceSpan) {
1620 this.modifiers = modifiers || [];
1621 this.sourceSpan = sourceSpan || null;
1622 }
1623 Statement.prototype.hasModifier = function (modifier) { return this.modifiers.indexOf(modifier) !== -1; };
1624 return Statement;
1625}());
1626var DeclareVarStmt = /** @class */ (function (_super) {
1627 __extends(DeclareVarStmt, _super);
1628 function DeclareVarStmt(name, value, type, modifiers, sourceSpan) {
1629 if (modifiers === void 0) { modifiers = null; }
1630 var _this = _super.call(this, modifiers, sourceSpan) || this;
1631 _this.name = name;
1632 _this.value = value;
1633 _this.type = type || (value && value.type) || null;
1634 return _this;
1635 }
1636 DeclareVarStmt.prototype.isEquivalent = function (stmt) {
1637 return stmt instanceof DeclareVarStmt && this.name === stmt.name &&
1638 (this.value ? !!stmt.value && this.value.isEquivalent(stmt.value) : !stmt.value);
1639 };
1640 DeclareVarStmt.prototype.visitStatement = function (visitor, context) {
1641 return visitor.visitDeclareVarStmt(this, context);
1642 };
1643 return DeclareVarStmt;
1644}(Statement));
1645var DeclareFunctionStmt = /** @class */ (function (_super) {
1646 __extends(DeclareFunctionStmt, _super);
1647 function DeclareFunctionStmt(name, params, statements, type, modifiers, sourceSpan) {
1648 if (modifiers === void 0) { modifiers = null; }
1649 var _this = _super.call(this, modifiers, sourceSpan) || this;
1650 _this.name = name;
1651 _this.params = params;
1652 _this.statements = statements;
1653 _this.type = type || null;
1654 return _this;
1655 }
1656 DeclareFunctionStmt.prototype.isEquivalent = function (stmt) {
1657 return stmt instanceof DeclareFunctionStmt && areAllEquivalent(this.params, stmt.params) &&
1658 areAllEquivalent(this.statements, stmt.statements);
1659 };
1660 DeclareFunctionStmt.prototype.visitStatement = function (visitor, context) {
1661 return visitor.visitDeclareFunctionStmt(this, context);
1662 };
1663 return DeclareFunctionStmt;
1664}(Statement));
1665var ExpressionStatement = /** @class */ (function (_super) {
1666 __extends(ExpressionStatement, _super);
1667 function ExpressionStatement(expr, sourceSpan) {
1668 var _this = _super.call(this, null, sourceSpan) || this;
1669 _this.expr = expr;
1670 return _this;
1671 }
1672 ExpressionStatement.prototype.isEquivalent = function (stmt) {
1673 return stmt instanceof ExpressionStatement && this.expr.isEquivalent(stmt.expr);
1674 };
1675 ExpressionStatement.prototype.visitStatement = function (visitor, context) {
1676 return visitor.visitExpressionStmt(this, context);
1677 };
1678 return ExpressionStatement;
1679}(Statement));
1680var ReturnStatement = /** @class */ (function (_super) {
1681 __extends(ReturnStatement, _super);
1682 function ReturnStatement(value, sourceSpan) {
1683 var _this = _super.call(this, null, sourceSpan) || this;
1684 _this.value = value;
1685 return _this;
1686 }
1687 ReturnStatement.prototype.isEquivalent = function (stmt) {
1688 return stmt instanceof ReturnStatement && this.value.isEquivalent(stmt.value);
1689 };
1690 ReturnStatement.prototype.visitStatement = function (visitor, context) {
1691 return visitor.visitReturnStmt(this, context);
1692 };
1693 return ReturnStatement;
1694}(Statement));
1695var AbstractClassPart = /** @class */ (function () {
1696 function AbstractClassPart(type, modifiers) {
1697 this.modifiers = modifiers;
1698 if (!modifiers) {
1699 this.modifiers = [];
1700 }
1701 this.type = type || null;
1702 }
1703 AbstractClassPart.prototype.hasModifier = function (modifier) { return this.modifiers.indexOf(modifier) !== -1; };
1704 return AbstractClassPart;
1705}());
1706var ClassField = /** @class */ (function (_super) {
1707 __extends(ClassField, _super);
1708 function ClassField(name, type, modifiers, initializer) {
1709 if (modifiers === void 0) { modifiers = null; }
1710 var _this = _super.call(this, type, modifiers) || this;
1711 _this.name = name;
1712 _this.initializer = initializer;
1713 return _this;
1714 }
1715 ClassField.prototype.isEquivalent = function (f) { return this.name === f.name; };
1716 return ClassField;
1717}(AbstractClassPart));
1718var ClassMethod = /** @class */ (function (_super) {
1719 __extends(ClassMethod, _super);
1720 function ClassMethod(name, params, body, type, modifiers) {
1721 if (modifiers === void 0) { modifiers = null; }
1722 var _this = _super.call(this, type, modifiers) || this;
1723 _this.name = name;
1724 _this.params = params;
1725 _this.body = body;
1726 return _this;
1727 }
1728 ClassMethod.prototype.isEquivalent = function (m) {
1729 return this.name === m.name && areAllEquivalent(this.body, m.body);
1730 };
1731 return ClassMethod;
1732}(AbstractClassPart));
1733var ClassGetter = /** @class */ (function (_super) {
1734 __extends(ClassGetter, _super);
1735 function ClassGetter(name, body, type, modifiers) {
1736 if (modifiers === void 0) { modifiers = null; }
1737 var _this = _super.call(this, type, modifiers) || this;
1738 _this.name = name;
1739 _this.body = body;
1740 return _this;
1741 }
1742 ClassGetter.prototype.isEquivalent = function (m) {
1743 return this.name === m.name && areAllEquivalent(this.body, m.body);
1744 };
1745 return ClassGetter;
1746}(AbstractClassPart));
1747var ClassStmt = /** @class */ (function (_super) {
1748 __extends(ClassStmt, _super);
1749 function ClassStmt(name, parent, fields, getters, constructorMethod, methods, modifiers, sourceSpan) {
1750 if (modifiers === void 0) { modifiers = null; }
1751 var _this = _super.call(this, modifiers, sourceSpan) || this;
1752 _this.name = name;
1753 _this.parent = parent;
1754 _this.fields = fields;
1755 _this.getters = getters;
1756 _this.constructorMethod = constructorMethod;
1757 _this.methods = methods;
1758 return _this;
1759 }
1760 ClassStmt.prototype.isEquivalent = function (stmt) {
1761 return stmt instanceof ClassStmt && this.name === stmt.name &&
1762 nullSafeIsEquivalent(this.parent, stmt.parent) &&
1763 areAllEquivalent(this.fields, stmt.fields) &&
1764 areAllEquivalent(this.getters, stmt.getters) &&
1765 this.constructorMethod.isEquivalent(stmt.constructorMethod) &&
1766 areAllEquivalent(this.methods, stmt.methods);
1767 };
1768 ClassStmt.prototype.visitStatement = function (visitor, context) {
1769 return visitor.visitDeclareClassStmt(this, context);
1770 };
1771 return ClassStmt;
1772}(Statement));
1773var IfStmt = /** @class */ (function (_super) {
1774 __extends(IfStmt, _super);
1775 function IfStmt(condition, trueCase, falseCase, sourceSpan) {
1776 if (falseCase === void 0) { falseCase = []; }
1777 var _this = _super.call(this, null, sourceSpan) || this;
1778 _this.condition = condition;
1779 _this.trueCase = trueCase;
1780 _this.falseCase = falseCase;
1781 return _this;
1782 }
1783 IfStmt.prototype.isEquivalent = function (stmt) {
1784 return stmt instanceof IfStmt && this.condition.isEquivalent(stmt.condition) &&
1785 areAllEquivalent(this.trueCase, stmt.trueCase) &&
1786 areAllEquivalent(this.falseCase, stmt.falseCase);
1787 };
1788 IfStmt.prototype.visitStatement = function (visitor, context) {
1789 return visitor.visitIfStmt(this, context);
1790 };
1791 return IfStmt;
1792}(Statement));
1793var CommentStmt = /** @class */ (function (_super) {
1794 __extends(CommentStmt, _super);
1795 function CommentStmt(comment, multiline, sourceSpan) {
1796 if (multiline === void 0) { multiline = false; }
1797 var _this = _super.call(this, null, sourceSpan) || this;
1798 _this.comment = comment;
1799 _this.multiline = multiline;
1800 return _this;
1801 }
1802 CommentStmt.prototype.isEquivalent = function (stmt) { return stmt instanceof CommentStmt; };
1803 CommentStmt.prototype.visitStatement = function (visitor, context) {
1804 return visitor.visitCommentStmt(this, context);
1805 };
1806 return CommentStmt;
1807}(Statement));
1808var JSDocCommentStmt = /** @class */ (function (_super) {
1809 __extends(JSDocCommentStmt, _super);
1810 function JSDocCommentStmt(tags, sourceSpan) {
1811 if (tags === void 0) { tags = []; }
1812 var _this = _super.call(this, null, sourceSpan) || this;
1813 _this.tags = tags;
1814 return _this;
1815 }
1816 JSDocCommentStmt.prototype.isEquivalent = function (stmt) {
1817 return stmt instanceof JSDocCommentStmt && this.toString() === stmt.toString();
1818 };
1819 JSDocCommentStmt.prototype.visitStatement = function (visitor, context) {
1820 return visitor.visitJSDocCommentStmt(this, context);
1821 };
1822 JSDocCommentStmt.prototype.toString = function () { return serializeTags(this.tags); };
1823 return JSDocCommentStmt;
1824}(Statement));
1825var TryCatchStmt = /** @class */ (function (_super) {
1826 __extends(TryCatchStmt, _super);
1827 function TryCatchStmt(bodyStmts, catchStmts, sourceSpan) {
1828 var _this = _super.call(this, null, sourceSpan) || this;
1829 _this.bodyStmts = bodyStmts;
1830 _this.catchStmts = catchStmts;
1831 return _this;
1832 }
1833 TryCatchStmt.prototype.isEquivalent = function (stmt) {
1834 return stmt instanceof TryCatchStmt && areAllEquivalent(this.bodyStmts, stmt.bodyStmts) &&
1835 areAllEquivalent(this.catchStmts, stmt.catchStmts);
1836 };
1837 TryCatchStmt.prototype.visitStatement = function (visitor, context) {
1838 return visitor.visitTryCatchStmt(this, context);
1839 };
1840 return TryCatchStmt;
1841}(Statement));
1842var ThrowStmt = /** @class */ (function (_super) {
1843 __extends(ThrowStmt, _super);
1844 function ThrowStmt(error, sourceSpan) {
1845 var _this = _super.call(this, null, sourceSpan) || this;
1846 _this.error = error;
1847 return _this;
1848 }
1849 ThrowStmt.prototype.isEquivalent = function (stmt) {
1850 return stmt instanceof TryCatchStmt && this.error.isEquivalent(stmt.error);
1851 };
1852 ThrowStmt.prototype.visitStatement = function (visitor, context) {
1853 return visitor.visitThrowStmt(this, context);
1854 };
1855 return ThrowStmt;
1856}(Statement));
1857var AstTransformer = /** @class */ (function () {
1858 function AstTransformer() {
1859 }
1860 AstTransformer.prototype.transformExpr = function (expr, context) { return expr; };
1861 AstTransformer.prototype.transformStmt = function (stmt, context) { return stmt; };
1862 AstTransformer.prototype.visitReadVarExpr = function (ast, context) { return this.transformExpr(ast, context); };
1863 AstTransformer.prototype.visitWrappedNodeExpr = function (ast, context) {
1864 return this.transformExpr(ast, context);
1865 };
1866 AstTransformer.prototype.visitTypeofExpr = function (expr, context) {
1867 return this.transformExpr(new TypeofExpr(expr.expr.visitExpression(this, context), expr.type, expr.sourceSpan), context);
1868 };
1869 AstTransformer.prototype.visitWriteVarExpr = function (expr, context) {
1870 return this.transformExpr(new WriteVarExpr(expr.name, expr.value.visitExpression(this, context), expr.type, expr.sourceSpan), context);
1871 };
1872 AstTransformer.prototype.visitWriteKeyExpr = function (expr, context) {
1873 return this.transformExpr(new WriteKeyExpr(expr.receiver.visitExpression(this, context), expr.index.visitExpression(this, context), expr.value.visitExpression(this, context), expr.type, expr.sourceSpan), context);
1874 };
1875 AstTransformer.prototype.visitWritePropExpr = function (expr, context) {
1876 return this.transformExpr(new WritePropExpr(expr.receiver.visitExpression(this, context), expr.name, expr.value.visitExpression(this, context), expr.type, expr.sourceSpan), context);
1877 };
1878 AstTransformer.prototype.visitInvokeMethodExpr = function (ast, context) {
1879 var method = ast.builtin || ast.name;
1880 return this.transformExpr(new InvokeMethodExpr(ast.receiver.visitExpression(this, context), method, this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context);
1881 };
1882 AstTransformer.prototype.visitInvokeFunctionExpr = function (ast, context) {
1883 return this.transformExpr(new InvokeFunctionExpr(ast.fn.visitExpression(this, context), this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context);
1884 };
1885 AstTransformer.prototype.visitInstantiateExpr = function (ast, context) {
1886 return this.transformExpr(new InstantiateExpr(ast.classExpr.visitExpression(this, context), this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context);
1887 };
1888 AstTransformer.prototype.visitLiteralExpr = function (ast, context) { return this.transformExpr(ast, context); };
1889 AstTransformer.prototype.visitExternalExpr = function (ast, context) {
1890 return this.transformExpr(ast, context);
1891 };
1892 AstTransformer.prototype.visitConditionalExpr = function (ast, context) {
1893 return this.transformExpr(new ConditionalExpr(ast.condition.visitExpression(this, context), ast.trueCase.visitExpression(this, context), ast.falseCase.visitExpression(this, context), ast.type, ast.sourceSpan), context);
1894 };
1895 AstTransformer.prototype.visitNotExpr = function (ast, context) {
1896 return this.transformExpr(new NotExpr(ast.condition.visitExpression(this, context), ast.sourceSpan), context);
1897 };
1898 AstTransformer.prototype.visitAssertNotNullExpr = function (ast, context) {
1899 return this.transformExpr(new AssertNotNull(ast.condition.visitExpression(this, context), ast.sourceSpan), context);
1900 };
1901 AstTransformer.prototype.visitCastExpr = function (ast, context) {
1902 return this.transformExpr(new CastExpr(ast.value.visitExpression(this, context), ast.type, ast.sourceSpan), context);
1903 };
1904 AstTransformer.prototype.visitFunctionExpr = function (ast, context) {
1905 return this.transformExpr(new FunctionExpr(ast.params, this.visitAllStatements(ast.statements, context), ast.type, ast.sourceSpan), context);
1906 };
1907 AstTransformer.prototype.visitBinaryOperatorExpr = function (ast, context) {
1908 return this.transformExpr(new BinaryOperatorExpr(ast.operator, ast.lhs.visitExpression(this, context), ast.rhs.visitExpression(this, context), ast.type, ast.sourceSpan), context);
1909 };
1910 AstTransformer.prototype.visitReadPropExpr = function (ast, context) {
1911 return this.transformExpr(new ReadPropExpr(ast.receiver.visitExpression(this, context), ast.name, ast.type, ast.sourceSpan), context);
1912 };
1913 AstTransformer.prototype.visitReadKeyExpr = function (ast, context) {
1914 return this.transformExpr(new ReadKeyExpr(ast.receiver.visitExpression(this, context), ast.index.visitExpression(this, context), ast.type, ast.sourceSpan), context);
1915 };
1916 AstTransformer.prototype.visitLiteralArrayExpr = function (ast, context) {
1917 return this.transformExpr(new LiteralArrayExpr(this.visitAllExpressions(ast.entries, context), ast.type, ast.sourceSpan), context);
1918 };
1919 AstTransformer.prototype.visitLiteralMapExpr = function (ast, context) {
1920 var _this = this;
1921 var entries = ast.entries.map(function (entry) { return new LiteralMapEntry(entry.key, entry.value.visitExpression(_this, context), entry.quoted); });
1922 var mapType = new MapType(ast.valueType, null);
1923 return this.transformExpr(new LiteralMapExpr(entries, mapType, ast.sourceSpan), context);
1924 };
1925 AstTransformer.prototype.visitCommaExpr = function (ast, context) {
1926 return this.transformExpr(new CommaExpr(this.visitAllExpressions(ast.parts, context), ast.sourceSpan), context);
1927 };
1928 AstTransformer.prototype.visitAllExpressions = function (exprs, context) {
1929 var _this = this;
1930 return exprs.map(function (expr) { return expr.visitExpression(_this, context); });
1931 };
1932 AstTransformer.prototype.visitDeclareVarStmt = function (stmt, context) {
1933 var value = stmt.value && stmt.value.visitExpression(this, context);
1934 return this.transformStmt(new DeclareVarStmt(stmt.name, value, stmt.type, stmt.modifiers, stmt.sourceSpan), context);
1935 };
1936 AstTransformer.prototype.visitDeclareFunctionStmt = function (stmt, context) {
1937 return this.transformStmt(new DeclareFunctionStmt(stmt.name, stmt.params, this.visitAllStatements(stmt.statements, context), stmt.type, stmt.modifiers, stmt.sourceSpan), context);
1938 };
1939 AstTransformer.prototype.visitExpressionStmt = function (stmt, context) {
1940 return this.transformStmt(new ExpressionStatement(stmt.expr.visitExpression(this, context), stmt.sourceSpan), context);
1941 };
1942 AstTransformer.prototype.visitReturnStmt = function (stmt, context) {
1943 return this.transformStmt(new ReturnStatement(stmt.value.visitExpression(this, context), stmt.sourceSpan), context);
1944 };
1945 AstTransformer.prototype.visitDeclareClassStmt = function (stmt, context) {
1946 var _this = this;
1947 var parent = stmt.parent.visitExpression(this, context);
1948 var getters = stmt.getters.map(function (getter) { return new ClassGetter(getter.name, _this.visitAllStatements(getter.body, context), getter.type, getter.modifiers); });
1949 var ctorMethod = stmt.constructorMethod &&
1950 new ClassMethod(stmt.constructorMethod.name, stmt.constructorMethod.params, this.visitAllStatements(stmt.constructorMethod.body, context), stmt.constructorMethod.type, stmt.constructorMethod.modifiers);
1951 var methods = stmt.methods.map(function (method) { return new ClassMethod(method.name, method.params, _this.visitAllStatements(method.body, context), method.type, method.modifiers); });
1952 return this.transformStmt(new ClassStmt(stmt.name, parent, stmt.fields, getters, ctorMethod, methods, stmt.modifiers, stmt.sourceSpan), context);
1953 };
1954 AstTransformer.prototype.visitIfStmt = function (stmt, context) {
1955 return this.transformStmt(new IfStmt(stmt.condition.visitExpression(this, context), this.visitAllStatements(stmt.trueCase, context), this.visitAllStatements(stmt.falseCase, context), stmt.sourceSpan), context);
1956 };
1957 AstTransformer.prototype.visitTryCatchStmt = function (stmt, context) {
1958 return this.transformStmt(new TryCatchStmt(this.visitAllStatements(stmt.bodyStmts, context), this.visitAllStatements(stmt.catchStmts, context), stmt.sourceSpan), context);
1959 };
1960 AstTransformer.prototype.visitThrowStmt = function (stmt, context) {
1961 return this.transformStmt(new ThrowStmt(stmt.error.visitExpression(this, context), stmt.sourceSpan), context);
1962 };
1963 AstTransformer.prototype.visitCommentStmt = function (stmt, context) {
1964 return this.transformStmt(stmt, context);
1965 };
1966 AstTransformer.prototype.visitJSDocCommentStmt = function (stmt, context) {
1967 return this.transformStmt(stmt, context);
1968 };
1969 AstTransformer.prototype.visitAllStatements = function (stmts, context) {
1970 var _this = this;
1971 return stmts.map(function (stmt) { return stmt.visitStatement(_this, context); });
1972 };
1973 return AstTransformer;
1974}());
1975var RecursiveAstVisitor = /** @class */ (function () {
1976 function RecursiveAstVisitor() {
1977 }
1978 RecursiveAstVisitor.prototype.visitType = function (ast, context) { return ast; };
1979 RecursiveAstVisitor.prototype.visitExpression = function (ast, context) {
1980 if (ast.type) {
1981 ast.type.visitType(this, context);
1982 }
1983 return ast;
1984 };
1985 RecursiveAstVisitor.prototype.visitBuiltinType = function (type, context) { return this.visitType(type, context); };
1986 RecursiveAstVisitor.prototype.visitExpressionType = function (type, context) {
1987 var _this = this;
1988 type.value.visitExpression(this, context);
1989 if (type.typeParams !== null) {
1990 type.typeParams.forEach(function (param) { return _this.visitType(param, context); });
1991 }
1992 return this.visitType(type, context);
1993 };
1994 RecursiveAstVisitor.prototype.visitArrayType = function (type, context) { return this.visitType(type, context); };
1995 RecursiveAstVisitor.prototype.visitMapType = function (type, context) { return this.visitType(type, context); };
1996 RecursiveAstVisitor.prototype.visitWrappedNodeExpr = function (ast, context) { return ast; };
1997 RecursiveAstVisitor.prototype.visitTypeofExpr = function (ast, context) { return this.visitExpression(ast, context); };
1998 RecursiveAstVisitor.prototype.visitReadVarExpr = function (ast, context) {
1999 return this.visitExpression(ast, context);
2000 };
2001 RecursiveAstVisitor.prototype.visitWriteVarExpr = function (ast, context) {
2002 ast.value.visitExpression(this, context);
2003 return this.visitExpression(ast, context);
2004 };
2005 RecursiveAstVisitor.prototype.visitWriteKeyExpr = function (ast, context) {
2006 ast.receiver.visitExpression(this, context);
2007 ast.index.visitExpression(this, context);
2008 ast.value.visitExpression(this, context);
2009 return this.visitExpression(ast, context);
2010 };
2011 RecursiveAstVisitor.prototype.visitWritePropExpr = function (ast, context) {
2012 ast.receiver.visitExpression(this, context);
2013 ast.value.visitExpression(this, context);
2014 return this.visitExpression(ast, context);
2015 };
2016 RecursiveAstVisitor.prototype.visitInvokeMethodExpr = function (ast, context) {
2017 ast.receiver.visitExpression(this, context);
2018 this.visitAllExpressions(ast.args, context);
2019 return this.visitExpression(ast, context);
2020 };
2021 RecursiveAstVisitor.prototype.visitInvokeFunctionExpr = function (ast, context) {
2022 ast.fn.visitExpression(this, context);
2023 this.visitAllExpressions(ast.args, context);
2024 return this.visitExpression(ast, context);
2025 };
2026 RecursiveAstVisitor.prototype.visitInstantiateExpr = function (ast, context) {
2027 ast.classExpr.visitExpression(this, context);
2028 this.visitAllExpressions(ast.args, context);
2029 return this.visitExpression(ast, context);
2030 };
2031 RecursiveAstVisitor.prototype.visitLiteralExpr = function (ast, context) {
2032 return this.visitExpression(ast, context);
2033 };
2034 RecursiveAstVisitor.prototype.visitExternalExpr = function (ast, context) {
2035 var _this = this;
2036 if (ast.typeParams) {
2037 ast.typeParams.forEach(function (type) { return type.visitType(_this, context); });
2038 }
2039 return this.visitExpression(ast, context);
2040 };
2041 RecursiveAstVisitor.prototype.visitConditionalExpr = function (ast, context) {
2042 ast.condition.visitExpression(this, context);
2043 ast.trueCase.visitExpression(this, context);
2044 ast.falseCase.visitExpression(this, context);
2045 return this.visitExpression(ast, context);
2046 };
2047 RecursiveAstVisitor.prototype.visitNotExpr = function (ast, context) {
2048 ast.condition.visitExpression(this, context);
2049 return this.visitExpression(ast, context);
2050 };
2051 RecursiveAstVisitor.prototype.visitAssertNotNullExpr = function (ast, context) {
2052 ast.condition.visitExpression(this, context);
2053 return this.visitExpression(ast, context);
2054 };
2055 RecursiveAstVisitor.prototype.visitCastExpr = function (ast, context) {
2056 ast.value.visitExpression(this, context);
2057 return this.visitExpression(ast, context);
2058 };
2059 RecursiveAstVisitor.prototype.visitFunctionExpr = function (ast, context) {
2060 this.visitAllStatements(ast.statements, context);
2061 return this.visitExpression(ast, context);
2062 };
2063 RecursiveAstVisitor.prototype.visitBinaryOperatorExpr = function (ast, context) {
2064 ast.lhs.visitExpression(this, context);
2065 ast.rhs.visitExpression(this, context);
2066 return this.visitExpression(ast, context);
2067 };
2068 RecursiveAstVisitor.prototype.visitReadPropExpr = function (ast, context) {
2069 ast.receiver.visitExpression(this, context);
2070 return this.visitExpression(ast, context);
2071 };
2072 RecursiveAstVisitor.prototype.visitReadKeyExpr = function (ast, context) {
2073 ast.receiver.visitExpression(this, context);
2074 ast.index.visitExpression(this, context);
2075 return this.visitExpression(ast, context);
2076 };
2077 RecursiveAstVisitor.prototype.visitLiteralArrayExpr = function (ast, context) {
2078 this.visitAllExpressions(ast.entries, context);
2079 return this.visitExpression(ast, context);
2080 };
2081 RecursiveAstVisitor.prototype.visitLiteralMapExpr = function (ast, context) {
2082 var _this = this;
2083 ast.entries.forEach(function (entry) { return entry.value.visitExpression(_this, context); });
2084 return this.visitExpression(ast, context);
2085 };
2086 RecursiveAstVisitor.prototype.visitCommaExpr = function (ast, context) {
2087 this.visitAllExpressions(ast.parts, context);
2088 return this.visitExpression(ast, context);
2089 };
2090 RecursiveAstVisitor.prototype.visitAllExpressions = function (exprs, context) {
2091 var _this = this;
2092 exprs.forEach(function (expr) { return expr.visitExpression(_this, context); });
2093 };
2094 RecursiveAstVisitor.prototype.visitDeclareVarStmt = function (stmt, context) {
2095 if (stmt.value) {
2096 stmt.value.visitExpression(this, context);
2097 }
2098 if (stmt.type) {
2099 stmt.type.visitType(this, context);
2100 }
2101 return stmt;
2102 };
2103 RecursiveAstVisitor.prototype.visitDeclareFunctionStmt = function (stmt, context) {
2104 this.visitAllStatements(stmt.statements, context);
2105 if (stmt.type) {
2106 stmt.type.visitType(this, context);
2107 }
2108 return stmt;
2109 };
2110 RecursiveAstVisitor.prototype.visitExpressionStmt = function (stmt, context) {
2111 stmt.expr.visitExpression(this, context);
2112 return stmt;
2113 };
2114 RecursiveAstVisitor.prototype.visitReturnStmt = function (stmt, context) {
2115 stmt.value.visitExpression(this, context);
2116 return stmt;
2117 };
2118 RecursiveAstVisitor.prototype.visitDeclareClassStmt = function (stmt, context) {
2119 var _this = this;
2120 stmt.parent.visitExpression(this, context);
2121 stmt.getters.forEach(function (getter) { return _this.visitAllStatements(getter.body, context); });
2122 if (stmt.constructorMethod) {
2123 this.visitAllStatements(stmt.constructorMethod.body, context);
2124 }
2125 stmt.methods.forEach(function (method) { return _this.visitAllStatements(method.body, context); });
2126 return stmt;
2127 };
2128 RecursiveAstVisitor.prototype.visitIfStmt = function (stmt, context) {
2129 stmt.condition.visitExpression(this, context);
2130 this.visitAllStatements(stmt.trueCase, context);
2131 this.visitAllStatements(stmt.falseCase, context);
2132 return stmt;
2133 };
2134 RecursiveAstVisitor.prototype.visitTryCatchStmt = function (stmt, context) {
2135 this.visitAllStatements(stmt.bodyStmts, context);
2136 this.visitAllStatements(stmt.catchStmts, context);
2137 return stmt;
2138 };
2139 RecursiveAstVisitor.prototype.visitThrowStmt = function (stmt, context) {
2140 stmt.error.visitExpression(this, context);
2141 return stmt;
2142 };
2143 RecursiveAstVisitor.prototype.visitCommentStmt = function (stmt, context) { return stmt; };
2144 RecursiveAstVisitor.prototype.visitJSDocCommentStmt = function (stmt, context) { return stmt; };
2145 RecursiveAstVisitor.prototype.visitAllStatements = function (stmts, context) {
2146 var _this = this;
2147 stmts.forEach(function (stmt) { return stmt.visitStatement(_this, context); });
2148 };
2149 return RecursiveAstVisitor;
2150}());
2151function findReadVarNames(stmts) {
2152 var visitor = new _ReadVarVisitor();
2153 visitor.visitAllStatements(stmts, null);
2154 return visitor.varNames;
2155}
2156var _ReadVarVisitor = /** @class */ (function (_super) {
2157 __extends(_ReadVarVisitor, _super);
2158 function _ReadVarVisitor() {
2159 var _this = _super !== null && _super.apply(this, arguments) || this;
2160 _this.varNames = new Set();
2161 return _this;
2162 }
2163 _ReadVarVisitor.prototype.visitDeclareFunctionStmt = function (stmt, context) {
2164 // Don't descend into nested functions
2165 return stmt;
2166 };
2167 _ReadVarVisitor.prototype.visitDeclareClassStmt = function (stmt, context) {
2168 // Don't descend into nested classes
2169 return stmt;
2170 };
2171 _ReadVarVisitor.prototype.visitReadVarExpr = function (ast, context) {
2172 if (ast.name) {
2173 this.varNames.add(ast.name);
2174 }
2175 return null;
2176 };
2177 return _ReadVarVisitor;
2178}(RecursiveAstVisitor));
2179function collectExternalReferences(stmts) {
2180 var visitor = new _FindExternalReferencesVisitor();
2181 visitor.visitAllStatements(stmts, null);
2182 return visitor.externalReferences;
2183}
2184var _FindExternalReferencesVisitor = /** @class */ (function (_super) {
2185 __extends(_FindExternalReferencesVisitor, _super);
2186 function _FindExternalReferencesVisitor() {
2187 var _this = _super !== null && _super.apply(this, arguments) || this;
2188 _this.externalReferences = [];
2189 return _this;
2190 }
2191 _FindExternalReferencesVisitor.prototype.visitExternalExpr = function (e, context) {
2192 this.externalReferences.push(e.value);
2193 return _super.prototype.visitExternalExpr.call(this, e, context);
2194 };
2195 return _FindExternalReferencesVisitor;
2196}(RecursiveAstVisitor));
2197function applySourceSpanToStatementIfNeeded(stmt, sourceSpan) {
2198 if (!sourceSpan) {
2199 return stmt;
2200 }
2201 var transformer = new _ApplySourceSpanTransformer(sourceSpan);
2202 return stmt.visitStatement(transformer, null);
2203}
2204function applySourceSpanToExpressionIfNeeded(expr, sourceSpan) {
2205 if (!sourceSpan) {
2206 return expr;
2207 }
2208 var transformer = new _ApplySourceSpanTransformer(sourceSpan);
2209 return expr.visitExpression(transformer, null);
2210}
2211var _ApplySourceSpanTransformer = /** @class */ (function (_super) {
2212 __extends(_ApplySourceSpanTransformer, _super);
2213 function _ApplySourceSpanTransformer(sourceSpan) {
2214 var _this = _super.call(this) || this;
2215 _this.sourceSpan = sourceSpan;
2216 return _this;
2217 }
2218 _ApplySourceSpanTransformer.prototype._clone = function (obj) {
2219 var e_1, _a;
2220 var clone = Object.create(obj.constructor.prototype);
2221 try {
2222 for (var _b = __values(Object.keys(obj)), _c = _b.next(); !_c.done; _c = _b.next()) {
2223 var prop = _c.value;
2224 clone[prop] = obj[prop];
2225 }
2226 }
2227 catch (e_1_1) { e_1 = { error: e_1_1 }; }
2228 finally {
2229 try {
2230 if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2231 }
2232 finally { if (e_1) throw e_1.error; }
2233 }
2234 return clone;
2235 };
2236 _ApplySourceSpanTransformer.prototype.transformExpr = function (expr, context) {
2237 if (!expr.sourceSpan) {
2238 expr = this._clone(expr);
2239 expr.sourceSpan = this.sourceSpan;
2240 }
2241 return expr;
2242 };
2243 _ApplySourceSpanTransformer.prototype.transformStmt = function (stmt, context) {
2244 if (!stmt.sourceSpan) {
2245 stmt = this._clone(stmt);
2246 stmt.sourceSpan = this.sourceSpan;
2247 }
2248 return stmt;
2249 };
2250 return _ApplySourceSpanTransformer;
2251}(AstTransformer));
2252function variable(name, type, sourceSpan) {
2253 return new ReadVarExpr(name, type, sourceSpan);
2254}
2255function importExpr(id, typeParams, sourceSpan) {
2256 if (typeParams === void 0) { typeParams = null; }
2257 return new ExternalExpr(id, null, typeParams, sourceSpan);
2258}
2259function importType(id, typeParams, typeModifiers) {
2260 if (typeParams === void 0) { typeParams = null; }
2261 if (typeModifiers === void 0) { typeModifiers = null; }
2262 return id != null ? expressionType(importExpr(id, typeParams, null), typeModifiers) : null;
2263}
2264function expressionType(expr, typeModifiers, typeParams) {
2265 if (typeModifiers === void 0) { typeModifiers = null; }
2266 if (typeParams === void 0) { typeParams = null; }
2267 return new ExpressionType(expr, typeModifiers, typeParams);
2268}
2269function typeofExpr(expr) {
2270 return new TypeofExpr(expr);
2271}
2272function literalArr(values, type, sourceSpan) {
2273 return new LiteralArrayExpr(values, type, sourceSpan);
2274}
2275function literalMap(values, type) {
2276 if (type === void 0) { type = null; }
2277 return new LiteralMapExpr(values.map(function (e) { return new LiteralMapEntry(e.key, e.value, e.quoted); }), type, null);
2278}
2279function not(expr, sourceSpan) {
2280 return new NotExpr(expr, sourceSpan);
2281}
2282function assertNotNull(expr, sourceSpan) {
2283 return new AssertNotNull(expr, sourceSpan);
2284}
2285function fn(params, body, type, sourceSpan, name) {
2286 return new FunctionExpr(params, body, type, sourceSpan, name);
2287}
2288function ifStmt(condition, thenClause, elseClause) {
2289 return new IfStmt(condition, thenClause, elseClause);
2290}
2291function literal(value, type, sourceSpan) {
2292 return new LiteralExpr(value, type, sourceSpan);
2293}
2294function isNull(exp) {
2295 return exp instanceof LiteralExpr && exp.value === null;
2296}
2297/*
2298 * Serializes a `Tag` into a string.
2299 * Returns a string like " @foo {bar} baz" (note the leading whitespace before `@foo`).
2300 */
2301function tagToString(tag) {
2302 var out = '';
2303 if (tag.tagName) {
2304 out += " @" + tag.tagName;
2305 }
2306 if (tag.text) {
2307 if (tag.text.match(/\/\*|\*\//)) {
2308 throw new Error('JSDoc text cannot contain "/*" and "*/"');
2309 }
2310 out += ' ' + tag.text.replace(/@/g, '\\@');
2311 }
2312 return out;
2313}
2314function serializeTags(tags) {
2315 var e_2, _a;
2316 if (tags.length === 0)
2317 return '';
2318 var out = '*\n';
2319 try {
2320 for (var tags_1 = __values(tags), tags_1_1 = tags_1.next(); !tags_1_1.done; tags_1_1 = tags_1.next()) {
2321 var tag = tags_1_1.value;
2322 out += ' *';
2323 // If the tagToString is multi-line, insert " * " prefixes on subsequent lines.
2324 out += tagToString(tag).replace(/\n/g, '\n * ');
2325 out += '\n';
2326 }
2327 }
2328 catch (e_2_1) { e_2 = { error: e_2_1 }; }
2329 finally {
2330 try {
2331 if (tags_1_1 && !tags_1_1.done && (_a = tags_1.return)) _a.call(tags_1);
2332 }
2333 finally { if (e_2) throw e_2.error; }
2334 }
2335 out += ' ';
2336 return out;
2337}
2338
2339/**
2340 * @license
2341 * Copyright Google Inc. All Rights Reserved.
2342 *
2343 * Use of this source code is governed by an MIT-style license that can be
2344 * found in the LICENSE file at https://angular.io/license
2345 */
2346var DASH_CASE_REGEXP = /-+([a-z0-9])/g;
2347function dashCaseToCamelCase(input) {
2348 return input.replace(DASH_CASE_REGEXP, function () {
2349 var m = [];
2350 for (var _i = 0; _i < arguments.length; _i++) {
2351 m[_i] = arguments[_i];
2352 }
2353 return m[1].toUpperCase();
2354 });
2355}
2356function splitAtColon(input, defaultValues) {
2357 return _splitAt(input, ':', defaultValues);
2358}
2359function splitAtPeriod(input, defaultValues) {
2360 return _splitAt(input, '.', defaultValues);
2361}
2362function _splitAt(input, character, defaultValues) {
2363 var characterIndex = input.indexOf(character);
2364 if (characterIndex == -1)
2365 return defaultValues;
2366 return [input.slice(0, characterIndex).trim(), input.slice(characterIndex + 1).trim()];
2367}
2368function visitValue(value, visitor, context) {
2369 if (Array.isArray(value)) {
2370 return visitor.visitArray(value, context);
2371 }
2372 if (isStrictStringMap(value)) {
2373 return visitor.visitStringMap(value, context);
2374 }
2375 if (value == null || typeof value == 'string' || typeof value == 'number' ||
2376 typeof value == 'boolean') {
2377 return visitor.visitPrimitive(value, context);
2378 }
2379 return visitor.visitOther(value, context);
2380}
2381function isDefined(val) {
2382 return val !== null && val !== undefined;
2383}
2384function noUndefined(val) {
2385 return val === undefined ? null : val;
2386}
2387var ValueTransformer = /** @class */ (function () {
2388 function ValueTransformer() {
2389 }
2390 ValueTransformer.prototype.visitArray = function (arr, context) {
2391 var _this = this;
2392 return arr.map(function (value) { return visitValue(value, _this, context); });
2393 };
2394 ValueTransformer.prototype.visitStringMap = function (map, context) {
2395 var _this = this;
2396 var result = {};
2397 Object.keys(map).forEach(function (key) { result[key] = visitValue(map[key], _this, context); });
2398 return result;
2399 };
2400 ValueTransformer.prototype.visitPrimitive = function (value, context) { return value; };
2401 ValueTransformer.prototype.visitOther = function (value, context) { return value; };
2402 return ValueTransformer;
2403}());
2404var SyncAsync = {
2405 assertSync: function (value) {
2406 if (isPromise(value)) {
2407 throw new Error("Illegal state: value cannot be a promise");
2408 }
2409 return value;
2410 },
2411 then: function (value, cb) { return isPromise(value) ? value.then(cb) : cb(value); },
2412 all: function (syncAsyncValues) {
2413 return syncAsyncValues.some(isPromise) ? Promise.all(syncAsyncValues) : syncAsyncValues;
2414 }
2415};
2416function error(msg) {
2417 throw new Error("Internal Error: " + msg);
2418}
2419function syntaxError(msg, parseErrors) {
2420 var error = Error(msg);
2421 error[ERROR_SYNTAX_ERROR] = true;
2422 if (parseErrors)
2423 error[ERROR_PARSE_ERRORS] = parseErrors;
2424 return error;
2425}
2426var ERROR_SYNTAX_ERROR = 'ngSyntaxError';
2427var ERROR_PARSE_ERRORS = 'ngParseErrors';
2428function isSyntaxError(error) {
2429 return error[ERROR_SYNTAX_ERROR];
2430}
2431function getParseErrors(error) {
2432 return error[ERROR_PARSE_ERRORS] || [];
2433}
2434// Escape characters that have a special meaning in Regular Expressions
2435function escapeRegExp(s) {
2436 return s.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
2437}
2438var STRING_MAP_PROTO = Object.getPrototypeOf({});
2439function isStrictStringMap(obj) {
2440 return typeof obj === 'object' && obj !== null && Object.getPrototypeOf(obj) === STRING_MAP_PROTO;
2441}
2442function utf8Encode(str) {
2443 var encoded = '';
2444 for (var index = 0; index < str.length; index++) {
2445 var codePoint = str.charCodeAt(index);
2446 // decode surrogate
2447 // see https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
2448 if (codePoint >= 0xd800 && codePoint <= 0xdbff && str.length > (index + 1)) {
2449 var low = str.charCodeAt(index + 1);
2450 if (low >= 0xdc00 && low <= 0xdfff) {
2451 index++;
2452 codePoint = ((codePoint - 0xd800) << 10) + low - 0xdc00 + 0x10000;
2453 }
2454 }
2455 if (codePoint <= 0x7f) {
2456 encoded += String.fromCharCode(codePoint);
2457 }
2458 else if (codePoint <= 0x7ff) {
2459 encoded += String.fromCharCode(((codePoint >> 6) & 0x1F) | 0xc0, (codePoint & 0x3f) | 0x80);
2460 }
2461 else if (codePoint <= 0xffff) {
2462 encoded += String.fromCharCode((codePoint >> 12) | 0xe0, ((codePoint >> 6) & 0x3f) | 0x80, (codePoint & 0x3f) | 0x80);
2463 }
2464 else if (codePoint <= 0x1fffff) {
2465 encoded += String.fromCharCode(((codePoint >> 18) & 0x07) | 0xf0, ((codePoint >> 12) & 0x3f) | 0x80, ((codePoint >> 6) & 0x3f) | 0x80, (codePoint & 0x3f) | 0x80);
2466 }
2467 }
2468 return encoded;
2469}
2470function stringify(token) {
2471 if (typeof token === 'string') {
2472 return token;
2473 }
2474 if (token instanceof Array) {
2475 return '[' + token.map(stringify).join(', ') + ']';
2476 }
2477 if (token == null) {
2478 return '' + token;
2479 }
2480 if (token.overriddenName) {
2481 return "" + token.overriddenName;
2482 }
2483 if (token.name) {
2484 return "" + token.name;
2485 }
2486 if (!token.toString) {
2487 return 'object';
2488 }
2489 // WARNING: do not try to `JSON.stringify(token)` here
2490 // see https://github.com/angular/angular/issues/23440
2491 var res = token.toString();
2492 if (res == null) {
2493 return '' + res;
2494 }
2495 var newLineIndex = res.indexOf('\n');
2496 return newLineIndex === -1 ? res : res.substring(0, newLineIndex);
2497}
2498/**
2499 * Lazily retrieves the reference value from a forwardRef.
2500 */
2501function resolveForwardRef(type) {
2502 if (typeof type === 'function' && type.hasOwnProperty('__forward_ref__')) {
2503 return type();
2504 }
2505 else {
2506 return type;
2507 }
2508}
2509/**
2510 * Determine if the argument is shaped like a Promise
2511 */
2512function isPromise(obj) {
2513 // allow any Promise/A+ compliant thenable.
2514 // It's up to the caller to ensure that obj.then conforms to the spec
2515 return !!obj && typeof obj.then === 'function';
2516}
2517var Version = /** @class */ (function () {
2518 function Version(full) {
2519 this.full = full;
2520 var splits = full.split('.');
2521 this.major = splits[0];
2522 this.minor = splits[1];
2523 this.patch = splits.slice(2).join('.');
2524 }
2525 return Version;
2526}());
2527var __window = typeof window !== 'undefined' && window;
2528var __self = typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' &&
2529 self instanceof WorkerGlobalScope && self;
2530var __global = typeof global !== 'undefined' && global;
2531// Check __global first, because in Node tests both __global and __window may be defined and _global
2532// should be __global in that case.
2533var _global = __global || __window || __self;
2534
2535/**
2536 * @license
2537 * Copyright Google Inc. All Rights Reserved.
2538 *
2539 * Use of this source code is governed by an MIT-style license that can be
2540 * found in the LICENSE file at https://angular.io/license
2541 */
2542var CONSTANT_PREFIX = '_c';
2543/**
2544 * Context to use when producing a key.
2545 *
2546 * This ensures we see the constant not the reference variable when producing
2547 * a key.
2548 */
2549var KEY_CONTEXT = {};
2550/**
2551 * A node that is a place-holder that allows the node to be replaced when the actual
2552 * node is known.
2553 *
2554 * This allows the constant pool to change an expression from a direct reference to
2555 * a constant to a shared constant. It returns a fix-up node that is later allowed to
2556 * change the referenced expression.
2557 */
2558var FixupExpression = /** @class */ (function (_super) {
2559 __extends(FixupExpression, _super);
2560 function FixupExpression(resolved) {
2561 var _this = _super.call(this, resolved.type) || this;
2562 _this.resolved = resolved;
2563 _this.original = resolved;
2564 return _this;
2565 }
2566 FixupExpression.prototype.visitExpression = function (visitor, context) {
2567 if (context === KEY_CONTEXT) {
2568 // When producing a key we want to traverse the constant not the
2569 // variable used to refer to it.
2570 return this.original.visitExpression(visitor, context);
2571 }
2572 else {
2573 return this.resolved.visitExpression(visitor, context);
2574 }
2575 };
2576 FixupExpression.prototype.isEquivalent = function (e) {
2577 return e instanceof FixupExpression && this.resolved.isEquivalent(e.resolved);
2578 };
2579 FixupExpression.prototype.isConstant = function () { return true; };
2580 FixupExpression.prototype.fixup = function (expression) {
2581 this.resolved = expression;
2582 this.shared = true;
2583 };
2584 return FixupExpression;
2585}(Expression));
2586/**
2587 * A constant pool allows a code emitter to share constant in an output context.
2588 *
2589 * The constant pool also supports sharing access to ivy definitions references.
2590 */
2591var ConstantPool = /** @class */ (function () {
2592 function ConstantPool() {
2593 this.statements = [];
2594 this.literals = new Map();
2595 this.literalFactories = new Map();
2596 this.injectorDefinitions = new Map();
2597 this.directiveDefinitions = new Map();
2598 this.componentDefinitions = new Map();
2599 this.pipeDefinitions = new Map();
2600 this.nextNameIndex = 0;
2601 }
2602 ConstantPool.prototype.getConstLiteral = function (literal, forceShared) {
2603 if (literal instanceof LiteralExpr || literal instanceof FixupExpression) {
2604 // Do no put simple literals into the constant pool or try to produce a constant for a
2605 // reference to a constant.
2606 return literal;
2607 }
2608 var key = this.keyOf(literal);
2609 var fixup = this.literals.get(key);
2610 var newValue = false;
2611 if (!fixup) {
2612 fixup = new FixupExpression(literal);
2613 this.literals.set(key, fixup);
2614 newValue = true;
2615 }
2616 if ((!newValue && !fixup.shared) || (newValue && forceShared)) {
2617 // Replace the expression with a variable
2618 var name_1 = this.freshName();
2619 this.statements.push(variable(name_1).set(literal).toDeclStmt(INFERRED_TYPE, [StmtModifier.Final]));
2620 fixup.fixup(variable(name_1));
2621 }
2622 return fixup;
2623 };
2624 ConstantPool.prototype.getDefinition = function (type, kind, ctx, forceShared) {
2625 if (forceShared === void 0) { forceShared = false; }
2626 var definitions = this.definitionsOf(kind);
2627 var fixup = definitions.get(type);
2628 var newValue = false;
2629 if (!fixup) {
2630 var property = this.propertyNameOf(kind);
2631 fixup = new FixupExpression(ctx.importExpr(type).prop(property));
2632 definitions.set(type, fixup);
2633 newValue = true;
2634 }
2635 if ((!newValue && !fixup.shared) || (newValue && forceShared)) {
2636 var name_2 = this.freshName();
2637 this.statements.push(variable(name_2).set(fixup.resolved).toDeclStmt(INFERRED_TYPE, [StmtModifier.Final]));
2638 fixup.fixup(variable(name_2));
2639 }
2640 return fixup;
2641 };
2642 ConstantPool.prototype.getLiteralFactory = function (literal$1) {
2643 // Create a pure function that builds an array of a mix of constant and variable expressions
2644 if (literal$1 instanceof LiteralArrayExpr) {
2645 var argumentsForKey = literal$1.entries.map(function (e) { return e.isConstant() ? e : literal(null); });
2646 var key = this.keyOf(literalArr(argumentsForKey));
2647 return this._getLiteralFactory(key, literal$1.entries, function (entries) { return literalArr(entries); });
2648 }
2649 else {
2650 var expressionForKey = literalMap(literal$1.entries.map(function (e) { return ({
2651 key: e.key,
2652 value: e.value.isConstant() ? e.value : literal(null),
2653 quoted: e.quoted
2654 }); }));
2655 var key = this.keyOf(expressionForKey);
2656 return this._getLiteralFactory(key, literal$1.entries.map(function (e) { return e.value; }), function (entries) { return literalMap(entries.map(function (value, index) { return ({
2657 key: literal$1.entries[index].key,
2658 value: value,
2659 quoted: literal$1.entries[index].quoted
2660 }); })); });
2661 }
2662 };
2663 ConstantPool.prototype._getLiteralFactory = function (key, values, resultMap) {
2664 var _this = this;
2665 var literalFactory = this.literalFactories.get(key);
2666 var literalFactoryArguments = values.filter((function (e) { return !e.isConstant(); }));
2667 if (!literalFactory) {
2668 var resultExpressions = values.map(function (e, index) { return e.isConstant() ? _this.getConstLiteral(e, true) : variable("a" + index); });
2669 var parameters = resultExpressions.filter(isVariable).map(function (e) { return new FnParam(e.name, DYNAMIC_TYPE); });
2670 var pureFunctionDeclaration = fn(parameters, [new ReturnStatement(resultMap(resultExpressions))], INFERRED_TYPE);
2671 var name_3 = this.freshName();
2672 this.statements.push(variable(name_3).set(pureFunctionDeclaration).toDeclStmt(INFERRED_TYPE, [
2673 StmtModifier.Final
2674 ]));
2675 literalFactory = variable(name_3);
2676 this.literalFactories.set(key, literalFactory);
2677 }
2678 return { literalFactory: literalFactory, literalFactoryArguments: literalFactoryArguments };
2679 };
2680 /**
2681 * Produce a unique name.
2682 *
2683 * The name might be unique among different prefixes if any of the prefixes end in
2684 * a digit so the prefix should be a constant string (not based on user input) and
2685 * must not end in a digit.
2686 */
2687 ConstantPool.prototype.uniqueName = function (prefix) { return "" + prefix + this.nextNameIndex++; };
2688 ConstantPool.prototype.definitionsOf = function (kind) {
2689 switch (kind) {
2690 case 2 /* Component */:
2691 return this.componentDefinitions;
2692 case 1 /* Directive */:
2693 return this.directiveDefinitions;
2694 case 0 /* Injector */:
2695 return this.injectorDefinitions;
2696 case 3 /* Pipe */:
2697 return this.pipeDefinitions;
2698 }
2699 error("Unknown definition kind " + kind);
2700 return this.componentDefinitions;
2701 };
2702 ConstantPool.prototype.propertyNameOf = function (kind) {
2703 switch (kind) {
2704 case 2 /* Component */:
2705 return 'ngComponentDef';
2706 case 1 /* Directive */:
2707 return 'ngDirectiveDef';
2708 case 0 /* Injector */:
2709 return 'ngInjectorDef';
2710 case 3 /* Pipe */:
2711 return 'ngPipeDef';
2712 }
2713 error("Unknown definition kind " + kind);
2714 return '<unknown>';
2715 };
2716 ConstantPool.prototype.freshName = function () { return this.uniqueName(CONSTANT_PREFIX); };
2717 ConstantPool.prototype.keyOf = function (expression) {
2718 return expression.visitExpression(new KeyVisitor(), KEY_CONTEXT);
2719 };
2720 return ConstantPool;
2721}());
2722/**
2723 * Visitor used to determine if 2 expressions are equivalent and can be shared in the
2724 * `ConstantPool`.
2725 *
2726 * When the id (string) generated by the visitor is equal, expressions are considered equivalent.
2727 */
2728var KeyVisitor = /** @class */ (function () {
2729 function KeyVisitor() {
2730 this.visitWrappedNodeExpr = invalid;
2731 this.visitWriteVarExpr = invalid;
2732 this.visitWriteKeyExpr = invalid;
2733 this.visitWritePropExpr = invalid;
2734 this.visitInvokeMethodExpr = invalid;
2735 this.visitInvokeFunctionExpr = invalid;
2736 this.visitInstantiateExpr = invalid;
2737 this.visitConditionalExpr = invalid;
2738 this.visitNotExpr = invalid;
2739 this.visitAssertNotNullExpr = invalid;
2740 this.visitCastExpr = invalid;
2741 this.visitFunctionExpr = invalid;
2742 this.visitBinaryOperatorExpr = invalid;
2743 this.visitReadPropExpr = invalid;
2744 this.visitReadKeyExpr = invalid;
2745 this.visitCommaExpr = invalid;
2746 }
2747 KeyVisitor.prototype.visitLiteralExpr = function (ast) {
2748 return "" + (typeof ast.value === 'string' ? '"' + ast.value + '"' : ast.value);
2749 };
2750 KeyVisitor.prototype.visitLiteralArrayExpr = function (ast, context) {
2751 var _this = this;
2752 return "[" + ast.entries.map(function (entry) { return entry.visitExpression(_this, context); }).join(',') + "]";
2753 };
2754 KeyVisitor.prototype.visitLiteralMapExpr = function (ast, context) {
2755 var _this = this;
2756 var mapKey = function (entry) {
2757 var quote = entry.quoted ? '"' : '';
2758 return "" + quote + entry.key + quote;
2759 };
2760 var mapEntry = function (entry) {
2761 return mapKey(entry) + ":" + entry.value.visitExpression(_this, context);
2762 };
2763 return "{" + ast.entries.map(mapEntry).join(',');
2764 };
2765 KeyVisitor.prototype.visitExternalExpr = function (ast) {
2766 return ast.value.moduleName ? "EX:" + ast.value.moduleName + ":" + ast.value.name :
2767 "EX:" + ast.value.runtime.name;
2768 };
2769 KeyVisitor.prototype.visitReadVarExpr = function (node) { return "VAR:" + node.name; };
2770 KeyVisitor.prototype.visitTypeofExpr = function (node, context) {
2771 return "TYPEOF:" + node.expr.visitExpression(this, context);
2772 };
2773 return KeyVisitor;
2774}());
2775function invalid(arg) {
2776 throw new Error("Invalid state: Visitor " + this.constructor.name + " doesn't handle " + arg.constructor.name);
2777}
2778function isVariable(e) {
2779 return e instanceof ReadVarExpr;
2780}
2781
2782/**
2783 * @license
2784 * Copyright Google Inc. All Rights Reserved.
2785 *
2786 * Use of this source code is governed by an MIT-style license that can be
2787 * found in the LICENSE file at https://angular.io/license
2788 */
2789var CORE = '@angular/core';
2790var Identifiers = /** @class */ (function () {
2791 function Identifiers() {
2792 }
2793 Identifiers.ANALYZE_FOR_ENTRY_COMPONENTS = {
2794 name: 'ANALYZE_FOR_ENTRY_COMPONENTS',
2795 moduleName: CORE,
2796 };
2797 Identifiers.ElementRef = { name: 'ElementRef', moduleName: CORE };
2798 Identifiers.NgModuleRef = { name: 'NgModuleRef', moduleName: CORE };
2799 Identifiers.ViewContainerRef = { name: 'ViewContainerRef', moduleName: CORE };
2800 Identifiers.ChangeDetectorRef = {
2801 name: 'ChangeDetectorRef',
2802 moduleName: CORE,
2803 };
2804 Identifiers.QueryList = { name: 'QueryList', moduleName: CORE };
2805 Identifiers.TemplateRef = { name: 'TemplateRef', moduleName: CORE };
2806 Identifiers.Renderer2 = { name: 'Renderer2', moduleName: CORE };
2807 Identifiers.CodegenComponentFactoryResolver = {
2808 name: 'ɵCodegenComponentFactoryResolver',
2809 moduleName: CORE,
2810 };
2811 Identifiers.ComponentFactoryResolver = {
2812 name: 'ComponentFactoryResolver',
2813 moduleName: CORE,
2814 };
2815 Identifiers.ComponentFactory = { name: 'ComponentFactory', moduleName: CORE };
2816 Identifiers.ComponentRef = { name: 'ComponentRef', moduleName: CORE };
2817 Identifiers.NgModuleFactory = { name: 'NgModuleFactory', moduleName: CORE };
2818 Identifiers.createModuleFactory = {
2819 name: 'ɵcmf',
2820 moduleName: CORE,
2821 };
2822 Identifiers.moduleDef = {
2823 name: 'ɵmod',
2824 moduleName: CORE,
2825 };
2826 Identifiers.moduleProviderDef = {
2827 name: 'ɵmpd',
2828 moduleName: CORE,
2829 };
2830 Identifiers.RegisterModuleFactoryFn = {
2831 name: 'ɵregisterModuleFactory',
2832 moduleName: CORE,
2833 };
2834 Identifiers.inject = { name: 'ɵɵinject', moduleName: CORE };
2835 Identifiers.INJECTOR = { name: 'INJECTOR', moduleName: CORE };
2836 Identifiers.Injector = { name: 'Injector', moduleName: CORE };
2837 Identifiers.ɵɵdefineInjectable = { name: 'ɵɵdefineInjectable', moduleName: CORE };
2838 Identifiers.InjectableDef = { name: 'ɵɵInjectableDef', moduleName: CORE };
2839 Identifiers.ViewEncapsulation = {
2840 name: 'ViewEncapsulation',
2841 moduleName: CORE,
2842 };
2843 Identifiers.ChangeDetectionStrategy = {
2844 name: 'ChangeDetectionStrategy',
2845 moduleName: CORE,
2846 };
2847 Identifiers.SecurityContext = {
2848 name: 'SecurityContext',
2849 moduleName: CORE,
2850 };
2851 Identifiers.LOCALE_ID = { name: 'LOCALE_ID', moduleName: CORE };
2852 Identifiers.TRANSLATIONS_FORMAT = {
2853 name: 'TRANSLATIONS_FORMAT',
2854 moduleName: CORE,
2855 };
2856 Identifiers.inlineInterpolate = {
2857 name: 'ɵinlineInterpolate',
2858 moduleName: CORE,
2859 };
2860 Identifiers.interpolate = { name: 'ɵinterpolate', moduleName: CORE };
2861 Identifiers.EMPTY_ARRAY = { name: 'ɵEMPTY_ARRAY', moduleName: CORE };
2862 Identifiers.EMPTY_MAP = { name: 'ɵEMPTY_MAP', moduleName: CORE };
2863 Identifiers.Renderer = { name: 'Renderer', moduleName: CORE };
2864 Identifiers.viewDef = { name: 'ɵvid', moduleName: CORE };
2865 Identifiers.elementDef = { name: 'ɵeld', moduleName: CORE };
2866 Identifiers.anchorDef = { name: 'ɵand', moduleName: CORE };
2867 Identifiers.textDef = { name: 'ɵted', moduleName: CORE };
2868 Identifiers.directiveDef = { name: 'ɵdid', moduleName: CORE };
2869 Identifiers.providerDef = { name: 'ɵprd', moduleName: CORE };
2870 Identifiers.queryDef = { name: 'ɵqud', moduleName: CORE };
2871 Identifiers.pureArrayDef = { name: 'ɵpad', moduleName: CORE };
2872 Identifiers.pureObjectDef = { name: 'ɵpod', moduleName: CORE };
2873 Identifiers.purePipeDef = { name: 'ɵppd', moduleName: CORE };
2874 Identifiers.pipeDef = { name: 'ɵpid', moduleName: CORE };
2875 Identifiers.nodeValue = { name: 'ɵnov', moduleName: CORE };
2876 Identifiers.ngContentDef = { name: 'ɵncd', moduleName: CORE };
2877 Identifiers.unwrapValue = { name: 'ɵunv', moduleName: CORE };
2878 Identifiers.createRendererType2 = { name: 'ɵcrt', moduleName: CORE };
2879 // type only
2880 Identifiers.RendererType2 = {
2881 name: 'RendererType2',
2882 moduleName: CORE,
2883 };
2884 // type only
2885 Identifiers.ViewDefinition = {
2886 name: 'ɵViewDefinition',
2887 moduleName: CORE,
2888 };
2889 Identifiers.createComponentFactory = { name: 'ɵccf', moduleName: CORE };
2890 Identifiers.setClassMetadata = { name: 'ɵsetClassMetadata', moduleName: CORE };
2891 return Identifiers;
2892}());
2893function createTokenForReference(reference) {
2894 return { identifier: { reference: reference } };
2895}
2896function createTokenForExternalReference(reflector, reference) {
2897 return createTokenForReference(reflector.resolveExternalReference(reference));
2898}
2899
2900/**
2901 * @license
2902 * Copyright Google Inc. All Rights Reserved.
2903 *
2904 * Use of this source code is governed by an MIT-style license that can be
2905 * found in the LICENSE file at https://angular.io/license
2906 */
2907/**
2908 * A token representing the a reference to a static type.
2909 *
2910 * This token is unique for a filePath and name and can be used as a hash table key.
2911 */
2912var StaticSymbol = /** @class */ (function () {
2913 function StaticSymbol(filePath, name, members) {
2914 this.filePath = filePath;
2915 this.name = name;
2916 this.members = members;
2917 }
2918 StaticSymbol.prototype.assertNoMembers = function () {
2919 if (this.members.length) {
2920 throw new Error("Illegal state: symbol without members expected, but got " + JSON.stringify(this) + ".");
2921 }
2922 };
2923 return StaticSymbol;
2924}());
2925/**
2926 * A cache of static symbol used by the StaticReflector to return the same symbol for the
2927 * same symbol values.
2928 */
2929var StaticSymbolCache = /** @class */ (function () {
2930 function StaticSymbolCache() {
2931 this.cache = new Map();
2932 }
2933 StaticSymbolCache.prototype.get = function (declarationFile, name, members) {
2934 members = members || [];
2935 var memberSuffix = members.length ? "." + members.join('.') : '';
2936 var key = "\"" + declarationFile + "\"." + name + memberSuffix;
2937 var result = this.cache.get(key);
2938 if (!result) {
2939 result = new StaticSymbol(declarationFile, name, members);
2940 this.cache.set(key, result);
2941 }
2942 return result;
2943 };
2944 return StaticSymbolCache;
2945}());
2946
2947/**
2948 * @license
2949 * Copyright Google Inc. All Rights Reserved.
2950 *
2951 * Use of this source code is governed by an MIT-style license that can be
2952 * found in the LICENSE file at https://angular.io/license
2953 */
2954// group 0: "[prop] or (event) or @trigger"
2955// group 1: "prop" from "[prop]"
2956// group 2: "event" from "(event)"
2957// group 3: "@trigger" from "@trigger"
2958var HOST_REG_EXP = /^(?:(?:\[([^\]]+)\])|(?:\(([^\)]+)\)))|(\@[-\w]+)$/;
2959function sanitizeIdentifier(name) {
2960 return name.replace(/\W/g, '_');
2961}
2962var _anonymousTypeIndex = 0;
2963function identifierName(compileIdentifier) {
2964 if (!compileIdentifier || !compileIdentifier.reference) {
2965 return null;
2966 }
2967 var ref = compileIdentifier.reference;
2968 if (ref instanceof StaticSymbol) {
2969 return ref.name;
2970 }
2971 if (ref['__anonymousType']) {
2972 return ref['__anonymousType'];
2973 }
2974 var identifier = stringify(ref);
2975 if (identifier.indexOf('(') >= 0) {
2976 // case: anonymous functions!
2977 identifier = "anonymous_" + _anonymousTypeIndex++;
2978 ref['__anonymousType'] = identifier;
2979 }
2980 else {
2981 identifier = sanitizeIdentifier(identifier);
2982 }
2983 return identifier;
2984}
2985function identifierModuleUrl(compileIdentifier) {
2986 var ref = compileIdentifier.reference;
2987 if (ref instanceof StaticSymbol) {
2988 return ref.filePath;
2989 }
2990 // Runtime type
2991 return "./" + stringify(ref);
2992}
2993function viewClassName(compType, embeddedTemplateIndex) {
2994 return "View_" + identifierName({ reference: compType }) + "_" + embeddedTemplateIndex;
2995}
2996function rendererTypeName(compType) {
2997 return "RenderType_" + identifierName({ reference: compType });
2998}
2999function hostViewClassName(compType) {
3000 return "HostView_" + identifierName({ reference: compType });
3001}
3002function componentFactoryName(compType) {
3003 return identifierName({ reference: compType }) + "NgFactory";
3004}
3005var CompileSummaryKind;
3006(function (CompileSummaryKind) {
3007 CompileSummaryKind[CompileSummaryKind["Pipe"] = 0] = "Pipe";
3008 CompileSummaryKind[CompileSummaryKind["Directive"] = 1] = "Directive";
3009 CompileSummaryKind[CompileSummaryKind["NgModule"] = 2] = "NgModule";
3010 CompileSummaryKind[CompileSummaryKind["Injectable"] = 3] = "Injectable";
3011})(CompileSummaryKind || (CompileSummaryKind = {}));
3012function tokenName(token) {
3013 return token.value != null ? sanitizeIdentifier(token.value) : identifierName(token.identifier);
3014}
3015function tokenReference(token) {
3016 if (token.identifier != null) {
3017 return token.identifier.reference;
3018 }
3019 else {
3020 return token.value;
3021 }
3022}
3023/**
3024 * Metadata about a stylesheet
3025 */
3026var CompileStylesheetMetadata = /** @class */ (function () {
3027 function CompileStylesheetMetadata(_a) {
3028 var _b = _a === void 0 ? {} : _a, moduleUrl = _b.moduleUrl, styles = _b.styles, styleUrls = _b.styleUrls;
3029 this.moduleUrl = moduleUrl || null;
3030 this.styles = _normalizeArray(styles);
3031 this.styleUrls = _normalizeArray(styleUrls);
3032 }
3033 return CompileStylesheetMetadata;
3034}());
3035/**
3036 * Metadata regarding compilation of a template.
3037 */
3038var CompileTemplateMetadata = /** @class */ (function () {
3039 function CompileTemplateMetadata(_a) {
3040 var encapsulation = _a.encapsulation, template = _a.template, templateUrl = _a.templateUrl, htmlAst = _a.htmlAst, styles = _a.styles, styleUrls = _a.styleUrls, externalStylesheets = _a.externalStylesheets, animations = _a.animations, ngContentSelectors = _a.ngContentSelectors, interpolation = _a.interpolation, isInline = _a.isInline, preserveWhitespaces = _a.preserveWhitespaces;
3041 this.encapsulation = encapsulation;
3042 this.template = template;
3043 this.templateUrl = templateUrl;
3044 this.htmlAst = htmlAst;
3045 this.styles = _normalizeArray(styles);
3046 this.styleUrls = _normalizeArray(styleUrls);
3047 this.externalStylesheets = _normalizeArray(externalStylesheets);
3048 this.animations = animations ? flatten(animations) : [];
3049 this.ngContentSelectors = ngContentSelectors || [];
3050 if (interpolation && interpolation.length != 2) {
3051 throw new Error("'interpolation' should have a start and an end symbol.");
3052 }
3053 this.interpolation = interpolation;
3054 this.isInline = isInline;
3055 this.preserveWhitespaces = preserveWhitespaces;
3056 }
3057 CompileTemplateMetadata.prototype.toSummary = function () {
3058 return {
3059 ngContentSelectors: this.ngContentSelectors,
3060 encapsulation: this.encapsulation,
3061 styles: this.styles,
3062 animations: this.animations
3063 };
3064 };
3065 return CompileTemplateMetadata;
3066}());
3067/**
3068 * Metadata regarding compilation of a directive.
3069 */
3070var CompileDirectiveMetadata = /** @class */ (function () {
3071 function CompileDirectiveMetadata(_a) {
3072 var isHost = _a.isHost, type = _a.type, isComponent = _a.isComponent, selector = _a.selector, exportAs = _a.exportAs, changeDetection = _a.changeDetection, inputs = _a.inputs, outputs = _a.outputs, hostListeners = _a.hostListeners, hostProperties = _a.hostProperties, hostAttributes = _a.hostAttributes, providers = _a.providers, viewProviders = _a.viewProviders, queries = _a.queries, guards = _a.guards, viewQueries = _a.viewQueries, entryComponents = _a.entryComponents, template = _a.template, componentViewType = _a.componentViewType, rendererType = _a.rendererType, componentFactory = _a.componentFactory;
3073 this.isHost = !!isHost;
3074 this.type = type;
3075 this.isComponent = isComponent;
3076 this.selector = selector;
3077 this.exportAs = exportAs;
3078 this.changeDetection = changeDetection;
3079 this.inputs = inputs;
3080 this.outputs = outputs;
3081 this.hostListeners = hostListeners;
3082 this.hostProperties = hostProperties;
3083 this.hostAttributes = hostAttributes;
3084 this.providers = _normalizeArray(providers);
3085 this.viewProviders = _normalizeArray(viewProviders);
3086 this.queries = _normalizeArray(queries);
3087 this.guards = guards;
3088 this.viewQueries = _normalizeArray(viewQueries);
3089 this.entryComponents = _normalizeArray(entryComponents);
3090 this.template = template;
3091 this.componentViewType = componentViewType;
3092 this.rendererType = rendererType;
3093 this.componentFactory = componentFactory;
3094 }
3095 CompileDirectiveMetadata.create = function (_a) {
3096 var isHost = _a.isHost, type = _a.type, isComponent = _a.isComponent, selector = _a.selector, exportAs = _a.exportAs, changeDetection = _a.changeDetection, inputs = _a.inputs, outputs = _a.outputs, host = _a.host, providers = _a.providers, viewProviders = _a.viewProviders, queries = _a.queries, guards = _a.guards, viewQueries = _a.viewQueries, entryComponents = _a.entryComponents, template = _a.template, componentViewType = _a.componentViewType, rendererType = _a.rendererType, componentFactory = _a.componentFactory;
3097 var hostListeners = {};
3098 var hostProperties = {};
3099 var hostAttributes = {};
3100 if (host != null) {
3101 Object.keys(host).forEach(function (key) {
3102 var value = host[key];
3103 var matches = key.match(HOST_REG_EXP);
3104 if (matches === null) {
3105 hostAttributes[key] = value;
3106 }
3107 else if (matches[1] != null) {
3108 hostProperties[matches[1]] = value;
3109 }
3110 else if (matches[2] != null) {
3111 hostListeners[matches[2]] = value;
3112 }
3113 });
3114 }
3115 var inputsMap = {};
3116 if (inputs != null) {
3117 inputs.forEach(function (bindConfig) {
3118 // canonical syntax: `dirProp: elProp`
3119 // if there is no `:`, use dirProp = elProp
3120 var parts = splitAtColon(bindConfig, [bindConfig, bindConfig]);
3121 inputsMap[parts[0]] = parts[1];
3122 });
3123 }
3124 var outputsMap = {};
3125 if (outputs != null) {
3126 outputs.forEach(function (bindConfig) {
3127 // canonical syntax: `dirProp: elProp`
3128 // if there is no `:`, use dirProp = elProp
3129 var parts = splitAtColon(bindConfig, [bindConfig, bindConfig]);
3130 outputsMap[parts[0]] = parts[1];
3131 });
3132 }
3133 return new CompileDirectiveMetadata({
3134 isHost: isHost,
3135 type: type,
3136 isComponent: !!isComponent, selector: selector, exportAs: exportAs, changeDetection: changeDetection,
3137 inputs: inputsMap,
3138 outputs: outputsMap,
3139 hostListeners: hostListeners,
3140 hostProperties: hostProperties,
3141 hostAttributes: hostAttributes,
3142 providers: providers,
3143 viewProviders: viewProviders,
3144 queries: queries,
3145 guards: guards,
3146 viewQueries: viewQueries,
3147 entryComponents: entryComponents,
3148 template: template,
3149 componentViewType: componentViewType,
3150 rendererType: rendererType,
3151 componentFactory: componentFactory,
3152 });
3153 };
3154 CompileDirectiveMetadata.prototype.toSummary = function () {
3155 return {
3156 summaryKind: CompileSummaryKind.Directive,
3157 type: this.type,
3158 isComponent: this.isComponent,
3159 selector: this.selector,
3160 exportAs: this.exportAs,
3161 inputs: this.inputs,
3162 outputs: this.outputs,
3163 hostListeners: this.hostListeners,
3164 hostProperties: this.hostProperties,
3165 hostAttributes: this.hostAttributes,
3166 providers: this.providers,
3167 viewProviders: this.viewProviders,
3168 queries: this.queries,
3169 guards: this.guards,
3170 viewQueries: this.viewQueries,
3171 entryComponents: this.entryComponents,
3172 changeDetection: this.changeDetection,
3173 template: this.template && this.template.toSummary(),
3174 componentViewType: this.componentViewType,
3175 rendererType: this.rendererType,
3176 componentFactory: this.componentFactory
3177 };
3178 };
3179 return CompileDirectiveMetadata;
3180}());
3181var CompilePipeMetadata = /** @class */ (function () {
3182 function CompilePipeMetadata(_a) {
3183 var type = _a.type, name = _a.name, pure = _a.pure;
3184 this.type = type;
3185 this.name = name;
3186 this.pure = !!pure;
3187 }
3188 CompilePipeMetadata.prototype.toSummary = function () {
3189 return {
3190 summaryKind: CompileSummaryKind.Pipe,
3191 type: this.type,
3192 name: this.name,
3193 pure: this.pure
3194 };
3195 };
3196 return CompilePipeMetadata;
3197}());
3198var CompileShallowModuleMetadata = /** @class */ (function () {
3199 function CompileShallowModuleMetadata() {
3200 }
3201 return CompileShallowModuleMetadata;
3202}());
3203/**
3204 * Metadata regarding compilation of a module.
3205 */
3206var CompileNgModuleMetadata = /** @class */ (function () {
3207 function CompileNgModuleMetadata(_a) {
3208 var type = _a.type, providers = _a.providers, declaredDirectives = _a.declaredDirectives, exportedDirectives = _a.exportedDirectives, declaredPipes = _a.declaredPipes, exportedPipes = _a.exportedPipes, entryComponents = _a.entryComponents, bootstrapComponents = _a.bootstrapComponents, importedModules = _a.importedModules, exportedModules = _a.exportedModules, schemas = _a.schemas, transitiveModule = _a.transitiveModule, id = _a.id;
3209 this.type = type || null;
3210 this.declaredDirectives = _normalizeArray(declaredDirectives);
3211 this.exportedDirectives = _normalizeArray(exportedDirectives);
3212 this.declaredPipes = _normalizeArray(declaredPipes);
3213 this.exportedPipes = _normalizeArray(exportedPipes);
3214 this.providers = _normalizeArray(providers);
3215 this.entryComponents = _normalizeArray(entryComponents);
3216 this.bootstrapComponents = _normalizeArray(bootstrapComponents);
3217 this.importedModules = _normalizeArray(importedModules);
3218 this.exportedModules = _normalizeArray(exportedModules);
3219 this.schemas = _normalizeArray(schemas);
3220 this.id = id || null;
3221 this.transitiveModule = transitiveModule || null;
3222 }
3223 CompileNgModuleMetadata.prototype.toSummary = function () {
3224 var module = this.transitiveModule;
3225 return {
3226 summaryKind: CompileSummaryKind.NgModule,
3227 type: this.type,
3228 entryComponents: module.entryComponents,
3229 providers: module.providers,
3230 modules: module.modules,
3231 exportedDirectives: module.exportedDirectives,
3232 exportedPipes: module.exportedPipes
3233 };
3234 };
3235 return CompileNgModuleMetadata;
3236}());
3237var TransitiveCompileNgModuleMetadata = /** @class */ (function () {
3238 function TransitiveCompileNgModuleMetadata() {
3239 this.directivesSet = new Set();
3240 this.directives = [];
3241 this.exportedDirectivesSet = new Set();
3242 this.exportedDirectives = [];
3243 this.pipesSet = new Set();
3244 this.pipes = [];
3245 this.exportedPipesSet = new Set();
3246 this.exportedPipes = [];
3247 this.modulesSet = new Set();
3248 this.modules = [];
3249 this.entryComponentsSet = new Set();
3250 this.entryComponents = [];
3251 this.providers = [];
3252 }
3253 TransitiveCompileNgModuleMetadata.prototype.addProvider = function (provider, module) {
3254 this.providers.push({ provider: provider, module: module });
3255 };
3256 TransitiveCompileNgModuleMetadata.prototype.addDirective = function (id) {
3257 if (!this.directivesSet.has(id.reference)) {
3258 this.directivesSet.add(id.reference);
3259 this.directives.push(id);
3260 }
3261 };
3262 TransitiveCompileNgModuleMetadata.prototype.addExportedDirective = function (id) {
3263 if (!this.exportedDirectivesSet.has(id.reference)) {
3264 this.exportedDirectivesSet.add(id.reference);
3265 this.exportedDirectives.push(id);
3266 }
3267 };
3268 TransitiveCompileNgModuleMetadata.prototype.addPipe = function (id) {
3269 if (!this.pipesSet.has(id.reference)) {
3270 this.pipesSet.add(id.reference);
3271 this.pipes.push(id);
3272 }
3273 };
3274 TransitiveCompileNgModuleMetadata.prototype.addExportedPipe = function (id) {
3275 if (!this.exportedPipesSet.has(id.reference)) {
3276 this.exportedPipesSet.add(id.reference);
3277 this.exportedPipes.push(id);
3278 }
3279 };
3280 TransitiveCompileNgModuleMetadata.prototype.addModule = function (id) {
3281 if (!this.modulesSet.has(id.reference)) {
3282 this.modulesSet.add(id.reference);
3283 this.modules.push(id);
3284 }
3285 };
3286 TransitiveCompileNgModuleMetadata.prototype.addEntryComponent = function (ec) {
3287 if (!this.entryComponentsSet.has(ec.componentType)) {
3288 this.entryComponentsSet.add(ec.componentType);
3289 this.entryComponents.push(ec);
3290 }
3291 };
3292 return TransitiveCompileNgModuleMetadata;
3293}());
3294function _normalizeArray(obj) {
3295 return obj || [];
3296}
3297var ProviderMeta = /** @class */ (function () {
3298 function ProviderMeta(token, _a) {
3299 var useClass = _a.useClass, useValue = _a.useValue, useExisting = _a.useExisting, useFactory = _a.useFactory, deps = _a.deps, multi = _a.multi;
3300 this.token = token;
3301 this.useClass = useClass || null;
3302 this.useValue = useValue;
3303 this.useExisting = useExisting;
3304 this.useFactory = useFactory || null;
3305 this.dependencies = deps || null;
3306 this.multi = !!multi;
3307 }
3308 return ProviderMeta;
3309}());
3310function flatten(list) {
3311 return list.reduce(function (flat, item) {
3312 var flatItem = Array.isArray(item) ? flatten(item) : item;
3313 return flat.concat(flatItem);
3314 }, []);
3315}
3316function jitSourceUrl(url) {
3317 // Note: We need 3 "/" so that ng shows up as a separate domain
3318 // in the chrome dev tools.
3319 return url.replace(/(\w+:\/\/[\w:-]+)?(\/+)?/, 'ng:///');
3320}
3321function templateSourceUrl(ngModuleType, compMeta, templateMeta) {
3322 var url;
3323 if (templateMeta.isInline) {
3324 if (compMeta.type.reference instanceof StaticSymbol) {
3325 // Note: a .ts file might contain multiple components with inline templates,
3326 // so we need to give them unique urls, as these will be used for sourcemaps.
3327 url = compMeta.type.reference.filePath + "." + compMeta.type.reference.name + ".html";
3328 }
3329 else {
3330 url = identifierName(ngModuleType) + "/" + identifierName(compMeta.type) + ".html";
3331 }
3332 }
3333 else {
3334 url = templateMeta.templateUrl;
3335 }
3336 return compMeta.type.reference instanceof StaticSymbol ? url : jitSourceUrl(url);
3337}
3338function sharedStylesheetJitUrl(meta, id) {
3339 var pathParts = meta.moduleUrl.split(/\/\\/g);
3340 var baseName = pathParts[pathParts.length - 1];
3341 return jitSourceUrl("css/" + id + baseName + ".ngstyle.js");
3342}
3343function ngModuleJitUrl(moduleMeta) {
3344 return jitSourceUrl(identifierName(moduleMeta.type) + "/module.ngfactory.js");
3345}
3346function templateJitUrl(ngModuleType, compMeta) {
3347 return jitSourceUrl(identifierName(ngModuleType) + "/" + identifierName(compMeta.type) + ".ngfactory.js");
3348}
3349
3350/**
3351 * @license
3352 * Copyright Google Inc. All Rights Reserved.
3353 *
3354 * Use of this source code is governed by an MIT-style license that can be
3355 * found in the LICENSE file at https://angular.io/license
3356 */
3357var CORE$1 = '@angular/core';
3358var Identifiers$1 = /** @class */ (function () {
3359 function Identifiers() {
3360 }
3361 /* Methods */
3362 Identifiers.NEW_METHOD = 'factory';
3363 Identifiers.TRANSFORM_METHOD = 'transform';
3364 Identifiers.PATCH_DEPS = 'patchedDeps';
3365 /* Instructions */
3366 Identifiers.namespaceHTML = { name: 'ɵɵnamespaceHTML', moduleName: CORE$1 };
3367 Identifiers.namespaceMathML = { name: 'ɵɵnamespaceMathML', moduleName: CORE$1 };
3368 Identifiers.namespaceSVG = { name: 'ɵɵnamespaceSVG', moduleName: CORE$1 };
3369 Identifiers.element = { name: 'ɵɵelement', moduleName: CORE$1 };
3370 Identifiers.elementStart = { name: 'ɵɵelementStart', moduleName: CORE$1 };
3371 Identifiers.elementEnd = { name: 'ɵɵelementEnd', moduleName: CORE$1 };
3372 Identifiers.select = { name: 'ɵɵselect', moduleName: CORE$1 };
3373 Identifiers.updateSyntheticHostBinding = { name: 'ɵɵupdateSyntheticHostBinding', moduleName: CORE$1 };
3374 Identifiers.componentHostSyntheticListener = { name: 'ɵɵcomponentHostSyntheticListener', moduleName: CORE$1 };
3375 Identifiers.attribute = { name: 'ɵɵattribute', moduleName: CORE$1 };
3376 Identifiers.attributeInterpolate1 = { name: 'ɵɵattributeInterpolate1', moduleName: CORE$1 };
3377 Identifiers.attributeInterpolate2 = { name: 'ɵɵattributeInterpolate2', moduleName: CORE$1 };
3378 Identifiers.attributeInterpolate3 = { name: 'ɵɵattributeInterpolate3', moduleName: CORE$1 };
3379 Identifiers.attributeInterpolate4 = { name: 'ɵɵattributeInterpolate4', moduleName: CORE$1 };
3380 Identifiers.attributeInterpolate5 = { name: 'ɵɵattributeInterpolate5', moduleName: CORE$1 };
3381 Identifiers.attributeInterpolate6 = { name: 'ɵɵattributeInterpolate6', moduleName: CORE$1 };
3382 Identifiers.attributeInterpolate7 = { name: 'ɵɵattributeInterpolate7', moduleName: CORE$1 };
3383 Identifiers.attributeInterpolate8 = { name: 'ɵɵattributeInterpolate8', moduleName: CORE$1 };
3384 Identifiers.attributeInterpolateV = { name: 'ɵɵattributeInterpolateV', moduleName: CORE$1 };
3385 Identifiers.classProp = { name: 'ɵɵclassProp', moduleName: CORE$1 };
3386 Identifiers.elementContainerStart = { name: 'ɵɵelementContainerStart', moduleName: CORE$1 };
3387 Identifiers.elementContainerEnd = { name: 'ɵɵelementContainerEnd', moduleName: CORE$1 };
3388 Identifiers.elementContainer = { name: 'ɵɵelementContainer', moduleName: CORE$1 };
3389 Identifiers.styling = { name: 'ɵɵstyling', moduleName: CORE$1 };
3390 Identifiers.styleMap = { name: 'ɵɵstyleMap', moduleName: CORE$1 };
3391 Identifiers.classMap = { name: 'ɵɵclassMap', moduleName: CORE$1 };
3392 Identifiers.classMapInterpolate1 = { name: 'ɵɵclassMapInterpolate1', moduleName: CORE$1 };
3393 Identifiers.classMapInterpolate2 = { name: 'ɵɵclassMapInterpolate2', moduleName: CORE$1 };
3394 Identifiers.classMapInterpolate3 = { name: 'ɵɵclassMapInterpolate3', moduleName: CORE$1 };
3395 Identifiers.classMapInterpolate4 = { name: 'ɵɵclassMapInterpolate4', moduleName: CORE$1 };
3396 Identifiers.classMapInterpolate5 = { name: 'ɵɵclassMapInterpolate5', moduleName: CORE$1 };
3397 Identifiers.classMapInterpolate6 = { name: 'ɵɵclassMapInterpolate6', moduleName: CORE$1 };
3398 Identifiers.classMapInterpolate7 = { name: 'ɵɵclassMapInterpolate7', moduleName: CORE$1 };
3399 Identifiers.classMapInterpolate8 = { name: 'ɵɵclassMapInterpolate8', moduleName: CORE$1 };
3400 Identifiers.classMapInterpolateV = { name: 'ɵɵclassMapInterpolateV', moduleName: CORE$1 };
3401 Identifiers.styleProp = { name: 'ɵɵstyleProp', moduleName: CORE$1 };
3402 Identifiers.stylePropInterpolate1 = { name: 'ɵɵstylePropInterpolate1', moduleName: CORE$1 };
3403 Identifiers.stylePropInterpolate2 = { name: 'ɵɵstylePropInterpolate2', moduleName: CORE$1 };
3404 Identifiers.stylePropInterpolate3 = { name: 'ɵɵstylePropInterpolate3', moduleName: CORE$1 };
3405 Identifiers.stylePropInterpolate4 = { name: 'ɵɵstylePropInterpolate4', moduleName: CORE$1 };
3406 Identifiers.stylePropInterpolate5 = { name: 'ɵɵstylePropInterpolate5', moduleName: CORE$1 };
3407 Identifiers.stylePropInterpolate6 = { name: 'ɵɵstylePropInterpolate6', moduleName: CORE$1 };
3408 Identifiers.stylePropInterpolate7 = { name: 'ɵɵstylePropInterpolate7', moduleName: CORE$1 };
3409 Identifiers.stylePropInterpolate8 = { name: 'ɵɵstylePropInterpolate8', moduleName: CORE$1 };
3410 Identifiers.stylePropInterpolateV = { name: 'ɵɵstylePropInterpolateV', moduleName: CORE$1 };
3411 Identifiers.stylingApply = { name: 'ɵɵstylingApply', moduleName: CORE$1 };
3412 Identifiers.styleSanitizer = { name: 'ɵɵstyleSanitizer', moduleName: CORE$1 };
3413 Identifiers.elementHostAttrs = { name: 'ɵɵelementHostAttrs', moduleName: CORE$1 };
3414 Identifiers.containerCreate = { name: 'ɵɵcontainer', moduleName: CORE$1 };
3415 Identifiers.nextContext = { name: 'ɵɵnextContext', moduleName: CORE$1 };
3416 Identifiers.templateCreate = { name: 'ɵɵtemplate', moduleName: CORE$1 };
3417 Identifiers.text = { name: 'ɵɵtext', moduleName: CORE$1 };
3418 Identifiers.textBinding = { name: 'ɵɵtextBinding', moduleName: CORE$1 };
3419 Identifiers.enableBindings = { name: 'ɵɵenableBindings', moduleName: CORE$1 };
3420 Identifiers.disableBindings = { name: 'ɵɵdisableBindings', moduleName: CORE$1 };
3421 Identifiers.allocHostVars = { name: 'ɵɵallocHostVars', moduleName: CORE$1 };
3422 Identifiers.getCurrentView = { name: 'ɵɵgetCurrentView', moduleName: CORE$1 };
3423 Identifiers.textInterpolate = { name: 'ɵɵtextInterpolate', moduleName: CORE$1 };
3424 Identifiers.textInterpolate1 = { name: 'ɵɵtextInterpolate1', moduleName: CORE$1 };
3425 Identifiers.textInterpolate2 = { name: 'ɵɵtextInterpolate2', moduleName: CORE$1 };
3426 Identifiers.textInterpolate3 = { name: 'ɵɵtextInterpolate3', moduleName: CORE$1 };
3427 Identifiers.textInterpolate4 = { name: 'ɵɵtextInterpolate4', moduleName: CORE$1 };
3428 Identifiers.textInterpolate5 = { name: 'ɵɵtextInterpolate5', moduleName: CORE$1 };
3429 Identifiers.textInterpolate6 = { name: 'ɵɵtextInterpolate6', moduleName: CORE$1 };
3430 Identifiers.textInterpolate7 = { name: 'ɵɵtextInterpolate7', moduleName: CORE$1 };
3431 Identifiers.textInterpolate8 = { name: 'ɵɵtextInterpolate8', moduleName: CORE$1 };
3432 Identifiers.textInterpolateV = { name: 'ɵɵtextInterpolateV', moduleName: CORE$1 };
3433 Identifiers.restoreView = { name: 'ɵɵrestoreView', moduleName: CORE$1 };
3434 Identifiers.pureFunction0 = { name: 'ɵɵpureFunction0', moduleName: CORE$1 };
3435 Identifiers.pureFunction1 = { name: 'ɵɵpureFunction1', moduleName: CORE$1 };
3436 Identifiers.pureFunction2 = { name: 'ɵɵpureFunction2', moduleName: CORE$1 };
3437 Identifiers.pureFunction3 = { name: 'ɵɵpureFunction3', moduleName: CORE$1 };
3438 Identifiers.pureFunction4 = { name: 'ɵɵpureFunction4', moduleName: CORE$1 };
3439 Identifiers.pureFunction5 = { name: 'ɵɵpureFunction5', moduleName: CORE$1 };
3440 Identifiers.pureFunction6 = { name: 'ɵɵpureFunction6', moduleName: CORE$1 };
3441 Identifiers.pureFunction7 = { name: 'ɵɵpureFunction7', moduleName: CORE$1 };
3442 Identifiers.pureFunction8 = { name: 'ɵɵpureFunction8', moduleName: CORE$1 };
3443 Identifiers.pureFunctionV = { name: 'ɵɵpureFunctionV', moduleName: CORE$1 };
3444 Identifiers.pipeBind1 = { name: 'ɵɵpipeBind1', moduleName: CORE$1 };
3445 Identifiers.pipeBind2 = { name: 'ɵɵpipeBind2', moduleName: CORE$1 };
3446 Identifiers.pipeBind3 = { name: 'ɵɵpipeBind3', moduleName: CORE$1 };
3447 Identifiers.pipeBind4 = { name: 'ɵɵpipeBind4', moduleName: CORE$1 };
3448 Identifiers.pipeBindV = { name: 'ɵɵpipeBindV', moduleName: CORE$1 };
3449 Identifiers.hostProperty = { name: 'ɵɵhostProperty', moduleName: CORE$1 };
3450 Identifiers.property = { name: 'ɵɵproperty', moduleName: CORE$1 };
3451 Identifiers.propertyInterpolate = { name: 'ɵɵpropertyInterpolate', moduleName: CORE$1 };
3452 Identifiers.propertyInterpolate1 = { name: 'ɵɵpropertyInterpolate1', moduleName: CORE$1 };
3453 Identifiers.propertyInterpolate2 = { name: 'ɵɵpropertyInterpolate2', moduleName: CORE$1 };
3454 Identifiers.propertyInterpolate3 = { name: 'ɵɵpropertyInterpolate3', moduleName: CORE$1 };
3455 Identifiers.propertyInterpolate4 = { name: 'ɵɵpropertyInterpolate4', moduleName: CORE$1 };
3456 Identifiers.propertyInterpolate5 = { name: 'ɵɵpropertyInterpolate5', moduleName: CORE$1 };
3457 Identifiers.propertyInterpolate6 = { name: 'ɵɵpropertyInterpolate6', moduleName: CORE$1 };
3458 Identifiers.propertyInterpolate7 = { name: 'ɵɵpropertyInterpolate7', moduleName: CORE$1 };
3459 Identifiers.propertyInterpolate8 = { name: 'ɵɵpropertyInterpolate8', moduleName: CORE$1 };
3460 Identifiers.propertyInterpolateV = { name: 'ɵɵpropertyInterpolateV', moduleName: CORE$1 };
3461 Identifiers.i18n = { name: 'ɵɵi18n', moduleName: CORE$1 };
3462 Identifiers.i18nAttributes = { name: 'ɵɵi18nAttributes', moduleName: CORE$1 };
3463 Identifiers.i18nExp = { name: 'ɵɵi18nExp', moduleName: CORE$1 };
3464 Identifiers.i18nStart = { name: 'ɵɵi18nStart', moduleName: CORE$1 };
3465 Identifiers.i18nEnd = { name: 'ɵɵi18nEnd', moduleName: CORE$1 };
3466 Identifiers.i18nApply = { name: 'ɵɵi18nApply', moduleName: CORE$1 };
3467 Identifiers.i18nPostprocess = { name: 'ɵɵi18nPostprocess', moduleName: CORE$1 };
3468 Identifiers.i18nLocalize = { name: 'ɵɵi18nLocalize', moduleName: CORE$1 };
3469 Identifiers.load = { name: 'ɵɵload', moduleName: CORE$1 };
3470 Identifiers.pipe = { name: 'ɵɵpipe', moduleName: CORE$1 };
3471 Identifiers.projection = { name: 'ɵɵprojection', moduleName: CORE$1 };
3472 Identifiers.projectionDef = { name: 'ɵɵprojectionDef', moduleName: CORE$1 };
3473 Identifiers.reference = { name: 'ɵɵreference', moduleName: CORE$1 };
3474 Identifiers.inject = { name: 'ɵɵinject', moduleName: CORE$1 };
3475 Identifiers.injectAttribute = { name: 'ɵɵinjectAttribute', moduleName: CORE$1 };
3476 Identifiers.injectPipeChangeDetectorRef = { name: 'ɵɵinjectPipeChangeDetectorRef', moduleName: CORE$1 };
3477 Identifiers.directiveInject = { name: 'ɵɵdirectiveInject', moduleName: CORE$1 };
3478 Identifiers.templateRefExtractor = { name: 'ɵɵtemplateRefExtractor', moduleName: CORE$1 };
3479 Identifiers.resolveWindow = { name: 'ɵɵresolveWindow', moduleName: CORE$1 };
3480 Identifiers.resolveDocument = { name: 'ɵɵresolveDocument', moduleName: CORE$1 };
3481 Identifiers.resolveBody = { name: 'ɵɵresolveBody', moduleName: CORE$1 };
3482 Identifiers.defineBase = { name: 'ɵɵdefineBase', moduleName: CORE$1 };
3483 Identifiers.BaseDef = {
3484 name: 'ɵɵBaseDef',
3485 moduleName: CORE$1,
3486 };
3487 Identifiers.defineComponent = { name: 'ɵɵdefineComponent', moduleName: CORE$1 };
3488 Identifiers.setComponentScope = { name: 'ɵɵsetComponentScope', moduleName: CORE$1 };
3489 Identifiers.ComponentDefWithMeta = {
3490 name: 'ɵɵComponentDefWithMeta',
3491 moduleName: CORE$1,
3492 };
3493 Identifiers.defineDirective = {
3494 name: 'ɵɵdefineDirective',
3495 moduleName: CORE$1,
3496 };
3497 Identifiers.DirectiveDefWithMeta = {
3498 name: 'ɵɵDirectiveDefWithMeta',
3499 moduleName: CORE$1,
3500 };
3501 Identifiers.InjectorDef = {
3502 name: 'ɵɵInjectorDef',
3503 moduleName: CORE$1,
3504 };
3505 Identifiers.defineInjector = {
3506 name: 'ɵɵdefineInjector',
3507 moduleName: CORE$1,
3508 };
3509 Identifiers.NgModuleDefWithMeta = {
3510 name: 'ɵɵNgModuleDefWithMeta',
3511 moduleName: CORE$1,
3512 };
3513 Identifiers.defineNgModule = { name: 'ɵɵdefineNgModule', moduleName: CORE$1 };
3514 Identifiers.setNgModuleScope = { name: 'ɵɵsetNgModuleScope', moduleName: CORE$1 };
3515 Identifiers.PipeDefWithMeta = { name: 'ɵɵPipeDefWithMeta', moduleName: CORE$1 };
3516 Identifiers.definePipe = { name: 'ɵɵdefinePipe', moduleName: CORE$1 };
3517 Identifiers.queryRefresh = { name: 'ɵɵqueryRefresh', moduleName: CORE$1 };
3518 Identifiers.viewQuery = { name: 'ɵɵviewQuery', moduleName: CORE$1 };
3519 Identifiers.staticViewQuery = { name: 'ɵɵstaticViewQuery', moduleName: CORE$1 };
3520 Identifiers.staticContentQuery = { name: 'ɵɵstaticContentQuery', moduleName: CORE$1 };
3521 Identifiers.loadViewQuery = { name: 'ɵɵloadViewQuery', moduleName: CORE$1 };
3522 Identifiers.contentQuery = { name: 'ɵɵcontentQuery', moduleName: CORE$1 };
3523 Identifiers.loadContentQuery = { name: 'ɵɵloadContentQuery', moduleName: CORE$1 };
3524 Identifiers.NgOnChangesFeature = { name: 'ɵɵNgOnChangesFeature', moduleName: CORE$1 };
3525 Identifiers.InheritDefinitionFeature = { name: 'ɵɵInheritDefinitionFeature', moduleName: CORE$1 };
3526 Identifiers.ProvidersFeature = { name: 'ɵɵProvidersFeature', moduleName: CORE$1 };
3527 Identifiers.listener = { name: 'ɵɵlistener', moduleName: CORE$1 };
3528 Identifiers.getFactoryOf = {
3529 name: 'ɵɵgetFactoryOf',
3530 moduleName: CORE$1,
3531 };
3532 Identifiers.getInheritedFactory = {
3533 name: 'ɵɵgetInheritedFactory',
3534 moduleName: CORE$1,
3535 };
3536 // sanitization-related functions
3537 Identifiers.sanitizeHtml = { name: 'ɵɵsanitizeHtml', moduleName: CORE$1 };
3538 Identifiers.sanitizeStyle = { name: 'ɵɵsanitizeStyle', moduleName: CORE$1 };
3539 Identifiers.defaultStyleSanitizer = { name: 'ɵɵdefaultStyleSanitizer', moduleName: CORE$1 };
3540 Identifiers.sanitizeResourceUrl = { name: 'ɵɵsanitizeResourceUrl', moduleName: CORE$1 };
3541 Identifiers.sanitizeScript = { name: 'ɵɵsanitizeScript', moduleName: CORE$1 };
3542 Identifiers.sanitizeUrl = { name: 'ɵɵsanitizeUrl', moduleName: CORE$1 };
3543 Identifiers.sanitizeUrlOrResourceUrl = { name: 'ɵɵsanitizeUrlOrResourceUrl', moduleName: CORE$1 };
3544 return Identifiers;
3545}());
3546
3547/**
3548 * @license
3549 * Copyright Google Inc. All Rights Reserved.
3550 *
3551 * Use of this source code is governed by an MIT-style license that can be
3552 * found in the LICENSE file at https://angular.io/license
3553 */
3554var $EOF = 0;
3555var $BSPACE = 8;
3556var $TAB = 9;
3557var $LF = 10;
3558var $VTAB = 11;
3559var $FF = 12;
3560var $CR = 13;
3561var $SPACE = 32;
3562var $BANG = 33;
3563var $DQ = 34;
3564var $HASH = 35;
3565var $$ = 36;
3566var $PERCENT = 37;
3567var $AMPERSAND = 38;
3568var $SQ = 39;
3569var $LPAREN = 40;
3570var $RPAREN = 41;
3571var $STAR = 42;
3572var $PLUS = 43;
3573var $COMMA = 44;
3574var $MINUS = 45;
3575var $PERIOD = 46;
3576var $SLASH = 47;
3577var $COLON = 58;
3578var $SEMICOLON = 59;
3579var $LT = 60;
3580var $EQ = 61;
3581var $GT = 62;
3582var $QUESTION = 63;
3583var $0 = 48;
3584var $7 = 55;
3585var $9 = 57;
3586var $A = 65;
3587var $E = 69;
3588var $F = 70;
3589var $X = 88;
3590var $Z = 90;
3591var $LBRACKET = 91;
3592var $BACKSLASH = 92;
3593var $RBRACKET = 93;
3594var $CARET = 94;
3595var $_ = 95;
3596var $a = 97;
3597var $b = 98;
3598var $e = 101;
3599var $f = 102;
3600var $n = 110;
3601var $r = 114;
3602var $t = 116;
3603var $u = 117;
3604var $v = 118;
3605var $x = 120;
3606var $z = 122;
3607var $LBRACE = 123;
3608var $BAR = 124;
3609var $RBRACE = 125;
3610var $NBSP = 160;
3611var $PIPE = 124;
3612var $TILDA = 126;
3613var $AT = 64;
3614var $BT = 96;
3615function isWhitespace(code) {
3616 return (code >= $TAB && code <= $SPACE) || (code == $NBSP);
3617}
3618function isDigit(code) {
3619 return $0 <= code && code <= $9;
3620}
3621function isAsciiLetter(code) {
3622 return code >= $a && code <= $z || code >= $A && code <= $Z;
3623}
3624function isAsciiHexDigit(code) {
3625 return code >= $a && code <= $f || code >= $A && code <= $F || isDigit(code);
3626}
3627function isNewLine(code) {
3628 return code === $LF || code === $CR;
3629}
3630function isOctalDigit(code) {
3631 return $0 <= code && code <= $7;
3632}
3633
3634/**
3635 * @license
3636 * Copyright Google Inc. All Rights Reserved.
3637 *
3638 * Use of this source code is governed by an MIT-style license that can be
3639 * found in the LICENSE file at https://angular.io/license
3640 */
3641var ParseLocation = /** @class */ (function () {
3642 function ParseLocation(file, offset, line, col) {
3643 this.file = file;
3644 this.offset = offset;
3645 this.line = line;
3646 this.col = col;
3647 }
3648 ParseLocation.prototype.toString = function () {
3649 return this.offset != null ? this.file.url + "@" + this.line + ":" + this.col : this.file.url;
3650 };
3651 ParseLocation.prototype.moveBy = function (delta) {
3652 var source = this.file.content;
3653 var len = source.length;
3654 var offset = this.offset;
3655 var line = this.line;
3656 var col = this.col;
3657 while (offset > 0 && delta < 0) {
3658 offset--;
3659 delta++;
3660 var ch = source.charCodeAt(offset);
3661 if (ch == $LF) {
3662 line--;
3663 var priorLine = source.substr(0, offset - 1).lastIndexOf(String.fromCharCode($LF));
3664 col = priorLine > 0 ? offset - priorLine : offset;
3665 }
3666 else {
3667 col--;
3668 }
3669 }
3670 while (offset < len && delta > 0) {
3671 var ch = source.charCodeAt(offset);
3672 offset++;
3673 delta--;
3674 if (ch == $LF) {
3675 line++;
3676 col = 0;
3677 }
3678 else {
3679 col++;
3680 }
3681 }
3682 return new ParseLocation(this.file, offset, line, col);
3683 };
3684 // Return the source around the location
3685 // Up to `maxChars` or `maxLines` on each side of the location
3686 ParseLocation.prototype.getContext = function (maxChars, maxLines) {
3687 var content = this.file.content;
3688 var startOffset = this.offset;
3689 if (startOffset != null) {
3690 if (startOffset > content.length - 1) {
3691 startOffset = content.length - 1;
3692 }
3693 var endOffset = startOffset;
3694 var ctxChars = 0;
3695 var ctxLines = 0;
3696 while (ctxChars < maxChars && startOffset > 0) {
3697 startOffset--;
3698 ctxChars++;
3699 if (content[startOffset] == '\n') {
3700 if (++ctxLines == maxLines) {
3701 break;
3702 }
3703 }
3704 }
3705 ctxChars = 0;
3706 ctxLines = 0;
3707 while (ctxChars < maxChars && endOffset < content.length - 1) {
3708 endOffset++;
3709 ctxChars++;
3710 if (content[endOffset] == '\n') {
3711 if (++ctxLines == maxLines) {
3712 break;
3713 }
3714 }
3715 }
3716 return {
3717 before: content.substring(startOffset, this.offset),
3718 after: content.substring(this.offset, endOffset + 1),
3719 };
3720 }
3721 return null;
3722 };
3723 return ParseLocation;
3724}());
3725var ParseSourceFile = /** @class */ (function () {
3726 function ParseSourceFile(content, url) {
3727 this.content = content;
3728 this.url = url;
3729 }
3730 return ParseSourceFile;
3731}());
3732var ParseSourceSpan = /** @class */ (function () {
3733 function ParseSourceSpan(start, end, details) {
3734 if (details === void 0) { details = null; }
3735 this.start = start;
3736 this.end = end;
3737 this.details = details;
3738 }
3739 ParseSourceSpan.prototype.toString = function () {
3740 return this.start.file.content.substring(this.start.offset, this.end.offset);
3741 };
3742 return ParseSourceSpan;
3743}());
3744var EMPTY_PARSE_LOCATION = new ParseLocation(new ParseSourceFile('', ''), 0, 0, 0);
3745var EMPTY_SOURCE_SPAN = new ParseSourceSpan(EMPTY_PARSE_LOCATION, EMPTY_PARSE_LOCATION);
3746var ParseErrorLevel;
3747(function (ParseErrorLevel) {
3748 ParseErrorLevel[ParseErrorLevel["WARNING"] = 0] = "WARNING";
3749 ParseErrorLevel[ParseErrorLevel["ERROR"] = 1] = "ERROR";
3750})(ParseErrorLevel || (ParseErrorLevel = {}));
3751var ParseError = /** @class */ (function () {
3752 function ParseError(span, msg, level) {
3753 if (level === void 0) { level = ParseErrorLevel.ERROR; }
3754 this.span = span;
3755 this.msg = msg;
3756 this.level = level;
3757 }
3758 ParseError.prototype.contextualMessage = function () {
3759 var ctx = this.span.start.getContext(100, 3);
3760 return ctx ? this.msg + " (\"" + ctx.before + "[" + ParseErrorLevel[this.level] + " ->]" + ctx.after + "\")" :
3761 this.msg;
3762 };
3763 ParseError.prototype.toString = function () {
3764 var details = this.span.details ? ", " + this.span.details : '';
3765 return this.contextualMessage() + ": " + this.span.start + details;
3766 };
3767 return ParseError;
3768}());
3769function typeSourceSpan(kind, type) {
3770 var moduleUrl = identifierModuleUrl(type);
3771 var sourceFileName = moduleUrl != null ? "in " + kind + " " + identifierName(type) + " in " + moduleUrl :
3772 "in " + kind + " " + identifierName(type);
3773 var sourceFile = new ParseSourceFile('', sourceFileName);
3774 return new ParseSourceSpan(new ParseLocation(sourceFile, -1, -1, -1), new ParseLocation(sourceFile, -1, -1, -1));
3775}
3776/**
3777 * Generates Source Span object for a given R3 Type for JIT mode.
3778 *
3779 * @param kind Component or Directive.
3780 * @param typeName name of the Component or Directive.
3781 * @param sourceUrl reference to Component or Directive source.
3782 * @returns instance of ParseSourceSpan that represent a given Component or Directive.
3783 */
3784function r3JitTypeSourceSpan(kind, typeName, sourceUrl) {
3785 var sourceFileName = "in " + kind + " " + typeName + " in " + sourceUrl;
3786 var sourceFile = new ParseSourceFile('', sourceFileName);
3787 return new ParseSourceSpan(new ParseLocation(sourceFile, -1, -1, -1), new ParseLocation(sourceFile, -1, -1, -1));
3788}
3789
3790/**
3791 * @license
3792 * Copyright Google Inc. All Rights Reserved.
3793 *
3794 * Use of this source code is governed by an MIT-style license that can be
3795 * found in the LICENSE file at https://angular.io/license
3796 */
3797var Text = /** @class */ (function () {
3798 function Text(value, sourceSpan) {
3799 this.value = value;
3800 this.sourceSpan = sourceSpan;
3801 }
3802 Text.prototype.visit = function (visitor) { return visitor.visitText(this); };
3803 return Text;
3804}());
3805var BoundText = /** @class */ (function () {
3806 function BoundText(value, sourceSpan, i18n) {
3807 this.value = value;
3808 this.sourceSpan = sourceSpan;
3809 this.i18n = i18n;
3810 }
3811 BoundText.prototype.visit = function (visitor) { return visitor.visitBoundText(this); };
3812 return BoundText;
3813}());
3814var TextAttribute = /** @class */ (function () {
3815 function TextAttribute(name, value, sourceSpan, valueSpan, i18n) {
3816 this.name = name;
3817 this.value = value;
3818 this.sourceSpan = sourceSpan;
3819 this.valueSpan = valueSpan;
3820 this.i18n = i18n;
3821 }
3822 TextAttribute.prototype.visit = function (visitor) { return visitor.visitTextAttribute(this); };
3823 return TextAttribute;
3824}());
3825var BoundAttribute = /** @class */ (function () {
3826 function BoundAttribute(name, type, securityContext, value, unit, sourceSpan, valueSpan, i18n) {
3827 this.name = name;
3828 this.type = type;
3829 this.securityContext = securityContext;
3830 this.value = value;
3831 this.unit = unit;
3832 this.sourceSpan = sourceSpan;
3833 this.valueSpan = valueSpan;
3834 this.i18n = i18n;
3835 }
3836 BoundAttribute.fromBoundElementProperty = function (prop, i18n) {
3837 return new BoundAttribute(prop.name, prop.type, prop.securityContext, prop.value, prop.unit, prop.sourceSpan, prop.valueSpan, i18n);
3838 };
3839 BoundAttribute.prototype.visit = function (visitor) { return visitor.visitBoundAttribute(this); };
3840 return BoundAttribute;
3841}());
3842var BoundEvent = /** @class */ (function () {
3843 function BoundEvent(name, type, handler, target, phase, sourceSpan, handlerSpan) {
3844 this.name = name;
3845 this.type = type;
3846 this.handler = handler;
3847 this.target = target;
3848 this.phase = phase;
3849 this.sourceSpan = sourceSpan;
3850 this.handlerSpan = handlerSpan;
3851 }
3852 BoundEvent.fromParsedEvent = function (event) {
3853 var target = event.type === 0 /* Regular */ ? event.targetOrPhase : null;
3854 var phase = event.type === 1 /* Animation */ ? event.targetOrPhase : null;
3855 return new BoundEvent(event.name, event.type, event.handler, target, phase, event.sourceSpan, event.handlerSpan);
3856 };
3857 BoundEvent.prototype.visit = function (visitor) { return visitor.visitBoundEvent(this); };
3858 return BoundEvent;
3859}());
3860var Element = /** @class */ (function () {
3861 function Element(name, attributes, inputs, outputs, children, references, sourceSpan, startSourceSpan, endSourceSpan, i18n) {
3862 this.name = name;
3863 this.attributes = attributes;
3864 this.inputs = inputs;
3865 this.outputs = outputs;
3866 this.children = children;
3867 this.references = references;
3868 this.sourceSpan = sourceSpan;
3869 this.startSourceSpan = startSourceSpan;
3870 this.endSourceSpan = endSourceSpan;
3871 this.i18n = i18n;
3872 // If the element is empty then the source span should include any closing tag
3873 if (children.length === 0 && startSourceSpan && endSourceSpan) {
3874 this.sourceSpan = new ParseSourceSpan(sourceSpan.start, endSourceSpan.end);
3875 }
3876 }
3877 Element.prototype.visit = function (visitor) { return visitor.visitElement(this); };
3878 return Element;
3879}());
3880var Template = /** @class */ (function () {
3881 function Template(tagName, attributes, inputs, outputs, templateAttrs, children, references, variables, sourceSpan, startSourceSpan, endSourceSpan, i18n) {
3882 this.tagName = tagName;
3883 this.attributes = attributes;
3884 this.inputs = inputs;
3885 this.outputs = outputs;
3886 this.templateAttrs = templateAttrs;
3887 this.children = children;
3888 this.references = references;
3889 this.variables = variables;
3890 this.sourceSpan = sourceSpan;
3891 this.startSourceSpan = startSourceSpan;
3892 this.endSourceSpan = endSourceSpan;
3893 this.i18n = i18n;
3894 }
3895 Template.prototype.visit = function (visitor) { return visitor.visitTemplate(this); };
3896 return Template;
3897}());
3898var Content = /** @class */ (function () {
3899 function Content(selector, attributes, sourceSpan, i18n) {
3900 this.selector = selector;
3901 this.attributes = attributes;
3902 this.sourceSpan = sourceSpan;
3903 this.i18n = i18n;
3904 }
3905 Content.prototype.visit = function (visitor) { return visitor.visitContent(this); };
3906 return Content;
3907}());
3908var Variable = /** @class */ (function () {
3909 function Variable(name, value, sourceSpan, valueSpan) {
3910 this.name = name;
3911 this.value = value;
3912 this.sourceSpan = sourceSpan;
3913 this.valueSpan = valueSpan;
3914 }
3915 Variable.prototype.visit = function (visitor) { return visitor.visitVariable(this); };
3916 return Variable;
3917}());
3918var Reference = /** @class */ (function () {
3919 function Reference(name, value, sourceSpan, valueSpan) {
3920 this.name = name;
3921 this.value = value;
3922 this.sourceSpan = sourceSpan;
3923 this.valueSpan = valueSpan;
3924 }
3925 Reference.prototype.visit = function (visitor) { return visitor.visitReference(this); };
3926 return Reference;
3927}());
3928var Icu = /** @class */ (function () {
3929 function Icu(vars, placeholders, sourceSpan, i18n) {
3930 this.vars = vars;
3931 this.placeholders = placeholders;
3932 this.sourceSpan = sourceSpan;
3933 this.i18n = i18n;
3934 }
3935 Icu.prototype.visit = function (visitor) { return visitor.visitIcu(this); };
3936 return Icu;
3937}());
3938var NullVisitor = /** @class */ (function () {
3939 function NullVisitor() {
3940 }
3941 NullVisitor.prototype.visitElement = function (element) { };
3942 NullVisitor.prototype.visitTemplate = function (template) { };
3943 NullVisitor.prototype.visitContent = function (content) { };
3944 NullVisitor.prototype.visitVariable = function (variable) { };
3945 NullVisitor.prototype.visitReference = function (reference) { };
3946 NullVisitor.prototype.visitTextAttribute = function (attribute) { };
3947 NullVisitor.prototype.visitBoundAttribute = function (attribute) { };
3948 NullVisitor.prototype.visitBoundEvent = function (attribute) { };
3949 NullVisitor.prototype.visitText = function (text) { };
3950 NullVisitor.prototype.visitBoundText = function (text) { };
3951 NullVisitor.prototype.visitIcu = function (icu) { };
3952 return NullVisitor;
3953}());
3954var RecursiveVisitor = /** @class */ (function () {
3955 function RecursiveVisitor() {
3956 }
3957 RecursiveVisitor.prototype.visitElement = function (element) {
3958 visitAll(this, element.attributes);
3959 visitAll(this, element.children);
3960 visitAll(this, element.references);
3961 };
3962 RecursiveVisitor.prototype.visitTemplate = function (template) {
3963 visitAll(this, template.attributes);
3964 visitAll(this, template.children);
3965 visitAll(this, template.references);
3966 visitAll(this, template.variables);
3967 };
3968 RecursiveVisitor.prototype.visitContent = function (content) { };
3969 RecursiveVisitor.prototype.visitVariable = function (variable) { };
3970 RecursiveVisitor.prototype.visitReference = function (reference) { };
3971 RecursiveVisitor.prototype.visitTextAttribute = function (attribute) { };
3972 RecursiveVisitor.prototype.visitBoundAttribute = function (attribute) { };
3973 RecursiveVisitor.prototype.visitBoundEvent = function (attribute) { };
3974 RecursiveVisitor.prototype.visitText = function (text) { };
3975 RecursiveVisitor.prototype.visitBoundText = function (text) { };
3976 RecursiveVisitor.prototype.visitIcu = function (icu) { };
3977 return RecursiveVisitor;
3978}());
3979var TransformVisitor = /** @class */ (function () {
3980 function TransformVisitor() {
3981 }
3982 TransformVisitor.prototype.visitElement = function (element) {
3983 var newAttributes = transformAll(this, element.attributes);
3984 var newInputs = transformAll(this, element.inputs);
3985 var newOutputs = transformAll(this, element.outputs);
3986 var newChildren = transformAll(this, element.children);
3987 var newReferences = transformAll(this, element.references);
3988 if (newAttributes != element.attributes || newInputs != element.inputs ||
3989 newOutputs != element.outputs || newChildren != element.children ||
3990 newReferences != element.references) {
3991 return new Element(element.name, newAttributes, newInputs, newOutputs, newChildren, newReferences, element.sourceSpan, element.startSourceSpan, element.endSourceSpan);
3992 }
3993 return element;
3994 };
3995 TransformVisitor.prototype.visitTemplate = function (template) {
3996 var newAttributes = transformAll(this, template.attributes);
3997 var newInputs = transformAll(this, template.inputs);
3998 var newOutputs = transformAll(this, template.outputs);
3999 var newTemplateAttrs = transformAll(this, template.templateAttrs);
4000 var newChildren = transformAll(this, template.children);
4001 var newReferences = transformAll(this, template.references);
4002 var newVariables = transformAll(this, template.variables);
4003 if (newAttributes != template.attributes || newInputs != template.inputs ||
4004 newOutputs != template.outputs || newTemplateAttrs != template.templateAttrs ||
4005 newChildren != template.children || newReferences != template.references ||
4006 newVariables != template.variables) {
4007 return new Template(template.tagName, newAttributes, newInputs, newOutputs, newTemplateAttrs, newChildren, newReferences, newVariables, template.sourceSpan, template.startSourceSpan, template.endSourceSpan);
4008 }
4009 return template;
4010 };
4011 TransformVisitor.prototype.visitContent = function (content) { return content; };
4012 TransformVisitor.prototype.visitVariable = function (variable) { return variable; };
4013 TransformVisitor.prototype.visitReference = function (reference) { return reference; };
4014 TransformVisitor.prototype.visitTextAttribute = function (attribute) { return attribute; };
4015 TransformVisitor.prototype.visitBoundAttribute = function (attribute) { return attribute; };
4016 TransformVisitor.prototype.visitBoundEvent = function (attribute) { return attribute; };
4017 TransformVisitor.prototype.visitText = function (text) { return text; };
4018 TransformVisitor.prototype.visitBoundText = function (text) { return text; };
4019 TransformVisitor.prototype.visitIcu = function (icu) { return icu; };
4020 return TransformVisitor;
4021}());
4022function visitAll(visitor, nodes) {
4023 var e_1, _a, e_2, _b;
4024 var result = [];
4025 if (visitor.visit) {
4026 try {
4027 for (var nodes_1 = __values(nodes), nodes_1_1 = nodes_1.next(); !nodes_1_1.done; nodes_1_1 = nodes_1.next()) {
4028 var node = nodes_1_1.value;
4029 var newNode = visitor.visit(node) || node.visit(visitor);
4030 }
4031 }
4032 catch (e_1_1) { e_1 = { error: e_1_1 }; }
4033 finally {
4034 try {
4035 if (nodes_1_1 && !nodes_1_1.done && (_a = nodes_1.return)) _a.call(nodes_1);
4036 }
4037 finally { if (e_1) throw e_1.error; }
4038 }
4039 }
4040 else {
4041 try {
4042 for (var nodes_2 = __values(nodes), nodes_2_1 = nodes_2.next(); !nodes_2_1.done; nodes_2_1 = nodes_2.next()) {
4043 var node = nodes_2_1.value;
4044 var newNode = node.visit(visitor);
4045 if (newNode) {
4046 result.push(newNode);
4047 }
4048 }
4049 }
4050 catch (e_2_1) { e_2 = { error: e_2_1 }; }
4051 finally {
4052 try {
4053 if (nodes_2_1 && !nodes_2_1.done && (_b = nodes_2.return)) _b.call(nodes_2);
4054 }
4055 finally { if (e_2) throw e_2.error; }
4056 }
4057 }
4058 return result;
4059}
4060function transformAll(visitor, nodes) {
4061 var e_3, _a;
4062 var result = [];
4063 var changed = false;
4064 try {
4065 for (var nodes_3 = __values(nodes), nodes_3_1 = nodes_3.next(); !nodes_3_1.done; nodes_3_1 = nodes_3.next()) {
4066 var node = nodes_3_1.value;
4067 var newNode = node.visit(visitor);
4068 if (newNode) {
4069 result.push(newNode);
4070 }
4071 changed = changed || newNode != node;
4072 }
4073 }
4074 catch (e_3_1) { e_3 = { error: e_3_1 }; }
4075 finally {
4076 try {
4077 if (nodes_3_1 && !nodes_3_1.done && (_a = nodes_3.return)) _a.call(nodes_3);
4078 }
4079 finally { if (e_3) throw e_3.error; }
4080 }
4081 return changed ? result : nodes;
4082}
4083
4084/**
4085 * @license
4086 * Copyright Google Inc. All Rights Reserved.
4087 *
4088 * Use of this source code is governed by an MIT-style license that can be
4089 * found in the LICENSE file at https://angular.io/license
4090 */
4091var Message = /** @class */ (function () {
4092 /**
4093 * @param nodes message AST
4094 * @param placeholders maps placeholder names to static content
4095 * @param placeholderToMessage maps placeholder names to messages (used for nested ICU messages)
4096 * @param meaning
4097 * @param description
4098 * @param id
4099 */
4100 function Message(nodes, placeholders, placeholderToMessage, meaning, description, id) {
4101 this.nodes = nodes;
4102 this.placeholders = placeholders;
4103 this.placeholderToMessage = placeholderToMessage;
4104 this.meaning = meaning;
4105 this.description = description;
4106 this.id = id;
4107 if (nodes.length) {
4108 this.sources = [{
4109 filePath: nodes[0].sourceSpan.start.file.url,
4110 startLine: nodes[0].sourceSpan.start.line + 1,
4111 startCol: nodes[0].sourceSpan.start.col + 1,
4112 endLine: nodes[nodes.length - 1].sourceSpan.end.line + 1,
4113 endCol: nodes[0].sourceSpan.start.col + 1
4114 }];
4115 }
4116 else {
4117 this.sources = [];
4118 }
4119 }
4120 return Message;
4121}());
4122var Text$1 = /** @class */ (function () {
4123 function Text(value, sourceSpan) {
4124 this.value = value;
4125 this.sourceSpan = sourceSpan;
4126 }
4127 Text.prototype.visit = function (visitor, context) { return visitor.visitText(this, context); };
4128 return Text;
4129}());
4130// TODO(vicb): do we really need this node (vs an array) ?
4131var Container = /** @class */ (function () {
4132 function Container(children, sourceSpan) {
4133 this.children = children;
4134 this.sourceSpan = sourceSpan;
4135 }
4136 Container.prototype.visit = function (visitor, context) { return visitor.visitContainer(this, context); };
4137 return Container;
4138}());
4139var Icu$1 = /** @class */ (function () {
4140 function Icu(expression, type, cases, sourceSpan) {
4141 this.expression = expression;
4142 this.type = type;
4143 this.cases = cases;
4144 this.sourceSpan = sourceSpan;
4145 }
4146 Icu.prototype.visit = function (visitor, context) { return visitor.visitIcu(this, context); };
4147 return Icu;
4148}());
4149var TagPlaceholder = /** @class */ (function () {
4150 function TagPlaceholder(tag, attrs, startName, closeName, children, isVoid, sourceSpan) {
4151 this.tag = tag;
4152 this.attrs = attrs;
4153 this.startName = startName;
4154 this.closeName = closeName;
4155 this.children = children;
4156 this.isVoid = isVoid;
4157 this.sourceSpan = sourceSpan;
4158 }
4159 TagPlaceholder.prototype.visit = function (visitor, context) { return visitor.visitTagPlaceholder(this, context); };
4160 return TagPlaceholder;
4161}());
4162var Placeholder = /** @class */ (function () {
4163 function Placeholder(value, name, sourceSpan) {
4164 this.value = value;
4165 this.name = name;
4166 this.sourceSpan = sourceSpan;
4167 }
4168 Placeholder.prototype.visit = function (visitor, context) { return visitor.visitPlaceholder(this, context); };
4169 return Placeholder;
4170}());
4171var IcuPlaceholder = /** @class */ (function () {
4172 function IcuPlaceholder(value, name, sourceSpan) {
4173 this.value = value;
4174 this.name = name;
4175 this.sourceSpan = sourceSpan;
4176 }
4177 IcuPlaceholder.prototype.visit = function (visitor, context) { return visitor.visitIcuPlaceholder(this, context); };
4178 return IcuPlaceholder;
4179}());
4180// Clone the AST
4181var CloneVisitor = /** @class */ (function () {
4182 function CloneVisitor() {
4183 }
4184 CloneVisitor.prototype.visitText = function (text, context) { return new Text$1(text.value, text.sourceSpan); };
4185 CloneVisitor.prototype.visitContainer = function (container, context) {
4186 var _this = this;
4187 var children = container.children.map(function (n) { return n.visit(_this, context); });
4188 return new Container(children, container.sourceSpan);
4189 };
4190 CloneVisitor.prototype.visitIcu = function (icu, context) {
4191 var _this = this;
4192 var cases = {};
4193 Object.keys(icu.cases).forEach(function (key) { return cases[key] = icu.cases[key].visit(_this, context); });
4194 var msg = new Icu$1(icu.expression, icu.type, cases, icu.sourceSpan);
4195 msg.expressionPlaceholder = icu.expressionPlaceholder;
4196 return msg;
4197 };
4198 CloneVisitor.prototype.visitTagPlaceholder = function (ph, context) {
4199 var _this = this;
4200 var children = ph.children.map(function (n) { return n.visit(_this, context); });
4201 return new TagPlaceholder(ph.tag, ph.attrs, ph.startName, ph.closeName, children, ph.isVoid, ph.sourceSpan);
4202 };
4203 CloneVisitor.prototype.visitPlaceholder = function (ph, context) {
4204 return new Placeholder(ph.value, ph.name, ph.sourceSpan);
4205 };
4206 CloneVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
4207 return new IcuPlaceholder(ph.value, ph.name, ph.sourceSpan);
4208 };
4209 return CloneVisitor;
4210}());
4211// Visit all the nodes recursively
4212var RecurseVisitor = /** @class */ (function () {
4213 function RecurseVisitor() {
4214 }
4215 RecurseVisitor.prototype.visitText = function (text, context) { };
4216 RecurseVisitor.prototype.visitContainer = function (container, context) {
4217 var _this = this;
4218 container.children.forEach(function (child) { return child.visit(_this); });
4219 };
4220 RecurseVisitor.prototype.visitIcu = function (icu, context) {
4221 var _this = this;
4222 Object.keys(icu.cases).forEach(function (k) { icu.cases[k].visit(_this); });
4223 };
4224 RecurseVisitor.prototype.visitTagPlaceholder = function (ph, context) {
4225 var _this = this;
4226 ph.children.forEach(function (child) { return child.visit(_this); });
4227 };
4228 RecurseVisitor.prototype.visitPlaceholder = function (ph, context) { };
4229 RecurseVisitor.prototype.visitIcuPlaceholder = function (ph, context) { };
4230 return RecurseVisitor;
4231}());
4232
4233/**
4234 * @license
4235 * Copyright Google Inc. All Rights Reserved.
4236 *
4237 * Use of this source code is governed by an MIT-style license that can be
4238 * found in the LICENSE file at https://angular.io/license
4239 */
4240function digest(message) {
4241 return message.id || sha1(serializeNodes(message.nodes).join('') + ("[" + message.meaning + "]"));
4242}
4243function decimalDigest(message) {
4244 if (message.id) {
4245 return message.id;
4246 }
4247 var visitor = new _SerializerIgnoreIcuExpVisitor();
4248 var parts = message.nodes.map(function (a) { return a.visit(visitor, null); });
4249 return computeMsgId(parts.join(''), message.meaning);
4250}
4251/**
4252 * Serialize the i18n ast to something xml-like in order to generate an UID.
4253 *
4254 * The visitor is also used in the i18n parser tests
4255 *
4256 * @internal
4257 */
4258var _SerializerVisitor = /** @class */ (function () {
4259 function _SerializerVisitor() {
4260 }
4261 _SerializerVisitor.prototype.visitText = function (text, context) { return text.value; };
4262 _SerializerVisitor.prototype.visitContainer = function (container, context) {
4263 var _this = this;
4264 return "[" + container.children.map(function (child) { return child.visit(_this); }).join(', ') + "]";
4265 };
4266 _SerializerVisitor.prototype.visitIcu = function (icu, context) {
4267 var _this = this;
4268 var strCases = Object.keys(icu.cases).map(function (k) { return k + " {" + icu.cases[k].visit(_this) + "}"; });
4269 return "{" + icu.expression + ", " + icu.type + ", " + strCases.join(', ') + "}";
4270 };
4271 _SerializerVisitor.prototype.visitTagPlaceholder = function (ph, context) {
4272 var _this = this;
4273 return ph.isVoid ?
4274 "<ph tag name=\"" + ph.startName + "\"/>" :
4275 "<ph tag name=\"" + ph.startName + "\">" + ph.children.map(function (child) { return child.visit(_this); }).join(', ') + "</ph name=\"" + ph.closeName + "\">";
4276 };
4277 _SerializerVisitor.prototype.visitPlaceholder = function (ph, context) {
4278 return ph.value ? "<ph name=\"" + ph.name + "\">" + ph.value + "</ph>" : "<ph name=\"" + ph.name + "\"/>";
4279 };
4280 _SerializerVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
4281 return "<ph icu name=\"" + ph.name + "\">" + ph.value.visit(this) + "</ph>";
4282 };
4283 return _SerializerVisitor;
4284}());
4285var serializerVisitor = new _SerializerVisitor();
4286function serializeNodes(nodes) {
4287 return nodes.map(function (a) { return a.visit(serializerVisitor, null); });
4288}
4289/**
4290 * Serialize the i18n ast to something xml-like in order to generate an UID.
4291 *
4292 * Ignore the ICU expressions so that message IDs stays identical if only the expression changes.
4293 *
4294 * @internal
4295 */
4296var _SerializerIgnoreIcuExpVisitor = /** @class */ (function (_super) {
4297 __extends(_SerializerIgnoreIcuExpVisitor, _super);
4298 function _SerializerIgnoreIcuExpVisitor() {
4299 return _super !== null && _super.apply(this, arguments) || this;
4300 }
4301 _SerializerIgnoreIcuExpVisitor.prototype.visitIcu = function (icu, context) {
4302 var _this = this;
4303 var strCases = Object.keys(icu.cases).map(function (k) { return k + " {" + icu.cases[k].visit(_this) + "}"; });
4304 // Do not take the expression into account
4305 return "{" + icu.type + ", " + strCases.join(', ') + "}";
4306 };
4307 return _SerializerIgnoreIcuExpVisitor;
4308}(_SerializerVisitor));
4309/**
4310 * Compute the SHA1 of the given string
4311 *
4312 * see http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf
4313 *
4314 * WARNING: this function has not been designed not tested with security in mind.
4315 * DO NOT USE IT IN A SECURITY SENSITIVE CONTEXT.
4316 */
4317function sha1(str) {
4318 var _a, _b;
4319 var utf8 = utf8Encode(str);
4320 var words32 = stringToWords32(utf8, Endian.Big);
4321 var len = utf8.length * 8;
4322 var w = new Array(80);
4323 var _c = __read([0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0], 5), a = _c[0], b = _c[1], c = _c[2], d = _c[3], e = _c[4];
4324 words32[len >> 5] |= 0x80 << (24 - len % 32);
4325 words32[((len + 64 >> 9) << 4) + 15] = len;
4326 for (var i = 0; i < words32.length; i += 16) {
4327 var _d = __read([a, b, c, d, e], 5), h0 = _d[0], h1 = _d[1], h2 = _d[2], h3 = _d[3], h4 = _d[4];
4328 for (var j = 0; j < 80; j++) {
4329 if (j < 16) {
4330 w[j] = words32[i + j];
4331 }
4332 else {
4333 w[j] = rol32(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
4334 }
4335 var _e = __read(fk(j, b, c, d), 2), f = _e[0], k = _e[1];
4336 var temp = [rol32(a, 5), f, e, k, w[j]].reduce(add32);
4337 _a = __read([d, c, rol32(b, 30), a, temp], 5), e = _a[0], d = _a[1], c = _a[2], b = _a[3], a = _a[4];
4338 }
4339 _b = __read([add32(a, h0), add32(b, h1), add32(c, h2), add32(d, h3), add32(e, h4)], 5), a = _b[0], b = _b[1], c = _b[2], d = _b[3], e = _b[4];
4340 }
4341 return byteStringToHexString(words32ToByteString([a, b, c, d, e]));
4342}
4343function fk(index, b, c, d) {
4344 if (index < 20) {
4345 return [(b & c) | (~b & d), 0x5a827999];
4346 }
4347 if (index < 40) {
4348 return [b ^ c ^ d, 0x6ed9eba1];
4349 }
4350 if (index < 60) {
4351 return [(b & c) | (b & d) | (c & d), 0x8f1bbcdc];
4352 }
4353 return [b ^ c ^ d, 0xca62c1d6];
4354}
4355/**
4356 * Compute the fingerprint of the given string
4357 *
4358 * The output is 64 bit number encoded as a decimal string
4359 *
4360 * based on:
4361 * https://github.com/google/closure-compiler/blob/master/src/com/google/javascript/jscomp/GoogleJsMessageIdGenerator.java
4362 */
4363function fingerprint(str) {
4364 var utf8 = utf8Encode(str);
4365 var _a = __read([hash32(utf8, 0), hash32(utf8, 102072)], 2), hi = _a[0], lo = _a[1];
4366 if (hi == 0 && (lo == 0 || lo == 1)) {
4367 hi = hi ^ 0x130f9bef;
4368 lo = lo ^ -0x6b5f56d8;
4369 }
4370 return [hi, lo];
4371}
4372function computeMsgId(msg, meaning) {
4373 var _a;
4374 var _b = __read(fingerprint(msg), 2), hi = _b[0], lo = _b[1];
4375 if (meaning) {
4376 var _c = __read(fingerprint(meaning), 2), him = _c[0], lom = _c[1];
4377 _a = __read(add64(rol64([hi, lo], 1), [him, lom]), 2), hi = _a[0], lo = _a[1];
4378 }
4379 return byteStringToDecString(words32ToByteString([hi & 0x7fffffff, lo]));
4380}
4381function hash32(str, c) {
4382 var _a;
4383 var _b = __read([0x9e3779b9, 0x9e3779b9], 2), a = _b[0], b = _b[1];
4384 var i;
4385 var len = str.length;
4386 for (i = 0; i + 12 <= len; i += 12) {
4387 a = add32(a, wordAt(str, i, Endian.Little));
4388 b = add32(b, wordAt(str, i + 4, Endian.Little));
4389 c = add32(c, wordAt(str, i + 8, Endian.Little));
4390 _a = __read(mix([a, b, c]), 3), a = _a[0], b = _a[1], c = _a[2];
4391 }
4392 a = add32(a, wordAt(str, i, Endian.Little));
4393 b = add32(b, wordAt(str, i + 4, Endian.Little));
4394 // the first byte of c is reserved for the length
4395 c = add32(c, len);
4396 c = add32(c, wordAt(str, i + 8, Endian.Little) << 8);
4397 return mix([a, b, c])[2];
4398}
4399// clang-format off
4400function mix(_a) {
4401 var _b = __read(_a, 3), a = _b[0], b = _b[1], c = _b[2];
4402 a = sub32(a, b);
4403 a = sub32(a, c);
4404 a ^= c >>> 13;
4405 b = sub32(b, c);
4406 b = sub32(b, a);
4407 b ^= a << 8;
4408 c = sub32(c, a);
4409 c = sub32(c, b);
4410 c ^= b >>> 13;
4411 a = sub32(a, b);
4412 a = sub32(a, c);
4413 a ^= c >>> 12;
4414 b = sub32(b, c);
4415 b = sub32(b, a);
4416 b ^= a << 16;
4417 c = sub32(c, a);
4418 c = sub32(c, b);
4419 c ^= b >>> 5;
4420 a = sub32(a, b);
4421 a = sub32(a, c);
4422 a ^= c >>> 3;
4423 b = sub32(b, c);
4424 b = sub32(b, a);
4425 b ^= a << 10;
4426 c = sub32(c, a);
4427 c = sub32(c, b);
4428 c ^= b >>> 15;
4429 return [a, b, c];
4430}
4431// clang-format on
4432// Utils
4433var Endian;
4434(function (Endian) {
4435 Endian[Endian["Little"] = 0] = "Little";
4436 Endian[Endian["Big"] = 1] = "Big";
4437})(Endian || (Endian = {}));
4438function add32(a, b) {
4439 return add32to64(a, b)[1];
4440}
4441function add32to64(a, b) {
4442 var low = (a & 0xffff) + (b & 0xffff);
4443 var high = (a >>> 16) + (b >>> 16) + (low >>> 16);
4444 return [high >>> 16, (high << 16) | (low & 0xffff)];
4445}
4446function add64(_a, _b) {
4447 var _c = __read(_a, 2), ah = _c[0], al = _c[1];
4448 var _d = __read(_b, 2), bh = _d[0], bl = _d[1];
4449 var _e = __read(add32to64(al, bl), 2), carry = _e[0], l = _e[1];
4450 var h = add32(add32(ah, bh), carry);
4451 return [h, l];
4452}
4453function sub32(a, b) {
4454 var low = (a & 0xffff) - (b & 0xffff);
4455 var high = (a >> 16) - (b >> 16) + (low >> 16);
4456 return (high << 16) | (low & 0xffff);
4457}
4458// Rotate a 32b number left `count` position
4459function rol32(a, count) {
4460 return (a << count) | (a >>> (32 - count));
4461}
4462// Rotate a 64b number left `count` position
4463function rol64(_a, count) {
4464 var _b = __read(_a, 2), hi = _b[0], lo = _b[1];
4465 var h = (hi << count) | (lo >>> (32 - count));
4466 var l = (lo << count) | (hi >>> (32 - count));
4467 return [h, l];
4468}
4469function stringToWords32(str, endian) {
4470 var words32 = Array((str.length + 3) >>> 2);
4471 for (var i = 0; i < words32.length; i++) {
4472 words32[i] = wordAt(str, i * 4, endian);
4473 }
4474 return words32;
4475}
4476function byteAt(str, index) {
4477 return index >= str.length ? 0 : str.charCodeAt(index) & 0xff;
4478}
4479function wordAt(str, index, endian) {
4480 var word = 0;
4481 if (endian === Endian.Big) {
4482 for (var i = 0; i < 4; i++) {
4483 word += byteAt(str, index + i) << (24 - 8 * i);
4484 }
4485 }
4486 else {
4487 for (var i = 0; i < 4; i++) {
4488 word += byteAt(str, index + i) << 8 * i;
4489 }
4490 }
4491 return word;
4492}
4493function words32ToByteString(words32) {
4494 return words32.reduce(function (str, word) { return str + word32ToByteString(word); }, '');
4495}
4496function word32ToByteString(word) {
4497 var str = '';
4498 for (var i = 0; i < 4; i++) {
4499 str += String.fromCharCode((word >>> 8 * (3 - i)) & 0xff);
4500 }
4501 return str;
4502}
4503function byteStringToHexString(str) {
4504 var hex = '';
4505 for (var i = 0; i < str.length; i++) {
4506 var b = byteAt(str, i);
4507 hex += (b >>> 4).toString(16) + (b & 0x0f).toString(16);
4508 }
4509 return hex.toLowerCase();
4510}
4511// based on http://www.danvk.org/hex2dec.html (JS can not handle more than 56b)
4512function byteStringToDecString(str) {
4513 var decimal = '';
4514 var toThePower = '1';
4515 for (var i = str.length - 1; i >= 0; i--) {
4516 decimal = addBigInt(decimal, numberTimesBigInt(byteAt(str, i), toThePower));
4517 toThePower = numberTimesBigInt(256, toThePower);
4518 }
4519 return decimal.split('').reverse().join('');
4520}
4521// x and y decimal, lowest significant digit first
4522function addBigInt(x, y) {
4523 var sum = '';
4524 var len = Math.max(x.length, y.length);
4525 for (var i = 0, carry = 0; i < len || carry; i++) {
4526 var tmpSum = carry + +(x[i] || 0) + +(y[i] || 0);
4527 if (tmpSum >= 10) {
4528 carry = 1;
4529 sum += tmpSum - 10;
4530 }
4531 else {
4532 carry = 0;
4533 sum += tmpSum;
4534 }
4535 }
4536 return sum;
4537}
4538function numberTimesBigInt(num, b) {
4539 var product = '';
4540 var bToThePower = b;
4541 for (; num !== 0; num = num >>> 1) {
4542 if (num & 1)
4543 product = addBigInt(product, bToThePower);
4544 bToThePower = addBigInt(bToThePower, bToThePower);
4545 }
4546 return product;
4547}
4548
4549/**
4550 * @license
4551 * Copyright Google Inc. All Rights Reserved.
4552 *
4553 * Use of this source code is governed by an MIT-style license that can be
4554 * found in the LICENSE file at https://angular.io/license
4555 */
4556var Serializer = /** @class */ (function () {
4557 function Serializer() {
4558 }
4559 // Creates a name mapper, see `PlaceholderMapper`
4560 // Returning `null` means that no name mapping is used.
4561 Serializer.prototype.createNameMapper = function (message) { return null; };
4562 return Serializer;
4563}());
4564/**
4565 * A simple mapper that take a function to transform an internal name to a public name
4566 */
4567var SimplePlaceholderMapper = /** @class */ (function (_super) {
4568 __extends(SimplePlaceholderMapper, _super);
4569 // create a mapping from the message
4570 function SimplePlaceholderMapper(message, mapName) {
4571 var _this = _super.call(this) || this;
4572 _this.mapName = mapName;
4573 _this.internalToPublic = {};
4574 _this.publicToNextId = {};
4575 _this.publicToInternal = {};
4576 message.nodes.forEach(function (node) { return node.visit(_this); });
4577 return _this;
4578 }
4579 SimplePlaceholderMapper.prototype.toPublicName = function (internalName) {
4580 return this.internalToPublic.hasOwnProperty(internalName) ?
4581 this.internalToPublic[internalName] :
4582 null;
4583 };
4584 SimplePlaceholderMapper.prototype.toInternalName = function (publicName) {
4585 return this.publicToInternal.hasOwnProperty(publicName) ? this.publicToInternal[publicName] :
4586 null;
4587 };
4588 SimplePlaceholderMapper.prototype.visitText = function (text, context) { return null; };
4589 SimplePlaceholderMapper.prototype.visitTagPlaceholder = function (ph, context) {
4590 this.visitPlaceholderName(ph.startName);
4591 _super.prototype.visitTagPlaceholder.call(this, ph, context);
4592 this.visitPlaceholderName(ph.closeName);
4593 };
4594 SimplePlaceholderMapper.prototype.visitPlaceholder = function (ph, context) { this.visitPlaceholderName(ph.name); };
4595 SimplePlaceholderMapper.prototype.visitIcuPlaceholder = function (ph, context) {
4596 this.visitPlaceholderName(ph.name);
4597 };
4598 // XMB placeholders could only contains A-Z, 0-9 and _
4599 SimplePlaceholderMapper.prototype.visitPlaceholderName = function (internalName) {
4600 if (!internalName || this.internalToPublic.hasOwnProperty(internalName)) {
4601 return;
4602 }
4603 var publicName = this.mapName(internalName);
4604 if (this.publicToInternal.hasOwnProperty(publicName)) {
4605 // Create a new XMB when it has already been used
4606 var nextId = this.publicToNextId[publicName];
4607 this.publicToNextId[publicName] = nextId + 1;
4608 publicName = publicName + "_" + nextId;
4609 }
4610 else {
4611 this.publicToNextId[publicName] = 1;
4612 }
4613 this.internalToPublic[internalName] = publicName;
4614 this.publicToInternal[publicName] = internalName;
4615 };
4616 return SimplePlaceholderMapper;
4617}(RecurseVisitor));
4618
4619/**
4620 * @license
4621 * Copyright Google Inc. All Rights Reserved.
4622 *
4623 * Use of this source code is governed by an MIT-style license that can be
4624 * found in the LICENSE file at https://angular.io/license
4625 */
4626var _Visitor = /** @class */ (function () {
4627 function _Visitor() {
4628 }
4629 _Visitor.prototype.visitTag = function (tag) {
4630 var _this = this;
4631 var strAttrs = this._serializeAttributes(tag.attrs);
4632 if (tag.children.length == 0) {
4633 return "<" + tag.name + strAttrs + "/>";
4634 }
4635 var strChildren = tag.children.map(function (node) { return node.visit(_this); });
4636 return "<" + tag.name + strAttrs + ">" + strChildren.join('') + "</" + tag.name + ">";
4637 };
4638 _Visitor.prototype.visitText = function (text) { return text.value; };
4639 _Visitor.prototype.visitDeclaration = function (decl) {
4640 return "<?xml" + this._serializeAttributes(decl.attrs) + " ?>";
4641 };
4642 _Visitor.prototype._serializeAttributes = function (attrs) {
4643 var strAttrs = Object.keys(attrs).map(function (name) { return name + "=\"" + attrs[name] + "\""; }).join(' ');
4644 return strAttrs.length > 0 ? ' ' + strAttrs : '';
4645 };
4646 _Visitor.prototype.visitDoctype = function (doctype) {
4647 return "<!DOCTYPE " + doctype.rootTag + " [\n" + doctype.dtd + "\n]>";
4648 };
4649 return _Visitor;
4650}());
4651var _visitor = new _Visitor();
4652function serialize(nodes) {
4653 return nodes.map(function (node) { return node.visit(_visitor); }).join('');
4654}
4655var Declaration = /** @class */ (function () {
4656 function Declaration(unescapedAttrs) {
4657 var _this = this;
4658 this.attrs = {};
4659 Object.keys(unescapedAttrs).forEach(function (k) {
4660 _this.attrs[k] = escapeXml(unescapedAttrs[k]);
4661 });
4662 }
4663 Declaration.prototype.visit = function (visitor) { return visitor.visitDeclaration(this); };
4664 return Declaration;
4665}());
4666var Doctype = /** @class */ (function () {
4667 function Doctype(rootTag, dtd) {
4668 this.rootTag = rootTag;
4669 this.dtd = dtd;
4670 }
4671 Doctype.prototype.visit = function (visitor) { return visitor.visitDoctype(this); };
4672 return Doctype;
4673}());
4674var Tag = /** @class */ (function () {
4675 function Tag(name, unescapedAttrs, children) {
4676 var _this = this;
4677 if (unescapedAttrs === void 0) { unescapedAttrs = {}; }
4678 if (children === void 0) { children = []; }
4679 this.name = name;
4680 this.children = children;
4681 this.attrs = {};
4682 Object.keys(unescapedAttrs).forEach(function (k) {
4683 _this.attrs[k] = escapeXml(unescapedAttrs[k]);
4684 });
4685 }
4686 Tag.prototype.visit = function (visitor) { return visitor.visitTag(this); };
4687 return Tag;
4688}());
4689var Text$2 = /** @class */ (function () {
4690 function Text(unescapedValue) {
4691 this.value = escapeXml(unescapedValue);
4692 }
4693 Text.prototype.visit = function (visitor) { return visitor.visitText(this); };
4694 return Text;
4695}());
4696var CR = /** @class */ (function (_super) {
4697 __extends(CR, _super);
4698 function CR(ws) {
4699 if (ws === void 0) { ws = 0; }
4700 return _super.call(this, "\n" + new Array(ws + 1).join(' ')) || this;
4701 }
4702 return CR;
4703}(Text$2));
4704var _ESCAPED_CHARS = [
4705 [/&/g, '&amp;'],
4706 [/"/g, '&quot;'],
4707 [/'/g, '&apos;'],
4708 [/</g, '&lt;'],
4709 [/>/g, '&gt;'],
4710];
4711// Escape `_ESCAPED_CHARS` characters in the given text with encoded entities
4712function escapeXml(text) {
4713 return _ESCAPED_CHARS.reduce(function (text, entry) { return text.replace(entry[0], entry[1]); }, text);
4714}
4715
4716/**
4717 * @license
4718 * Copyright Google Inc. All Rights Reserved.
4719 *
4720 * Use of this source code is governed by an MIT-style license that can be
4721 * found in the LICENSE file at https://angular.io/license
4722 */
4723var _MESSAGES_TAG = 'messagebundle';
4724var _MESSAGE_TAG = 'msg';
4725var _PLACEHOLDER_TAG = 'ph';
4726var _EXAMPLE_TAG = 'ex';
4727var _SOURCE_TAG = 'source';
4728var _DOCTYPE = "<!ELEMENT messagebundle (msg)*>\n<!ATTLIST messagebundle class CDATA #IMPLIED>\n\n<!ELEMENT msg (#PCDATA|ph|source)*>\n<!ATTLIST msg id CDATA #IMPLIED>\n<!ATTLIST msg seq CDATA #IMPLIED>\n<!ATTLIST msg name CDATA #IMPLIED>\n<!ATTLIST msg desc CDATA #IMPLIED>\n<!ATTLIST msg meaning CDATA #IMPLIED>\n<!ATTLIST msg obsolete (obsolete) #IMPLIED>\n<!ATTLIST msg xml:space (default|preserve) \"default\">\n<!ATTLIST msg is_hidden CDATA #IMPLIED>\n\n<!ELEMENT source (#PCDATA)>\n\n<!ELEMENT ph (#PCDATA|ex)*>\n<!ATTLIST ph name CDATA #REQUIRED>\n\n<!ELEMENT ex (#PCDATA)>";
4729var Xmb = /** @class */ (function (_super) {
4730 __extends(Xmb, _super);
4731 function Xmb() {
4732 return _super !== null && _super.apply(this, arguments) || this;
4733 }
4734 Xmb.prototype.write = function (messages, locale) {
4735 var exampleVisitor = new ExampleVisitor();
4736 var visitor = new _Visitor$1();
4737 var rootNode = new Tag(_MESSAGES_TAG);
4738 messages.forEach(function (message) {
4739 var attrs = { id: message.id };
4740 if (message.description) {
4741 attrs['desc'] = message.description;
4742 }
4743 if (message.meaning) {
4744 attrs['meaning'] = message.meaning;
4745 }
4746 var sourceTags = [];
4747 message.sources.forEach(function (source) {
4748 sourceTags.push(new Tag(_SOURCE_TAG, {}, [
4749 new Text$2(source.filePath + ":" + source.startLine + (source.endLine !== source.startLine ? ',' + source.endLine : ''))
4750 ]));
4751 });
4752 rootNode.children.push(new CR(2), new Tag(_MESSAGE_TAG, attrs, __spread(sourceTags, visitor.serialize(message.nodes))));
4753 });
4754 rootNode.children.push(new CR());
4755 return serialize([
4756 new Declaration({ version: '1.0', encoding: 'UTF-8' }),
4757 new CR(),
4758 new Doctype(_MESSAGES_TAG, _DOCTYPE),
4759 new CR(),
4760 exampleVisitor.addDefaultExamples(rootNode),
4761 new CR(),
4762 ]);
4763 };
4764 Xmb.prototype.load = function (content, url) {
4765 throw new Error('Unsupported');
4766 };
4767 Xmb.prototype.digest = function (message) { return digest$1(message); };
4768 Xmb.prototype.createNameMapper = function (message) {
4769 return new SimplePlaceholderMapper(message, toPublicName);
4770 };
4771 return Xmb;
4772}(Serializer));
4773var _Visitor$1 = /** @class */ (function () {
4774 function _Visitor() {
4775 }
4776 _Visitor.prototype.visitText = function (text, context) { return [new Text$2(text.value)]; };
4777 _Visitor.prototype.visitContainer = function (container, context) {
4778 var _this = this;
4779 var nodes = [];
4780 container.children.forEach(function (node) { return nodes.push.apply(nodes, __spread(node.visit(_this))); });
4781 return nodes;
4782 };
4783 _Visitor.prototype.visitIcu = function (icu, context) {
4784 var _this = this;
4785 var nodes = [new Text$2("{" + icu.expressionPlaceholder + ", " + icu.type + ", ")];
4786 Object.keys(icu.cases).forEach(function (c) {
4787 nodes.push.apply(nodes, __spread([new Text$2(c + " {")], icu.cases[c].visit(_this), [new Text$2("} ")]));
4788 });
4789 nodes.push(new Text$2("}"));
4790 return nodes;
4791 };
4792 _Visitor.prototype.visitTagPlaceholder = function (ph, context) {
4793 var startTagAsText = new Text$2("<" + ph.tag + ">");
4794 var startEx = new Tag(_EXAMPLE_TAG, {}, [startTagAsText]);
4795 // TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
4796 var startTagPh = new Tag(_PLACEHOLDER_TAG, { name: ph.startName }, [startEx, startTagAsText]);
4797 if (ph.isVoid) {
4798 // void tags have no children nor closing tags
4799 return [startTagPh];
4800 }
4801 var closeTagAsText = new Text$2("</" + ph.tag + ">");
4802 var closeEx = new Tag(_EXAMPLE_TAG, {}, [closeTagAsText]);
4803 // TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
4804 var closeTagPh = new Tag(_PLACEHOLDER_TAG, { name: ph.closeName }, [closeEx, closeTagAsText]);
4805 return __spread([startTagPh], this.serialize(ph.children), [closeTagPh]);
4806 };
4807 _Visitor.prototype.visitPlaceholder = function (ph, context) {
4808 var interpolationAsText = new Text$2("{{" + ph.value + "}}");
4809 // Example tag needs to be not-empty for TC.
4810 var exTag = new Tag(_EXAMPLE_TAG, {}, [interpolationAsText]);
4811 return [
4812 // TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
4813 new Tag(_PLACEHOLDER_TAG, { name: ph.name }, [exTag, interpolationAsText])
4814 ];
4815 };
4816 _Visitor.prototype.visitIcuPlaceholder = function (ph, context) {
4817 var icuExpression = ph.value.expression;
4818 var icuType = ph.value.type;
4819 var icuCases = Object.keys(ph.value.cases).map(function (value) { return value + ' {...}'; }).join(' ');
4820 var icuAsText = new Text$2("{" + icuExpression + ", " + icuType + ", " + icuCases + "}");
4821 var exTag = new Tag(_EXAMPLE_TAG, {}, [icuAsText]);
4822 return [
4823 // TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
4824 new Tag(_PLACEHOLDER_TAG, { name: ph.name }, [exTag, icuAsText])
4825 ];
4826 };
4827 _Visitor.prototype.serialize = function (nodes) {
4828 var _this = this;
4829 return [].concat.apply([], __spread(nodes.map(function (node) { return node.visit(_this); })));
4830 };
4831 return _Visitor;
4832}());
4833function digest$1(message) {
4834 return decimalDigest(message);
4835}
4836// TC requires at least one non-empty example on placeholders
4837var ExampleVisitor = /** @class */ (function () {
4838 function ExampleVisitor() {
4839 }
4840 ExampleVisitor.prototype.addDefaultExamples = function (node) {
4841 node.visit(this);
4842 return node;
4843 };
4844 ExampleVisitor.prototype.visitTag = function (tag) {
4845 var _this = this;
4846 if (tag.name === _PLACEHOLDER_TAG) {
4847 if (!tag.children || tag.children.length == 0) {
4848 var exText = new Text$2(tag.attrs['name'] || '...');
4849 tag.children = [new Tag(_EXAMPLE_TAG, {}, [exText])];
4850 }
4851 }
4852 else if (tag.children) {
4853 tag.children.forEach(function (node) { return node.visit(_this); });
4854 }
4855 };
4856 ExampleVisitor.prototype.visitText = function (text) { };
4857 ExampleVisitor.prototype.visitDeclaration = function (decl) { };
4858 ExampleVisitor.prototype.visitDoctype = function (doctype) { };
4859 return ExampleVisitor;
4860}());
4861// XMB/XTB placeholders can only contain A-Z, 0-9 and _
4862function toPublicName(internalName) {
4863 return internalName.toUpperCase().replace(/[^A-Z0-9_]/g, '_');
4864}
4865
4866/**
4867 * @license
4868 * Copyright Google Inc. All Rights Reserved.
4869 *
4870 * Use of this source code is governed by an MIT-style license that can be
4871 * found in the LICENSE file at https://angular.io/license
4872 */
4873function mapEntry(key, value) {
4874 return { key: key, value: value, quoted: false };
4875}
4876function mapLiteral(obj, quoted) {
4877 if (quoted === void 0) { quoted = false; }
4878 return literalMap(Object.keys(obj).map(function (key) { return ({
4879 key: key,
4880 quoted: quoted,
4881 value: obj[key],
4882 }); }));
4883}
4884
4885/**
4886 * @license
4887 * Copyright Google Inc. All Rights Reserved.
4888 *
4889 * Use of this source code is governed by an MIT-style license that can be
4890 * found in the LICENSE file at https://angular.io/license
4891 */
4892/* Closure variables holding messages must be named `MSG_[A-Z0-9]+` */
4893var CLOSURE_TRANSLATION_PREFIX = 'MSG_';
4894/* Prefix for non-`goog.getMsg` i18n-related vars */
4895var TRANSLATION_PREFIX = 'I18N_';
4896/** Closure uses `goog.getMsg(message)` to lookup translations */
4897var GOOG_GET_MSG = 'goog.getMsg';
4898/** Name of the global variable that is used to determine if we use Closure translations or not */
4899var NG_I18N_CLOSURE_MODE = 'ngI18nClosureMode';
4900/** I18n separators for metadata **/
4901var I18N_MEANING_SEPARATOR = '|';
4902var I18N_ID_SEPARATOR = '@@';
4903/** Name of the i18n attributes **/
4904var I18N_ATTR = 'i18n';
4905var I18N_ATTR_PREFIX = 'i18n-';
4906/** Prefix of var expressions used in ICUs */
4907var I18N_ICU_VAR_PREFIX = 'VAR_';
4908/** Prefix of ICU expressions for post processing */
4909var I18N_ICU_MAPPING_PREFIX = 'I18N_EXP_';
4910/** Placeholder wrapper for i18n expressions **/
4911var I18N_PLACEHOLDER_SYMBOL = '�';
4912function i18nTranslationToDeclStmt(variable$1, closureVar, message, meta, params) {
4913 var statements = [];
4914 // var I18N_X;
4915 statements.push(new DeclareVarStmt(variable$1.name, undefined, INFERRED_TYPE, null, variable$1.sourceSpan));
4916 var args = [literal(message)];
4917 if (params && Object.keys(params).length) {
4918 args.push(mapLiteral(params, true));
4919 }
4920 // Closure JSDoc comments
4921 var docStatements = i18nMetaToDocStmt(meta);
4922 var thenStatements = docStatements ? [docStatements] : [];
4923 var googFnCall = variable(GOOG_GET_MSG).callFn(args);
4924 // const MSG_... = goog.getMsg(..);
4925 thenStatements.push(closureVar.set(googFnCall).toConstDecl());
4926 // I18N_X = MSG_...;
4927 thenStatements.push(new ExpressionStatement(variable$1.set(closureVar)));
4928 var localizeFnCall = importExpr(Identifiers$1.i18nLocalize).callFn(args);
4929 // I18N_X = i18nLocalize(...);
4930 var elseStatements = [new ExpressionStatement(variable$1.set(localizeFnCall))];
4931 // if(ngI18nClosureMode) { ... } else { ... }
4932 statements.push(ifStmt(variable(NG_I18N_CLOSURE_MODE), thenStatements, elseStatements));
4933 return statements;
4934}
4935// Converts i18n meta information for a message (id, description, meaning)
4936// to a JsDoc statement formatted as expected by the Closure compiler.
4937function i18nMetaToDocStmt(meta) {
4938 var tags = [];
4939 if (meta.description) {
4940 tags.push({ tagName: "desc" /* Desc */, text: meta.description });
4941 }
4942 if (meta.meaning) {
4943 tags.push({ tagName: "meaning" /* Meaning */, text: meta.meaning });
4944 }
4945 return tags.length == 0 ? null : new JSDocCommentStmt(tags);
4946}
4947function isI18nAttribute(name) {
4948 return name === I18N_ATTR || name.startsWith(I18N_ATTR_PREFIX);
4949}
4950function isI18nRootNode(meta) {
4951 return meta instanceof Message;
4952}
4953function isSingleI18nIcu(meta) {
4954 return isI18nRootNode(meta) && meta.nodes.length === 1 && meta.nodes[0] instanceof Icu$1;
4955}
4956function hasI18nAttrs(element) {
4957 return element.attrs.some(function (attr) { return isI18nAttribute(attr.name); });
4958}
4959function metaFromI18nMessage(message, id) {
4960 if (id === void 0) { id = null; }
4961 return {
4962 id: typeof id === 'string' ? id : message.id || '',
4963 meaning: message.meaning || '',
4964 description: message.description || ''
4965 };
4966}
4967function icuFromI18nMessage(message) {
4968 return message.nodes[0];
4969}
4970function wrapI18nPlaceholder(content, contextId) {
4971 if (contextId === void 0) { contextId = 0; }
4972 var blockId = contextId > 0 ? ":" + contextId : '';
4973 return "" + I18N_PLACEHOLDER_SYMBOL + content + blockId + I18N_PLACEHOLDER_SYMBOL;
4974}
4975function assembleI18nBoundString(strings, bindingStartIndex, contextId) {
4976 if (bindingStartIndex === void 0) { bindingStartIndex = 0; }
4977 if (contextId === void 0) { contextId = 0; }
4978 if (!strings.length)
4979 return '';
4980 var acc = '';
4981 var lastIdx = strings.length - 1;
4982 for (var i = 0; i < lastIdx; i++) {
4983 acc += "" + strings[i] + wrapI18nPlaceholder(bindingStartIndex + i, contextId);
4984 }
4985 acc += strings[lastIdx];
4986 return acc;
4987}
4988function getSeqNumberGenerator(startsAt) {
4989 if (startsAt === void 0) { startsAt = 0; }
4990 var current = startsAt;
4991 return function () { return current++; };
4992}
4993function placeholdersToParams(placeholders) {
4994 var params = {};
4995 placeholders.forEach(function (values, key) {
4996 params[key] = literal(values.length > 1 ? "[" + values.join('|') + "]" : values[0]);
4997 });
4998 return params;
4999}
5000function updatePlaceholderMap(map, name) {
5001 var values = [];
5002 for (var _i = 2; _i < arguments.length; _i++) {
5003 values[_i - 2] = arguments[_i];
5004 }
5005 var current = map.get(name) || [];
5006 current.push.apply(current, __spread(values));
5007 map.set(name, current);
5008}
5009function assembleBoundTextPlaceholders(meta, bindingStartIndex, contextId) {
5010 if (bindingStartIndex === void 0) { bindingStartIndex = 0; }
5011 if (contextId === void 0) { contextId = 0; }
5012 var startIdx = bindingStartIndex;
5013 var placeholders = new Map();
5014 var node = meta instanceof Message ? meta.nodes.find(function (node) { return node instanceof Container; }) : meta;
5015 if (node) {
5016 node
5017 .children
5018 .filter(function (child) { return child instanceof Placeholder; })
5019 .forEach(function (child, idx) {
5020 var content = wrapI18nPlaceholder(startIdx + idx, contextId);
5021 updatePlaceholderMap(placeholders, child.name, content);
5022 });
5023 }
5024 return placeholders;
5025}
5026function findIndex(items, callback) {
5027 for (var i = 0; i < items.length; i++) {
5028 if (callback(items[i])) {
5029 return i;
5030 }
5031 }
5032 return -1;
5033}
5034/**
5035 * Parses i18n metas like:
5036 * - "@@id",
5037 * - "description[@@id]",
5038 * - "meaning|description[@@id]"
5039 * and returns an object with parsed output.
5040 *
5041 * @param meta String that represents i18n meta
5042 * @returns Object with id, meaning and description fields
5043 */
5044function parseI18nMeta(meta) {
5045 var _a, _b;
5046 var id;
5047 var meaning;
5048 var description;
5049 if (meta) {
5050 var idIndex = meta.indexOf(I18N_ID_SEPARATOR);
5051 var descIndex = meta.indexOf(I18N_MEANING_SEPARATOR);
5052 var meaningAndDesc = void 0;
5053 _a = __read((idIndex > -1) ? [meta.slice(0, idIndex), meta.slice(idIndex + 2)] : [meta, ''], 2), meaningAndDesc = _a[0], id = _a[1];
5054 _b = __read((descIndex > -1) ?
5055 [meaningAndDesc.slice(0, descIndex), meaningAndDesc.slice(descIndex + 1)] :
5056 ['', meaningAndDesc], 2), meaning = _b[0], description = _b[1];
5057 }
5058 return { id: id, meaning: meaning, description: description };
5059}
5060/**
5061 * Converts internal placeholder names to public-facing format
5062 * (for example to use in goog.getMsg call).
5063 * Example: `START_TAG_DIV_1` is converted to `startTagDiv_1`.
5064 *
5065 * @param name The placeholder name that should be formatted
5066 * @returns Formatted placeholder name
5067 */
5068function formatI18nPlaceholderName(name, useCamelCase) {
5069 if (useCamelCase === void 0) { useCamelCase = true; }
5070 var publicName = toPublicName(name);
5071 if (!useCamelCase) {
5072 return publicName;
5073 }
5074 var chunks = publicName.split('_');
5075 if (chunks.length === 1) {
5076 // if no "_" found - just lowercase the value
5077 return name.toLowerCase();
5078 }
5079 var postfix;
5080 // eject last element if it's a number
5081 if (/^\d+$/.test(chunks[chunks.length - 1])) {
5082 postfix = chunks.pop();
5083 }
5084 var raw = chunks.shift().toLowerCase();
5085 if (chunks.length) {
5086 raw += chunks.map(function (c) { return c.charAt(0).toUpperCase() + c.slice(1).toLowerCase(); }).join('');
5087 }
5088 return postfix ? raw + "_" + postfix : raw;
5089}
5090/**
5091 * Generates a prefix for translation const name.
5092 *
5093 * @param extra Additional local prefix that should be injected into translation var name
5094 * @returns Complete translation const prefix
5095 */
5096function getTranslationConstPrefix(extra) {
5097 return ("" + CLOSURE_TRANSLATION_PREFIX + extra).toUpperCase();
5098}
5099/**
5100 * Generates translation declaration statements.
5101 *
5102 * @param variable Translation value reference
5103 * @param closureVar Variable for Closure `goog.getMsg` calls
5104 * @param message Text message to be translated
5105 * @param meta Object that contains meta information (id, meaning and description)
5106 * @param params Object with placeholders key-value pairs
5107 * @param transformFn Optional transformation (post processing) function reference
5108 * @returns Array of Statements that represent a given translation
5109 */
5110function getTranslationDeclStmts(variable, closureVar, message, meta, params, transformFn) {
5111 if (params === void 0) { params = {}; }
5112 var statements = [];
5113 statements.push.apply(statements, __spread(i18nTranslationToDeclStmt(variable, closureVar, message, meta, params)));
5114 if (transformFn) {
5115 statements.push(new ExpressionStatement(variable.set(transformFn(variable))));
5116 }
5117 return statements;
5118}
5119
5120/**
5121 * @license
5122 * Copyright Google Inc. All Rights Reserved.
5123 *
5124 * Use of this source code is governed by an MIT-style license that can be
5125 * found in the LICENSE file at https://angular.io/license
5126 */
5127/**
5128 * Checks whether an object key contains potentially unsafe chars, thus the key should be wrapped in
5129 * quotes. Note: we do not wrap all keys into quotes, as it may have impact on minification and may
5130 * bot work in some cases when object keys are mangled by minifier.
5131 *
5132 * TODO(FW-1136): this is a temporary solution, we need to come up with a better way of working with
5133 * inputs that contain potentially unsafe chars.
5134 */
5135var UNSAFE_OBJECT_KEY_NAME_REGEXP = /[-.]/;
5136/** Name of the temporary to use during data binding */
5137var TEMPORARY_NAME = '_t';
5138/** Name of the context parameter passed into a template function */
5139var CONTEXT_NAME = 'ctx';
5140/** Name of the RenderFlag passed into a template function */
5141var RENDER_FLAGS = 'rf';
5142/** The prefix reference variables */
5143var REFERENCE_PREFIX = '_r';
5144/** The name of the implicit context reference */
5145var IMPLICIT_REFERENCE = '$implicit';
5146/** Non bindable attribute name **/
5147var NON_BINDABLE_ATTR = 'ngNonBindable';
5148/**
5149 * Creates an allocator for a temporary variable.
5150 *
5151 * A variable declaration is added to the statements the first time the allocator is invoked.
5152 */
5153function temporaryAllocator(statements, name) {
5154 var temp = null;
5155 return function () {
5156 if (!temp) {
5157 statements.push(new DeclareVarStmt(TEMPORARY_NAME, undefined, DYNAMIC_TYPE));
5158 temp = variable(name);
5159 }
5160 return temp;
5161 };
5162}
5163function unsupported(feature) {
5164 if (this) {
5165 throw new Error("Builder " + this.constructor.name + " doesn't support " + feature + " yet");
5166 }
5167 throw new Error("Feature " + feature + " is not supported yet");
5168}
5169function invalid$1(arg) {
5170 throw new Error("Invalid state: Visitor " + this.constructor.name + " doesn't handle " + arg.constructor.name);
5171}
5172function asLiteral(value) {
5173 if (Array.isArray(value)) {
5174 return literalArr(value.map(asLiteral));
5175 }
5176 return literal(value, INFERRED_TYPE);
5177}
5178function conditionallyCreateMapObjectLiteral(keys, keepDeclared) {
5179 if (Object.getOwnPropertyNames(keys).length > 0) {
5180 return mapToExpression(keys, keepDeclared);
5181 }
5182 return null;
5183}
5184function mapToExpression(map, keepDeclared) {
5185 return literalMap(Object.getOwnPropertyNames(map).map(function (key) {
5186 var _a, _b;
5187 // canonical syntax: `dirProp: publicProp`
5188 // if there is no `:`, use dirProp = elProp
5189 var value = map[key];
5190 var declaredName;
5191 var publicName;
5192 var minifiedName;
5193 if (Array.isArray(value)) {
5194 _a = __read(value, 2), publicName = _a[0], declaredName = _a[1];
5195 }
5196 else {
5197 _b = __read(splitAtColon(key, [key, value]), 2), declaredName = _b[0], publicName = _b[1];
5198 }
5199 minifiedName = declaredName;
5200 return {
5201 key: minifiedName,
5202 // put quotes around keys that contain potentially unsafe characters
5203 quoted: UNSAFE_OBJECT_KEY_NAME_REGEXP.test(minifiedName),
5204 value: (keepDeclared && publicName !== declaredName) ?
5205 literalArr([asLiteral(publicName), asLiteral(declaredName)]) :
5206 asLiteral(publicName)
5207 };
5208 }));
5209}
5210/**
5211 * Remove trailing null nodes as they are implied.
5212 */
5213function trimTrailingNulls(parameters) {
5214 while (isNull(parameters[parameters.length - 1])) {
5215 parameters.pop();
5216 }
5217 return parameters;
5218}
5219function getQueryPredicate(query, constantPool) {
5220 if (Array.isArray(query.predicate)) {
5221 var predicate_1 = [];
5222 query.predicate.forEach(function (selector) {
5223 // Each item in predicates array may contain strings with comma-separated refs
5224 // (for ex. 'ref, ref1, ..., refN'), thus we extract individual refs and store them
5225 // as separate array entities
5226 var selectors = selector.split(',').map(function (token) { return literal(token.trim()); });
5227 predicate_1.push.apply(predicate_1, __spread(selectors));
5228 });
5229 return constantPool.getConstLiteral(literalArr(predicate_1), true);
5230 }
5231 else {
5232 return query.predicate;
5233 }
5234}
5235function noop() { }
5236var DefinitionMap = /** @class */ (function () {
5237 function DefinitionMap() {
5238 this.values = [];
5239 }
5240 DefinitionMap.prototype.set = function (key, value) {
5241 if (value) {
5242 this.values.push({ key: key, value: value, quoted: false });
5243 }
5244 };
5245 DefinitionMap.prototype.toLiteralMap = function () { return literalMap(this.values); };
5246 return DefinitionMap;
5247}());
5248/**
5249 * Extract a map of properties to values for a given element or template node, which can be used
5250 * by the directive matching machinery.
5251 *
5252 * @param elOrTpl the element or template in question
5253 * @return an object set up for directive matching. For attributes on the element/template, this
5254 * object maps a property name to its (static) value. For any bindings, this map simply maps the
5255 * property name to an empty string.
5256 */
5257function getAttrsForDirectiveMatching(elOrTpl) {
5258 var attributesMap = {};
5259 if (elOrTpl instanceof Template && elOrTpl.tagName !== 'ng-template') {
5260 elOrTpl.templateAttrs.forEach(function (a) { return attributesMap[a.name] = ''; });
5261 }
5262 else {
5263 elOrTpl.attributes.forEach(function (a) {
5264 if (!isI18nAttribute(a.name)) {
5265 attributesMap[a.name] = a.value;
5266 }
5267 });
5268 elOrTpl.inputs.forEach(function (i) { attributesMap[i.name] = ''; });
5269 elOrTpl.outputs.forEach(function (o) { attributesMap[o.name] = ''; });
5270 }
5271 return attributesMap;
5272}
5273/** Returns a call expression to a chained instruction, e.g. `property(params[0])(params[1])`. */
5274function chainedInstruction(reference, calls, span) {
5275 var expression = importExpr(reference, null, span);
5276 if (calls.length > 0) {
5277 for (var i = 0; i < calls.length; i++) {
5278 expression = expression.callFn(calls[i], span);
5279 }
5280 }
5281 else {
5282 // Add a blank invocation, in case the `calls` array is empty.
5283 expression = expression.callFn([], span);
5284 }
5285 return expression;
5286}
5287/**
5288 * Gets the number of arguments expected to be passed to a generated instruction in the case of
5289 * interpolation instructions.
5290 * @param interpolation An interpolation ast
5291 */
5292function getInterpolationArgsLength(interpolation) {
5293 var expressions = interpolation.expressions, strings = interpolation.strings;
5294 if (expressions.length === 1 && strings.length === 2 && strings[0] === '' && strings[1] === '') {
5295 // If the interpolation has one interpolated value, but the prefix and suffix are both empty
5296 // strings, we only pass one argument, to a special instruction like `propertyInterpolate` or
5297 // `textInterpolate`.
5298 return 1;
5299 }
5300 else {
5301 return expressions.length + strings.length;
5302 }
5303}
5304
5305/**
5306 * @license
5307 * Copyright Google Inc. All Rights Reserved.
5308 *
5309 * Use of this source code is governed by an MIT-style license that can be
5310 * found in the LICENSE file at https://angular.io/license
5311 */
5312var R3FactoryDelegateType;
5313(function (R3FactoryDelegateType) {
5314 R3FactoryDelegateType[R3FactoryDelegateType["Class"] = 0] = "Class";
5315 R3FactoryDelegateType[R3FactoryDelegateType["Function"] = 1] = "Function";
5316 R3FactoryDelegateType[R3FactoryDelegateType["Factory"] = 2] = "Factory";
5317})(R3FactoryDelegateType || (R3FactoryDelegateType = {}));
5318/**
5319 * Resolved type of a dependency.
5320 *
5321 * Occasionally, dependencies will have special significance which is known statically. In that
5322 * case the `R3ResolvedDependencyType` informs the factory generator that a particular dependency
5323 * should be generated specially (usually by calling a special injection function instead of the
5324 * standard one).
5325 */
5326var R3ResolvedDependencyType;
5327(function (R3ResolvedDependencyType) {
5328 /**
5329 * A normal token dependency.
5330 */
5331 R3ResolvedDependencyType[R3ResolvedDependencyType["Token"] = 0] = "Token";
5332 /**
5333 * The dependency is for an attribute.
5334 *
5335 * The token expression is a string representing the attribute name.
5336 */
5337 R3ResolvedDependencyType[R3ResolvedDependencyType["Attribute"] = 1] = "Attribute";
5338 /**
5339 * Injecting the `ChangeDetectorRef` token. Needs special handling when injected into a pipe.
5340 */
5341 R3ResolvedDependencyType[R3ResolvedDependencyType["ChangeDetectorRef"] = 2] = "ChangeDetectorRef";
5342})(R3ResolvedDependencyType || (R3ResolvedDependencyType = {}));
5343/**
5344 * Construct a factory function expression for the given `R3FactoryMetadata`.
5345 */
5346function compileFactoryFunction(meta, isPipe) {
5347 if (isPipe === void 0) { isPipe = false; }
5348 var t = variable('t');
5349 var statements = [];
5350 // The type to instantiate via constructor invocation. If there is no delegated factory, meaning
5351 // this type is always created by constructor invocation, then this is the type-to-create
5352 // parameter provided by the user (t) if specified, or the current type if not. If there is a
5353 // delegated factory (which is used to create the current type) then this is only the type-to-
5354 // create parameter (t).
5355 var typeForCtor = !isDelegatedMetadata(meta) ? new BinaryOperatorExpr(BinaryOperator.Or, t, meta.type) : t;
5356 var ctorExpr = null;
5357 if (meta.deps !== null) {
5358 // There is a constructor (either explicitly or implicitly defined).
5359 if (meta.deps !== 'invalid') {
5360 ctorExpr =
5361 new InstantiateExpr(typeForCtor, injectDependencies(meta.deps, meta.injectFn, isPipe));
5362 }
5363 }
5364 else {
5365 var baseFactory = variable("\u0275" + meta.name + "_BaseFactory");
5366 var getInheritedFactory = importExpr(Identifiers$1.getInheritedFactory);
5367 var baseFactoryStmt = baseFactory.set(getInheritedFactory.callFn([meta.type])).toDeclStmt(INFERRED_TYPE, [
5368 StmtModifier.Exported, StmtModifier.Final
5369 ]);
5370 statements.push(baseFactoryStmt);
5371 // There is no constructor, use the base class' factory to construct typeForCtor.
5372 ctorExpr = baseFactory.callFn([typeForCtor]);
5373 }
5374 var ctorExprFinal = ctorExpr;
5375 var body = [];
5376 var retExpr = null;
5377 function makeConditionalFactory(nonCtorExpr) {
5378 var r = variable('r');
5379 body.push(r.set(NULL_EXPR).toDeclStmt());
5380 var ctorStmt = null;
5381 if (ctorExprFinal !== null) {
5382 ctorStmt = r.set(ctorExprFinal).toStmt();
5383 }
5384 else {
5385 ctorStmt = makeErrorStmt(meta.name);
5386 }
5387 body.push(ifStmt(t, [ctorStmt], [r.set(nonCtorExpr).toStmt()]));
5388 return r;
5389 }
5390 if (isDelegatedMetadata(meta) && meta.delegateType === R3FactoryDelegateType.Factory) {
5391 var delegateFactory = variable("\u0275" + meta.name + "_BaseFactory");
5392 var getFactoryOf = importExpr(Identifiers$1.getFactoryOf);
5393 if (meta.delegate.isEquivalent(meta.type)) {
5394 throw new Error("Illegal state: compiling factory that delegates to itself");
5395 }
5396 var delegateFactoryStmt = delegateFactory.set(getFactoryOf.callFn([meta.delegate])).toDeclStmt(INFERRED_TYPE, [
5397 StmtModifier.Exported, StmtModifier.Final
5398 ]);
5399 statements.push(delegateFactoryStmt);
5400 retExpr = makeConditionalFactory(delegateFactory.callFn([]));
5401 }
5402 else if (isDelegatedMetadata(meta)) {
5403 // This type is created with a delegated factory. If a type parameter is not specified, call
5404 // the factory instead.
5405 var delegateArgs = injectDependencies(meta.delegateDeps, meta.injectFn, isPipe);
5406 // Either call `new delegate(...)` or `delegate(...)` depending on meta.useNewForDelegate.
5407 var factoryExpr = new (meta.delegateType === R3FactoryDelegateType.Class ?
5408 InstantiateExpr :
5409 InvokeFunctionExpr)(meta.delegate, delegateArgs);
5410 retExpr = makeConditionalFactory(factoryExpr);
5411 }
5412 else if (isExpressionFactoryMetadata(meta)) {
5413 // TODO(alxhub): decide whether to lower the value here or in the caller
5414 retExpr = makeConditionalFactory(meta.expression);
5415 }
5416 else {
5417 retExpr = ctorExpr;
5418 }
5419 if (retExpr !== null) {
5420 body.push(new ReturnStatement(retExpr));
5421 }
5422 else {
5423 body.push(makeErrorStmt(meta.name));
5424 }
5425 return {
5426 factory: fn([new FnParam('t', DYNAMIC_TYPE)], body, INFERRED_TYPE, undefined, meta.name + "_Factory"),
5427 statements: statements,
5428 };
5429}
5430function injectDependencies(deps, injectFn, isPipe) {
5431 return deps.map(function (dep) { return compileInjectDependency(dep, injectFn, isPipe); });
5432}
5433function compileInjectDependency(dep, injectFn, isPipe) {
5434 // Interpret the dependency according to its resolved type.
5435 switch (dep.resolved) {
5436 case R3ResolvedDependencyType.Token:
5437 case R3ResolvedDependencyType.ChangeDetectorRef:
5438 // Build up the injection flags according to the metadata.
5439 var flags = 0 /* Default */ | (dep.self ? 2 /* Self */ : 0) |
5440 (dep.skipSelf ? 4 /* SkipSelf */ : 0) | (dep.host ? 1 /* Host */ : 0) |
5441 (dep.optional ? 8 /* Optional */ : 0);
5442 // If this dependency is optional or otherwise has non-default flags, then additional
5443 // parameters describing how to inject the dependency must be passed to the inject function
5444 // that's being used.
5445 var flagsParam = (flags !== 0 /* Default */ || dep.optional) ? literal(flags) : null;
5446 // We have a separate instruction for injecting ChangeDetectorRef into a pipe.
5447 if (isPipe && dep.resolved === R3ResolvedDependencyType.ChangeDetectorRef) {
5448 return importExpr(Identifiers$1.injectPipeChangeDetectorRef).callFn(flagsParam ? [flagsParam] : []);
5449 }
5450 // Build up the arguments to the injectFn call.
5451 var injectArgs = [dep.token];
5452 if (flagsParam) {
5453 injectArgs.push(flagsParam);
5454 }
5455 return importExpr(injectFn).callFn(injectArgs);
5456 case R3ResolvedDependencyType.Attribute:
5457 // In the case of attributes, the attribute name in question is given as the token.
5458 return importExpr(Identifiers$1.injectAttribute).callFn([dep.token]);
5459 default:
5460 return unsupported("Unknown R3ResolvedDependencyType: " + R3ResolvedDependencyType[dep.resolved]);
5461 }
5462}
5463/**
5464 * A helper function useful for extracting `R3DependencyMetadata` from a Render2
5465 * `CompileTypeMetadata` instance.
5466 */
5467function dependenciesFromGlobalMetadata(type, outputCtx, reflector) {
5468 var e_1, _a;
5469 // Use the `CompileReflector` to look up references to some well-known Angular types. These will
5470 // be compared with the token to statically determine whether the token has significance to
5471 // Angular, and set the correct `R3ResolvedDependencyType` as a result.
5472 var injectorRef = reflector.resolveExternalReference(Identifiers.Injector);
5473 // Iterate through the type's DI dependencies and produce `R3DependencyMetadata` for each of them.
5474 var deps = [];
5475 try {
5476 for (var _b = __values(type.diDeps), _c = _b.next(); !_c.done; _c = _b.next()) {
5477 var dependency = _c.value;
5478 if (dependency.token) {
5479 var tokenRef = tokenReference(dependency.token);
5480 var resolved = dependency.isAttribute ?
5481 R3ResolvedDependencyType.Attribute :
5482 R3ResolvedDependencyType.Token;
5483 // In the case of most dependencies, the token will be a reference to a type. Sometimes,
5484 // however, it can be a string, in the case of older Angular code or @Attribute injection.
5485 var token = tokenRef instanceof StaticSymbol ? outputCtx.importExpr(tokenRef) : literal(tokenRef);
5486 // Construct the dependency.
5487 deps.push({
5488 token: token,
5489 resolved: resolved,
5490 host: !!dependency.isHost,
5491 optional: !!dependency.isOptional,
5492 self: !!dependency.isSelf,
5493 skipSelf: !!dependency.isSkipSelf,
5494 });
5495 }
5496 else {
5497 unsupported('dependency without a token');
5498 }
5499 }
5500 }
5501 catch (e_1_1) { e_1 = { error: e_1_1 }; }
5502 finally {
5503 try {
5504 if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
5505 }
5506 finally { if (e_1) throw e_1.error; }
5507 }
5508 return deps;
5509}
5510function makeErrorStmt(name) {
5511 return new ThrowStmt(new InstantiateExpr(new ReadVarExpr('Error'), [
5512 literal(name + " has a constructor which is not compatible with Dependency Injection. It should probably not be @Injectable().")
5513 ]));
5514}
5515function isDelegatedMetadata(meta) {
5516 return meta.delegateType !== undefined;
5517}
5518function isExpressionFactoryMetadata(meta) {
5519 return meta.expression !== undefined;
5520}
5521
5522/**
5523 * @license
5524 * Copyright Google Inc. All Rights Reserved.
5525 *
5526 * Use of this source code is governed by an MIT-style license that can be
5527 * found in the LICENSE file at https://angular.io/license
5528 */
5529/**
5530 * Convert an object map with `Expression` values into a `LiteralMapExpr`.
5531 */
5532function mapToMapExpression(map) {
5533 var result = Object.keys(map).map(function (key) { return ({ key: key, value: map[key], quoted: false }); });
5534 return literalMap(result);
5535}
5536/**
5537 * Convert metadata into an `Expression` in the given `OutputContext`.
5538 *
5539 * This operation will handle arrays, references to symbols, or literal `null` or `undefined`.
5540 */
5541function convertMetaToOutput(meta, ctx) {
5542 if (Array.isArray(meta)) {
5543 return literalArr(meta.map(function (entry) { return convertMetaToOutput(entry, ctx); }));
5544 }
5545 if (meta instanceof StaticSymbol) {
5546 return ctx.importExpr(meta);
5547 }
5548 if (meta == null) {
5549 return literal(meta);
5550 }
5551 throw new Error("Internal error: Unsupported or unknown metadata: " + meta);
5552}
5553function typeWithParameters(type, numParams) {
5554 var params = null;
5555 if (numParams > 0) {
5556 params = [];
5557 for (var i = 0; i < numParams; i++) {
5558 params.push(DYNAMIC_TYPE);
5559 }
5560 }
5561 return expressionType(type, null, params);
5562}
5563var ANIMATE_SYMBOL_PREFIX = '@';
5564function prepareSyntheticPropertyName(name) {
5565 return "" + ANIMATE_SYMBOL_PREFIX + name;
5566}
5567function prepareSyntheticListenerName(name, phase) {
5568 return "" + ANIMATE_SYMBOL_PREFIX + name + "." + phase;
5569}
5570function isSyntheticPropertyOrListener(name) {
5571 return name.charAt(0) == ANIMATE_SYMBOL_PREFIX;
5572}
5573function getSyntheticPropertyName(name) {
5574 // this will strip out listener phase values...
5575 // @foo.start => @foo
5576 var i = name.indexOf('.');
5577 name = i > 0 ? name.substring(0, i) : name;
5578 if (name.charAt(0) !== ANIMATE_SYMBOL_PREFIX) {
5579 name = ANIMATE_SYMBOL_PREFIX + name;
5580 }
5581 return name;
5582}
5583function prepareSyntheticListenerFunctionName(name, phase) {
5584 return "animation_" + name + "_" + phase;
5585}
5586
5587/**
5588 * @license
5589 * Copyright Google Inc. All Rights Reserved.
5590 *
5591 * Use of this source code is governed by an MIT-style license that can be
5592 * found in the LICENSE file at https://angular.io/license
5593 */
5594function compileInjectable(meta) {
5595 var result = null;
5596 var factoryMeta = {
5597 name: meta.name,
5598 type: meta.type,
5599 deps: meta.ctorDeps,
5600 injectFn: Identifiers.inject,
5601 };
5602 if (meta.useClass !== undefined) {
5603 // meta.useClass has two modes of operation. Either deps are specified, in which case `new` is
5604 // used to instantiate the class with dependencies injected, or deps are not specified and
5605 // the factory of the class is used to instantiate it.
5606 //
5607 // A special case exists for useClass: Type where Type is the injectable type itself and no
5608 // deps are specified, in which case 'useClass' is effectively ignored.
5609 var useClassOnSelf = meta.useClass.isEquivalent(meta.type);
5610 var deps = undefined;
5611 if (meta.userDeps !== undefined) {
5612 deps = meta.userDeps;
5613 }
5614 if (deps !== undefined) {
5615 // factory: () => new meta.useClass(...deps)
5616 result = compileFactoryFunction(__assign({}, factoryMeta, { delegate: meta.useClass, delegateDeps: deps, delegateType: R3FactoryDelegateType.Class }));
5617 }
5618 else if (useClassOnSelf) {
5619 result = compileFactoryFunction(factoryMeta);
5620 }
5621 else {
5622 result = compileFactoryFunction(__assign({}, factoryMeta, { delegate: meta.useClass, delegateType: R3FactoryDelegateType.Factory }));
5623 }
5624 }
5625 else if (meta.useFactory !== undefined) {
5626 result = compileFactoryFunction(__assign({}, factoryMeta, { delegate: meta.useFactory, delegateDeps: meta.userDeps || [], delegateType: R3FactoryDelegateType.Function }));
5627 }
5628 else if (meta.useValue !== undefined) {
5629 // Note: it's safe to use `meta.useValue` instead of the `USE_VALUE in meta` check used for
5630 // client code because meta.useValue is an Expression which will be defined even if the actual
5631 // value is undefined.
5632 result = compileFactoryFunction(__assign({}, factoryMeta, { expression: meta.useValue }));
5633 }
5634 else if (meta.useExisting !== undefined) {
5635 // useExisting is an `inject` call on the existing token.
5636 result = compileFactoryFunction(__assign({}, factoryMeta, { expression: importExpr(Identifiers.inject).callFn([meta.useExisting]) }));
5637 }
5638 else {
5639 result = compileFactoryFunction(factoryMeta);
5640 }
5641 var token = meta.type;
5642 var providedIn = meta.providedIn;
5643 var expression = importExpr(Identifiers.ɵɵdefineInjectable).callFn([mapToMapExpression({ token: token, factory: result.factory, providedIn: providedIn })]);
5644 var type = new ExpressionType(importExpr(Identifiers.InjectableDef, [typeWithParameters(meta.type, meta.typeArgumentCount)]));
5645 return {
5646 expression: expression,
5647 type: type,
5648 statements: result.statements,
5649 };
5650}
5651
5652/**
5653 * @license
5654 * Copyright Google Inc. All Rights Reserved.
5655 *
5656 * Use of this source code is governed by an MIT-style license that can be
5657 * found in the LICENSE file at https://angular.io/license
5658 */
5659function assertArrayOfStrings(identifier, value) {
5660 if (value == null) {
5661 return;
5662 }
5663 if (!Array.isArray(value)) {
5664 throw new Error("Expected '" + identifier + "' to be an array of strings.");
5665 }
5666 for (var i = 0; i < value.length; i += 1) {
5667 if (typeof value[i] !== 'string') {
5668 throw new Error("Expected '" + identifier + "' to be an array of strings.");
5669 }
5670 }
5671}
5672var UNUSABLE_INTERPOLATION_REGEXPS = [
5673 /^\s*$/,
5674 /[<>]/,
5675 /^[{}]$/,
5676 /&(#|[a-z])/i,
5677 /^\/\//,
5678];
5679function assertInterpolationSymbols(identifier, value) {
5680 if (value != null && !(Array.isArray(value) && value.length == 2)) {
5681 throw new Error("Expected '" + identifier + "' to be an array, [start, end].");
5682 }
5683 else if (value != null) {
5684 var start_1 = value[0];
5685 var end_1 = value[1];
5686 // Check for unusable interpolation symbols
5687 UNUSABLE_INTERPOLATION_REGEXPS.forEach(function (regexp) {
5688 if (regexp.test(start_1) || regexp.test(end_1)) {
5689 throw new Error("['" + start_1 + "', '" + end_1 + "'] contains unusable interpolation symbol.");
5690 }
5691 });
5692 }
5693}
5694
5695/**
5696 * @license
5697 * Copyright Google Inc. All Rights Reserved.
5698 *
5699 * Use of this source code is governed by an MIT-style license that can be
5700 * found in the LICENSE file at https://angular.io/license
5701 */
5702var InterpolationConfig = /** @class */ (function () {
5703 function InterpolationConfig(start, end) {
5704 this.start = start;
5705 this.end = end;
5706 }
5707 InterpolationConfig.fromArray = function (markers) {
5708 if (!markers) {
5709 return DEFAULT_INTERPOLATION_CONFIG;
5710 }
5711 assertInterpolationSymbols('interpolation', markers);
5712 return new InterpolationConfig(markers[0], markers[1]);
5713 };
5714 return InterpolationConfig;
5715}());
5716var DEFAULT_INTERPOLATION_CONFIG = new InterpolationConfig('{{', '}}');
5717
5718/**
5719 * @license
5720 * Copyright Google Inc. All Rights Reserved.
5721 *
5722 * Use of this source code is governed by an MIT-style license that can be
5723 * found in the LICENSE file at https://angular.io/license
5724 */
5725// https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
5726var VERSION = 3;
5727var JS_B64_PREFIX = '# sourceMappingURL=data:application/json;base64,';
5728var SourceMapGenerator = /** @class */ (function () {
5729 function SourceMapGenerator(file) {
5730 if (file === void 0) { file = null; }
5731 this.file = file;
5732 this.sourcesContent = new Map();
5733 this.lines = [];
5734 this.lastCol0 = 0;
5735 this.hasMappings = false;
5736 }
5737 // The content is `null` when the content is expected to be loaded using the URL
5738 SourceMapGenerator.prototype.addSource = function (url, content) {
5739 if (content === void 0) { content = null; }
5740 if (!this.sourcesContent.has(url)) {
5741 this.sourcesContent.set(url, content);
5742 }
5743 return this;
5744 };
5745 SourceMapGenerator.prototype.addLine = function () {
5746 this.lines.push([]);
5747 this.lastCol0 = 0;
5748 return this;
5749 };
5750 SourceMapGenerator.prototype.addMapping = function (col0, sourceUrl, sourceLine0, sourceCol0) {
5751 if (!this.currentLine) {
5752 throw new Error("A line must be added before mappings can be added");
5753 }
5754 if (sourceUrl != null && !this.sourcesContent.has(sourceUrl)) {
5755 throw new Error("Unknown source file \"" + sourceUrl + "\"");
5756 }
5757 if (col0 == null) {
5758 throw new Error("The column in the generated code must be provided");
5759 }
5760 if (col0 < this.lastCol0) {
5761 throw new Error("Mapping should be added in output order");
5762 }
5763 if (sourceUrl && (sourceLine0 == null || sourceCol0 == null)) {
5764 throw new Error("The source location must be provided when a source url is provided");
5765 }
5766 this.hasMappings = true;
5767 this.lastCol0 = col0;
5768 this.currentLine.push({ col0: col0, sourceUrl: sourceUrl, sourceLine0: sourceLine0, sourceCol0: sourceCol0 });
5769 return this;
5770 };
5771 Object.defineProperty(SourceMapGenerator.prototype, "currentLine", {
5772 get: function () { return this.lines.slice(-1)[0]; },
5773 enumerable: true,
5774 configurable: true
5775 });
5776 SourceMapGenerator.prototype.toJSON = function () {
5777 var _this = this;
5778 if (!this.hasMappings) {
5779 return null;
5780 }
5781 var sourcesIndex = new Map();
5782 var sources = [];
5783 var sourcesContent = [];
5784 Array.from(this.sourcesContent.keys()).forEach(function (url, i) {
5785 sourcesIndex.set(url, i);
5786 sources.push(url);
5787 sourcesContent.push(_this.sourcesContent.get(url) || null);
5788 });
5789 var mappings = '';
5790 var lastCol0 = 0;
5791 var lastSourceIndex = 0;
5792 var lastSourceLine0 = 0;
5793 var lastSourceCol0 = 0;
5794 this.lines.forEach(function (segments) {
5795 lastCol0 = 0;
5796 mappings += segments
5797 .map(function (segment) {
5798 // zero-based starting column of the line in the generated code
5799 var segAsStr = toBase64VLQ(segment.col0 - lastCol0);
5800 lastCol0 = segment.col0;
5801 if (segment.sourceUrl != null) {
5802 // zero-based index into the “sources” list
5803 segAsStr +=
5804 toBase64VLQ(sourcesIndex.get(segment.sourceUrl) - lastSourceIndex);
5805 lastSourceIndex = sourcesIndex.get(segment.sourceUrl);
5806 // the zero-based starting line in the original source
5807 segAsStr += toBase64VLQ(segment.sourceLine0 - lastSourceLine0);
5808 lastSourceLine0 = segment.sourceLine0;
5809 // the zero-based starting column in the original source
5810 segAsStr += toBase64VLQ(segment.sourceCol0 - lastSourceCol0);
5811 lastSourceCol0 = segment.sourceCol0;
5812 }
5813 return segAsStr;
5814 })
5815 .join(',');
5816 mappings += ';';
5817 });
5818 mappings = mappings.slice(0, -1);
5819 return {
5820 'file': this.file || '',
5821 'version': VERSION,
5822 'sourceRoot': '',
5823 'sources': sources,
5824 'sourcesContent': sourcesContent,
5825 'mappings': mappings,
5826 };
5827 };
5828 SourceMapGenerator.prototype.toJsComment = function () {
5829 return this.hasMappings ? '//' + JS_B64_PREFIX + toBase64String(JSON.stringify(this, null, 0)) :
5830 '';
5831 };
5832 return SourceMapGenerator;
5833}());
5834function toBase64String(value) {
5835 var b64 = '';
5836 value = utf8Encode(value);
5837 for (var i = 0; i < value.length;) {
5838 var i1 = value.charCodeAt(i++);
5839 var i2 = value.charCodeAt(i++);
5840 var i3 = value.charCodeAt(i++);
5841 b64 += toBase64Digit(i1 >> 2);
5842 b64 += toBase64Digit(((i1 & 3) << 4) | (isNaN(i2) ? 0 : i2 >> 4));
5843 b64 += isNaN(i2) ? '=' : toBase64Digit(((i2 & 15) << 2) | (i3 >> 6));
5844 b64 += isNaN(i2) || isNaN(i3) ? '=' : toBase64Digit(i3 & 63);
5845 }
5846 return b64;
5847}
5848function toBase64VLQ(value) {
5849 value = value < 0 ? ((-value) << 1) + 1 : value << 1;
5850 var out = '';
5851 do {
5852 var digit = value & 31;
5853 value = value >> 5;
5854 if (value > 0) {
5855 digit = digit | 32;
5856 }
5857 out += toBase64Digit(digit);
5858 } while (value > 0);
5859 return out;
5860}
5861var B64_DIGITS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
5862function toBase64Digit(value) {
5863 if (value < 0 || value >= 64) {
5864 throw new Error("Can only encode value in the range [0, 63]");
5865 }
5866 return B64_DIGITS[value];
5867}
5868
5869/**
5870 * @license
5871 * Copyright Google Inc. All Rights Reserved.
5872 *
5873 * Use of this source code is governed by an MIT-style license that can be
5874 * found in the LICENSE file at https://angular.io/license
5875 */
5876var _SINGLE_QUOTE_ESCAPE_STRING_RE = /'|\\|\n|\r|\$/g;
5877var _LEGAL_IDENTIFIER_RE = /^[$A-Z_][0-9A-Z_$]*$/i;
5878var _INDENT_WITH = ' ';
5879var CATCH_ERROR_VAR$1 = variable('error', null, null);
5880var CATCH_STACK_VAR$1 = variable('stack', null, null);
5881var _EmittedLine = /** @class */ (function () {
5882 function _EmittedLine(indent) {
5883 this.indent = indent;
5884 this.partsLength = 0;
5885 this.parts = [];
5886 this.srcSpans = [];
5887 }
5888 return _EmittedLine;
5889}());
5890var EmitterVisitorContext = /** @class */ (function () {
5891 function EmitterVisitorContext(_indent) {
5892 this._indent = _indent;
5893 this._classes = [];
5894 this._preambleLineCount = 0;
5895 this._lines = [new _EmittedLine(_indent)];
5896 }
5897 EmitterVisitorContext.createRoot = function () { return new EmitterVisitorContext(0); };
5898 Object.defineProperty(EmitterVisitorContext.prototype, "_currentLine", {
5899 get: function () { return this._lines[this._lines.length - 1]; },
5900 enumerable: true,
5901 configurable: true
5902 });
5903 EmitterVisitorContext.prototype.println = function (from, lastPart) {
5904 if (lastPart === void 0) { lastPart = ''; }
5905 this.print(from || null, lastPart, true);
5906 };
5907 EmitterVisitorContext.prototype.lineIsEmpty = function () { return this._currentLine.parts.length === 0; };
5908 EmitterVisitorContext.prototype.lineLength = function () {
5909 return this._currentLine.indent * _INDENT_WITH.length + this._currentLine.partsLength;
5910 };
5911 EmitterVisitorContext.prototype.print = function (from, part, newLine) {
5912 if (newLine === void 0) { newLine = false; }
5913 if (part.length > 0) {
5914 this._currentLine.parts.push(part);
5915 this._currentLine.partsLength += part.length;
5916 this._currentLine.srcSpans.push(from && from.sourceSpan || null);
5917 }
5918 if (newLine) {
5919 this._lines.push(new _EmittedLine(this._indent));
5920 }
5921 };
5922 EmitterVisitorContext.prototype.removeEmptyLastLine = function () {
5923 if (this.lineIsEmpty()) {
5924 this._lines.pop();
5925 }
5926 };
5927 EmitterVisitorContext.prototype.incIndent = function () {
5928 this._indent++;
5929 if (this.lineIsEmpty()) {
5930 this._currentLine.indent = this._indent;
5931 }
5932 };
5933 EmitterVisitorContext.prototype.decIndent = function () {
5934 this._indent--;
5935 if (this.lineIsEmpty()) {
5936 this._currentLine.indent = this._indent;
5937 }
5938 };
5939 EmitterVisitorContext.prototype.pushClass = function (clazz) { this._classes.push(clazz); };
5940 EmitterVisitorContext.prototype.popClass = function () { return this._classes.pop(); };
5941 Object.defineProperty(EmitterVisitorContext.prototype, "currentClass", {
5942 get: function () {
5943 return this._classes.length > 0 ? this._classes[this._classes.length - 1] : null;
5944 },
5945 enumerable: true,
5946 configurable: true
5947 });
5948 EmitterVisitorContext.prototype.toSource = function () {
5949 return this.sourceLines
5950 .map(function (l) { return l.parts.length > 0 ? _createIndent(l.indent) + l.parts.join('') : ''; })
5951 .join('\n');
5952 };
5953 EmitterVisitorContext.prototype.toSourceMapGenerator = function (genFilePath, startsAtLine) {
5954 if (startsAtLine === void 0) { startsAtLine = 0; }
5955 var map = new SourceMapGenerator(genFilePath);
5956 var firstOffsetMapped = false;
5957 var mapFirstOffsetIfNeeded = function () {
5958 if (!firstOffsetMapped) {
5959 // Add a single space so that tools won't try to load the file from disk.
5960 // Note: We are using virtual urls like `ng:///`, so we have to
5961 // provide a content here.
5962 map.addSource(genFilePath, ' ').addMapping(0, genFilePath, 0, 0);
5963 firstOffsetMapped = true;
5964 }
5965 };
5966 for (var i = 0; i < startsAtLine; i++) {
5967 map.addLine();
5968 mapFirstOffsetIfNeeded();
5969 }
5970 this.sourceLines.forEach(function (line, lineIdx) {
5971 map.addLine();
5972 var spans = line.srcSpans;
5973 var parts = line.parts;
5974 var col0 = line.indent * _INDENT_WITH.length;
5975 var spanIdx = 0;
5976 // skip leading parts without source spans
5977 while (spanIdx < spans.length && !spans[spanIdx]) {
5978 col0 += parts[spanIdx].length;
5979 spanIdx++;
5980 }
5981 if (spanIdx < spans.length && lineIdx === 0 && col0 === 0) {
5982 firstOffsetMapped = true;
5983 }
5984 else {
5985 mapFirstOffsetIfNeeded();
5986 }
5987 while (spanIdx < spans.length) {
5988 var span = spans[spanIdx];
5989 var source = span.start.file;
5990 var sourceLine = span.start.line;
5991 var sourceCol = span.start.col;
5992 map.addSource(source.url, source.content)
5993 .addMapping(col0, source.url, sourceLine, sourceCol);
5994 col0 += parts[spanIdx].length;
5995 spanIdx++;
5996 // assign parts without span or the same span to the previous segment
5997 while (spanIdx < spans.length && (span === spans[spanIdx] || !spans[spanIdx])) {
5998 col0 += parts[spanIdx].length;
5999 spanIdx++;
6000 }
6001 }
6002 });
6003 return map;
6004 };
6005 EmitterVisitorContext.prototype.setPreambleLineCount = function (count) { return this._preambleLineCount = count; };
6006 EmitterVisitorContext.prototype.spanOf = function (line, column) {
6007 var emittedLine = this._lines[line - this._preambleLineCount];
6008 if (emittedLine) {
6009 var columnsLeft = column - _createIndent(emittedLine.indent).length;
6010 for (var partIndex = 0; partIndex < emittedLine.parts.length; partIndex++) {
6011 var part = emittedLine.parts[partIndex];
6012 if (part.length > columnsLeft) {
6013 return emittedLine.srcSpans[partIndex];
6014 }
6015 columnsLeft -= part.length;
6016 }
6017 }
6018 return null;
6019 };
6020 Object.defineProperty(EmitterVisitorContext.prototype, "sourceLines", {
6021 get: function () {
6022 if (this._lines.length && this._lines[this._lines.length - 1].parts.length === 0) {
6023 return this._lines.slice(0, -1);
6024 }
6025 return this._lines;
6026 },
6027 enumerable: true,
6028 configurable: true
6029 });
6030 return EmitterVisitorContext;
6031}());
6032var AbstractEmitterVisitor = /** @class */ (function () {
6033 function AbstractEmitterVisitor(_escapeDollarInStrings) {
6034 this._escapeDollarInStrings = _escapeDollarInStrings;
6035 }
6036 AbstractEmitterVisitor.prototype.visitExpressionStmt = function (stmt, ctx) {
6037 stmt.expr.visitExpression(this, ctx);
6038 ctx.println(stmt, ';');
6039 return null;
6040 };
6041 AbstractEmitterVisitor.prototype.visitReturnStmt = function (stmt, ctx) {
6042 ctx.print(stmt, "return ");
6043 stmt.value.visitExpression(this, ctx);
6044 ctx.println(stmt, ';');
6045 return null;
6046 };
6047 AbstractEmitterVisitor.prototype.visitIfStmt = function (stmt, ctx) {
6048 ctx.print(stmt, "if (");
6049 stmt.condition.visitExpression(this, ctx);
6050 ctx.print(stmt, ") {");
6051 var hasElseCase = stmt.falseCase != null && stmt.falseCase.length > 0;
6052 if (stmt.trueCase.length <= 1 && !hasElseCase) {
6053 ctx.print(stmt, " ");
6054 this.visitAllStatements(stmt.trueCase, ctx);
6055 ctx.removeEmptyLastLine();
6056 ctx.print(stmt, " ");
6057 }
6058 else {
6059 ctx.println();
6060 ctx.incIndent();
6061 this.visitAllStatements(stmt.trueCase, ctx);
6062 ctx.decIndent();
6063 if (hasElseCase) {
6064 ctx.println(stmt, "} else {");
6065 ctx.incIndent();
6066 this.visitAllStatements(stmt.falseCase, ctx);
6067 ctx.decIndent();
6068 }
6069 }
6070 ctx.println(stmt, "}");
6071 return null;
6072 };
6073 AbstractEmitterVisitor.prototype.visitThrowStmt = function (stmt, ctx) {
6074 ctx.print(stmt, "throw ");
6075 stmt.error.visitExpression(this, ctx);
6076 ctx.println(stmt, ";");
6077 return null;
6078 };
6079 AbstractEmitterVisitor.prototype.visitCommentStmt = function (stmt, ctx) {
6080 if (stmt.multiline) {
6081 ctx.println(stmt, "/* " + stmt.comment + " */");
6082 }
6083 else {
6084 stmt.comment.split('\n').forEach(function (line) { ctx.println(stmt, "// " + line); });
6085 }
6086 return null;
6087 };
6088 AbstractEmitterVisitor.prototype.visitJSDocCommentStmt = function (stmt, ctx) {
6089 ctx.println(stmt, "/*" + stmt.toString() + "*/");
6090 return null;
6091 };
6092 AbstractEmitterVisitor.prototype.visitWriteVarExpr = function (expr, ctx) {
6093 var lineWasEmpty = ctx.lineIsEmpty();
6094 if (!lineWasEmpty) {
6095 ctx.print(expr, '(');
6096 }
6097 ctx.print(expr, expr.name + " = ");
6098 expr.value.visitExpression(this, ctx);
6099 if (!lineWasEmpty) {
6100 ctx.print(expr, ')');
6101 }
6102 return null;
6103 };
6104 AbstractEmitterVisitor.prototype.visitWriteKeyExpr = function (expr, ctx) {
6105 var lineWasEmpty = ctx.lineIsEmpty();
6106 if (!lineWasEmpty) {
6107 ctx.print(expr, '(');
6108 }
6109 expr.receiver.visitExpression(this, ctx);
6110 ctx.print(expr, "[");
6111 expr.index.visitExpression(this, ctx);
6112 ctx.print(expr, "] = ");
6113 expr.value.visitExpression(this, ctx);
6114 if (!lineWasEmpty) {
6115 ctx.print(expr, ')');
6116 }
6117 return null;
6118 };
6119 AbstractEmitterVisitor.prototype.visitWritePropExpr = function (expr, ctx) {
6120 var lineWasEmpty = ctx.lineIsEmpty();
6121 if (!lineWasEmpty) {
6122 ctx.print(expr, '(');
6123 }
6124 expr.receiver.visitExpression(this, ctx);
6125 ctx.print(expr, "." + expr.name + " = ");
6126 expr.value.visitExpression(this, ctx);
6127 if (!lineWasEmpty) {
6128 ctx.print(expr, ')');
6129 }
6130 return null;
6131 };
6132 AbstractEmitterVisitor.prototype.visitInvokeMethodExpr = function (expr, ctx) {
6133 expr.receiver.visitExpression(this, ctx);
6134 var name = expr.name;
6135 if (expr.builtin != null) {
6136 name = this.getBuiltinMethodName(expr.builtin);
6137 if (name == null) {
6138 // some builtins just mean to skip the call.
6139 return null;
6140 }
6141 }
6142 ctx.print(expr, "." + name + "(");
6143 this.visitAllExpressions(expr.args, ctx, ",");
6144 ctx.print(expr, ")");
6145 return null;
6146 };
6147 AbstractEmitterVisitor.prototype.visitInvokeFunctionExpr = function (expr, ctx) {
6148 expr.fn.visitExpression(this, ctx);
6149 ctx.print(expr, "(");
6150 this.visitAllExpressions(expr.args, ctx, ',');
6151 ctx.print(expr, ")");
6152 return null;
6153 };
6154 AbstractEmitterVisitor.prototype.visitWrappedNodeExpr = function (ast, ctx) {
6155 throw new Error('Abstract emitter cannot visit WrappedNodeExpr.');
6156 };
6157 AbstractEmitterVisitor.prototype.visitTypeofExpr = function (expr, ctx) {
6158 ctx.print(expr, 'typeof ');
6159 expr.expr.visitExpression(this, ctx);
6160 };
6161 AbstractEmitterVisitor.prototype.visitReadVarExpr = function (ast, ctx) {
6162 var varName = ast.name;
6163 if (ast.builtin != null) {
6164 switch (ast.builtin) {
6165 case BuiltinVar.Super:
6166 varName = 'super';
6167 break;
6168 case BuiltinVar.This:
6169 varName = 'this';
6170 break;
6171 case BuiltinVar.CatchError:
6172 varName = CATCH_ERROR_VAR$1.name;
6173 break;
6174 case BuiltinVar.CatchStack:
6175 varName = CATCH_STACK_VAR$1.name;
6176 break;
6177 default:
6178 throw new Error("Unknown builtin variable " + ast.builtin);
6179 }
6180 }
6181 ctx.print(ast, varName);
6182 return null;
6183 };
6184 AbstractEmitterVisitor.prototype.visitInstantiateExpr = function (ast, ctx) {
6185 ctx.print(ast, "new ");
6186 ast.classExpr.visitExpression(this, ctx);
6187 ctx.print(ast, "(");
6188 this.visitAllExpressions(ast.args, ctx, ',');
6189 ctx.print(ast, ")");
6190 return null;
6191 };
6192 AbstractEmitterVisitor.prototype.visitLiteralExpr = function (ast, ctx) {
6193 var value = ast.value;
6194 if (typeof value === 'string') {
6195 ctx.print(ast, escapeIdentifier(value, this._escapeDollarInStrings));
6196 }
6197 else {
6198 ctx.print(ast, "" + value);
6199 }
6200 return null;
6201 };
6202 AbstractEmitterVisitor.prototype.visitConditionalExpr = function (ast, ctx) {
6203 ctx.print(ast, "(");
6204 ast.condition.visitExpression(this, ctx);
6205 ctx.print(ast, '? ');
6206 ast.trueCase.visitExpression(this, ctx);
6207 ctx.print(ast, ': ');
6208 ast.falseCase.visitExpression(this, ctx);
6209 ctx.print(ast, ")");
6210 return null;
6211 };
6212 AbstractEmitterVisitor.prototype.visitNotExpr = function (ast, ctx) {
6213 ctx.print(ast, '!');
6214 ast.condition.visitExpression(this, ctx);
6215 return null;
6216 };
6217 AbstractEmitterVisitor.prototype.visitAssertNotNullExpr = function (ast, ctx) {
6218 ast.condition.visitExpression(this, ctx);
6219 return null;
6220 };
6221 AbstractEmitterVisitor.prototype.visitBinaryOperatorExpr = function (ast, ctx) {
6222 var opStr;
6223 switch (ast.operator) {
6224 case BinaryOperator.Equals:
6225 opStr = '==';
6226 break;
6227 case BinaryOperator.Identical:
6228 opStr = '===';
6229 break;
6230 case BinaryOperator.NotEquals:
6231 opStr = '!=';
6232 break;
6233 case BinaryOperator.NotIdentical:
6234 opStr = '!==';
6235 break;
6236 case BinaryOperator.And:
6237 opStr = '&&';
6238 break;
6239 case BinaryOperator.BitwiseAnd:
6240 opStr = '&';
6241 break;
6242 case BinaryOperator.Or:
6243 opStr = '||';
6244 break;
6245 case BinaryOperator.Plus:
6246 opStr = '+';
6247 break;
6248 case BinaryOperator.Minus:
6249 opStr = '-';
6250 break;
6251 case BinaryOperator.Divide:
6252 opStr = '/';
6253 break;
6254 case BinaryOperator.Multiply:
6255 opStr = '*';
6256 break;
6257 case BinaryOperator.Modulo:
6258 opStr = '%';
6259 break;
6260 case BinaryOperator.Lower:
6261 opStr = '<';
6262 break;
6263 case BinaryOperator.LowerEquals:
6264 opStr = '<=';
6265 break;
6266 case BinaryOperator.Bigger:
6267 opStr = '>';
6268 break;
6269 case BinaryOperator.BiggerEquals:
6270 opStr = '>=';
6271 break;
6272 default:
6273 throw new Error("Unknown operator " + ast.operator);
6274 }
6275 if (ast.parens)
6276 ctx.print(ast, "(");
6277 ast.lhs.visitExpression(this, ctx);
6278 ctx.print(ast, " " + opStr + " ");
6279 ast.rhs.visitExpression(this, ctx);
6280 if (ast.parens)
6281 ctx.print(ast, ")");
6282 return null;
6283 };
6284 AbstractEmitterVisitor.prototype.visitReadPropExpr = function (ast, ctx) {
6285 ast.receiver.visitExpression(this, ctx);
6286 ctx.print(ast, ".");
6287 ctx.print(ast, ast.name);
6288 return null;
6289 };
6290 AbstractEmitterVisitor.prototype.visitReadKeyExpr = function (ast, ctx) {
6291 ast.receiver.visitExpression(this, ctx);
6292 ctx.print(ast, "[");
6293 ast.index.visitExpression(this, ctx);
6294 ctx.print(ast, "]");
6295 return null;
6296 };
6297 AbstractEmitterVisitor.prototype.visitLiteralArrayExpr = function (ast, ctx) {
6298 ctx.print(ast, "[");
6299 this.visitAllExpressions(ast.entries, ctx, ',');
6300 ctx.print(ast, "]");
6301 return null;
6302 };
6303 AbstractEmitterVisitor.prototype.visitLiteralMapExpr = function (ast, ctx) {
6304 var _this = this;
6305 ctx.print(ast, "{");
6306 this.visitAllObjects(function (entry) {
6307 ctx.print(ast, escapeIdentifier(entry.key, _this._escapeDollarInStrings, entry.quoted) + ":");
6308 entry.value.visitExpression(_this, ctx);
6309 }, ast.entries, ctx, ',');
6310 ctx.print(ast, "}");
6311 return null;
6312 };
6313 AbstractEmitterVisitor.prototype.visitCommaExpr = function (ast, ctx) {
6314 ctx.print(ast, '(');
6315 this.visitAllExpressions(ast.parts, ctx, ',');
6316 ctx.print(ast, ')');
6317 return null;
6318 };
6319 AbstractEmitterVisitor.prototype.visitAllExpressions = function (expressions, ctx, separator) {
6320 var _this = this;
6321 this.visitAllObjects(function (expr) { return expr.visitExpression(_this, ctx); }, expressions, ctx, separator);
6322 };
6323 AbstractEmitterVisitor.prototype.visitAllObjects = function (handler, expressions, ctx, separator) {
6324 var incrementedIndent = false;
6325 for (var i = 0; i < expressions.length; i++) {
6326 if (i > 0) {
6327 if (ctx.lineLength() > 80) {
6328 ctx.print(null, separator, true);
6329 if (!incrementedIndent) {
6330 // continuation are marked with double indent.
6331 ctx.incIndent();
6332 ctx.incIndent();
6333 incrementedIndent = true;
6334 }
6335 }
6336 else {
6337 ctx.print(null, separator, false);
6338 }
6339 }
6340 handler(expressions[i]);
6341 }
6342 if (incrementedIndent) {
6343 // continuation are marked with double indent.
6344 ctx.decIndent();
6345 ctx.decIndent();
6346 }
6347 };
6348 AbstractEmitterVisitor.prototype.visitAllStatements = function (statements, ctx) {
6349 var _this = this;
6350 statements.forEach(function (stmt) { return stmt.visitStatement(_this, ctx); });
6351 };
6352 return AbstractEmitterVisitor;
6353}());
6354function escapeIdentifier(input, escapeDollar, alwaysQuote) {
6355 if (alwaysQuote === void 0) { alwaysQuote = true; }
6356 if (input == null) {
6357 return null;
6358 }
6359 var body = input.replace(_SINGLE_QUOTE_ESCAPE_STRING_RE, function () {
6360 var match = [];
6361 for (var _i = 0; _i < arguments.length; _i++) {
6362 match[_i] = arguments[_i];
6363 }
6364 if (match[0] == '$') {
6365 return escapeDollar ? '\\$' : '$';
6366 }
6367 else if (match[0] == '\n') {
6368 return '\\n';
6369 }
6370 else if (match[0] == '\r') {
6371 return '\\r';
6372 }
6373 else {
6374 return "\\" + match[0];
6375 }
6376 });
6377 var requiresQuotes = alwaysQuote || !_LEGAL_IDENTIFIER_RE.test(body);
6378 return requiresQuotes ? "'" + body + "'" : body;
6379}
6380function _createIndent(count) {
6381 var res = '';
6382 for (var i = 0; i < count; i++) {
6383 res += _INDENT_WITH;
6384 }
6385 return res;
6386}
6387
6388/**
6389 * @license
6390 * Copyright Google Inc. All Rights Reserved.
6391 *
6392 * Use of this source code is governed by an MIT-style license that can be
6393 * found in the LICENSE file at https://angular.io/license
6394 */
6395var AbstractJsEmitterVisitor = /** @class */ (function (_super) {
6396 __extends(AbstractJsEmitterVisitor, _super);
6397 function AbstractJsEmitterVisitor() {
6398 return _super.call(this, false) || this;
6399 }
6400 AbstractJsEmitterVisitor.prototype.visitDeclareClassStmt = function (stmt, ctx) {
6401 var _this = this;
6402 ctx.pushClass(stmt);
6403 this._visitClassConstructor(stmt, ctx);
6404 if (stmt.parent != null) {
6405 ctx.print(stmt, stmt.name + ".prototype = Object.create(");
6406 stmt.parent.visitExpression(this, ctx);
6407 ctx.println(stmt, ".prototype);");
6408 }
6409 stmt.getters.forEach(function (getter) { return _this._visitClassGetter(stmt, getter, ctx); });
6410 stmt.methods.forEach(function (method) { return _this._visitClassMethod(stmt, method, ctx); });
6411 ctx.popClass();
6412 return null;
6413 };
6414 AbstractJsEmitterVisitor.prototype._visitClassConstructor = function (stmt, ctx) {
6415 ctx.print(stmt, "function " + stmt.name + "(");
6416 if (stmt.constructorMethod != null) {
6417 this._visitParams(stmt.constructorMethod.params, ctx);
6418 }
6419 ctx.println(stmt, ") {");
6420 ctx.incIndent();
6421 if (stmt.constructorMethod != null) {
6422 if (stmt.constructorMethod.body.length > 0) {
6423 ctx.println(stmt, "var self = this;");
6424 this.visitAllStatements(stmt.constructorMethod.body, ctx);
6425 }
6426 }
6427 ctx.decIndent();
6428 ctx.println(stmt, "}");
6429 };
6430 AbstractJsEmitterVisitor.prototype._visitClassGetter = function (stmt, getter, ctx) {
6431 ctx.println(stmt, "Object.defineProperty(" + stmt.name + ".prototype, '" + getter.name + "', { get: function() {");
6432 ctx.incIndent();
6433 if (getter.body.length > 0) {
6434 ctx.println(stmt, "var self = this;");
6435 this.visitAllStatements(getter.body, ctx);
6436 }
6437 ctx.decIndent();
6438 ctx.println(stmt, "}});");
6439 };
6440 AbstractJsEmitterVisitor.prototype._visitClassMethod = function (stmt, method, ctx) {
6441 ctx.print(stmt, stmt.name + ".prototype." + method.name + " = function(");
6442 this._visitParams(method.params, ctx);
6443 ctx.println(stmt, ") {");
6444 ctx.incIndent();
6445 if (method.body.length > 0) {
6446 ctx.println(stmt, "var self = this;");
6447 this.visitAllStatements(method.body, ctx);
6448 }
6449 ctx.decIndent();
6450 ctx.println(stmt, "};");
6451 };
6452 AbstractJsEmitterVisitor.prototype.visitWrappedNodeExpr = function (ast, ctx) {
6453 throw new Error('Cannot emit a WrappedNodeExpr in Javascript.');
6454 };
6455 AbstractJsEmitterVisitor.prototype.visitReadVarExpr = function (ast, ctx) {
6456 if (ast.builtin === BuiltinVar.This) {
6457 ctx.print(ast, 'self');
6458 }
6459 else if (ast.builtin === BuiltinVar.Super) {
6460 throw new Error("'super' needs to be handled at a parent ast node, not at the variable level!");
6461 }
6462 else {
6463 _super.prototype.visitReadVarExpr.call(this, ast, ctx);
6464 }
6465 return null;
6466 };
6467 AbstractJsEmitterVisitor.prototype.visitDeclareVarStmt = function (stmt, ctx) {
6468 ctx.print(stmt, "var " + stmt.name);
6469 if (stmt.value) {
6470 ctx.print(stmt, ' = ');
6471 stmt.value.visitExpression(this, ctx);
6472 }
6473 ctx.println(stmt, ";");
6474 return null;
6475 };
6476 AbstractJsEmitterVisitor.prototype.visitCastExpr = function (ast, ctx) {
6477 ast.value.visitExpression(this, ctx);
6478 return null;
6479 };
6480 AbstractJsEmitterVisitor.prototype.visitInvokeFunctionExpr = function (expr, ctx) {
6481 var fnExpr = expr.fn;
6482 if (fnExpr instanceof ReadVarExpr && fnExpr.builtin === BuiltinVar.Super) {
6483 ctx.currentClass.parent.visitExpression(this, ctx);
6484 ctx.print(expr, ".call(this");
6485 if (expr.args.length > 0) {
6486 ctx.print(expr, ", ");
6487 this.visitAllExpressions(expr.args, ctx, ',');
6488 }
6489 ctx.print(expr, ")");
6490 }
6491 else {
6492 _super.prototype.visitInvokeFunctionExpr.call(this, expr, ctx);
6493 }
6494 return null;
6495 };
6496 AbstractJsEmitterVisitor.prototype.visitFunctionExpr = function (ast, ctx) {
6497 ctx.print(ast, "function" + (ast.name ? ' ' + ast.name : '') + "(");
6498 this._visitParams(ast.params, ctx);
6499 ctx.println(ast, ") {");
6500 ctx.incIndent();
6501 this.visitAllStatements(ast.statements, ctx);
6502 ctx.decIndent();
6503 ctx.print(ast, "}");
6504 return null;
6505 };
6506 AbstractJsEmitterVisitor.prototype.visitDeclareFunctionStmt = function (stmt, ctx) {
6507 ctx.print(stmt, "function " + stmt.name + "(");
6508 this._visitParams(stmt.params, ctx);
6509 ctx.println(stmt, ") {");
6510 ctx.incIndent();
6511 this.visitAllStatements(stmt.statements, ctx);
6512 ctx.decIndent();
6513 ctx.println(stmt, "}");
6514 return null;
6515 };
6516 AbstractJsEmitterVisitor.prototype.visitTryCatchStmt = function (stmt, ctx) {
6517 ctx.println(stmt, "try {");
6518 ctx.incIndent();
6519 this.visitAllStatements(stmt.bodyStmts, ctx);
6520 ctx.decIndent();
6521 ctx.println(stmt, "} catch (" + CATCH_ERROR_VAR$1.name + ") {");
6522 ctx.incIndent();
6523 var catchStmts = [CATCH_STACK_VAR$1.set(CATCH_ERROR_VAR$1.prop('stack')).toDeclStmt(null, [
6524 StmtModifier.Final
6525 ])].concat(stmt.catchStmts);
6526 this.visitAllStatements(catchStmts, ctx);
6527 ctx.decIndent();
6528 ctx.println(stmt, "}");
6529 return null;
6530 };
6531 AbstractJsEmitterVisitor.prototype._visitParams = function (params, ctx) {
6532 this.visitAllObjects(function (param) { return ctx.print(null, param.name); }, params, ctx, ',');
6533 };
6534 AbstractJsEmitterVisitor.prototype.getBuiltinMethodName = function (method) {
6535 var name;
6536 switch (method) {
6537 case BuiltinMethod.ConcatArray:
6538 name = 'concat';
6539 break;
6540 case BuiltinMethod.SubscribeObservable:
6541 name = 'subscribe';
6542 break;
6543 case BuiltinMethod.Bind:
6544 name = 'bind';
6545 break;
6546 default:
6547 throw new Error("Unknown builtin method: " + method);
6548 }
6549 return name;
6550 };
6551 return AbstractJsEmitterVisitor;
6552}(AbstractEmitterVisitor));
6553
6554/**
6555 * @license
6556 * Copyright Google Inc. All Rights Reserved.
6557 *
6558 * Use of this source code is governed by an MIT-style license that can be
6559 * found in the LICENSE file at https://angular.io/license
6560 */
6561/**
6562 * A helper class to manage the evaluation of JIT generated code.
6563 */
6564var JitEvaluator = /** @class */ (function () {
6565 function JitEvaluator() {
6566 }
6567 /**
6568 *
6569 * @param sourceUrl The URL of the generated code.
6570 * @param statements An array of Angular statement AST nodes to be evaluated.
6571 * @param reflector A helper used when converting the statements to executable code.
6572 * @param createSourceMaps If true then create a source-map for the generated code and include it
6573 * inline as a source-map comment.
6574 * @returns A map of all the variables in the generated code.
6575 */
6576 JitEvaluator.prototype.evaluateStatements = function (sourceUrl, statements, reflector, createSourceMaps) {
6577 var converter = new JitEmitterVisitor(reflector);
6578 var ctx = EmitterVisitorContext.createRoot();
6579 // Ensure generated code is in strict mode
6580 if (statements.length > 0 && !isUseStrictStatement(statements[0])) {
6581 statements = __spread([
6582 literal('use strict').toStmt()
6583 ], statements);
6584 }
6585 converter.visitAllStatements(statements, ctx);
6586 converter.createReturnStmt(ctx);
6587 return this.evaluateCode(sourceUrl, ctx, converter.getArgs(), createSourceMaps);
6588 };
6589 /**
6590 * Evaluate a piece of JIT generated code.
6591 * @param sourceUrl The URL of this generated code.
6592 * @param ctx A context object that contains an AST of the code to be evaluated.
6593 * @param vars A map containing the names and values of variables that the evaluated code might
6594 * reference.
6595 * @param createSourceMap If true then create a source-map for the generated code and include it
6596 * inline as a source-map comment.
6597 * @returns The result of evaluating the code.
6598 */
6599 JitEvaluator.prototype.evaluateCode = function (sourceUrl, ctx, vars, createSourceMap) {
6600 var fnBody = "\"use strict\";" + ctx.toSource() + "\n//# sourceURL=" + sourceUrl;
6601 var fnArgNames = [];
6602 var fnArgValues = [];
6603 for (var argName in vars) {
6604 fnArgValues.push(vars[argName]);
6605 fnArgNames.push(argName);
6606 }
6607 if (createSourceMap) {
6608 // using `new Function(...)` generates a header, 1 line of no arguments, 2 lines otherwise
6609 // E.g. ```
6610 // function anonymous(a,b,c
6611 // /**/) { ... }```
6612 // We don't want to hard code this fact, so we auto detect it via an empty function first.
6613 var emptyFn = new (Function.bind.apply(Function, __spread([void 0], fnArgNames.concat('return null;'))))().toString();
6614 var headerLines = emptyFn.slice(0, emptyFn.indexOf('return null;')).split('\n').length - 1;
6615 fnBody += "\n" + ctx.toSourceMapGenerator(sourceUrl, headerLines).toJsComment();
6616 }
6617 var fn = new (Function.bind.apply(Function, __spread([void 0], fnArgNames.concat(fnBody))))();
6618 return this.executeFunction(fn, fnArgValues);
6619 };
6620 /**
6621 * Execute a JIT generated function by calling it.
6622 *
6623 * This method can be overridden in tests to capture the functions that are generated
6624 * by this `JitEvaluator` class.
6625 *
6626 * @param fn A function to execute.
6627 * @param args The arguments to pass to the function being executed.
6628 * @returns The return value of the executed function.
6629 */
6630 JitEvaluator.prototype.executeFunction = function (fn, args) { return fn.apply(void 0, __spread(args)); };
6631 return JitEvaluator;
6632}());
6633/**
6634 * An Angular AST visitor that converts AST nodes into executable JavaScript code.
6635 */
6636var JitEmitterVisitor = /** @class */ (function (_super) {
6637 __extends(JitEmitterVisitor, _super);
6638 function JitEmitterVisitor(reflector) {
6639 var _this = _super.call(this) || this;
6640 _this.reflector = reflector;
6641 _this._evalArgNames = [];
6642 _this._evalArgValues = [];
6643 _this._evalExportedVars = [];
6644 return _this;
6645 }
6646 JitEmitterVisitor.prototype.createReturnStmt = function (ctx) {
6647 var stmt = new ReturnStatement(new LiteralMapExpr(this._evalExportedVars.map(function (resultVar) { return new LiteralMapEntry(resultVar, variable(resultVar), false); })));
6648 stmt.visitStatement(this, ctx);
6649 };
6650 JitEmitterVisitor.prototype.getArgs = function () {
6651 var result = {};
6652 for (var i = 0; i < this._evalArgNames.length; i++) {
6653 result[this._evalArgNames[i]] = this._evalArgValues[i];
6654 }
6655 return result;
6656 };
6657 JitEmitterVisitor.prototype.visitExternalExpr = function (ast, ctx) {
6658 this._emitReferenceToExternal(ast, this.reflector.resolveExternalReference(ast.value), ctx);
6659 return null;
6660 };
6661 JitEmitterVisitor.prototype.visitWrappedNodeExpr = function (ast, ctx) {
6662 this._emitReferenceToExternal(ast, ast.node, ctx);
6663 return null;
6664 };
6665 JitEmitterVisitor.prototype.visitDeclareVarStmt = function (stmt, ctx) {
6666 if (stmt.hasModifier(StmtModifier.Exported)) {
6667 this._evalExportedVars.push(stmt.name);
6668 }
6669 return _super.prototype.visitDeclareVarStmt.call(this, stmt, ctx);
6670 };
6671 JitEmitterVisitor.prototype.visitDeclareFunctionStmt = function (stmt, ctx) {
6672 if (stmt.hasModifier(StmtModifier.Exported)) {
6673 this._evalExportedVars.push(stmt.name);
6674 }
6675 return _super.prototype.visitDeclareFunctionStmt.call(this, stmt, ctx);
6676 };
6677 JitEmitterVisitor.prototype.visitDeclareClassStmt = function (stmt, ctx) {
6678 if (stmt.hasModifier(StmtModifier.Exported)) {
6679 this._evalExportedVars.push(stmt.name);
6680 }
6681 return _super.prototype.visitDeclareClassStmt.call(this, stmt, ctx);
6682 };
6683 JitEmitterVisitor.prototype._emitReferenceToExternal = function (ast, value, ctx) {
6684 var id = this._evalArgValues.indexOf(value);
6685 if (id === -1) {
6686 id = this._evalArgValues.length;
6687 this._evalArgValues.push(value);
6688 var name_1 = identifierName({ reference: value }) || 'val';
6689 this._evalArgNames.push("jit_" + name_1 + "_" + id);
6690 }
6691 ctx.print(ast, this._evalArgNames[id]);
6692 };
6693 return JitEmitterVisitor;
6694}(AbstractJsEmitterVisitor));
6695function isUseStrictStatement(statement) {
6696 return statement.isEquivalent(literal('use strict').toStmt());
6697}
6698
6699/**
6700 * @license
6701 * Copyright Google Inc. All Rights Reserved.
6702 *
6703 * Use of this source code is governed by an MIT-style license that can be
6704 * found in the LICENSE file at https://angular.io/license
6705 */
6706/**
6707 * Implementation of `CompileReflector` which resolves references to @angular/core
6708 * symbols at runtime, according to a consumer-provided mapping.
6709 *
6710 * Only supports `resolveExternalReference`, all other methods throw.
6711 */
6712var R3JitReflector = /** @class */ (function () {
6713 function R3JitReflector(context) {
6714 this.context = context;
6715 }
6716 R3JitReflector.prototype.resolveExternalReference = function (ref) {
6717 // This reflector only handles @angular/core imports.
6718 if (ref.moduleName !== '@angular/core') {
6719 throw new Error("Cannot resolve external reference to " + ref.moduleName + ", only references to @angular/core are supported.");
6720 }
6721 if (!this.context.hasOwnProperty(ref.name)) {
6722 throw new Error("No value provided for @angular/core symbol '" + ref.name + "'.");
6723 }
6724 return this.context[ref.name];
6725 };
6726 R3JitReflector.prototype.parameters = function (typeOrFunc) { throw new Error('Not implemented.'); };
6727 R3JitReflector.prototype.annotations = function (typeOrFunc) { throw new Error('Not implemented.'); };
6728 R3JitReflector.prototype.shallowAnnotations = function (typeOrFunc) { throw new Error('Not implemented.'); };
6729 R3JitReflector.prototype.tryAnnotations = function (typeOrFunc) { throw new Error('Not implemented.'); };
6730 R3JitReflector.prototype.propMetadata = function (typeOrFunc) { throw new Error('Not implemented.'); };
6731 R3JitReflector.prototype.hasLifecycleHook = function (type, lcProperty) { throw new Error('Not implemented.'); };
6732 R3JitReflector.prototype.guards = function (typeOrFunc) { throw new Error('Not implemented.'); };
6733 R3JitReflector.prototype.componentModuleUrl = function (type, cmpMetadata) { throw new Error('Not implemented.'); };
6734 return R3JitReflector;
6735}());
6736
6737/**
6738 * @license
6739 * Copyright Google Inc. All Rights Reserved.
6740 *
6741 * Use of this source code is governed by an MIT-style license that can be
6742 * found in the LICENSE file at https://angular.io/license
6743 */
6744/**
6745 * Construct an `R3NgModuleDef` for the given `R3NgModuleMetadata`.
6746 */
6747function compileNgModule(meta) {
6748 var moduleType = meta.type, bootstrap = meta.bootstrap, declarations = meta.declarations, imports = meta.imports, exports = meta.exports, schemas = meta.schemas, containsForwardDecls = meta.containsForwardDecls, emitInline = meta.emitInline, id = meta.id;
6749 var additionalStatements = [];
6750 var definitionMap = {
6751 type: moduleType
6752 };
6753 // Only generate the keys in the metadata if the arrays have values.
6754 if (bootstrap.length) {
6755 definitionMap.bootstrap = refsToArray(bootstrap, containsForwardDecls);
6756 }
6757 // If requested to emit scope information inline, pass the declarations, imports and exports to
6758 // the `ɵɵdefineNgModule` call. The JIT compilation uses this.
6759 if (emitInline) {
6760 if (declarations.length) {
6761 definitionMap.declarations = refsToArray(declarations, containsForwardDecls);
6762 }
6763 if (imports.length) {
6764 definitionMap.imports = refsToArray(imports, containsForwardDecls);
6765 }
6766 if (exports.length) {
6767 definitionMap.exports = refsToArray(exports, containsForwardDecls);
6768 }
6769 }
6770 // If not emitting inline, the scope information is not passed into `ɵɵdefineNgModule` as it would
6771 // prevent tree-shaking of the declarations, imports and exports references.
6772 else {
6773 var setNgModuleScopeCall = generateSetNgModuleScopeCall(meta);
6774 if (setNgModuleScopeCall !== null) {
6775 additionalStatements.push(setNgModuleScopeCall);
6776 }
6777 }
6778 if (schemas && schemas.length) {
6779 definitionMap.schemas = literalArr(schemas.map(function (ref) { return ref.value; }));
6780 }
6781 if (id) {
6782 definitionMap.id = id;
6783 }
6784 var expression = importExpr(Identifiers$1.defineNgModule).callFn([mapToMapExpression(definitionMap)]);
6785 var type = new ExpressionType(importExpr(Identifiers$1.NgModuleDefWithMeta, [
6786 new ExpressionType(moduleType), tupleTypeOf(declarations), tupleTypeOf(imports),
6787 tupleTypeOf(exports)
6788 ]));
6789 return { expression: expression, type: type, additionalStatements: additionalStatements };
6790}
6791/**
6792 * Generates a function call to `ɵɵsetNgModuleScope` with all necessary information so that the
6793 * transitive module scope can be computed during runtime in JIT mode. This call is marked pure
6794 * such that the references to declarations, imports and exports may be elided causing these
6795 * symbols to become tree-shakeable.
6796 */
6797function generateSetNgModuleScopeCall(meta) {
6798 var moduleType = meta.type, declarations = meta.declarations, imports = meta.imports, exports = meta.exports, containsForwardDecls = meta.containsForwardDecls;
6799 var scopeMap = {};
6800 if (declarations.length) {
6801 scopeMap.declarations = refsToArray(declarations, containsForwardDecls);
6802 }
6803 if (imports.length) {
6804 scopeMap.imports = refsToArray(imports, containsForwardDecls);
6805 }
6806 if (exports.length) {
6807 scopeMap.exports = refsToArray(exports, containsForwardDecls);
6808 }
6809 if (Object.keys(scopeMap).length === 0) {
6810 return null;
6811 }
6812 var fnCall = new InvokeFunctionExpr(
6813 /* fn */ importExpr(Identifiers$1.setNgModuleScope),
6814 /* args */ [moduleType, mapToMapExpression(scopeMap)],
6815 /* type */ undefined,
6816 /* sourceSpan */ undefined,
6817 /* pure */ true);
6818 return fnCall.toStmt();
6819}
6820function compileInjector(meta) {
6821 var result = compileFactoryFunction({
6822 name: meta.name,
6823 type: meta.type,
6824 deps: meta.deps,
6825 injectFn: Identifiers$1.inject,
6826 });
6827 var definitionMap = {
6828 factory: result.factory,
6829 };
6830 if (meta.providers !== null) {
6831 definitionMap.providers = meta.providers;
6832 }
6833 if (meta.imports.length > 0) {
6834 definitionMap.imports = literalArr(meta.imports);
6835 }
6836 var expression = importExpr(Identifiers$1.defineInjector).callFn([mapToMapExpression(definitionMap)]);
6837 var type = new ExpressionType(importExpr(Identifiers$1.InjectorDef, [new ExpressionType(meta.type)]));
6838 return { expression: expression, type: type, statements: result.statements };
6839}
6840// TODO(alxhub): integrate this with `compileNgModule`. Currently the two are separate operations.
6841function compileNgModuleFromRender2(ctx, ngModule, injectableCompiler) {
6842 var className = identifierName(ngModule.type);
6843 var rawImports = ngModule.rawImports ? [ngModule.rawImports] : [];
6844 var rawExports = ngModule.rawExports ? [ngModule.rawExports] : [];
6845 var injectorDefArg = mapLiteral({
6846 'factory': injectableCompiler.factoryFor({ type: ngModule.type, symbol: ngModule.type.reference }, ctx),
6847 'providers': convertMetaToOutput(ngModule.rawProviders, ctx),
6848 'imports': convertMetaToOutput(__spread(rawImports, rawExports), ctx),
6849 });
6850 var injectorDef = importExpr(Identifiers$1.defineInjector).callFn([injectorDefArg]);
6851 ctx.statements.push(new ClassStmt(
6852 /* name */ className,
6853 /* parent */ null,
6854 /* fields */ [new ClassField(
6855 /* name */ 'ngInjectorDef',
6856 /* type */ INFERRED_TYPE,
6857 /* modifiers */ [StmtModifier.Static],
6858 /* initializer */ injectorDef)],
6859 /* getters */ [],
6860 /* constructorMethod */ new ClassMethod(null, [], []),
6861 /* methods */ []));
6862}
6863function accessExportScope(module) {
6864 var selectorScope = new ReadPropExpr(module, 'ngModuleDef');
6865 return new ReadPropExpr(selectorScope, 'exported');
6866}
6867function tupleTypeOf(exp) {
6868 var types = exp.map(function (ref) { return typeofExpr(ref.type); });
6869 return exp.length > 0 ? expressionType(literalArr(types)) : NONE_TYPE;
6870}
6871function refsToArray(refs, shouldForwardDeclare) {
6872 var values = literalArr(refs.map(function (ref) { return ref.value; }));
6873 return shouldForwardDeclare ? fn([], [new ReturnStatement(values)]) : values;
6874}
6875
6876/**
6877 * @license
6878 * Copyright Google Inc. All Rights Reserved.
6879 *
6880 * Use of this source code is governed by an MIT-style license that can be
6881 * found in the LICENSE file at https://angular.io/license
6882 */
6883function compilePipeFromMetadata(metadata) {
6884 var definitionMapValues = [];
6885 // e.g. `name: 'myPipe'`
6886 definitionMapValues.push({ key: 'name', value: literal(metadata.pipeName), quoted: false });
6887 // e.g. `type: MyPipe`
6888 definitionMapValues.push({ key: 'type', value: metadata.type, quoted: false });
6889 var templateFactory = compileFactoryFunction({
6890 name: metadata.name,
6891 type: metadata.type,
6892 deps: metadata.deps,
6893 injectFn: Identifiers$1.directiveInject,
6894 }, true);
6895 definitionMapValues.push({ key: 'factory', value: templateFactory.factory, quoted: false });
6896 // e.g. `pure: true`
6897 definitionMapValues.push({ key: 'pure', value: literal(metadata.pure), quoted: false });
6898 var expression = importExpr(Identifiers$1.definePipe).callFn([literalMap(definitionMapValues)]);
6899 var type = new ExpressionType(importExpr(Identifiers$1.PipeDefWithMeta, [
6900 typeWithParameters(metadata.type, metadata.typeArgumentCount),
6901 new ExpressionType(new LiteralExpr(metadata.pipeName)),
6902 ]));
6903 return { expression: expression, type: type, statements: templateFactory.statements };
6904}
6905/**
6906 * Write a pipe definition to the output context.
6907 */
6908function compilePipeFromRender2(outputCtx, pipe, reflector) {
6909 var definitionMapValues = [];
6910 var name = identifierName(pipe.type);
6911 if (!name) {
6912 return error("Cannot resolve the name of " + pipe.type);
6913 }
6914 var metadata = {
6915 name: name,
6916 pipeName: pipe.name,
6917 type: outputCtx.importExpr(pipe.type.reference),
6918 typeArgumentCount: 0,
6919 deps: dependenciesFromGlobalMetadata(pipe.type, outputCtx, reflector),
6920 pure: pipe.pure,
6921 };
6922 var res = compilePipeFromMetadata(metadata);
6923 var definitionField = outputCtx.constantPool.propertyNameOf(3 /* Pipe */);
6924 outputCtx.statements.push(new ClassStmt(
6925 /* name */ name,
6926 /* parent */ null,
6927 /* fields */ [new ClassField(
6928 /* name */ definitionField,
6929 /* type */ INFERRED_TYPE,
6930 /* modifiers */ [StmtModifier.Static],
6931 /* initializer */ res.expression)],
6932 /* getters */ [],
6933 /* constructorMethod */ new ClassMethod(null, [], []),
6934 /* methods */ []));
6935}
6936
6937/**
6938 * @license
6939 * Copyright Google Inc. All Rights Reserved.
6940 *
6941 * Use of this source code is governed by an MIT-style license that can be
6942 * found in the LICENSE file at https://angular.io/license
6943 */
6944var ParserError = /** @class */ (function () {
6945 function ParserError(message, input, errLocation, ctxLocation) {
6946 this.input = input;
6947 this.errLocation = errLocation;
6948 this.ctxLocation = ctxLocation;
6949 this.message = "Parser Error: " + message + " " + errLocation + " [" + input + "] in " + ctxLocation;
6950 }
6951 return ParserError;
6952}());
6953var ParseSpan = /** @class */ (function () {
6954 function ParseSpan(start, end) {
6955 this.start = start;
6956 this.end = end;
6957 }
6958 return ParseSpan;
6959}());
6960var AST = /** @class */ (function () {
6961 function AST(span) {
6962 this.span = span;
6963 }
6964 AST.prototype.visit = function (visitor, context) {
6965 if (context === void 0) { context = null; }
6966 return null;
6967 };
6968 AST.prototype.toString = function () { return 'AST'; };
6969 return AST;
6970}());
6971/**
6972 * Represents a quoted expression of the form:
6973 *
6974 * quote = prefix `:` uninterpretedExpression
6975 * prefix = identifier
6976 * uninterpretedExpression = arbitrary string
6977 *
6978 * A quoted expression is meant to be pre-processed by an AST transformer that
6979 * converts it into another AST that no longer contains quoted expressions.
6980 * It is meant to allow third-party developers to extend Angular template
6981 * expression language. The `uninterpretedExpression` part of the quote is
6982 * therefore not interpreted by the Angular's own expression parser.
6983 */
6984var Quote = /** @class */ (function (_super) {
6985 __extends(Quote, _super);
6986 function Quote(span, prefix, uninterpretedExpression, location) {
6987 var _this = _super.call(this, span) || this;
6988 _this.prefix = prefix;
6989 _this.uninterpretedExpression = uninterpretedExpression;
6990 _this.location = location;
6991 return _this;
6992 }
6993 Quote.prototype.visit = function (visitor, context) {
6994 if (context === void 0) { context = null; }
6995 return visitor.visitQuote(this, context);
6996 };
6997 Quote.prototype.toString = function () { return 'Quote'; };
6998 return Quote;
6999}(AST));
7000var EmptyExpr = /** @class */ (function (_super) {
7001 __extends(EmptyExpr, _super);
7002 function EmptyExpr() {
7003 return _super !== null && _super.apply(this, arguments) || this;
7004 }
7005 EmptyExpr.prototype.visit = function (visitor, context) {
7006 if (context === void 0) { context = null; }
7007 // do nothing
7008 };
7009 return EmptyExpr;
7010}(AST));
7011var ImplicitReceiver = /** @class */ (function (_super) {
7012 __extends(ImplicitReceiver, _super);
7013 function ImplicitReceiver() {
7014 return _super !== null && _super.apply(this, arguments) || this;
7015 }
7016 ImplicitReceiver.prototype.visit = function (visitor, context) {
7017 if (context === void 0) { context = null; }
7018 return visitor.visitImplicitReceiver(this, context);
7019 };
7020 return ImplicitReceiver;
7021}(AST));
7022/**
7023 * Multiple expressions separated by a semicolon.
7024 */
7025var Chain = /** @class */ (function (_super) {
7026 __extends(Chain, _super);
7027 function Chain(span, expressions) {
7028 var _this = _super.call(this, span) || this;
7029 _this.expressions = expressions;
7030 return _this;
7031 }
7032 Chain.prototype.visit = function (visitor, context) {
7033 if (context === void 0) { context = null; }
7034 return visitor.visitChain(this, context);
7035 };
7036 return Chain;
7037}(AST));
7038var Conditional = /** @class */ (function (_super) {
7039 __extends(Conditional, _super);
7040 function Conditional(span, condition, trueExp, falseExp) {
7041 var _this = _super.call(this, span) || this;
7042 _this.condition = condition;
7043 _this.trueExp = trueExp;
7044 _this.falseExp = falseExp;
7045 return _this;
7046 }
7047 Conditional.prototype.visit = function (visitor, context) {
7048 if (context === void 0) { context = null; }
7049 return visitor.visitConditional(this, context);
7050 };
7051 return Conditional;
7052}(AST));
7053var PropertyRead = /** @class */ (function (_super) {
7054 __extends(PropertyRead, _super);
7055 function PropertyRead(span, receiver, name) {
7056 var _this = _super.call(this, span) || this;
7057 _this.receiver = receiver;
7058 _this.name = name;
7059 return _this;
7060 }
7061 PropertyRead.prototype.visit = function (visitor, context) {
7062 if (context === void 0) { context = null; }
7063 return visitor.visitPropertyRead(this, context);
7064 };
7065 return PropertyRead;
7066}(AST));
7067var PropertyWrite = /** @class */ (function (_super) {
7068 __extends(PropertyWrite, _super);
7069 function PropertyWrite(span, receiver, name, value) {
7070 var _this = _super.call(this, span) || this;
7071 _this.receiver = receiver;
7072 _this.name = name;
7073 _this.value = value;
7074 return _this;
7075 }
7076 PropertyWrite.prototype.visit = function (visitor, context) {
7077 if (context === void 0) { context = null; }
7078 return visitor.visitPropertyWrite(this, context);
7079 };
7080 return PropertyWrite;
7081}(AST));
7082var SafePropertyRead = /** @class */ (function (_super) {
7083 __extends(SafePropertyRead, _super);
7084 function SafePropertyRead(span, receiver, name) {
7085 var _this = _super.call(this, span) || this;
7086 _this.receiver = receiver;
7087 _this.name = name;
7088 return _this;
7089 }
7090 SafePropertyRead.prototype.visit = function (visitor, context) {
7091 if (context === void 0) { context = null; }
7092 return visitor.visitSafePropertyRead(this, context);
7093 };
7094 return SafePropertyRead;
7095}(AST));
7096var KeyedRead = /** @class */ (function (_super) {
7097 __extends(KeyedRead, _super);
7098 function KeyedRead(span, obj, key) {
7099 var _this = _super.call(this, span) || this;
7100 _this.obj = obj;
7101 _this.key = key;
7102 return _this;
7103 }
7104 KeyedRead.prototype.visit = function (visitor, context) {
7105 if (context === void 0) { context = null; }
7106 return visitor.visitKeyedRead(this, context);
7107 };
7108 return KeyedRead;
7109}(AST));
7110var KeyedWrite = /** @class */ (function (_super) {
7111 __extends(KeyedWrite, _super);
7112 function KeyedWrite(span, obj, key, value) {
7113 var _this = _super.call(this, span) || this;
7114 _this.obj = obj;
7115 _this.key = key;
7116 _this.value = value;
7117 return _this;
7118 }
7119 KeyedWrite.prototype.visit = function (visitor, context) {
7120 if (context === void 0) { context = null; }
7121 return visitor.visitKeyedWrite(this, context);
7122 };
7123 return KeyedWrite;
7124}(AST));
7125var BindingPipe = /** @class */ (function (_super) {
7126 __extends(BindingPipe, _super);
7127 function BindingPipe(span, exp, name, args) {
7128 var _this = _super.call(this, span) || this;
7129 _this.exp = exp;
7130 _this.name = name;
7131 _this.args = args;
7132 return _this;
7133 }
7134 BindingPipe.prototype.visit = function (visitor, context) {
7135 if (context === void 0) { context = null; }
7136 return visitor.visitPipe(this, context);
7137 };
7138 return BindingPipe;
7139}(AST));
7140var LiteralPrimitive = /** @class */ (function (_super) {
7141 __extends(LiteralPrimitive, _super);
7142 function LiteralPrimitive(span, value) {
7143 var _this = _super.call(this, span) || this;
7144 _this.value = value;
7145 return _this;
7146 }
7147 LiteralPrimitive.prototype.visit = function (visitor, context) {
7148 if (context === void 0) { context = null; }
7149 return visitor.visitLiteralPrimitive(this, context);
7150 };
7151 return LiteralPrimitive;
7152}(AST));
7153var LiteralArray = /** @class */ (function (_super) {
7154 __extends(LiteralArray, _super);
7155 function LiteralArray(span, expressions) {
7156 var _this = _super.call(this, span) || this;
7157 _this.expressions = expressions;
7158 return _this;
7159 }
7160 LiteralArray.prototype.visit = function (visitor, context) {
7161 if (context === void 0) { context = null; }
7162 return visitor.visitLiteralArray(this, context);
7163 };
7164 return LiteralArray;
7165}(AST));
7166var LiteralMap = /** @class */ (function (_super) {
7167 __extends(LiteralMap, _super);
7168 function LiteralMap(span, keys, values) {
7169 var _this = _super.call(this, span) || this;
7170 _this.keys = keys;
7171 _this.values = values;
7172 return _this;
7173 }
7174 LiteralMap.prototype.visit = function (visitor, context) {
7175 if (context === void 0) { context = null; }
7176 return visitor.visitLiteralMap(this, context);
7177 };
7178 return LiteralMap;
7179}(AST));
7180var Interpolation = /** @class */ (function (_super) {
7181 __extends(Interpolation, _super);
7182 function Interpolation(span, strings, expressions) {
7183 var _this = _super.call(this, span) || this;
7184 _this.strings = strings;
7185 _this.expressions = expressions;
7186 return _this;
7187 }
7188 Interpolation.prototype.visit = function (visitor, context) {
7189 if (context === void 0) { context = null; }
7190 return visitor.visitInterpolation(this, context);
7191 };
7192 return Interpolation;
7193}(AST));
7194var Binary = /** @class */ (function (_super) {
7195 __extends(Binary, _super);
7196 function Binary(span, operation, left, right) {
7197 var _this = _super.call(this, span) || this;
7198 _this.operation = operation;
7199 _this.left = left;
7200 _this.right = right;
7201 return _this;
7202 }
7203 Binary.prototype.visit = function (visitor, context) {
7204 if (context === void 0) { context = null; }
7205 return visitor.visitBinary(this, context);
7206 };
7207 return Binary;
7208}(AST));
7209var PrefixNot = /** @class */ (function (_super) {
7210 __extends(PrefixNot, _super);
7211 function PrefixNot(span, expression) {
7212 var _this = _super.call(this, span) || this;
7213 _this.expression = expression;
7214 return _this;
7215 }
7216 PrefixNot.prototype.visit = function (visitor, context) {
7217 if (context === void 0) { context = null; }
7218 return visitor.visitPrefixNot(this, context);
7219 };
7220 return PrefixNot;
7221}(AST));
7222var NonNullAssert = /** @class */ (function (_super) {
7223 __extends(NonNullAssert, _super);
7224 function NonNullAssert(span, expression) {
7225 var _this = _super.call(this, span) || this;
7226 _this.expression = expression;
7227 return _this;
7228 }
7229 NonNullAssert.prototype.visit = function (visitor, context) {
7230 if (context === void 0) { context = null; }
7231 return visitor.visitNonNullAssert(this, context);
7232 };
7233 return NonNullAssert;
7234}(AST));
7235var MethodCall = /** @class */ (function (_super) {
7236 __extends(MethodCall, _super);
7237 function MethodCall(span, receiver, name, args) {
7238 var _this = _super.call(this, span) || this;
7239 _this.receiver = receiver;
7240 _this.name = name;
7241 _this.args = args;
7242 return _this;
7243 }
7244 MethodCall.prototype.visit = function (visitor, context) {
7245 if (context === void 0) { context = null; }
7246 return visitor.visitMethodCall(this, context);
7247 };
7248 return MethodCall;
7249}(AST));
7250var SafeMethodCall = /** @class */ (function (_super) {
7251 __extends(SafeMethodCall, _super);
7252 function SafeMethodCall(span, receiver, name, args) {
7253 var _this = _super.call(this, span) || this;
7254 _this.receiver = receiver;
7255 _this.name = name;
7256 _this.args = args;
7257 return _this;
7258 }
7259 SafeMethodCall.prototype.visit = function (visitor, context) {
7260 if (context === void 0) { context = null; }
7261 return visitor.visitSafeMethodCall(this, context);
7262 };
7263 return SafeMethodCall;
7264}(AST));
7265var FunctionCall = /** @class */ (function (_super) {
7266 __extends(FunctionCall, _super);
7267 function FunctionCall(span, target, args) {
7268 var _this = _super.call(this, span) || this;
7269 _this.target = target;
7270 _this.args = args;
7271 return _this;
7272 }
7273 FunctionCall.prototype.visit = function (visitor, context) {
7274 if (context === void 0) { context = null; }
7275 return visitor.visitFunctionCall(this, context);
7276 };
7277 return FunctionCall;
7278}(AST));
7279/**
7280 * Records the absolute position of a text span in a source file, where `start` and `end` are the
7281 * starting and ending byte offsets, respectively, of the text span in a source file.
7282 */
7283var AbsoluteSourceSpan = /** @class */ (function () {
7284 function AbsoluteSourceSpan(start, end) {
7285 this.start = start;
7286 this.end = end;
7287 }
7288 return AbsoluteSourceSpan;
7289}());
7290var ASTWithSource = /** @class */ (function (_super) {
7291 __extends(ASTWithSource, _super);
7292 function ASTWithSource(ast, source, location, absoluteOffset, errors) {
7293 var _this = _super.call(this, new ParseSpan(0, source == null ? 0 : source.length)) || this;
7294 _this.ast = ast;
7295 _this.source = source;
7296 _this.location = location;
7297 _this.errors = errors;
7298 _this.sourceSpan = new AbsoluteSourceSpan(absoluteOffset, absoluteOffset + _this.span.end);
7299 return _this;
7300 }
7301 ASTWithSource.prototype.visit = function (visitor, context) {
7302 if (context === void 0) { context = null; }
7303 if (visitor.visitASTWithSource) {
7304 return visitor.visitASTWithSource(this, context);
7305 }
7306 return this.ast.visit(visitor, context);
7307 };
7308 ASTWithSource.prototype.toString = function () { return this.source + " in " + this.location; };
7309 return ASTWithSource;
7310}(AST));
7311var TemplateBinding = /** @class */ (function () {
7312 function TemplateBinding(span, key, keyIsVar, name, expression) {
7313 this.span = span;
7314 this.key = key;
7315 this.keyIsVar = keyIsVar;
7316 this.name = name;
7317 this.expression = expression;
7318 }
7319 return TemplateBinding;
7320}());
7321var NullAstVisitor = /** @class */ (function () {
7322 function NullAstVisitor() {
7323 }
7324 NullAstVisitor.prototype.visitBinary = function (ast, context) { };
7325 NullAstVisitor.prototype.visitChain = function (ast, context) { };
7326 NullAstVisitor.prototype.visitConditional = function (ast, context) { };
7327 NullAstVisitor.prototype.visitFunctionCall = function (ast, context) { };
7328 NullAstVisitor.prototype.visitImplicitReceiver = function (ast, context) { };
7329 NullAstVisitor.prototype.visitInterpolation = function (ast, context) { };
7330 NullAstVisitor.prototype.visitKeyedRead = function (ast, context) { };
7331 NullAstVisitor.prototype.visitKeyedWrite = function (ast, context) { };
7332 NullAstVisitor.prototype.visitLiteralArray = function (ast, context) { };
7333 NullAstVisitor.prototype.visitLiteralMap = function (ast, context) { };
7334 NullAstVisitor.prototype.visitLiteralPrimitive = function (ast, context) { };
7335 NullAstVisitor.prototype.visitMethodCall = function (ast, context) { };
7336 NullAstVisitor.prototype.visitPipe = function (ast, context) { };
7337 NullAstVisitor.prototype.visitPrefixNot = function (ast, context) { };
7338 NullAstVisitor.prototype.visitNonNullAssert = function (ast, context) { };
7339 NullAstVisitor.prototype.visitPropertyRead = function (ast, context) { };
7340 NullAstVisitor.prototype.visitPropertyWrite = function (ast, context) { };
7341 NullAstVisitor.prototype.visitQuote = function (ast, context) { };
7342 NullAstVisitor.prototype.visitSafeMethodCall = function (ast, context) { };
7343 NullAstVisitor.prototype.visitSafePropertyRead = function (ast, context) { };
7344 return NullAstVisitor;
7345}());
7346var RecursiveAstVisitor$1 = /** @class */ (function () {
7347 function RecursiveAstVisitor() {
7348 }
7349 RecursiveAstVisitor.prototype.visitBinary = function (ast, context) {
7350 ast.left.visit(this, context);
7351 ast.right.visit(this, context);
7352 return null;
7353 };
7354 RecursiveAstVisitor.prototype.visitChain = function (ast, context) { return this.visitAll(ast.expressions, context); };
7355 RecursiveAstVisitor.prototype.visitConditional = function (ast, context) {
7356 ast.condition.visit(this, context);
7357 ast.trueExp.visit(this, context);
7358 ast.falseExp.visit(this, context);
7359 return null;
7360 };
7361 RecursiveAstVisitor.prototype.visitPipe = function (ast, context) {
7362 ast.exp.visit(this, context);
7363 this.visitAll(ast.args, context);
7364 return null;
7365 };
7366 RecursiveAstVisitor.prototype.visitFunctionCall = function (ast, context) {
7367 ast.target.visit(this, context);
7368 this.visitAll(ast.args, context);
7369 return null;
7370 };
7371 RecursiveAstVisitor.prototype.visitImplicitReceiver = function (ast, context) { return null; };
7372 RecursiveAstVisitor.prototype.visitInterpolation = function (ast, context) {
7373 return this.visitAll(ast.expressions, context);
7374 };
7375 RecursiveAstVisitor.prototype.visitKeyedRead = function (ast, context) {
7376 ast.obj.visit(this, context);
7377 ast.key.visit(this, context);
7378 return null;
7379 };
7380 RecursiveAstVisitor.prototype.visitKeyedWrite = function (ast, context) {
7381 ast.obj.visit(this, context);
7382 ast.key.visit(this, context);
7383 ast.value.visit(this, context);
7384 return null;
7385 };
7386 RecursiveAstVisitor.prototype.visitLiteralArray = function (ast, context) {
7387 return this.visitAll(ast.expressions, context);
7388 };
7389 RecursiveAstVisitor.prototype.visitLiteralMap = function (ast, context) { return this.visitAll(ast.values, context); };
7390 RecursiveAstVisitor.prototype.visitLiteralPrimitive = function (ast, context) { return null; };
7391 RecursiveAstVisitor.prototype.visitMethodCall = function (ast, context) {
7392 ast.receiver.visit(this, context);
7393 return this.visitAll(ast.args, context);
7394 };
7395 RecursiveAstVisitor.prototype.visitPrefixNot = function (ast, context) {
7396 ast.expression.visit(this, context);
7397 return null;
7398 };
7399 RecursiveAstVisitor.prototype.visitNonNullAssert = function (ast, context) {
7400 ast.expression.visit(this, context);
7401 return null;
7402 };
7403 RecursiveAstVisitor.prototype.visitPropertyRead = function (ast, context) {
7404 ast.receiver.visit(this, context);
7405 return null;
7406 };
7407 RecursiveAstVisitor.prototype.visitPropertyWrite = function (ast, context) {
7408 ast.receiver.visit(this, context);
7409 ast.value.visit(this, context);
7410 return null;
7411 };
7412 RecursiveAstVisitor.prototype.visitSafePropertyRead = function (ast, context) {
7413 ast.receiver.visit(this, context);
7414 return null;
7415 };
7416 RecursiveAstVisitor.prototype.visitSafeMethodCall = function (ast, context) {
7417 ast.receiver.visit(this, context);
7418 return this.visitAll(ast.args, context);
7419 };
7420 RecursiveAstVisitor.prototype.visitAll = function (asts, context) {
7421 var _this = this;
7422 asts.forEach(function (ast) { return ast.visit(_this, context); });
7423 return null;
7424 };
7425 RecursiveAstVisitor.prototype.visitQuote = function (ast, context) { return null; };
7426 return RecursiveAstVisitor;
7427}());
7428var AstTransformer$1 = /** @class */ (function () {
7429 function AstTransformer() {
7430 }
7431 AstTransformer.prototype.visitImplicitReceiver = function (ast, context) { return ast; };
7432 AstTransformer.prototype.visitInterpolation = function (ast, context) {
7433 return new Interpolation(ast.span, ast.strings, this.visitAll(ast.expressions));
7434 };
7435 AstTransformer.prototype.visitLiteralPrimitive = function (ast, context) {
7436 return new LiteralPrimitive(ast.span, ast.value);
7437 };
7438 AstTransformer.prototype.visitPropertyRead = function (ast, context) {
7439 return new PropertyRead(ast.span, ast.receiver.visit(this), ast.name);
7440 };
7441 AstTransformer.prototype.visitPropertyWrite = function (ast, context) {
7442 return new PropertyWrite(ast.span, ast.receiver.visit(this), ast.name, ast.value.visit(this));
7443 };
7444 AstTransformer.prototype.visitSafePropertyRead = function (ast, context) {
7445 return new SafePropertyRead(ast.span, ast.receiver.visit(this), ast.name);
7446 };
7447 AstTransformer.prototype.visitMethodCall = function (ast, context) {
7448 return new MethodCall(ast.span, ast.receiver.visit(this), ast.name, this.visitAll(ast.args));
7449 };
7450 AstTransformer.prototype.visitSafeMethodCall = function (ast, context) {
7451 return new SafeMethodCall(ast.span, ast.receiver.visit(this), ast.name, this.visitAll(ast.args));
7452 };
7453 AstTransformer.prototype.visitFunctionCall = function (ast, context) {
7454 return new FunctionCall(ast.span, ast.target.visit(this), this.visitAll(ast.args));
7455 };
7456 AstTransformer.prototype.visitLiteralArray = function (ast, context) {
7457 return new LiteralArray(ast.span, this.visitAll(ast.expressions));
7458 };
7459 AstTransformer.prototype.visitLiteralMap = function (ast, context) {
7460 return new LiteralMap(ast.span, ast.keys, this.visitAll(ast.values));
7461 };
7462 AstTransformer.prototype.visitBinary = function (ast, context) {
7463 return new Binary(ast.span, ast.operation, ast.left.visit(this), ast.right.visit(this));
7464 };
7465 AstTransformer.prototype.visitPrefixNot = function (ast, context) {
7466 return new PrefixNot(ast.span, ast.expression.visit(this));
7467 };
7468 AstTransformer.prototype.visitNonNullAssert = function (ast, context) {
7469 return new NonNullAssert(ast.span, ast.expression.visit(this));
7470 };
7471 AstTransformer.prototype.visitConditional = function (ast, context) {
7472 return new Conditional(ast.span, ast.condition.visit(this), ast.trueExp.visit(this), ast.falseExp.visit(this));
7473 };
7474 AstTransformer.prototype.visitPipe = function (ast, context) {
7475 return new BindingPipe(ast.span, ast.exp.visit(this), ast.name, this.visitAll(ast.args));
7476 };
7477 AstTransformer.prototype.visitKeyedRead = function (ast, context) {
7478 return new KeyedRead(ast.span, ast.obj.visit(this), ast.key.visit(this));
7479 };
7480 AstTransformer.prototype.visitKeyedWrite = function (ast, context) {
7481 return new KeyedWrite(ast.span, ast.obj.visit(this), ast.key.visit(this), ast.value.visit(this));
7482 };
7483 AstTransformer.prototype.visitAll = function (asts) {
7484 var res = new Array(asts.length);
7485 for (var i = 0; i < asts.length; ++i) {
7486 res[i] = asts[i].visit(this);
7487 }
7488 return res;
7489 };
7490 AstTransformer.prototype.visitChain = function (ast, context) {
7491 return new Chain(ast.span, this.visitAll(ast.expressions));
7492 };
7493 AstTransformer.prototype.visitQuote = function (ast, context) {
7494 return new Quote(ast.span, ast.prefix, ast.uninterpretedExpression, ast.location);
7495 };
7496 return AstTransformer;
7497}());
7498// A transformer that only creates new nodes if the transformer makes a change or
7499// a change is made a child node.
7500var AstMemoryEfficientTransformer = /** @class */ (function () {
7501 function AstMemoryEfficientTransformer() {
7502 }
7503 AstMemoryEfficientTransformer.prototype.visitImplicitReceiver = function (ast, context) { return ast; };
7504 AstMemoryEfficientTransformer.prototype.visitInterpolation = function (ast, context) {
7505 var expressions = this.visitAll(ast.expressions);
7506 if (expressions !== ast.expressions)
7507 return new Interpolation(ast.span, ast.strings, expressions);
7508 return ast;
7509 };
7510 AstMemoryEfficientTransformer.prototype.visitLiteralPrimitive = function (ast, context) { return ast; };
7511 AstMemoryEfficientTransformer.prototype.visitPropertyRead = function (ast, context) {
7512 var receiver = ast.receiver.visit(this);
7513 if (receiver !== ast.receiver) {
7514 return new PropertyRead(ast.span, receiver, ast.name);
7515 }
7516 return ast;
7517 };
7518 AstMemoryEfficientTransformer.prototype.visitPropertyWrite = function (ast, context) {
7519 var receiver = ast.receiver.visit(this);
7520 var value = ast.value.visit(this);
7521 if (receiver !== ast.receiver || value !== ast.value) {
7522 return new PropertyWrite(ast.span, receiver, ast.name, value);
7523 }
7524 return ast;
7525 };
7526 AstMemoryEfficientTransformer.prototype.visitSafePropertyRead = function (ast, context) {
7527 var receiver = ast.receiver.visit(this);
7528 if (receiver !== ast.receiver) {
7529 return new SafePropertyRead(ast.span, receiver, ast.name);
7530 }
7531 return ast;
7532 };
7533 AstMemoryEfficientTransformer.prototype.visitMethodCall = function (ast, context) {
7534 var receiver = ast.receiver.visit(this);
7535 var args = this.visitAll(ast.args);
7536 if (receiver !== ast.receiver || args !== ast.args) {
7537 return new MethodCall(ast.span, receiver, ast.name, args);
7538 }
7539 return ast;
7540 };
7541 AstMemoryEfficientTransformer.prototype.visitSafeMethodCall = function (ast, context) {
7542 var receiver = ast.receiver.visit(this);
7543 var args = this.visitAll(ast.args);
7544 if (receiver !== ast.receiver || args !== ast.args) {
7545 return new SafeMethodCall(ast.span, receiver, ast.name, args);
7546 }
7547 return ast;
7548 };
7549 AstMemoryEfficientTransformer.prototype.visitFunctionCall = function (ast, context) {
7550 var target = ast.target && ast.target.visit(this);
7551 var args = this.visitAll(ast.args);
7552 if (target !== ast.target || args !== ast.args) {
7553 return new FunctionCall(ast.span, target, args);
7554 }
7555 return ast;
7556 };
7557 AstMemoryEfficientTransformer.prototype.visitLiteralArray = function (ast, context) {
7558 var expressions = this.visitAll(ast.expressions);
7559 if (expressions !== ast.expressions) {
7560 return new LiteralArray(ast.span, expressions);
7561 }
7562 return ast;
7563 };
7564 AstMemoryEfficientTransformer.prototype.visitLiteralMap = function (ast, context) {
7565 var values = this.visitAll(ast.values);
7566 if (values !== ast.values) {
7567 return new LiteralMap(ast.span, ast.keys, values);
7568 }
7569 return ast;
7570 };
7571 AstMemoryEfficientTransformer.prototype.visitBinary = function (ast, context) {
7572 var left = ast.left.visit(this);
7573 var right = ast.right.visit(this);
7574 if (left !== ast.left || right !== ast.right) {
7575 return new Binary(ast.span, ast.operation, left, right);
7576 }
7577 return ast;
7578 };
7579 AstMemoryEfficientTransformer.prototype.visitPrefixNot = function (ast, context) {
7580 var expression = ast.expression.visit(this);
7581 if (expression !== ast.expression) {
7582 return new PrefixNot(ast.span, expression);
7583 }
7584 return ast;
7585 };
7586 AstMemoryEfficientTransformer.prototype.visitNonNullAssert = function (ast, context) {
7587 var expression = ast.expression.visit(this);
7588 if (expression !== ast.expression) {
7589 return new NonNullAssert(ast.span, expression);
7590 }
7591 return ast;
7592 };
7593 AstMemoryEfficientTransformer.prototype.visitConditional = function (ast, context) {
7594 var condition = ast.condition.visit(this);
7595 var trueExp = ast.trueExp.visit(this);
7596 var falseExp = ast.falseExp.visit(this);
7597 if (condition !== ast.condition || trueExp !== ast.trueExp || falseExp !== ast.falseExp) {
7598 return new Conditional(ast.span, condition, trueExp, falseExp);
7599 }
7600 return ast;
7601 };
7602 AstMemoryEfficientTransformer.prototype.visitPipe = function (ast, context) {
7603 var exp = ast.exp.visit(this);
7604 var args = this.visitAll(ast.args);
7605 if (exp !== ast.exp || args !== ast.args) {
7606 return new BindingPipe(ast.span, exp, ast.name, args);
7607 }
7608 return ast;
7609 };
7610 AstMemoryEfficientTransformer.prototype.visitKeyedRead = function (ast, context) {
7611 var obj = ast.obj.visit(this);
7612 var key = ast.key.visit(this);
7613 if (obj !== ast.obj || key !== ast.key) {
7614 return new KeyedRead(ast.span, obj, key);
7615 }
7616 return ast;
7617 };
7618 AstMemoryEfficientTransformer.prototype.visitKeyedWrite = function (ast, context) {
7619 var obj = ast.obj.visit(this);
7620 var key = ast.key.visit(this);
7621 var value = ast.value.visit(this);
7622 if (obj !== ast.obj || key !== ast.key || value !== ast.value) {
7623 return new KeyedWrite(ast.span, obj, key, value);
7624 }
7625 return ast;
7626 };
7627 AstMemoryEfficientTransformer.prototype.visitAll = function (asts) {
7628 var res = new Array(asts.length);
7629 var modified = false;
7630 for (var i = 0; i < asts.length; ++i) {
7631 var original = asts[i];
7632 var value = original.visit(this);
7633 res[i] = value;
7634 modified = modified || value !== original;
7635 }
7636 return modified ? res : asts;
7637 };
7638 AstMemoryEfficientTransformer.prototype.visitChain = function (ast, context) {
7639 var expressions = this.visitAll(ast.expressions);
7640 if (expressions !== ast.expressions) {
7641 return new Chain(ast.span, expressions);
7642 }
7643 return ast;
7644 };
7645 AstMemoryEfficientTransformer.prototype.visitQuote = function (ast, context) { return ast; };
7646 return AstMemoryEfficientTransformer;
7647}());
7648function visitAstChildren(ast, visitor, context) {
7649 function visit(ast) {
7650 visitor.visit && visitor.visit(ast, context) || ast.visit(visitor, context);
7651 }
7652 function visitAll(asts) { asts.forEach(visit); }
7653 ast.visit({
7654 visitBinary: function (ast) {
7655 visit(ast.left);
7656 visit(ast.right);
7657 },
7658 visitChain: function (ast) { visitAll(ast.expressions); },
7659 visitConditional: function (ast) {
7660 visit(ast.condition);
7661 visit(ast.trueExp);
7662 visit(ast.falseExp);
7663 },
7664 visitFunctionCall: function (ast) {
7665 if (ast.target) {
7666 visit(ast.target);
7667 }
7668 visitAll(ast.args);
7669 },
7670 visitImplicitReceiver: function (ast) { },
7671 visitInterpolation: function (ast) { visitAll(ast.expressions); },
7672 visitKeyedRead: function (ast) {
7673 visit(ast.obj);
7674 visit(ast.key);
7675 },
7676 visitKeyedWrite: function (ast) {
7677 visit(ast.obj);
7678 visit(ast.key);
7679 visit(ast.obj);
7680 },
7681 visitLiteralArray: function (ast) { visitAll(ast.expressions); },
7682 visitLiteralMap: function (ast) { },
7683 visitLiteralPrimitive: function (ast) { },
7684 visitMethodCall: function (ast) {
7685 visit(ast.receiver);
7686 visitAll(ast.args);
7687 },
7688 visitPipe: function (ast) {
7689 visit(ast.exp);
7690 visitAll(ast.args);
7691 },
7692 visitPrefixNot: function (ast) { visit(ast.expression); },
7693 visitNonNullAssert: function (ast) { visit(ast.expression); },
7694 visitPropertyRead: function (ast) { visit(ast.receiver); },
7695 visitPropertyWrite: function (ast) {
7696 visit(ast.receiver);
7697 visit(ast.value);
7698 },
7699 visitQuote: function (ast) { },
7700 visitSafeMethodCall: function (ast) {
7701 visit(ast.receiver);
7702 visitAll(ast.args);
7703 },
7704 visitSafePropertyRead: function (ast) { visit(ast.receiver); },
7705 });
7706}
7707// Bindings
7708var ParsedProperty = /** @class */ (function () {
7709 function ParsedProperty(name, expression, type, sourceSpan, valueSpan) {
7710 this.name = name;
7711 this.expression = expression;
7712 this.type = type;
7713 this.sourceSpan = sourceSpan;
7714 this.valueSpan = valueSpan;
7715 this.isLiteral = this.type === ParsedPropertyType.LITERAL_ATTR;
7716 this.isAnimation = this.type === ParsedPropertyType.ANIMATION;
7717 }
7718 return ParsedProperty;
7719}());
7720var ParsedPropertyType;
7721(function (ParsedPropertyType) {
7722 ParsedPropertyType[ParsedPropertyType["DEFAULT"] = 0] = "DEFAULT";
7723 ParsedPropertyType[ParsedPropertyType["LITERAL_ATTR"] = 1] = "LITERAL_ATTR";
7724 ParsedPropertyType[ParsedPropertyType["ANIMATION"] = 2] = "ANIMATION";
7725})(ParsedPropertyType || (ParsedPropertyType = {}));
7726var ParsedEvent = /** @class */ (function () {
7727 // Regular events have a target
7728 // Animation events have a phase
7729 function ParsedEvent(name, targetOrPhase, type, handler, sourceSpan, handlerSpan) {
7730 this.name = name;
7731 this.targetOrPhase = targetOrPhase;
7732 this.type = type;
7733 this.handler = handler;
7734 this.sourceSpan = sourceSpan;
7735 this.handlerSpan = handlerSpan;
7736 }
7737 return ParsedEvent;
7738}());
7739var ParsedVariable = /** @class */ (function () {
7740 function ParsedVariable(name, value, sourceSpan) {
7741 this.name = name;
7742 this.value = value;
7743 this.sourceSpan = sourceSpan;
7744 }
7745 return ParsedVariable;
7746}());
7747var BoundElementProperty = /** @class */ (function () {
7748 function BoundElementProperty(name, type, securityContext, value, unit, sourceSpan, valueSpan) {
7749 this.name = name;
7750 this.type = type;
7751 this.securityContext = securityContext;
7752 this.value = value;
7753 this.unit = unit;
7754 this.sourceSpan = sourceSpan;
7755 this.valueSpan = valueSpan;
7756 }
7757 return BoundElementProperty;
7758}());
7759
7760/**
7761 * @license
7762 * Copyright Google Inc. All Rights Reserved.
7763 *
7764 * Use of this source code is governed by an MIT-style license that can be
7765 * found in the LICENSE file at https://angular.io/license
7766 */
7767var EventHandlerVars = /** @class */ (function () {
7768 function EventHandlerVars() {
7769 }
7770 EventHandlerVars.event = variable('$event');
7771 return EventHandlerVars;
7772}());
7773var ConvertActionBindingResult = /** @class */ (function () {
7774 function ConvertActionBindingResult(
7775 /**
7776 * Render2 compatible statements,
7777 */
7778 stmts,
7779 /**
7780 * Variable name used with render2 compatible statements.
7781 */
7782 allowDefault) {
7783 this.stmts = stmts;
7784 this.allowDefault = allowDefault;
7785 /**
7786 * This is bit of a hack. It converts statements which render2 expects to statements which are
7787 * expected by render3.
7788 *
7789 * Example: `<div click="doSomething($event)">` will generate:
7790 *
7791 * Render3:
7792 * ```
7793 * const pd_b:any = ((<any>ctx.doSomething($event)) !== false);
7794 * return pd_b;
7795 * ```
7796 *
7797 * but render2 expects:
7798 * ```
7799 * return ctx.doSomething($event);
7800 * ```
7801 */
7802 // TODO(misko): remove this hack once we no longer support ViewEngine.
7803 this.render3Stmts = stmts.map(function (statement) {
7804 if (statement instanceof DeclareVarStmt && statement.name == allowDefault.name &&
7805 statement.value instanceof BinaryOperatorExpr) {
7806 var lhs = statement.value.lhs;
7807 return new ReturnStatement(lhs.value);
7808 }
7809 return statement;
7810 });
7811 }
7812 return ConvertActionBindingResult;
7813}());
7814/**
7815 * Converts the given expression AST into an executable output AST, assuming the expression is
7816 * used in an action binding (e.g. an event handler).
7817 */
7818function convertActionBinding(localResolver, implicitReceiver, action, bindingId, interpolationFunction, baseSourceSpan) {
7819 if (!localResolver) {
7820 localResolver = new DefaultLocalResolver();
7821 }
7822 var actionWithoutBuiltins = convertPropertyBindingBuiltins({
7823 createLiteralArrayConverter: function (argCount) {
7824 // Note: no caching for literal arrays in actions.
7825 return function (args) { return literalArr(args); };
7826 },
7827 createLiteralMapConverter: function (keys) {
7828 // Note: no caching for literal maps in actions.
7829 return function (values) {
7830 var entries = keys.map(function (k, i) { return ({
7831 key: k.key,
7832 value: values[i],
7833 quoted: k.quoted,
7834 }); });
7835 return literalMap(entries);
7836 };
7837 },
7838 createPipeConverter: function (name) {
7839 throw new Error("Illegal State: Actions are not allowed to contain pipes. Pipe: " + name);
7840 }
7841 }, action);
7842 var visitor = new _AstToIrVisitor(localResolver, implicitReceiver, bindingId, interpolationFunction, baseSourceSpan);
7843 var actionStmts = [];
7844 flattenStatements(actionWithoutBuiltins.visit(visitor, _Mode.Statement), actionStmts);
7845 prependTemporaryDecls(visitor.temporaryCount, bindingId, actionStmts);
7846 if (visitor.usesImplicitReceiver) {
7847 localResolver.notifyImplicitReceiverUse();
7848 }
7849 var lastIndex = actionStmts.length - 1;
7850 var preventDefaultVar = null;
7851 if (lastIndex >= 0) {
7852 var lastStatement = actionStmts[lastIndex];
7853 var returnExpr = convertStmtIntoExpression(lastStatement);
7854 if (returnExpr) {
7855 // Note: We need to cast the result of the method call to dynamic,
7856 // as it might be a void method!
7857 preventDefaultVar = createPreventDefaultVar(bindingId);
7858 actionStmts[lastIndex] =
7859 preventDefaultVar.set(returnExpr.cast(DYNAMIC_TYPE).notIdentical(literal(false)))
7860 .toDeclStmt(null, [StmtModifier.Final]);
7861 }
7862 }
7863 return new ConvertActionBindingResult(actionStmts, preventDefaultVar);
7864}
7865function convertPropertyBindingBuiltins(converterFactory, ast) {
7866 return convertBuiltins(converterFactory, ast);
7867}
7868var ConvertPropertyBindingResult = /** @class */ (function () {
7869 function ConvertPropertyBindingResult(stmts, currValExpr) {
7870 this.stmts = stmts;
7871 this.currValExpr = currValExpr;
7872 }
7873 return ConvertPropertyBindingResult;
7874}());
7875var BindingForm;
7876(function (BindingForm) {
7877 // The general form of binding expression, supports all expressions.
7878 BindingForm[BindingForm["General"] = 0] = "General";
7879 // Try to generate a simple binding (no temporaries or statements)
7880 // otherwise generate a general binding
7881 BindingForm[BindingForm["TrySimple"] = 1] = "TrySimple";
7882})(BindingForm || (BindingForm = {}));
7883/**
7884 * Converts the given expression AST into an executable output AST, assuming the expression
7885 * is used in property binding. The expression has to be preprocessed via
7886 * `convertPropertyBindingBuiltins`.
7887 */
7888function convertPropertyBinding(localResolver, implicitReceiver, expressionWithoutBuiltins, bindingId, form, interpolationFunction) {
7889 if (!localResolver) {
7890 localResolver = new DefaultLocalResolver();
7891 }
7892 var currValExpr = createCurrValueExpr(bindingId);
7893 var visitor = new _AstToIrVisitor(localResolver, implicitReceiver, bindingId, interpolationFunction);
7894 var outputExpr = expressionWithoutBuiltins.visit(visitor, _Mode.Expression);
7895 var stmts = getStatementsFromVisitor(visitor, bindingId);
7896 if (visitor.usesImplicitReceiver) {
7897 localResolver.notifyImplicitReceiverUse();
7898 }
7899 if (visitor.temporaryCount === 0 && form == BindingForm.TrySimple) {
7900 return new ConvertPropertyBindingResult([], outputExpr);
7901 }
7902 stmts.push(currValExpr.set(outputExpr).toDeclStmt(DYNAMIC_TYPE, [StmtModifier.Final]));
7903 return new ConvertPropertyBindingResult(stmts, currValExpr);
7904}
7905/**
7906 * Given some expression, such as a binding or interpolation expression, and a context expression to
7907 * look values up on, visit each facet of the given expression resolving values from the context
7908 * expression such that a list of arguments can be derived from the found values that can be used as
7909 * arguments to an external update instruction.
7910 *
7911 * @param localResolver The resolver to use to look up expressions by name appropriately
7912 * @param contextVariableExpression The expression representing the context variable used to create
7913 * the final argument expressions
7914 * @param expressionWithArgumentsToExtract The expression to visit to figure out what values need to
7915 * be resolved and what arguments list to build.
7916 * @param bindingId A name prefix used to create temporary variable names if they're needed for the
7917 * arguments generated
7918 * @returns An array of expressions that can be passed as arguments to instruction expressions like
7919 * `o.importExpr(R3.propertyInterpolate).callFn(result)`
7920 */
7921function convertUpdateArguments(localResolver, contextVariableExpression, expressionWithArgumentsToExtract, bindingId) {
7922 var visitor = new _AstToIrVisitor(localResolver, contextVariableExpression, bindingId, undefined);
7923 var outputExpr = expressionWithArgumentsToExtract.visit(visitor, _Mode.Expression);
7924 if (visitor.usesImplicitReceiver) {
7925 localResolver.notifyImplicitReceiverUse();
7926 }
7927 var stmts = getStatementsFromVisitor(visitor, bindingId);
7928 // Removing the first argument, because it was a length for ViewEngine, not Ivy.
7929 var args = outputExpr.args.slice(1);
7930 if (expressionWithArgumentsToExtract instanceof Interpolation) {
7931 // If we're dealing with an interpolation of 1 value with an empty prefix and suffix, reduce the
7932 // args returned to just the value, because we're going to pass it to a special instruction.
7933 var strings = expressionWithArgumentsToExtract.strings;
7934 if (args.length === 3 && strings[0] === '' && strings[1] === '') {
7935 // Single argument interpolate instructions.
7936 args = [args[1]];
7937 }
7938 else if (args.length >= 19) {
7939 // 19 or more arguments must be passed to the `interpolateV`-style instructions, which accept
7940 // an array of arguments
7941 args = [literalArr(args)];
7942 }
7943 }
7944 return { stmts: stmts, args: args };
7945}
7946function getStatementsFromVisitor(visitor, bindingId) {
7947 var stmts = [];
7948 for (var i = 0; i < visitor.temporaryCount; i++) {
7949 stmts.push(temporaryDeclaration(bindingId, i));
7950 }
7951 return stmts;
7952}
7953function convertBuiltins(converterFactory, ast) {
7954 var visitor = new _BuiltinAstConverter(converterFactory);
7955 return ast.visit(visitor);
7956}
7957function temporaryName(bindingId, temporaryNumber) {
7958 return "tmp_" + bindingId + "_" + temporaryNumber;
7959}
7960function temporaryDeclaration(bindingId, temporaryNumber) {
7961 return new DeclareVarStmt(temporaryName(bindingId, temporaryNumber), NULL_EXPR);
7962}
7963function prependTemporaryDecls(temporaryCount, bindingId, statements) {
7964 for (var i = temporaryCount - 1; i >= 0; i--) {
7965 statements.unshift(temporaryDeclaration(bindingId, i));
7966 }
7967}
7968var _Mode;
7969(function (_Mode) {
7970 _Mode[_Mode["Statement"] = 0] = "Statement";
7971 _Mode[_Mode["Expression"] = 1] = "Expression";
7972})(_Mode || (_Mode = {}));
7973function ensureStatementMode(mode, ast) {
7974 if (mode !== _Mode.Statement) {
7975 throw new Error("Expected a statement, but saw " + ast);
7976 }
7977}
7978function ensureExpressionMode(mode, ast) {
7979 if (mode !== _Mode.Expression) {
7980 throw new Error("Expected an expression, but saw " + ast);
7981 }
7982}
7983function convertToStatementIfNeeded(mode, expr) {
7984 if (mode === _Mode.Statement) {
7985 return expr.toStmt();
7986 }
7987 else {
7988 return expr;
7989 }
7990}
7991var _BuiltinAstConverter = /** @class */ (function (_super) {
7992 __extends(_BuiltinAstConverter, _super);
7993 function _BuiltinAstConverter(_converterFactory) {
7994 var _this = _super.call(this) || this;
7995 _this._converterFactory = _converterFactory;
7996 return _this;
7997 }
7998 _BuiltinAstConverter.prototype.visitPipe = function (ast, context) {
7999 var _this = this;
8000 var args = __spread([ast.exp], ast.args).map(function (ast) { return ast.visit(_this, context); });
8001 return new BuiltinFunctionCall(ast.span, args, this._converterFactory.createPipeConverter(ast.name, args.length));
8002 };
8003 _BuiltinAstConverter.prototype.visitLiteralArray = function (ast, context) {
8004 var _this = this;
8005 var args = ast.expressions.map(function (ast) { return ast.visit(_this, context); });
8006 return new BuiltinFunctionCall(ast.span, args, this._converterFactory.createLiteralArrayConverter(ast.expressions.length));
8007 };
8008 _BuiltinAstConverter.prototype.visitLiteralMap = function (ast, context) {
8009 var _this = this;
8010 var args = ast.values.map(function (ast) { return ast.visit(_this, context); });
8011 return new BuiltinFunctionCall(ast.span, args, this._converterFactory.createLiteralMapConverter(ast.keys));
8012 };
8013 return _BuiltinAstConverter;
8014}(AstTransformer$1));
8015var _AstToIrVisitor = /** @class */ (function () {
8016 function _AstToIrVisitor(_localResolver, _implicitReceiver, bindingId, interpolationFunction, baseSourceSpan) {
8017 this._localResolver = _localResolver;
8018 this._implicitReceiver = _implicitReceiver;
8019 this.bindingId = bindingId;
8020 this.interpolationFunction = interpolationFunction;
8021 this.baseSourceSpan = baseSourceSpan;
8022 this._nodeMap = new Map();
8023 this._resultMap = new Map();
8024 this._currentTemporary = 0;
8025 this.temporaryCount = 0;
8026 this.usesImplicitReceiver = false;
8027 }
8028 _AstToIrVisitor.prototype.visitBinary = function (ast, mode) {
8029 var op;
8030 switch (ast.operation) {
8031 case '+':
8032 op = BinaryOperator.Plus;
8033 break;
8034 case '-':
8035 op = BinaryOperator.Minus;
8036 break;
8037 case '*':
8038 op = BinaryOperator.Multiply;
8039 break;
8040 case '/':
8041 op = BinaryOperator.Divide;
8042 break;
8043 case '%':
8044 op = BinaryOperator.Modulo;
8045 break;
8046 case '&&':
8047 op = BinaryOperator.And;
8048 break;
8049 case '||':
8050 op = BinaryOperator.Or;
8051 break;
8052 case '==':
8053 op = BinaryOperator.Equals;
8054 break;
8055 case '!=':
8056 op = BinaryOperator.NotEquals;
8057 break;
8058 case '===':
8059 op = BinaryOperator.Identical;
8060 break;
8061 case '!==':
8062 op = BinaryOperator.NotIdentical;
8063 break;
8064 case '<':
8065 op = BinaryOperator.Lower;
8066 break;
8067 case '>':
8068 op = BinaryOperator.Bigger;
8069 break;
8070 case '<=':
8071 op = BinaryOperator.LowerEquals;
8072 break;
8073 case '>=':
8074 op = BinaryOperator.BiggerEquals;
8075 break;
8076 default:
8077 throw new Error("Unsupported operation " + ast.operation);
8078 }
8079 return convertToStatementIfNeeded(mode, new BinaryOperatorExpr(op, this._visit(ast.left, _Mode.Expression), this._visit(ast.right, _Mode.Expression), undefined, this.convertSourceSpan(ast.span)));
8080 };
8081 _AstToIrVisitor.prototype.visitChain = function (ast, mode) {
8082 ensureStatementMode(mode, ast);
8083 return this.visitAll(ast.expressions, mode);
8084 };
8085 _AstToIrVisitor.prototype.visitConditional = function (ast, mode) {
8086 var value = this._visit(ast.condition, _Mode.Expression);
8087 return convertToStatementIfNeeded(mode, value.conditional(this._visit(ast.trueExp, _Mode.Expression), this._visit(ast.falseExp, _Mode.Expression), this.convertSourceSpan(ast.span)));
8088 };
8089 _AstToIrVisitor.prototype.visitPipe = function (ast, mode) {
8090 throw new Error("Illegal state: Pipes should have been converted into functions. Pipe: " + ast.name);
8091 };
8092 _AstToIrVisitor.prototype.visitFunctionCall = function (ast, mode) {
8093 var convertedArgs = this.visitAll(ast.args, _Mode.Expression);
8094 var fnResult;
8095 if (ast instanceof BuiltinFunctionCall) {
8096 fnResult = ast.converter(convertedArgs);
8097 }
8098 else {
8099 fnResult = this._visit(ast.target, _Mode.Expression)
8100 .callFn(convertedArgs, this.convertSourceSpan(ast.span));
8101 }
8102 return convertToStatementIfNeeded(mode, fnResult);
8103 };
8104 _AstToIrVisitor.prototype.visitImplicitReceiver = function (ast, mode) {
8105 ensureExpressionMode(mode, ast);
8106 this.usesImplicitReceiver = true;
8107 return this._implicitReceiver;
8108 };
8109 _AstToIrVisitor.prototype.visitInterpolation = function (ast, mode) {
8110 ensureExpressionMode(mode, ast);
8111 var args = [literal(ast.expressions.length)];
8112 for (var i = 0; i < ast.strings.length - 1; i++) {
8113 args.push(literal(ast.strings[i]));
8114 args.push(this._visit(ast.expressions[i], _Mode.Expression));
8115 }
8116 args.push(literal(ast.strings[ast.strings.length - 1]));
8117 if (this.interpolationFunction) {
8118 return this.interpolationFunction(args);
8119 }
8120 return ast.expressions.length <= 9 ?
8121 importExpr(Identifiers.inlineInterpolate).callFn(args) :
8122 importExpr(Identifiers.interpolate).callFn([
8123 args[0], literalArr(args.slice(1), undefined, this.convertSourceSpan(ast.span))
8124 ]);
8125 };
8126 _AstToIrVisitor.prototype.visitKeyedRead = function (ast, mode) {
8127 var leftMostSafe = this.leftMostSafeNode(ast);
8128 if (leftMostSafe) {
8129 return this.convertSafeAccess(ast, leftMostSafe, mode);
8130 }
8131 else {
8132 return convertToStatementIfNeeded(mode, this._visit(ast.obj, _Mode.Expression).key(this._visit(ast.key, _Mode.Expression)));
8133 }
8134 };
8135 _AstToIrVisitor.prototype.visitKeyedWrite = function (ast, mode) {
8136 var obj = this._visit(ast.obj, _Mode.Expression);
8137 var key = this._visit(ast.key, _Mode.Expression);
8138 var value = this._visit(ast.value, _Mode.Expression);
8139 return convertToStatementIfNeeded(mode, obj.key(key).set(value));
8140 };
8141 _AstToIrVisitor.prototype.visitLiteralArray = function (ast, mode) {
8142 throw new Error("Illegal State: literal arrays should have been converted into functions");
8143 };
8144 _AstToIrVisitor.prototype.visitLiteralMap = function (ast, mode) {
8145 throw new Error("Illegal State: literal maps should have been converted into functions");
8146 };
8147 _AstToIrVisitor.prototype.visitLiteralPrimitive = function (ast, mode) {
8148 // For literal values of null, undefined, true, or false allow type interference
8149 // to infer the type.
8150 var type = ast.value === null || ast.value === undefined || ast.value === true || ast.value === true ?
8151 INFERRED_TYPE :
8152 undefined;
8153 return convertToStatementIfNeeded(mode, literal(ast.value, type, this.convertSourceSpan(ast.span)));
8154 };
8155 _AstToIrVisitor.prototype._getLocal = function (name) { return this._localResolver.getLocal(name); };
8156 _AstToIrVisitor.prototype.visitMethodCall = function (ast, mode) {
8157 if (ast.receiver instanceof ImplicitReceiver && ast.name == '$any') {
8158 var args = this.visitAll(ast.args, _Mode.Expression);
8159 if (args.length != 1) {
8160 throw new Error("Invalid call to $any, expected 1 argument but received " + (args.length || 'none'));
8161 }
8162 return args[0].cast(DYNAMIC_TYPE, this.convertSourceSpan(ast.span));
8163 }
8164 var leftMostSafe = this.leftMostSafeNode(ast);
8165 if (leftMostSafe) {
8166 return this.convertSafeAccess(ast, leftMostSafe, mode);
8167 }
8168 else {
8169 var args = this.visitAll(ast.args, _Mode.Expression);
8170 var prevUsesImplicitReceiver = this.usesImplicitReceiver;
8171 var result = null;
8172 var receiver = this._visit(ast.receiver, _Mode.Expression);
8173 if (receiver === this._implicitReceiver) {
8174 var varExpr = this._getLocal(ast.name);
8175 if (varExpr) {
8176 // Restore the previous "usesImplicitReceiver" state since the implicit
8177 // receiver has been replaced with a resolved local expression.
8178 this.usesImplicitReceiver = prevUsesImplicitReceiver;
8179 result = varExpr.callFn(args);
8180 }
8181 }
8182 if (result == null) {
8183 result = receiver.callMethod(ast.name, args, this.convertSourceSpan(ast.span));
8184 }
8185 return convertToStatementIfNeeded(mode, result);
8186 }
8187 };
8188 _AstToIrVisitor.prototype.visitPrefixNot = function (ast, mode) {
8189 return convertToStatementIfNeeded(mode, not(this._visit(ast.expression, _Mode.Expression)));
8190 };
8191 _AstToIrVisitor.prototype.visitNonNullAssert = function (ast, mode) {
8192 return convertToStatementIfNeeded(mode, assertNotNull(this._visit(ast.expression, _Mode.Expression)));
8193 };
8194 _AstToIrVisitor.prototype.visitPropertyRead = function (ast, mode) {
8195 var leftMostSafe = this.leftMostSafeNode(ast);
8196 if (leftMostSafe) {
8197 return this.convertSafeAccess(ast, leftMostSafe, mode);
8198 }
8199 else {
8200 var result = null;
8201 var prevUsesImplicitReceiver = this.usesImplicitReceiver;
8202 var receiver = this._visit(ast.receiver, _Mode.Expression);
8203 if (receiver === this._implicitReceiver) {
8204 result = this._getLocal(ast.name);
8205 if (result) {
8206 // Restore the previous "usesImplicitReceiver" state since the implicit
8207 // receiver has been replaced with a resolved local expression.
8208 this.usesImplicitReceiver = prevUsesImplicitReceiver;
8209 }
8210 }
8211 if (result == null) {
8212 result = receiver.prop(ast.name);
8213 }
8214 return convertToStatementIfNeeded(mode, result);
8215 }
8216 };
8217 _AstToIrVisitor.prototype.visitPropertyWrite = function (ast, mode) {
8218 var receiver = this._visit(ast.receiver, _Mode.Expression);
8219 var prevUsesImplicitReceiver = this.usesImplicitReceiver;
8220 var varExpr = null;
8221 if (receiver === this._implicitReceiver) {
8222 var localExpr = this._getLocal(ast.name);
8223 if (localExpr) {
8224 if (localExpr instanceof ReadPropExpr) {
8225 // If the local variable is a property read expression, it's a reference
8226 // to a 'context.property' value and will be used as the target of the
8227 // write expression.
8228 varExpr = localExpr;
8229 // Restore the previous "usesImplicitReceiver" state since the implicit
8230 // receiver has been replaced with a resolved local expression.
8231 this.usesImplicitReceiver = prevUsesImplicitReceiver;
8232 }
8233 else {
8234 // Otherwise it's an error.
8235 throw new Error('Cannot assign to a reference or variable!');
8236 }
8237 }
8238 }
8239 // If no local expression could be produced, use the original receiver's
8240 // property as the target.
8241 if (varExpr === null) {
8242 varExpr = receiver.prop(ast.name);
8243 }
8244 return convertToStatementIfNeeded(mode, varExpr.set(this._visit(ast.value, _Mode.Expression)));
8245 };
8246 _AstToIrVisitor.prototype.visitSafePropertyRead = function (ast, mode) {
8247 return this.convertSafeAccess(ast, this.leftMostSafeNode(ast), mode);
8248 };
8249 _AstToIrVisitor.prototype.visitSafeMethodCall = function (ast, mode) {
8250 return this.convertSafeAccess(ast, this.leftMostSafeNode(ast), mode);
8251 };
8252 _AstToIrVisitor.prototype.visitAll = function (asts, mode) {
8253 var _this = this;
8254 return asts.map(function (ast) { return _this._visit(ast, mode); });
8255 };
8256 _AstToIrVisitor.prototype.visitQuote = function (ast, mode) {
8257 throw new Error("Quotes are not supported for evaluation!\n Statement: " + ast.uninterpretedExpression + " located at " + ast.location);
8258 };
8259 _AstToIrVisitor.prototype._visit = function (ast, mode) {
8260 var result = this._resultMap.get(ast);
8261 if (result)
8262 return result;
8263 return (this._nodeMap.get(ast) || ast).visit(this, mode);
8264 };
8265 _AstToIrVisitor.prototype.convertSafeAccess = function (ast, leftMostSafe, mode) {
8266 // If the expression contains a safe access node on the left it needs to be converted to
8267 // an expression that guards the access to the member by checking the receiver for blank. As
8268 // execution proceeds from left to right, the left most part of the expression must be guarded
8269 // first but, because member access is left associative, the right side of the expression is at
8270 // the top of the AST. The desired result requires lifting a copy of the the left part of the
8271 // expression up to test it for blank before generating the unguarded version.
8272 // Consider, for example the following expression: a?.b.c?.d.e
8273 // This results in the ast:
8274 // .
8275 // / \
8276 // ?. e
8277 // / \
8278 // . d
8279 // / \
8280 // ?. c
8281 // / \
8282 // a b
8283 // The following tree should be generated:
8284 //
8285 // /---- ? ----\
8286 // / | \
8287 // a /--- ? ---\ null
8288 // / | \
8289 // . . null
8290 // / \ / \
8291 // . c . e
8292 // / \ / \
8293 // a b . d
8294 // / \
8295 // . c
8296 // / \
8297 // a b
8298 //
8299 // Notice that the first guard condition is the left hand of the left most safe access node
8300 // which comes in as leftMostSafe to this routine.
8301 var guardedExpression = this._visit(leftMostSafe.receiver, _Mode.Expression);
8302 var temporary = undefined;
8303 if (this.needsTemporary(leftMostSafe.receiver)) {
8304 // If the expression has method calls or pipes then we need to save the result into a
8305 // temporary variable to avoid calling stateful or impure code more than once.
8306 temporary = this.allocateTemporary();
8307 // Preserve the result in the temporary variable
8308 guardedExpression = temporary.set(guardedExpression);
8309 // Ensure all further references to the guarded expression refer to the temporary instead.
8310 this._resultMap.set(leftMostSafe.receiver, temporary);
8311 }
8312 var condition = guardedExpression.isBlank();
8313 // Convert the ast to an unguarded access to the receiver's member. The map will substitute
8314 // leftMostNode with its unguarded version in the call to `this.visit()`.
8315 if (leftMostSafe instanceof SafeMethodCall) {
8316 this._nodeMap.set(leftMostSafe, new MethodCall(leftMostSafe.span, leftMostSafe.receiver, leftMostSafe.name, leftMostSafe.args));
8317 }
8318 else {
8319 this._nodeMap.set(leftMostSafe, new PropertyRead(leftMostSafe.span, leftMostSafe.receiver, leftMostSafe.name));
8320 }
8321 // Recursively convert the node now without the guarded member access.
8322 var access = this._visit(ast, _Mode.Expression);
8323 // Remove the mapping. This is not strictly required as the converter only traverses each node
8324 // once but is safer if the conversion is changed to traverse the nodes more than once.
8325 this._nodeMap.delete(leftMostSafe);
8326 // If we allocated a temporary, release it.
8327 if (temporary) {
8328 this.releaseTemporary(temporary);
8329 }
8330 // Produce the conditional
8331 return convertToStatementIfNeeded(mode, condition.conditional(literal(null), access));
8332 };
8333 // Given a expression of the form a?.b.c?.d.e the the left most safe node is
8334 // the (a?.b). The . and ?. are left associative thus can be rewritten as:
8335 // ((((a?.c).b).c)?.d).e. This returns the most deeply nested safe read or
8336 // safe method call as this needs be transform initially to:
8337 // a == null ? null : a.c.b.c?.d.e
8338 // then to:
8339 // a == null ? null : a.b.c == null ? null : a.b.c.d.e
8340 _AstToIrVisitor.prototype.leftMostSafeNode = function (ast) {
8341 var _this = this;
8342 var visit = function (visitor, ast) {
8343 return (_this._nodeMap.get(ast) || ast).visit(visitor);
8344 };
8345 return ast.visit({
8346 visitBinary: function (ast) { return null; },
8347 visitChain: function (ast) { return null; },
8348 visitConditional: function (ast) { return null; },
8349 visitFunctionCall: function (ast) { return null; },
8350 visitImplicitReceiver: function (ast) { return null; },
8351 visitInterpolation: function (ast) { return null; },
8352 visitKeyedRead: function (ast) { return visit(this, ast.obj); },
8353 visitKeyedWrite: function (ast) { return null; },
8354 visitLiteralArray: function (ast) { return null; },
8355 visitLiteralMap: function (ast) { return null; },
8356 visitLiteralPrimitive: function (ast) { return null; },
8357 visitMethodCall: function (ast) { return visit(this, ast.receiver); },
8358 visitPipe: function (ast) { return null; },
8359 visitPrefixNot: function (ast) { return null; },
8360 visitNonNullAssert: function (ast) { return null; },
8361 visitPropertyRead: function (ast) { return visit(this, ast.receiver); },
8362 visitPropertyWrite: function (ast) { return null; },
8363 visitQuote: function (ast) { return null; },
8364 visitSafeMethodCall: function (ast) { return visit(this, ast.receiver) || ast; },
8365 visitSafePropertyRead: function (ast) {
8366 return visit(this, ast.receiver) || ast;
8367 }
8368 });
8369 };
8370 // Returns true of the AST includes a method or a pipe indicating that, if the
8371 // expression is used as the target of a safe property or method access then
8372 // the expression should be stored into a temporary variable.
8373 _AstToIrVisitor.prototype.needsTemporary = function (ast) {
8374 var _this = this;
8375 var visit = function (visitor, ast) {
8376 return ast && (_this._nodeMap.get(ast) || ast).visit(visitor);
8377 };
8378 var visitSome = function (visitor, ast) {
8379 return ast.some(function (ast) { return visit(visitor, ast); });
8380 };
8381 return ast.visit({
8382 visitBinary: function (ast) { return visit(this, ast.left) || visit(this, ast.right); },
8383 visitChain: function (ast) { return false; },
8384 visitConditional: function (ast) {
8385 return visit(this, ast.condition) || visit(this, ast.trueExp) ||
8386 visit(this, ast.falseExp);
8387 },
8388 visitFunctionCall: function (ast) { return true; },
8389 visitImplicitReceiver: function (ast) { return false; },
8390 visitInterpolation: function (ast) { return visitSome(this, ast.expressions); },
8391 visitKeyedRead: function (ast) { return false; },
8392 visitKeyedWrite: function (ast) { return false; },
8393 visitLiteralArray: function (ast) { return true; },
8394 visitLiteralMap: function (ast) { return true; },
8395 visitLiteralPrimitive: function (ast) { return false; },
8396 visitMethodCall: function (ast) { return true; },
8397 visitPipe: function (ast) { return true; },
8398 visitPrefixNot: function (ast) { return visit(this, ast.expression); },
8399 visitNonNullAssert: function (ast) { return visit(this, ast.expression); },
8400 visitPropertyRead: function (ast) { return false; },
8401 visitPropertyWrite: function (ast) { return false; },
8402 visitQuote: function (ast) { return false; },
8403 visitSafeMethodCall: function (ast) { return true; },
8404 visitSafePropertyRead: function (ast) { return false; }
8405 });
8406 };
8407 _AstToIrVisitor.prototype.allocateTemporary = function () {
8408 var tempNumber = this._currentTemporary++;
8409 this.temporaryCount = Math.max(this._currentTemporary, this.temporaryCount);
8410 return new ReadVarExpr(temporaryName(this.bindingId, tempNumber));
8411 };
8412 _AstToIrVisitor.prototype.releaseTemporary = function (temporary) {
8413 this._currentTemporary--;
8414 if (temporary.name != temporaryName(this.bindingId, this._currentTemporary)) {
8415 throw new Error("Temporary " + temporary.name + " released out of order");
8416 }
8417 };
8418 /**
8419 * Creates an absolute `ParseSourceSpan` from the relative `ParseSpan`.
8420 *
8421 * `ParseSpan` objects are relative to the start of the expression.
8422 * This method converts these to full `ParseSourceSpan` objects that
8423 * show where the span is within the overall source file.
8424 *
8425 * @param span the relative span to convert.
8426 * @returns a `ParseSourceSpan` for the the given span or null if no
8427 * `baseSourceSpan` was provided to this class.
8428 */
8429 _AstToIrVisitor.prototype.convertSourceSpan = function (span) {
8430 if (this.baseSourceSpan) {
8431 var start = this.baseSourceSpan.start.moveBy(span.start);
8432 var end = this.baseSourceSpan.start.moveBy(span.end);
8433 return new ParseSourceSpan(start, end);
8434 }
8435 else {
8436 return null;
8437 }
8438 };
8439 return _AstToIrVisitor;
8440}());
8441function flattenStatements(arg, output) {
8442 if (Array.isArray(arg)) {
8443 arg.forEach(function (entry) { return flattenStatements(entry, output); });
8444 }
8445 else {
8446 output.push(arg);
8447 }
8448}
8449var DefaultLocalResolver = /** @class */ (function () {
8450 function DefaultLocalResolver() {
8451 }
8452 DefaultLocalResolver.prototype.notifyImplicitReceiverUse = function () { };
8453 DefaultLocalResolver.prototype.getLocal = function (name) {
8454 if (name === EventHandlerVars.event.name) {
8455 return EventHandlerVars.event;
8456 }
8457 return null;
8458 };
8459 return DefaultLocalResolver;
8460}());
8461function createCurrValueExpr(bindingId) {
8462 return variable("currVal_" + bindingId); // fix syntax highlighting: `
8463}
8464function createPreventDefaultVar(bindingId) {
8465 return variable("pd_" + bindingId);
8466}
8467function convertStmtIntoExpression(stmt) {
8468 if (stmt instanceof ExpressionStatement) {
8469 return stmt.expr;
8470 }
8471 else if (stmt instanceof ReturnStatement) {
8472 return stmt.value;
8473 }
8474 return null;
8475}
8476var BuiltinFunctionCall = /** @class */ (function (_super) {
8477 __extends(BuiltinFunctionCall, _super);
8478 function BuiltinFunctionCall(span, args, converter) {
8479 var _this = _super.call(this, span, null, args) || this;
8480 _this.args = args;
8481 _this.converter = converter;
8482 return _this;
8483 }
8484 return BuiltinFunctionCall;
8485}(FunctionCall));
8486
8487/**
8488 * @license
8489 * Copyright Google Inc. All Rights Reserved.
8490 *
8491 * Use of this source code is governed by an MIT-style license that can be
8492 * found in the LICENSE file at https://angular.io/license
8493 */
8494/**
8495 * This file is a port of shadowCSS from webcomponents.js to TypeScript.
8496 *
8497 * Please make sure to keep to edits in sync with the source file.
8498 *
8499 * Source:
8500 * https://github.com/webcomponents/webcomponentsjs/blob/4efecd7e0e/src/ShadowCSS/ShadowCSS.js
8501 *
8502 * The original file level comment is reproduced below
8503 */
8504/*
8505 This is a limited shim for ShadowDOM css styling.
8506 https://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/shadow/index.html#styles
8507
8508 The intention here is to support only the styling features which can be
8509 relatively simply implemented. The goal is to allow users to avoid the
8510 most obvious pitfalls and do so without compromising performance significantly.
8511 For ShadowDOM styling that's not covered here, a set of best practices
8512 can be provided that should allow users to accomplish more complex styling.
8513
8514 The following is a list of specific ShadowDOM styling features and a brief
8515 discussion of the approach used to shim.
8516
8517 Shimmed features:
8518
8519 * :host, :host-context: ShadowDOM allows styling of the shadowRoot's host
8520 element using the :host rule. To shim this feature, the :host styles are
8521 reformatted and prefixed with a given scope name and promoted to a
8522 document level stylesheet.
8523 For example, given a scope name of .foo, a rule like this:
8524
8525 :host {
8526 background: red;
8527 }
8528 }
8529
8530 becomes:
8531
8532 .foo {
8533 background: red;
8534 }
8535
8536 * encapsulation: Styles defined within ShadowDOM, apply only to
8537 dom inside the ShadowDOM. Polymer uses one of two techniques to implement
8538 this feature.
8539
8540 By default, rules are prefixed with the host element tag name
8541 as a descendant selector. This ensures styling does not leak out of the 'top'
8542 of the element's ShadowDOM. For example,
8543
8544 div {
8545 font-weight: bold;
8546 }
8547
8548 becomes:
8549
8550 x-foo div {
8551 font-weight: bold;
8552 }
8553
8554 becomes:
8555
8556
8557 Alternatively, if WebComponents.ShadowCSS.strictStyling is set to true then
8558 selectors are scoped by adding an attribute selector suffix to each
8559 simple selector that contains the host element tag name. Each element
8560 in the element's ShadowDOM template is also given the scope attribute.
8561 Thus, these rules match only elements that have the scope attribute.
8562 For example, given a scope name of x-foo, a rule like this:
8563
8564 div {
8565 font-weight: bold;
8566 }
8567
8568 becomes:
8569
8570 div[x-foo] {
8571 font-weight: bold;
8572 }
8573
8574 Note that elements that are dynamically added to a scope must have the scope
8575 selector added to them manually.
8576
8577 * upper/lower bound encapsulation: Styles which are defined outside a
8578 shadowRoot should not cross the ShadowDOM boundary and should not apply
8579 inside a shadowRoot.
8580
8581 This styling behavior is not emulated. Some possible ways to do this that
8582 were rejected due to complexity and/or performance concerns include: (1) reset
8583 every possible property for every possible selector for a given scope name;
8584 (2) re-implement css in javascript.
8585
8586 As an alternative, users should make sure to use selectors
8587 specific to the scope in which they are working.
8588
8589 * ::distributed: This behavior is not emulated. It's often not necessary
8590 to style the contents of a specific insertion point and instead, descendants
8591 of the host element can be styled selectively. Users can also create an
8592 extra node around an insertion point and style that node's contents
8593 via descendent selectors. For example, with a shadowRoot like this:
8594
8595 <style>
8596 ::content(div) {
8597 background: red;
8598 }
8599 </style>
8600 <content></content>
8601
8602 could become:
8603
8604 <style>
8605 / *@polyfill .content-container div * /
8606 ::content(div) {
8607 background: red;
8608 }
8609 </style>
8610 <div class="content-container">
8611 <content></content>
8612 </div>
8613
8614 Note the use of @polyfill in the comment above a ShadowDOM specific style
8615 declaration. This is a directive to the styling shim to use the selector
8616 in comments in lieu of the next selector when running under polyfill.
8617*/
8618var ShadowCss = /** @class */ (function () {
8619 function ShadowCss() {
8620 this.strictStyling = true;
8621 }
8622 /*
8623 * Shim some cssText with the given selector. Returns cssText that can
8624 * be included in the document via WebComponents.ShadowCSS.addCssToDocument(css).
8625 *
8626 * When strictStyling is true:
8627 * - selector is the attribute added to all elements inside the host,
8628 * - hostSelector is the attribute added to the host itself.
8629 */
8630 ShadowCss.prototype.shimCssText = function (cssText, selector, hostSelector) {
8631 if (hostSelector === void 0) { hostSelector = ''; }
8632 var commentsWithHash = extractCommentsWithHash(cssText);
8633 cssText = stripComments(cssText);
8634 cssText = this._insertDirectives(cssText);
8635 var scopedCssText = this._scopeCssText(cssText, selector, hostSelector);
8636 return __spread([scopedCssText], commentsWithHash).join('\n');
8637 };
8638 ShadowCss.prototype._insertDirectives = function (cssText) {
8639 cssText = this._insertPolyfillDirectivesInCssText(cssText);
8640 return this._insertPolyfillRulesInCssText(cssText);
8641 };
8642 /*
8643 * Process styles to convert native ShadowDOM rules that will trip
8644 * up the css parser; we rely on decorating the stylesheet with inert rules.
8645 *
8646 * For example, we convert this rule:
8647 *
8648 * polyfill-next-selector { content: ':host menu-item'; }
8649 * ::content menu-item {
8650 *
8651 * to this:
8652 *
8653 * scopeName menu-item {
8654 *
8655 **/
8656 ShadowCss.prototype._insertPolyfillDirectivesInCssText = function (cssText) {
8657 // Difference with webcomponents.js: does not handle comments
8658 return cssText.replace(_cssContentNextSelectorRe, function () {
8659 var m = [];
8660 for (var _i = 0; _i < arguments.length; _i++) {
8661 m[_i] = arguments[_i];
8662 }
8663 return m[2] + '{';
8664 });
8665 };
8666 /*
8667 * Process styles to add rules which will only apply under the polyfill
8668 *
8669 * For example, we convert this rule:
8670 *
8671 * polyfill-rule {
8672 * content: ':host menu-item';
8673 * ...
8674 * }
8675 *
8676 * to this:
8677 *
8678 * scopeName menu-item {...}
8679 *
8680 **/
8681 ShadowCss.prototype._insertPolyfillRulesInCssText = function (cssText) {
8682 // Difference with webcomponents.js: does not handle comments
8683 return cssText.replace(_cssContentRuleRe, function () {
8684 var m = [];
8685 for (var _i = 0; _i < arguments.length; _i++) {
8686 m[_i] = arguments[_i];
8687 }
8688 var rule = m[0].replace(m[1], '').replace(m[2], '');
8689 return m[4] + rule;
8690 });
8691 };
8692 /* Ensure styles are scoped. Pseudo-scoping takes a rule like:
8693 *
8694 * .foo {... }
8695 *
8696 * and converts this to
8697 *
8698 * scopeName .foo { ... }
8699 */
8700 ShadowCss.prototype._scopeCssText = function (cssText, scopeSelector, hostSelector) {
8701 var unscopedRules = this._extractUnscopedRulesFromCssText(cssText);
8702 // replace :host and :host-context -shadowcsshost and -shadowcsshost respectively
8703 cssText = this._insertPolyfillHostInCssText(cssText);
8704 cssText = this._convertColonHost(cssText);
8705 cssText = this._convertColonHostContext(cssText);
8706 cssText = this._convertShadowDOMSelectors(cssText);
8707 if (scopeSelector) {
8708 cssText = this._scopeSelectors(cssText, scopeSelector, hostSelector);
8709 }
8710 cssText = cssText + '\n' + unscopedRules;
8711 return cssText.trim();
8712 };
8713 /*
8714 * Process styles to add rules which will only apply under the polyfill
8715 * and do not process via CSSOM. (CSSOM is destructive to rules on rare
8716 * occasions, e.g. -webkit-calc on Safari.)
8717 * For example, we convert this rule:
8718 *
8719 * @polyfill-unscoped-rule {
8720 * content: 'menu-item';
8721 * ... }
8722 *
8723 * to this:
8724 *
8725 * menu-item {...}
8726 *
8727 **/
8728 ShadowCss.prototype._extractUnscopedRulesFromCssText = function (cssText) {
8729 // Difference with webcomponents.js: does not handle comments
8730 var r = '';
8731 var m;
8732 _cssContentUnscopedRuleRe.lastIndex = 0;
8733 while ((m = _cssContentUnscopedRuleRe.exec(cssText)) !== null) {
8734 var rule = m[0].replace(m[2], '').replace(m[1], m[4]);
8735 r += rule + '\n\n';
8736 }
8737 return r;
8738 };
8739 /*
8740 * convert a rule like :host(.foo) > .bar { }
8741 *
8742 * to
8743 *
8744 * .foo<scopeName> > .bar
8745 */
8746 ShadowCss.prototype._convertColonHost = function (cssText) {
8747 return this._convertColonRule(cssText, _cssColonHostRe, this._colonHostPartReplacer);
8748 };
8749 /*
8750 * convert a rule like :host-context(.foo) > .bar { }
8751 *
8752 * to
8753 *
8754 * .foo<scopeName> > .bar, .foo scopeName > .bar { }
8755 *
8756 * and
8757 *
8758 * :host-context(.foo:host) .bar { ... }
8759 *
8760 * to
8761 *
8762 * .foo<scopeName> .bar { ... }
8763 */
8764 ShadowCss.prototype._convertColonHostContext = function (cssText) {
8765 return this._convertColonRule(cssText, _cssColonHostContextRe, this._colonHostContextPartReplacer);
8766 };
8767 ShadowCss.prototype._convertColonRule = function (cssText, regExp, partReplacer) {
8768 // m[1] = :host(-context), m[2] = contents of (), m[3] rest of rule
8769 return cssText.replace(regExp, function () {
8770 var m = [];
8771 for (var _i = 0; _i < arguments.length; _i++) {
8772 m[_i] = arguments[_i];
8773 }
8774 if (m[2]) {
8775 var parts = m[2].split(',');
8776 var r = [];
8777 for (var i = 0; i < parts.length; i++) {
8778 var p = parts[i].trim();
8779 if (!p)
8780 break;
8781 r.push(partReplacer(_polyfillHostNoCombinator, p, m[3]));
8782 }
8783 return r.join(',');
8784 }
8785 else {
8786 return _polyfillHostNoCombinator + m[3];
8787 }
8788 });
8789 };
8790 ShadowCss.prototype._colonHostContextPartReplacer = function (host, part, suffix) {
8791 if (part.indexOf(_polyfillHost) > -1) {
8792 return this._colonHostPartReplacer(host, part, suffix);
8793 }
8794 else {
8795 return host + part + suffix + ', ' + part + ' ' + host + suffix;
8796 }
8797 };
8798 ShadowCss.prototype._colonHostPartReplacer = function (host, part, suffix) {
8799 return host + part.replace(_polyfillHost, '') + suffix;
8800 };
8801 /*
8802 * Convert combinators like ::shadow and pseudo-elements like ::content
8803 * by replacing with space.
8804 */
8805 ShadowCss.prototype._convertShadowDOMSelectors = function (cssText) {
8806 return _shadowDOMSelectorsRe.reduce(function (result, pattern) { return result.replace(pattern, ' '); }, cssText);
8807 };
8808 // change a selector like 'div' to 'name div'
8809 ShadowCss.prototype._scopeSelectors = function (cssText, scopeSelector, hostSelector) {
8810 var _this = this;
8811 return processRules(cssText, function (rule) {
8812 var selector = rule.selector;
8813 var content = rule.content;
8814 if (rule.selector[0] != '@') {
8815 selector =
8816 _this._scopeSelector(rule.selector, scopeSelector, hostSelector, _this.strictStyling);
8817 }
8818 else if (rule.selector.startsWith('@media') || rule.selector.startsWith('@supports') ||
8819 rule.selector.startsWith('@page') || rule.selector.startsWith('@document')) {
8820 content = _this._scopeSelectors(rule.content, scopeSelector, hostSelector);
8821 }
8822 return new CssRule(selector, content);
8823 });
8824 };
8825 ShadowCss.prototype._scopeSelector = function (selector, scopeSelector, hostSelector, strict) {
8826 var _this = this;
8827 return selector.split(',')
8828 .map(function (part) { return part.trim().split(_shadowDeepSelectors); })
8829 .map(function (deepParts) {
8830 var _a = __read(deepParts), shallowPart = _a[0], otherParts = _a.slice(1);
8831 var applyScope = function (shallowPart) {
8832 if (_this._selectorNeedsScoping(shallowPart, scopeSelector)) {
8833 return strict ?
8834 _this._applyStrictSelectorScope(shallowPart, scopeSelector, hostSelector) :
8835 _this._applySelectorScope(shallowPart, scopeSelector, hostSelector);
8836 }
8837 else {
8838 return shallowPart;
8839 }
8840 };
8841 return __spread([applyScope(shallowPart)], otherParts).join(' ');
8842 })
8843 .join(', ');
8844 };
8845 ShadowCss.prototype._selectorNeedsScoping = function (selector, scopeSelector) {
8846 var re = this._makeScopeMatcher(scopeSelector);
8847 return !re.test(selector);
8848 };
8849 ShadowCss.prototype._makeScopeMatcher = function (scopeSelector) {
8850 var lre = /\[/g;
8851 var rre = /\]/g;
8852 scopeSelector = scopeSelector.replace(lre, '\\[').replace(rre, '\\]');
8853 return new RegExp('^(' + scopeSelector + ')' + _selectorReSuffix, 'm');
8854 };
8855 ShadowCss.prototype._applySelectorScope = function (selector, scopeSelector, hostSelector) {
8856 // Difference from webcomponents.js: scopeSelector could not be an array
8857 return this._applySimpleSelectorScope(selector, scopeSelector, hostSelector);
8858 };
8859 // scope via name and [is=name]
8860 ShadowCss.prototype._applySimpleSelectorScope = function (selector, scopeSelector, hostSelector) {
8861 // In Android browser, the lastIndex is not reset when the regex is used in String.replace()
8862 _polyfillHostRe.lastIndex = 0;
8863 if (_polyfillHostRe.test(selector)) {
8864 var replaceBy_1 = this.strictStyling ? "[" + hostSelector + "]" : scopeSelector;
8865 return selector
8866 .replace(_polyfillHostNoCombinatorRe, function (hnc, selector) {
8867 return selector.replace(/([^:]*)(:*)(.*)/, function (_, before, colon, after) {
8868 return before + replaceBy_1 + colon + after;
8869 });
8870 })
8871 .replace(_polyfillHostRe, replaceBy_1 + ' ');
8872 }
8873 return scopeSelector + ' ' + selector;
8874 };
8875 // return a selector with [name] suffix on each simple selector
8876 // e.g. .foo.bar > .zot becomes .foo[name].bar[name] > .zot[name] /** @internal */
8877 ShadowCss.prototype._applyStrictSelectorScope = function (selector, scopeSelector, hostSelector) {
8878 var _this = this;
8879 var isRe = /\[is=([^\]]*)\]/g;
8880 scopeSelector = scopeSelector.replace(isRe, function (_) {
8881 var parts = [];
8882 for (var _i = 1; _i < arguments.length; _i++) {
8883 parts[_i - 1] = arguments[_i];
8884 }
8885 return parts[0];
8886 });
8887 var attrName = '[' + scopeSelector + ']';
8888 var _scopeSelectorPart = function (p) {
8889 var scopedP = p.trim();
8890 if (!scopedP) {
8891 return '';
8892 }
8893 if (p.indexOf(_polyfillHostNoCombinator) > -1) {
8894 scopedP = _this._applySimpleSelectorScope(p, scopeSelector, hostSelector);
8895 }
8896 else {
8897 // remove :host since it should be unnecessary
8898 var t = p.replace(_polyfillHostRe, '');
8899 if (t.length > 0) {
8900 var matches = t.match(/([^:]*)(:*)(.*)/);
8901 if (matches) {
8902 scopedP = matches[1] + attrName + matches[2] + matches[3];
8903 }
8904 }
8905 }
8906 return scopedP;
8907 };
8908 var safeContent = new SafeSelector(selector);
8909 selector = safeContent.content();
8910 var scopedSelector = '';
8911 var startIndex = 0;
8912 var res;
8913 var sep = /( |>|\+|~(?!=))\s*/g;
8914 // If a selector appears before :host it should not be shimmed as it
8915 // matches on ancestor elements and not on elements in the host's shadow
8916 // `:host-context(div)` is transformed to
8917 // `-shadowcsshost-no-combinatordiv, div -shadowcsshost-no-combinator`
8918 // the `div` is not part of the component in the 2nd selectors and should not be scoped.
8919 // Historically `component-tag:host` was matching the component so we also want to preserve
8920 // this behavior to avoid breaking legacy apps (it should not match).
8921 // The behavior should be:
8922 // - `tag:host` -> `tag[h]` (this is to avoid breaking legacy apps, should not match anything)
8923 // - `tag :host` -> `tag [h]` (`tag` is not scoped because it's considered part of a
8924 // `:host-context(tag)`)
8925 var hasHost = selector.indexOf(_polyfillHostNoCombinator) > -1;
8926 // Only scope parts after the first `-shadowcsshost-no-combinator` when it is present
8927 var shouldScope = !hasHost;
8928 while ((res = sep.exec(selector)) !== null) {
8929 var separator = res[1];
8930 var part_1 = selector.slice(startIndex, res.index).trim();
8931 shouldScope = shouldScope || part_1.indexOf(_polyfillHostNoCombinator) > -1;
8932 var scopedPart = shouldScope ? _scopeSelectorPart(part_1) : part_1;
8933 scopedSelector += scopedPart + " " + separator + " ";
8934 startIndex = sep.lastIndex;
8935 }
8936 var part = selector.substring(startIndex);
8937 shouldScope = shouldScope || part.indexOf(_polyfillHostNoCombinator) > -1;
8938 scopedSelector += shouldScope ? _scopeSelectorPart(part) : part;
8939 // replace the placeholders with their original values
8940 return safeContent.restore(scopedSelector);
8941 };
8942 ShadowCss.prototype._insertPolyfillHostInCssText = function (selector) {
8943 return selector.replace(_colonHostContextRe, _polyfillHostContext)
8944 .replace(_colonHostRe, _polyfillHost);
8945 };
8946 return ShadowCss;
8947}());
8948var SafeSelector = /** @class */ (function () {
8949 function SafeSelector(selector) {
8950 var _this = this;
8951 this.placeholders = [];
8952 this.index = 0;
8953 // Replaces attribute selectors with placeholders.
8954 // The WS in [attr="va lue"] would otherwise be interpreted as a selector separator.
8955 selector = selector.replace(/(\[[^\]]*\])/g, function (_, keep) {
8956 var replaceBy = "__ph-" + _this.index + "__";
8957 _this.placeholders.push(keep);
8958 _this.index++;
8959 return replaceBy;
8960 });
8961 // Replaces the expression in `:nth-child(2n + 1)` with a placeholder.
8962 // WS and "+" would otherwise be interpreted as selector separators.
8963 this._content = selector.replace(/(:nth-[-\w]+)(\([^)]+\))/g, function (_, pseudo, exp) {
8964 var replaceBy = "__ph-" + _this.index + "__";
8965 _this.placeholders.push(exp);
8966 _this.index++;
8967 return pseudo + replaceBy;
8968 });
8969 }
8970 SafeSelector.prototype.restore = function (content) {
8971 var _this = this;
8972 return content.replace(/__ph-(\d+)__/g, function (ph, index) { return _this.placeholders[+index]; });
8973 };
8974 SafeSelector.prototype.content = function () { return this._content; };
8975 return SafeSelector;
8976}());
8977var _cssContentNextSelectorRe = /polyfill-next-selector[^}]*content:[\s]*?(['"])(.*?)\1[;\s]*}([^{]*?){/gim;
8978var _cssContentRuleRe = /(polyfill-rule)[^}]*(content:[\s]*(['"])(.*?)\3)[;\s]*[^}]*}/gim;
8979var _cssContentUnscopedRuleRe = /(polyfill-unscoped-rule)[^}]*(content:[\s]*(['"])(.*?)\3)[;\s]*[^}]*}/gim;
8980var _polyfillHost = '-shadowcsshost';
8981// note: :host-context pre-processed to -shadowcsshostcontext.
8982var _polyfillHostContext = '-shadowcsscontext';
8983var _parenSuffix = ')(?:\\((' +
8984 '(?:\\([^)(]*\\)|[^)(]*)+?' +
8985 ')\\))?([^,{]*)';
8986var _cssColonHostRe = new RegExp('(' + _polyfillHost + _parenSuffix, 'gim');
8987var _cssColonHostContextRe = new RegExp('(' + _polyfillHostContext + _parenSuffix, 'gim');
8988var _polyfillHostNoCombinator = _polyfillHost + '-no-combinator';
8989var _polyfillHostNoCombinatorRe = /-shadowcsshost-no-combinator([^\s]*)/;
8990var _shadowDOMSelectorsRe = [
8991 /::shadow/g,
8992 /::content/g,
8993 // Deprecated selectors
8994 /\/shadow-deep\//g,
8995 /\/shadow\//g,
8996];
8997// The deep combinator is deprecated in the CSS spec
8998// Support for `>>>`, `deep`, `::ng-deep` is then also deprecated and will be removed in the future.
8999// see https://github.com/angular/angular/pull/17677
9000var _shadowDeepSelectors = /(?:>>>)|(?:\/deep\/)|(?:::ng-deep)/g;
9001var _selectorReSuffix = '([>\\s~+\[.,{:][\\s\\S]*)?$';
9002var _polyfillHostRe = /-shadowcsshost/gim;
9003var _colonHostRe = /:host/gim;
9004var _colonHostContextRe = /:host-context/gim;
9005var _commentRe = /\/\*\s*[\s\S]*?\*\//g;
9006function stripComments(input) {
9007 return input.replace(_commentRe, '');
9008}
9009var _commentWithHashRe = /\/\*\s*#\s*source(Mapping)?URL=[\s\S]+?\*\//g;
9010function extractCommentsWithHash(input) {
9011 return input.match(_commentWithHashRe) || [];
9012}
9013var _ruleRe = /(\s*)([^;\{\}]+?)(\s*)((?:{%BLOCK%}?\s*;?)|(?:\s*;))/g;
9014var _curlyRe = /([{}])/g;
9015var OPEN_CURLY = '{';
9016var CLOSE_CURLY = '}';
9017var BLOCK_PLACEHOLDER = '%BLOCK%';
9018var CssRule = /** @class */ (function () {
9019 function CssRule(selector, content) {
9020 this.selector = selector;
9021 this.content = content;
9022 }
9023 return CssRule;
9024}());
9025function processRules(input, ruleCallback) {
9026 var inputWithEscapedBlocks = escapeBlocks(input);
9027 var nextBlockIndex = 0;
9028 return inputWithEscapedBlocks.escapedString.replace(_ruleRe, function () {
9029 var m = [];
9030 for (var _i = 0; _i < arguments.length; _i++) {
9031 m[_i] = arguments[_i];
9032 }
9033 var selector = m[2];
9034 var content = '';
9035 var suffix = m[4];
9036 var contentPrefix = '';
9037 if (suffix && suffix.startsWith('{' + BLOCK_PLACEHOLDER)) {
9038 content = inputWithEscapedBlocks.blocks[nextBlockIndex++];
9039 suffix = suffix.substring(BLOCK_PLACEHOLDER.length + 1);
9040 contentPrefix = '{';
9041 }
9042 var rule = ruleCallback(new CssRule(selector, content));
9043 return "" + m[1] + rule.selector + m[3] + contentPrefix + rule.content + suffix;
9044 });
9045}
9046var StringWithEscapedBlocks = /** @class */ (function () {
9047 function StringWithEscapedBlocks(escapedString, blocks) {
9048 this.escapedString = escapedString;
9049 this.blocks = blocks;
9050 }
9051 return StringWithEscapedBlocks;
9052}());
9053function escapeBlocks(input) {
9054 var inputParts = input.split(_curlyRe);
9055 var resultParts = [];
9056 var escapedBlocks = [];
9057 var bracketCount = 0;
9058 var currentBlockParts = [];
9059 for (var partIndex = 0; partIndex < inputParts.length; partIndex++) {
9060 var part = inputParts[partIndex];
9061 if (part == CLOSE_CURLY) {
9062 bracketCount--;
9063 }
9064 if (bracketCount > 0) {
9065 currentBlockParts.push(part);
9066 }
9067 else {
9068 if (currentBlockParts.length > 0) {
9069 escapedBlocks.push(currentBlockParts.join(''));
9070 resultParts.push(BLOCK_PLACEHOLDER);
9071 currentBlockParts = [];
9072 }
9073 resultParts.push(part);
9074 }
9075 if (part == OPEN_CURLY) {
9076 bracketCount++;
9077 }
9078 }
9079 if (currentBlockParts.length > 0) {
9080 escapedBlocks.push(currentBlockParts.join(''));
9081 resultParts.push(BLOCK_PLACEHOLDER);
9082 }
9083 return new StringWithEscapedBlocks(resultParts.join(''), escapedBlocks);
9084}
9085
9086/**
9087 * @license
9088 * Copyright Google Inc. All Rights Reserved.
9089 *
9090 * Use of this source code is governed by an MIT-style license that can be
9091 * found in the LICENSE file at https://angular.io/license
9092 */
9093var COMPONENT_VARIABLE = '%COMP%';
9094var HOST_ATTR = "_nghost-" + COMPONENT_VARIABLE;
9095var CONTENT_ATTR = "_ngcontent-" + COMPONENT_VARIABLE;
9096var StylesCompileDependency = /** @class */ (function () {
9097 function StylesCompileDependency(name, moduleUrl, setValue) {
9098 this.name = name;
9099 this.moduleUrl = moduleUrl;
9100 this.setValue = setValue;
9101 }
9102 return StylesCompileDependency;
9103}());
9104var CompiledStylesheet = /** @class */ (function () {
9105 function CompiledStylesheet(outputCtx, stylesVar, dependencies, isShimmed, meta) {
9106 this.outputCtx = outputCtx;
9107 this.stylesVar = stylesVar;
9108 this.dependencies = dependencies;
9109 this.isShimmed = isShimmed;
9110 this.meta = meta;
9111 }
9112 return CompiledStylesheet;
9113}());
9114var StyleCompiler = /** @class */ (function () {
9115 function StyleCompiler(_urlResolver) {
9116 this._urlResolver = _urlResolver;
9117 this._shadowCss = new ShadowCss();
9118 }
9119 StyleCompiler.prototype.compileComponent = function (outputCtx, comp) {
9120 var template = comp.template;
9121 return this._compileStyles(outputCtx, comp, new CompileStylesheetMetadata({
9122 styles: template.styles,
9123 styleUrls: template.styleUrls,
9124 moduleUrl: identifierModuleUrl(comp.type)
9125 }), this.needsStyleShim(comp), true);
9126 };
9127 StyleCompiler.prototype.compileStyles = function (outputCtx, comp, stylesheet, shim) {
9128 if (shim === void 0) { shim = this.needsStyleShim(comp); }
9129 return this._compileStyles(outputCtx, comp, stylesheet, shim, false);
9130 };
9131 StyleCompiler.prototype.needsStyleShim = function (comp) {
9132 return comp.template.encapsulation === ViewEncapsulation.Emulated;
9133 };
9134 StyleCompiler.prototype._compileStyles = function (outputCtx, comp, stylesheet, shim, isComponentStylesheet) {
9135 var _this = this;
9136 var styleExpressions = stylesheet.styles.map(function (plainStyle) { return literal(_this._shimIfNeeded(plainStyle, shim)); });
9137 var dependencies = [];
9138 stylesheet.styleUrls.forEach(function (styleUrl) {
9139 var exprIndex = styleExpressions.length;
9140 // Note: This placeholder will be filled later.
9141 styleExpressions.push(null);
9142 dependencies.push(new StylesCompileDependency(getStylesVarName(null), styleUrl, function (value) { return styleExpressions[exprIndex] = outputCtx.importExpr(value); }));
9143 });
9144 // styles variable contains plain strings and arrays of other styles arrays (recursive),
9145 // so we set its type to dynamic.
9146 var stylesVar = getStylesVarName(isComponentStylesheet ? comp : null);
9147 var stmt = variable(stylesVar)
9148 .set(literalArr(styleExpressions, new ArrayType(DYNAMIC_TYPE, [TypeModifier.Const])))
9149 .toDeclStmt(null, isComponentStylesheet ? [StmtModifier.Final] : [
9150 StmtModifier.Final, StmtModifier.Exported
9151 ]);
9152 outputCtx.statements.push(stmt);
9153 return new CompiledStylesheet(outputCtx, stylesVar, dependencies, shim, stylesheet);
9154 };
9155 StyleCompiler.prototype._shimIfNeeded = function (style, shim) {
9156 return shim ? this._shadowCss.shimCssText(style, CONTENT_ATTR, HOST_ATTR) : style;
9157 };
9158 return StyleCompiler;
9159}());
9160function getStylesVarName(component) {
9161 var result = "styles";
9162 if (component) {
9163 result += "_" + identifierName(component.type);
9164 }
9165 return result;
9166}
9167
9168/**
9169 * @license
9170 * Copyright Google Inc. All Rights Reserved.
9171 *
9172 * Use of this source code is governed by an MIT-style license that can be
9173 * found in the LICENSE file at https://angular.io/license
9174 */
9175/**
9176 * A path is an ordered set of elements. Typically a path is to a
9177 * particular offset in a source file. The head of the list is the top
9178 * most node. The tail is the node that contains the offset directly.
9179 *
9180 * For example, the expression `a + b + c` might have an ast that looks
9181 * like:
9182 * +
9183 * / \
9184 * a +
9185 * / \
9186 * b c
9187 *
9188 * The path to the node at offset 9 would be `['+' at 1-10, '+' at 7-10,
9189 * 'c' at 9-10]` and the path the node at offset 1 would be
9190 * `['+' at 1-10, 'a' at 1-2]`.
9191 */
9192var AstPath = /** @class */ (function () {
9193 function AstPath(path, position) {
9194 if (position === void 0) { position = -1; }
9195 this.path = path;
9196 this.position = position;
9197 }
9198 Object.defineProperty(AstPath.prototype, "empty", {
9199 get: function () { return !this.path || !this.path.length; },
9200 enumerable: true,
9201 configurable: true
9202 });
9203 Object.defineProperty(AstPath.prototype, "head", {
9204 get: function () { return this.path[0]; },
9205 enumerable: true,
9206 configurable: true
9207 });
9208 Object.defineProperty(AstPath.prototype, "tail", {
9209 get: function () { return this.path[this.path.length - 1]; },
9210 enumerable: true,
9211 configurable: true
9212 });
9213 AstPath.prototype.parentOf = function (node) {
9214 return node && this.path[this.path.indexOf(node) - 1];
9215 };
9216 AstPath.prototype.childOf = function (node) { return this.path[this.path.indexOf(node) + 1]; };
9217 AstPath.prototype.first = function (ctor) {
9218 for (var i = this.path.length - 1; i >= 0; i--) {
9219 var item = this.path[i];
9220 if (item instanceof ctor)
9221 return item;
9222 }
9223 };
9224 AstPath.prototype.push = function (node) { this.path.push(node); };
9225 AstPath.prototype.pop = function () { return this.path.pop(); };
9226 return AstPath;
9227}());
9228
9229/**
9230 * @license
9231 * Copyright Google Inc. All Rights Reserved.
9232 *
9233 * Use of this source code is governed by an MIT-style license that can be
9234 * found in the LICENSE file at https://angular.io/license
9235 */
9236var Text$3 = /** @class */ (function () {
9237 function Text(value, sourceSpan, i18n) {
9238 this.value = value;
9239 this.sourceSpan = sourceSpan;
9240 this.i18n = i18n;
9241 }
9242 Text.prototype.visit = function (visitor, context) { return visitor.visitText(this, context); };
9243 return Text;
9244}());
9245var Expansion = /** @class */ (function () {
9246 function Expansion(switchValue, type, cases, sourceSpan, switchValueSourceSpan, i18n) {
9247 this.switchValue = switchValue;
9248 this.type = type;
9249 this.cases = cases;
9250 this.sourceSpan = sourceSpan;
9251 this.switchValueSourceSpan = switchValueSourceSpan;
9252 this.i18n = i18n;
9253 }
9254 Expansion.prototype.visit = function (visitor, context) { return visitor.visitExpansion(this, context); };
9255 return Expansion;
9256}());
9257var ExpansionCase = /** @class */ (function () {
9258 function ExpansionCase(value, expression, sourceSpan, valueSourceSpan, expSourceSpan) {
9259 this.value = value;
9260 this.expression = expression;
9261 this.sourceSpan = sourceSpan;
9262 this.valueSourceSpan = valueSourceSpan;
9263 this.expSourceSpan = expSourceSpan;
9264 }
9265 ExpansionCase.prototype.visit = function (visitor, context) { return visitor.visitExpansionCase(this, context); };
9266 return ExpansionCase;
9267}());
9268var Attribute = /** @class */ (function () {
9269 function Attribute(name, value, sourceSpan, valueSpan, i18n) {
9270 this.name = name;
9271 this.value = value;
9272 this.sourceSpan = sourceSpan;
9273 this.valueSpan = valueSpan;
9274 this.i18n = i18n;
9275 }
9276 Attribute.prototype.visit = function (visitor, context) { return visitor.visitAttribute(this, context); };
9277 return Attribute;
9278}());
9279var Element$1 = /** @class */ (function () {
9280 function Element(name, attrs, children, sourceSpan, startSourceSpan, endSourceSpan, i18n) {
9281 if (startSourceSpan === void 0) { startSourceSpan = null; }
9282 if (endSourceSpan === void 0) { endSourceSpan = null; }
9283 this.name = name;
9284 this.attrs = attrs;
9285 this.children = children;
9286 this.sourceSpan = sourceSpan;
9287 this.startSourceSpan = startSourceSpan;
9288 this.endSourceSpan = endSourceSpan;
9289 this.i18n = i18n;
9290 }
9291 Element.prototype.visit = function (visitor, context) { return visitor.visitElement(this, context); };
9292 return Element;
9293}());
9294var Comment = /** @class */ (function () {
9295 function Comment(value, sourceSpan) {
9296 this.value = value;
9297 this.sourceSpan = sourceSpan;
9298 }
9299 Comment.prototype.visit = function (visitor, context) { return visitor.visitComment(this, context); };
9300 return Comment;
9301}());
9302function visitAll$1(visitor, nodes, context) {
9303 if (context === void 0) { context = null; }
9304 var result = [];
9305 var visit = visitor.visit ?
9306 function (ast) { return visitor.visit(ast, context) || ast.visit(visitor, context); } :
9307 function (ast) { return ast.visit(visitor, context); };
9308 nodes.forEach(function (ast) {
9309 var astResult = visit(ast);
9310 if (astResult) {
9311 result.push(astResult);
9312 }
9313 });
9314 return result;
9315}
9316var RecursiveVisitor$1 = /** @class */ (function () {
9317 function RecursiveVisitor() {
9318 }
9319 RecursiveVisitor.prototype.visitElement = function (ast, context) {
9320 this.visitChildren(context, function (visit) {
9321 visit(ast.attrs);
9322 visit(ast.children);
9323 });
9324 };
9325 RecursiveVisitor.prototype.visitAttribute = function (ast, context) { };
9326 RecursiveVisitor.prototype.visitText = function (ast, context) { };
9327 RecursiveVisitor.prototype.visitComment = function (ast, context) { };
9328 RecursiveVisitor.prototype.visitExpansion = function (ast, context) {
9329 return this.visitChildren(context, function (visit) { visit(ast.cases); });
9330 };
9331 RecursiveVisitor.prototype.visitExpansionCase = function (ast, context) { };
9332 RecursiveVisitor.prototype.visitChildren = function (context, cb) {
9333 var results = [];
9334 var t = this;
9335 function visit(children) {
9336 if (children)
9337 results.push(visitAll$1(t, children, context));
9338 }
9339 cb(visit);
9340 return Array.prototype.concat.apply([], results);
9341 };
9342 return RecursiveVisitor;
9343}());
9344function spanOf(ast) {
9345 var start = ast.sourceSpan.start.offset;
9346 var end = ast.sourceSpan.end.offset;
9347 if (ast instanceof Element$1) {
9348 if (ast.endSourceSpan) {
9349 end = ast.endSourceSpan.end.offset;
9350 }
9351 else if (ast.children && ast.children.length) {
9352 end = spanOf(ast.children[ast.children.length - 1]).end;
9353 }
9354 }
9355 return { start: start, end: end };
9356}
9357function findNode(nodes, position) {
9358 var path = [];
9359 var visitor = new /** @class */ (function (_super) {
9360 __extends(class_1, _super);
9361 function class_1() {
9362 return _super !== null && _super.apply(this, arguments) || this;
9363 }
9364 class_1.prototype.visit = function (ast, context) {
9365 var span = spanOf(ast);
9366 if (span.start <= position && position < span.end) {
9367 path.push(ast);
9368 }
9369 else {
9370 // Returning a value here will result in the children being skipped.
9371 return true;
9372 }
9373 };
9374 return class_1;
9375 }(RecursiveVisitor$1));
9376 visitAll$1(visitor, nodes);
9377 return new AstPath(path, position);
9378}
9379
9380/**
9381 * @license
9382 * Copyright Google Inc. All Rights Reserved.
9383 *
9384 * Use of this source code is governed by an MIT-style license that can be
9385 * found in the LICENSE file at https://angular.io/license
9386 */
9387var TokenType;
9388(function (TokenType) {
9389 TokenType[TokenType["TAG_OPEN_START"] = 0] = "TAG_OPEN_START";
9390 TokenType[TokenType["TAG_OPEN_END"] = 1] = "TAG_OPEN_END";
9391 TokenType[TokenType["TAG_OPEN_END_VOID"] = 2] = "TAG_OPEN_END_VOID";
9392 TokenType[TokenType["TAG_CLOSE"] = 3] = "TAG_CLOSE";
9393 TokenType[TokenType["TEXT"] = 4] = "TEXT";
9394 TokenType[TokenType["ESCAPABLE_RAW_TEXT"] = 5] = "ESCAPABLE_RAW_TEXT";
9395 TokenType[TokenType["RAW_TEXT"] = 6] = "RAW_TEXT";
9396 TokenType[TokenType["COMMENT_START"] = 7] = "COMMENT_START";
9397 TokenType[TokenType["COMMENT_END"] = 8] = "COMMENT_END";
9398 TokenType[TokenType["CDATA_START"] = 9] = "CDATA_START";
9399 TokenType[TokenType["CDATA_END"] = 10] = "CDATA_END";
9400 TokenType[TokenType["ATTR_NAME"] = 11] = "ATTR_NAME";
9401 TokenType[TokenType["ATTR_QUOTE"] = 12] = "ATTR_QUOTE";
9402 TokenType[TokenType["ATTR_VALUE"] = 13] = "ATTR_VALUE";
9403 TokenType[TokenType["DOC_TYPE"] = 14] = "DOC_TYPE";
9404 TokenType[TokenType["EXPANSION_FORM_START"] = 15] = "EXPANSION_FORM_START";
9405 TokenType[TokenType["EXPANSION_CASE_VALUE"] = 16] = "EXPANSION_CASE_VALUE";
9406 TokenType[TokenType["EXPANSION_CASE_EXP_START"] = 17] = "EXPANSION_CASE_EXP_START";
9407 TokenType[TokenType["EXPANSION_CASE_EXP_END"] = 18] = "EXPANSION_CASE_EXP_END";
9408 TokenType[TokenType["EXPANSION_FORM_END"] = 19] = "EXPANSION_FORM_END";
9409 TokenType[TokenType["EOF"] = 20] = "EOF";
9410})(TokenType || (TokenType = {}));
9411var Token = /** @class */ (function () {
9412 function Token(type, parts, sourceSpan) {
9413 this.type = type;
9414 this.parts = parts;
9415 this.sourceSpan = sourceSpan;
9416 }
9417 return Token;
9418}());
9419var TokenError = /** @class */ (function (_super) {
9420 __extends(TokenError, _super);
9421 function TokenError(errorMsg, tokenType, span) {
9422 var _this = _super.call(this, span, errorMsg) || this;
9423 _this.tokenType = tokenType;
9424 return _this;
9425 }
9426 return TokenError;
9427}(ParseError));
9428var TokenizeResult = /** @class */ (function () {
9429 function TokenizeResult(tokens, errors) {
9430 this.tokens = tokens;
9431 this.errors = errors;
9432 }
9433 return TokenizeResult;
9434}());
9435function tokenize(source, url, getTagDefinition, options) {
9436 if (options === void 0) { options = {}; }
9437 return new _Tokenizer(new ParseSourceFile(source, url), getTagDefinition, options).tokenize();
9438}
9439var _CR_OR_CRLF_REGEXP = /\r\n?/g;
9440function _unexpectedCharacterErrorMsg(charCode) {
9441 var char = charCode === $EOF ? 'EOF' : String.fromCharCode(charCode);
9442 return "Unexpected character \"" + char + "\"";
9443}
9444function _unknownEntityErrorMsg(entitySrc) {
9445 return "Unknown entity \"" + entitySrc + "\" - use the \"&#<decimal>;\" or \"&#x<hex>;\" syntax";
9446}
9447var _ControlFlowError = /** @class */ (function () {
9448 function _ControlFlowError(error) {
9449 this.error = error;
9450 }
9451 return _ControlFlowError;
9452}());
9453// See http://www.w3.org/TR/html51/syntax.html#writing
9454var _Tokenizer = /** @class */ (function () {
9455 /**
9456 * @param _file The html source file being tokenized.
9457 * @param _getTagDefinition A function that will retrieve a tag definition for a given tag name.
9458 * @param options Configuration of the tokenization.
9459 */
9460 function _Tokenizer(_file, _getTagDefinition, options) {
9461 this._getTagDefinition = _getTagDefinition;
9462 this._currentTokenStart = null;
9463 this._currentTokenType = null;
9464 this._expansionCaseStack = [];
9465 this._inInterpolation = false;
9466 this.tokens = [];
9467 this.errors = [];
9468 this._tokenizeIcu = options.tokenizeExpansionForms || false;
9469 this._interpolationConfig = options.interpolationConfig || DEFAULT_INTERPOLATION_CONFIG;
9470 this._leadingTriviaCodePoints =
9471 options.leadingTriviaChars && options.leadingTriviaChars.map(function (c) { return c.codePointAt(0) || 0; });
9472 var range = options.range || { endPos: _file.content.length, startPos: 0, startLine: 0, startCol: 0 };
9473 this._cursor = options.escapedString ? new EscapedCharacterCursor(_file, range) :
9474 new PlainCharacterCursor(_file, range);
9475 try {
9476 this._cursor.init();
9477 }
9478 catch (e) {
9479 this.handleError(e);
9480 }
9481 }
9482 _Tokenizer.prototype._processCarriageReturns = function (content) {
9483 // http://www.w3.org/TR/html5/syntax.html#preprocessing-the-input-stream
9484 // In order to keep the original position in the source, we can not
9485 // pre-process it.
9486 // Instead CRs are processed right before instantiating the tokens.
9487 return content.replace(_CR_OR_CRLF_REGEXP, '\n');
9488 };
9489 _Tokenizer.prototype.tokenize = function () {
9490 while (this._cursor.peek() !== $EOF) {
9491 var start = this._cursor.clone();
9492 try {
9493 if (this._attemptCharCode($LT)) {
9494 if (this._attemptCharCode($BANG)) {
9495 if (this._attemptCharCode($LBRACKET)) {
9496 this._consumeCdata(start);
9497 }
9498 else if (this._attemptCharCode($MINUS)) {
9499 this._consumeComment(start);
9500 }
9501 else {
9502 this._consumeDocType(start);
9503 }
9504 }
9505 else if (this._attemptCharCode($SLASH)) {
9506 this._consumeTagClose(start);
9507 }
9508 else {
9509 this._consumeTagOpen(start);
9510 }
9511 }
9512 else if (!(this._tokenizeIcu && this._tokenizeExpansionForm())) {
9513 this._consumeText();
9514 }
9515 }
9516 catch (e) {
9517 this.handleError(e);
9518 }
9519 }
9520 this._beginToken(TokenType.EOF);
9521 this._endToken([]);
9522 return new TokenizeResult(mergeTextTokens(this.tokens), this.errors);
9523 };
9524 /**
9525 * @returns whether an ICU token has been created
9526 * @internal
9527 */
9528 _Tokenizer.prototype._tokenizeExpansionForm = function () {
9529 if (this.isExpansionFormStart()) {
9530 this._consumeExpansionFormStart();
9531 return true;
9532 }
9533 if (isExpansionCaseStart(this._cursor.peek()) && this._isInExpansionForm()) {
9534 this._consumeExpansionCaseStart();
9535 return true;
9536 }
9537 if (this._cursor.peek() === $RBRACE) {
9538 if (this._isInExpansionCase()) {
9539 this._consumeExpansionCaseEnd();
9540 return true;
9541 }
9542 if (this._isInExpansionForm()) {
9543 this._consumeExpansionFormEnd();
9544 return true;
9545 }
9546 }
9547 return false;
9548 };
9549 _Tokenizer.prototype._beginToken = function (type, start) {
9550 if (start === void 0) { start = this._cursor.clone(); }
9551 this._currentTokenStart = start;
9552 this._currentTokenType = type;
9553 };
9554 _Tokenizer.prototype._endToken = function (parts, end) {
9555 if (end === void 0) { end = this._cursor.clone(); }
9556 if (this._currentTokenStart === null) {
9557 throw new TokenError('Programming error - attempted to end a token when there was no start to the token', this._currentTokenType, this._cursor.getSpan(end));
9558 }
9559 if (this._currentTokenType === null) {
9560 throw new TokenError('Programming error - attempted to end a token which has no token type', null, this._cursor.getSpan(this._currentTokenStart));
9561 }
9562 var token = new Token(this._currentTokenType, parts, this._cursor.getSpan(this._currentTokenStart, this._leadingTriviaCodePoints));
9563 this.tokens.push(token);
9564 this._currentTokenStart = null;
9565 this._currentTokenType = null;
9566 return token;
9567 };
9568 _Tokenizer.prototype._createError = function (msg, span) {
9569 if (this._isInExpansionForm()) {
9570 msg += " (Do you have an unescaped \"{\" in your template? Use \"{{ '{' }}\") to escape it.)";
9571 }
9572 var error = new TokenError(msg, this._currentTokenType, span);
9573 this._currentTokenStart = null;
9574 this._currentTokenType = null;
9575 return new _ControlFlowError(error);
9576 };
9577 _Tokenizer.prototype.handleError = function (e) {
9578 if (e instanceof CursorError) {
9579 e = this._createError(e.msg, this._cursor.getSpan(e.cursor));
9580 }
9581 if (e instanceof _ControlFlowError) {
9582 this.errors.push(e.error);
9583 }
9584 else {
9585 throw e;
9586 }
9587 };
9588 _Tokenizer.prototype._attemptCharCode = function (charCode) {
9589 if (this._cursor.peek() === charCode) {
9590 this._cursor.advance();
9591 return true;
9592 }
9593 return false;
9594 };
9595 _Tokenizer.prototype._attemptCharCodeCaseInsensitive = function (charCode) {
9596 if (compareCharCodeCaseInsensitive(this._cursor.peek(), charCode)) {
9597 this._cursor.advance();
9598 return true;
9599 }
9600 return false;
9601 };
9602 _Tokenizer.prototype._requireCharCode = function (charCode) {
9603 var location = this._cursor.clone();
9604 if (!this._attemptCharCode(charCode)) {
9605 throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(location));
9606 }
9607 };
9608 _Tokenizer.prototype._attemptStr = function (chars) {
9609 var len = chars.length;
9610 if (this._cursor.charsLeft() < len) {
9611 return false;
9612 }
9613 var initialPosition = this._cursor.clone();
9614 for (var i = 0; i < len; i++) {
9615 if (!this._attemptCharCode(chars.charCodeAt(i))) {
9616 // If attempting to parse the string fails, we want to reset the parser
9617 // to where it was before the attempt
9618 this._cursor = initialPosition;
9619 return false;
9620 }
9621 }
9622 return true;
9623 };
9624 _Tokenizer.prototype._attemptStrCaseInsensitive = function (chars) {
9625 for (var i = 0; i < chars.length; i++) {
9626 if (!this._attemptCharCodeCaseInsensitive(chars.charCodeAt(i))) {
9627 return false;
9628 }
9629 }
9630 return true;
9631 };
9632 _Tokenizer.prototype._requireStr = function (chars) {
9633 var location = this._cursor.clone();
9634 if (!this._attemptStr(chars)) {
9635 throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(location));
9636 }
9637 };
9638 _Tokenizer.prototype._attemptCharCodeUntilFn = function (predicate) {
9639 while (!predicate(this._cursor.peek())) {
9640 this._cursor.advance();
9641 }
9642 };
9643 _Tokenizer.prototype._requireCharCodeUntilFn = function (predicate, len) {
9644 var start = this._cursor.clone();
9645 this._attemptCharCodeUntilFn(predicate);
9646 var end = this._cursor.clone();
9647 if (end.diff(start) < len) {
9648 throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(start));
9649 }
9650 };
9651 _Tokenizer.prototype._attemptUntilChar = function (char) {
9652 while (this._cursor.peek() !== char) {
9653 this._cursor.advance();
9654 }
9655 };
9656 _Tokenizer.prototype._readChar = function (decodeEntities) {
9657 if (decodeEntities && this._cursor.peek() === $AMPERSAND) {
9658 return this._decodeEntity();
9659 }
9660 else {
9661 // Don't rely upon reading directly from `_input` as the actual char value
9662 // may have been generated from an escape sequence.
9663 var char = String.fromCodePoint(this._cursor.peek());
9664 this._cursor.advance();
9665 return char;
9666 }
9667 };
9668 _Tokenizer.prototype._decodeEntity = function () {
9669 var start = this._cursor.clone();
9670 this._cursor.advance();
9671 if (this._attemptCharCode($HASH)) {
9672 var isHex = this._attemptCharCode($x) || this._attemptCharCode($X);
9673 var codeStart = this._cursor.clone();
9674 this._attemptCharCodeUntilFn(isDigitEntityEnd);
9675 if (this._cursor.peek() != $SEMICOLON) {
9676 throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan());
9677 }
9678 var strNum = this._cursor.getChars(codeStart);
9679 this._cursor.advance();
9680 try {
9681 var charCode = parseInt(strNum, isHex ? 16 : 10);
9682 return String.fromCharCode(charCode);
9683 }
9684 catch (_a) {
9685 throw this._createError(_unknownEntityErrorMsg(this._cursor.getChars(start)), this._cursor.getSpan());
9686 }
9687 }
9688 else {
9689 var nameStart = this._cursor.clone();
9690 this._attemptCharCodeUntilFn(isNamedEntityEnd);
9691 if (this._cursor.peek() != $SEMICOLON) {
9692 this._cursor = nameStart;
9693 return '&';
9694 }
9695 var name_1 = this._cursor.getChars(nameStart);
9696 this._cursor.advance();
9697 var char = NAMED_ENTITIES[name_1];
9698 if (!char) {
9699 throw this._createError(_unknownEntityErrorMsg(name_1), this._cursor.getSpan(start));
9700 }
9701 return char;
9702 }
9703 };
9704 _Tokenizer.prototype._consumeRawText = function (decodeEntities, endMarkerPredicate) {
9705 this._beginToken(decodeEntities ? TokenType.ESCAPABLE_RAW_TEXT : TokenType.RAW_TEXT);
9706 var parts = [];
9707 while (true) {
9708 var tagCloseStart = this._cursor.clone();
9709 var foundEndMarker = endMarkerPredicate();
9710 this._cursor = tagCloseStart;
9711 if (foundEndMarker) {
9712 break;
9713 }
9714 parts.push(this._readChar(decodeEntities));
9715 }
9716 return this._endToken([this._processCarriageReturns(parts.join(''))]);
9717 };
9718 _Tokenizer.prototype._consumeComment = function (start) {
9719 var _this = this;
9720 this._beginToken(TokenType.COMMENT_START, start);
9721 this._requireCharCode($MINUS);
9722 this._endToken([]);
9723 this._consumeRawText(false, function () { return _this._attemptStr('-->'); });
9724 this._beginToken(TokenType.COMMENT_END);
9725 this._requireStr('-->');
9726 this._endToken([]);
9727 };
9728 _Tokenizer.prototype._consumeCdata = function (start) {
9729 var _this = this;
9730 this._beginToken(TokenType.CDATA_START, start);
9731 this._requireStr('CDATA[');
9732 this._endToken([]);
9733 this._consumeRawText(false, function () { return _this._attemptStr(']]>'); });
9734 this._beginToken(TokenType.CDATA_END);
9735 this._requireStr(']]>');
9736 this._endToken([]);
9737 };
9738 _Tokenizer.prototype._consumeDocType = function (start) {
9739 this._beginToken(TokenType.DOC_TYPE, start);
9740 var contentStart = this._cursor.clone();
9741 this._attemptUntilChar($GT);
9742 var content = this._cursor.getChars(contentStart);
9743 this._cursor.advance();
9744 this._endToken([content]);
9745 };
9746 _Tokenizer.prototype._consumePrefixAndName = function () {
9747 var nameOrPrefixStart = this._cursor.clone();
9748 var prefix = '';
9749 while (this._cursor.peek() !== $COLON && !isPrefixEnd(this._cursor.peek())) {
9750 this._cursor.advance();
9751 }
9752 var nameStart;
9753 if (this._cursor.peek() === $COLON) {
9754 prefix = this._cursor.getChars(nameOrPrefixStart);
9755 this._cursor.advance();
9756 nameStart = this._cursor.clone();
9757 }
9758 else {
9759 nameStart = nameOrPrefixStart;
9760 }
9761 this._requireCharCodeUntilFn(isNameEnd, prefix === '' ? 0 : 1);
9762 var name = this._cursor.getChars(nameStart);
9763 return [prefix, name];
9764 };
9765 _Tokenizer.prototype._consumeTagOpen = function (start) {
9766 var tagName;
9767 var prefix;
9768 var openTagToken;
9769 var tokensBeforeTagOpen = this.tokens.length;
9770 var innerStart = this._cursor.clone();
9771 try {
9772 if (!isAsciiLetter(this._cursor.peek())) {
9773 throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(start));
9774 }
9775 openTagToken = this._consumeTagOpenStart(start);
9776 prefix = openTagToken.parts[0];
9777 tagName = openTagToken.parts[1];
9778 this._attemptCharCodeUntilFn(isNotWhitespace);
9779 while (this._cursor.peek() !== $SLASH && this._cursor.peek() !== $GT) {
9780 this._consumeAttributeName();
9781 this._attemptCharCodeUntilFn(isNotWhitespace);
9782 if (this._attemptCharCode($EQ)) {
9783 this._attemptCharCodeUntilFn(isNotWhitespace);
9784 this._consumeAttributeValue();
9785 }
9786 this._attemptCharCodeUntilFn(isNotWhitespace);
9787 }
9788 this._consumeTagOpenEnd();
9789 }
9790 catch (e) {
9791 if (e instanceof _ControlFlowError) {
9792 // When the start tag is invalid (including invalid "attributes"), assume we want a "<"
9793 this._cursor = innerStart;
9794 if (openTagToken) {
9795 this.tokens.length = tokensBeforeTagOpen;
9796 }
9797 // Back to back text tokens are merged at the end
9798 this._beginToken(TokenType.TEXT, start);
9799 this._endToken(['<']);
9800 return;
9801 }
9802 throw e;
9803 }
9804 var contentTokenType = this._getTagDefinition(tagName).contentType;
9805 if (contentTokenType === TagContentType.RAW_TEXT) {
9806 this._consumeRawTextWithTagClose(prefix, tagName, false);
9807 }
9808 else if (contentTokenType === TagContentType.ESCAPABLE_RAW_TEXT) {
9809 this._consumeRawTextWithTagClose(prefix, tagName, true);
9810 }
9811 };
9812 _Tokenizer.prototype._consumeRawTextWithTagClose = function (prefix, tagName, decodeEntities) {
9813 var _this = this;
9814 var textToken = this._consumeRawText(decodeEntities, function () {
9815 if (!_this._attemptCharCode($LT))
9816 return false;
9817 if (!_this._attemptCharCode($SLASH))
9818 return false;
9819 _this._attemptCharCodeUntilFn(isNotWhitespace);
9820 if (!_this._attemptStrCaseInsensitive(tagName))
9821 return false;
9822 _this._attemptCharCodeUntilFn(isNotWhitespace);
9823 return _this._attemptCharCode($GT);
9824 });
9825 this._beginToken(TokenType.TAG_CLOSE);
9826 this._requireCharCodeUntilFn(function (code) { return code === $GT; }, 3);
9827 this._cursor.advance(); // Consume the `>`
9828 this._endToken([prefix, tagName]);
9829 };
9830 _Tokenizer.prototype._consumeTagOpenStart = function (start) {
9831 this._beginToken(TokenType.TAG_OPEN_START, start);
9832 var parts = this._consumePrefixAndName();
9833 return this._endToken(parts);
9834 };
9835 _Tokenizer.prototype._consumeAttributeName = function () {
9836 var attrNameStart = this._cursor.peek();
9837 if (attrNameStart === $SQ || attrNameStart === $DQ) {
9838 throw this._createError(_unexpectedCharacterErrorMsg(attrNameStart), this._cursor.getSpan());
9839 }
9840 this._beginToken(TokenType.ATTR_NAME);
9841 var prefixAndName = this._consumePrefixAndName();
9842 this._endToken(prefixAndName);
9843 };
9844 _Tokenizer.prototype._consumeAttributeValue = function () {
9845 var value;
9846 if (this._cursor.peek() === $SQ || this._cursor.peek() === $DQ) {
9847 this._beginToken(TokenType.ATTR_QUOTE);
9848 var quoteChar = this._cursor.peek();
9849 this._cursor.advance();
9850 this._endToken([String.fromCodePoint(quoteChar)]);
9851 this._beginToken(TokenType.ATTR_VALUE);
9852 var parts = [];
9853 while (this._cursor.peek() !== quoteChar) {
9854 parts.push(this._readChar(true));
9855 }
9856 value = parts.join('');
9857 this._endToken([this._processCarriageReturns(value)]);
9858 this._beginToken(TokenType.ATTR_QUOTE);
9859 this._cursor.advance();
9860 this._endToken([String.fromCodePoint(quoteChar)]);
9861 }
9862 else {
9863 this._beginToken(TokenType.ATTR_VALUE);
9864 var valueStart = this._cursor.clone();
9865 this._requireCharCodeUntilFn(isNameEnd, 1);
9866 value = this._cursor.getChars(valueStart);
9867 this._endToken([this._processCarriageReturns(value)]);
9868 }
9869 };
9870 _Tokenizer.prototype._consumeTagOpenEnd = function () {
9871 var tokenType = this._attemptCharCode($SLASH) ? TokenType.TAG_OPEN_END_VOID : TokenType.TAG_OPEN_END;
9872 this._beginToken(tokenType);
9873 this._requireCharCode($GT);
9874 this._endToken([]);
9875 };
9876 _Tokenizer.prototype._consumeTagClose = function (start) {
9877 this._beginToken(TokenType.TAG_CLOSE, start);
9878 this._attemptCharCodeUntilFn(isNotWhitespace);
9879 var prefixAndName = this._consumePrefixAndName();
9880 this._attemptCharCodeUntilFn(isNotWhitespace);
9881 this._requireCharCode($GT);
9882 this._endToken(prefixAndName);
9883 };
9884 _Tokenizer.prototype._consumeExpansionFormStart = function () {
9885 this._beginToken(TokenType.EXPANSION_FORM_START);
9886 this._requireCharCode($LBRACE);
9887 this._endToken([]);
9888 this._expansionCaseStack.push(TokenType.EXPANSION_FORM_START);
9889 this._beginToken(TokenType.RAW_TEXT);
9890 var condition = this._readUntil($COMMA);
9891 this._endToken([condition]);
9892 this._requireCharCode($COMMA);
9893 this._attemptCharCodeUntilFn(isNotWhitespace);
9894 this._beginToken(TokenType.RAW_TEXT);
9895 var type = this._readUntil($COMMA);
9896 this._endToken([type]);
9897 this._requireCharCode($COMMA);
9898 this._attemptCharCodeUntilFn(isNotWhitespace);
9899 };
9900 _Tokenizer.prototype._consumeExpansionCaseStart = function () {
9901 this._beginToken(TokenType.EXPANSION_CASE_VALUE);
9902 var value = this._readUntil($LBRACE).trim();
9903 this._endToken([value]);
9904 this._attemptCharCodeUntilFn(isNotWhitespace);
9905 this._beginToken(TokenType.EXPANSION_CASE_EXP_START);
9906 this._requireCharCode($LBRACE);
9907 this._endToken([]);
9908 this._attemptCharCodeUntilFn(isNotWhitespace);
9909 this._expansionCaseStack.push(TokenType.EXPANSION_CASE_EXP_START);
9910 };
9911 _Tokenizer.prototype._consumeExpansionCaseEnd = function () {
9912 this._beginToken(TokenType.EXPANSION_CASE_EXP_END);
9913 this._requireCharCode($RBRACE);
9914 this._endToken([]);
9915 this._attemptCharCodeUntilFn(isNotWhitespace);
9916 this._expansionCaseStack.pop();
9917 };
9918 _Tokenizer.prototype._consumeExpansionFormEnd = function () {
9919 this._beginToken(TokenType.EXPANSION_FORM_END);
9920 this._requireCharCode($RBRACE);
9921 this._endToken([]);
9922 this._expansionCaseStack.pop();
9923 };
9924 _Tokenizer.prototype._consumeText = function () {
9925 var start = this._cursor.clone();
9926 this._beginToken(TokenType.TEXT, start);
9927 var parts = [];
9928 do {
9929 if (this._interpolationConfig && this._attemptStr(this._interpolationConfig.start)) {
9930 parts.push(this._interpolationConfig.start);
9931 this._inInterpolation = true;
9932 }
9933 else if (this._interpolationConfig && this._inInterpolation &&
9934 this._attemptStr(this._interpolationConfig.end)) {
9935 parts.push(this._interpolationConfig.end);
9936 this._inInterpolation = false;
9937 }
9938 else {
9939 parts.push(this._readChar(true));
9940 }
9941 } while (!this._isTextEnd());
9942 this._endToken([this._processCarriageReturns(parts.join(''))]);
9943 };
9944 _Tokenizer.prototype._isTextEnd = function () {
9945 if (this._cursor.peek() === $LT || this._cursor.peek() === $EOF) {
9946 return true;
9947 }
9948 if (this._tokenizeIcu && !this._inInterpolation) {
9949 if (this.isExpansionFormStart()) {
9950 // start of an expansion form
9951 return true;
9952 }
9953 if (this._cursor.peek() === $RBRACE && this._isInExpansionCase()) {
9954 // end of and expansion case
9955 return true;
9956 }
9957 }
9958 return false;
9959 };
9960 _Tokenizer.prototype._readUntil = function (char) {
9961 var start = this._cursor.clone();
9962 this._attemptUntilChar(char);
9963 return this._cursor.getChars(start);
9964 };
9965 _Tokenizer.prototype._isInExpansionCase = function () {
9966 return this._expansionCaseStack.length > 0 &&
9967 this._expansionCaseStack[this._expansionCaseStack.length - 1] ===
9968 TokenType.EXPANSION_CASE_EXP_START;
9969 };
9970 _Tokenizer.prototype._isInExpansionForm = function () {
9971 return this._expansionCaseStack.length > 0 &&
9972 this._expansionCaseStack[this._expansionCaseStack.length - 1] ===
9973 TokenType.EXPANSION_FORM_START;
9974 };
9975 _Tokenizer.prototype.isExpansionFormStart = function () {
9976 if (this._cursor.peek() !== $LBRACE) {
9977 return false;
9978 }
9979 if (this._interpolationConfig) {
9980 var start = this._cursor.clone();
9981 var isInterpolation = this._attemptStr(this._interpolationConfig.start);
9982 this._cursor = start;
9983 return !isInterpolation;
9984 }
9985 return true;
9986 };
9987 return _Tokenizer;
9988}());
9989function isNotWhitespace(code) {
9990 return !isWhitespace(code) || code === $EOF;
9991}
9992function isNameEnd(code) {
9993 return isWhitespace(code) || code === $GT || code === $SLASH ||
9994 code === $SQ || code === $DQ || code === $EQ;
9995}
9996function isPrefixEnd(code) {
9997 return (code < $a || $z < code) && (code < $A || $Z < code) &&
9998 (code < $0 || code > $9);
9999}
10000function isDigitEntityEnd(code) {
10001 return code == $SEMICOLON || code == $EOF || !isAsciiHexDigit(code);
10002}
10003function isNamedEntityEnd(code) {
10004 return code == $SEMICOLON || code == $EOF || !isAsciiLetter(code);
10005}
10006function isExpansionCaseStart(peek) {
10007 return peek === $EQ || isAsciiLetter(peek) || isDigit(peek);
10008}
10009function compareCharCodeCaseInsensitive(code1, code2) {
10010 return toUpperCaseCharCode(code1) == toUpperCaseCharCode(code2);
10011}
10012function toUpperCaseCharCode(code) {
10013 return code >= $a && code <= $z ? code - $a + $A : code;
10014}
10015function mergeTextTokens(srcTokens) {
10016 var dstTokens = [];
10017 var lastDstToken = undefined;
10018 for (var i = 0; i < srcTokens.length; i++) {
10019 var token = srcTokens[i];
10020 if (lastDstToken && lastDstToken.type == TokenType.TEXT && token.type == TokenType.TEXT) {
10021 lastDstToken.parts[0] += token.parts[0];
10022 lastDstToken.sourceSpan.end = token.sourceSpan.end;
10023 }
10024 else {
10025 lastDstToken = token;
10026 dstTokens.push(lastDstToken);
10027 }
10028 }
10029 return dstTokens;
10030}
10031var PlainCharacterCursor = /** @class */ (function () {
10032 function PlainCharacterCursor(fileOrCursor, range) {
10033 if (fileOrCursor instanceof PlainCharacterCursor) {
10034 this.file = fileOrCursor.file;
10035 this.input = fileOrCursor.input;
10036 this.end = fileOrCursor.end;
10037 this.state = __assign({}, fileOrCursor.state);
10038 }
10039 else {
10040 if (!range) {
10041 throw new Error('Programming error: the range argument must be provided with a file argument.');
10042 }
10043 this.file = fileOrCursor;
10044 this.input = fileOrCursor.content;
10045 this.end = range.endPos;
10046 this.state = {
10047 peek: -1,
10048 offset: range.startPos,
10049 line: range.startLine,
10050 column: range.startCol,
10051 };
10052 }
10053 }
10054 PlainCharacterCursor.prototype.clone = function () { return new PlainCharacterCursor(this); };
10055 PlainCharacterCursor.prototype.peek = function () { return this.state.peek; };
10056 PlainCharacterCursor.prototype.charsLeft = function () { return this.end - this.state.offset; };
10057 PlainCharacterCursor.prototype.diff = function (other) { return this.state.offset - other.state.offset; };
10058 PlainCharacterCursor.prototype.advance = function () { this.advanceState(this.state); };
10059 PlainCharacterCursor.prototype.init = function () { this.updatePeek(this.state); };
10060 PlainCharacterCursor.prototype.getSpan = function (start, leadingTriviaCodePoints) {
10061 start = start || this;
10062 if (leadingTriviaCodePoints) {
10063 start = start.clone();
10064 while (this.diff(start) > 0 && leadingTriviaCodePoints.indexOf(start.peek()) !== -1) {
10065 start.advance();
10066 }
10067 }
10068 return new ParseSourceSpan(new ParseLocation(start.file, start.state.offset, start.state.line, start.state.column), new ParseLocation(this.file, this.state.offset, this.state.line, this.state.column));
10069 };
10070 PlainCharacterCursor.prototype.getChars = function (start) {
10071 return this.input.substring(start.state.offset, this.state.offset);
10072 };
10073 PlainCharacterCursor.prototype.charAt = function (pos) { return this.input.charCodeAt(pos); };
10074 PlainCharacterCursor.prototype.advanceState = function (state) {
10075 if (state.offset >= this.end) {
10076 this.state = state;
10077 throw new CursorError('Unexpected character "EOF"', this);
10078 }
10079 var currentChar = this.charAt(state.offset);
10080 if (currentChar === $LF) {
10081 state.line++;
10082 state.column = 0;
10083 }
10084 else if (!isNewLine(currentChar)) {
10085 state.column++;
10086 }
10087 state.offset++;
10088 this.updatePeek(state);
10089 };
10090 PlainCharacterCursor.prototype.updatePeek = function (state) {
10091 state.peek = state.offset >= this.end ? $EOF : this.charAt(state.offset);
10092 };
10093 return PlainCharacterCursor;
10094}());
10095var EscapedCharacterCursor = /** @class */ (function (_super) {
10096 __extends(EscapedCharacterCursor, _super);
10097 function EscapedCharacterCursor(fileOrCursor, range) {
10098 var _this = this;
10099 if (fileOrCursor instanceof EscapedCharacterCursor) {
10100 _this = _super.call(this, fileOrCursor) || this;
10101 _this.internalState = __assign({}, fileOrCursor.internalState);
10102 }
10103 else {
10104 _this = _super.call(this, fileOrCursor, range) || this;
10105 _this.internalState = _this.state;
10106 }
10107 return _this;
10108 }
10109 EscapedCharacterCursor.prototype.advance = function () {
10110 this.state = this.internalState;
10111 _super.prototype.advance.call(this);
10112 this.processEscapeSequence();
10113 };
10114 EscapedCharacterCursor.prototype.init = function () {
10115 _super.prototype.init.call(this);
10116 this.processEscapeSequence();
10117 };
10118 EscapedCharacterCursor.prototype.clone = function () { return new EscapedCharacterCursor(this); };
10119 EscapedCharacterCursor.prototype.getChars = function (start) {
10120 var cursor = start.clone();
10121 var chars = '';
10122 while (cursor.internalState.offset < this.internalState.offset) {
10123 chars += String.fromCodePoint(cursor.peek());
10124 cursor.advance();
10125 }
10126 return chars;
10127 };
10128 /**
10129 * Process the escape sequence that starts at the current position in the text.
10130 *
10131 * This method is called to ensure that `peek` has the unescaped value of escape sequences.
10132 */
10133 EscapedCharacterCursor.prototype.processEscapeSequence = function () {
10134 var _this = this;
10135 var peek = function () { return _this.internalState.peek; };
10136 if (peek() === $BACKSLASH) {
10137 // We have hit an escape sequence so we need the internal state to become independent
10138 // of the external state.
10139 this.internalState = __assign({}, this.state);
10140 // Move past the backslash
10141 this.advanceState(this.internalState);
10142 // First check for standard control char sequences
10143 if (peek() === $n) {
10144 this.state.peek = $LF;
10145 }
10146 else if (peek() === $r) {
10147 this.state.peek = $CR;
10148 }
10149 else if (peek() === $v) {
10150 this.state.peek = $VTAB;
10151 }
10152 else if (peek() === $t) {
10153 this.state.peek = $TAB;
10154 }
10155 else if (peek() === $b) {
10156 this.state.peek = $BSPACE;
10157 }
10158 else if (peek() === $f) {
10159 this.state.peek = $FF;
10160 }
10161 // Now consider more complex sequences
10162 else if (peek() === $u) {
10163 // Unicode code-point sequence
10164 this.advanceState(this.internalState); // advance past the `u` char
10165 if (peek() === $LBRACE) {
10166 // Variable length Unicode, e.g. `\x{123}`
10167 this.advanceState(this.internalState); // advance past the `{` char
10168 // Advance past the variable number of hex digits until we hit a `}` char
10169 var digitStart = this.clone();
10170 var length_1 = 0;
10171 while (peek() !== $RBRACE) {
10172 this.advanceState(this.internalState);
10173 length_1++;
10174 }
10175 this.state.peek = this.decodeHexDigits(digitStart, length_1);
10176 }
10177 else {
10178 // Fixed length Unicode, e.g. `\u1234`
10179 var digitStart = this.clone();
10180 this.advanceState(this.internalState);
10181 this.advanceState(this.internalState);
10182 this.advanceState(this.internalState);
10183 this.state.peek = this.decodeHexDigits(digitStart, 4);
10184 }
10185 }
10186 else if (peek() === $x) {
10187 // Hex char code, e.g. `\x2F`
10188 this.advanceState(this.internalState); // advance past the `x` char
10189 var digitStart = this.clone();
10190 this.advanceState(this.internalState);
10191 this.state.peek = this.decodeHexDigits(digitStart, 2);
10192 }
10193 else if (isOctalDigit(peek())) {
10194 // Octal char code, e.g. `\012`,
10195 var octal = '';
10196 var length_2 = 0;
10197 var previous = this.clone();
10198 while (isOctalDigit(peek()) && length_2 < 3) {
10199 previous = this.clone();
10200 octal += String.fromCodePoint(peek());
10201 this.advanceState(this.internalState);
10202 length_2++;
10203 }
10204 this.state.peek = parseInt(octal, 8);
10205 // Backup one char
10206 this.internalState = previous.internalState;
10207 }
10208 else if (isNewLine(this.internalState.peek)) {
10209 // Line continuation `\` followed by a new line
10210 this.advanceState(this.internalState); // advance over the newline
10211 this.state = this.internalState;
10212 }
10213 else {
10214 // If none of the `if` blocks were executed then we just have an escaped normal character.
10215 // In that case we just, effectively, skip the backslash from the character.
10216 this.state.peek = this.internalState.peek;
10217 }
10218 }
10219 };
10220 EscapedCharacterCursor.prototype.decodeHexDigits = function (start, length) {
10221 var hex = this.input.substr(start.internalState.offset, length);
10222 var charCode = parseInt(hex, 16);
10223 if (!isNaN(charCode)) {
10224 return charCode;
10225 }
10226 else {
10227 start.state = start.internalState;
10228 throw new CursorError('Invalid hexadecimal escape sequence', start);
10229 }
10230 };
10231 return EscapedCharacterCursor;
10232}(PlainCharacterCursor));
10233var CursorError = /** @class */ (function () {
10234 function CursorError(msg, cursor) {
10235 this.msg = msg;
10236 this.cursor = cursor;
10237 }
10238 return CursorError;
10239}());
10240
10241/**
10242 * @license
10243 * Copyright Google Inc. All Rights Reserved.
10244 *
10245 * Use of this source code is governed by an MIT-style license that can be
10246 * found in the LICENSE file at https://angular.io/license
10247 */
10248var TreeError = /** @class */ (function (_super) {
10249 __extends(TreeError, _super);
10250 function TreeError(elementName, span, msg) {
10251 var _this = _super.call(this, span, msg) || this;
10252 _this.elementName = elementName;
10253 return _this;
10254 }
10255 TreeError.create = function (elementName, span, msg) {
10256 return new TreeError(elementName, span, msg);
10257 };
10258 return TreeError;
10259}(ParseError));
10260var ParseTreeResult = /** @class */ (function () {
10261 function ParseTreeResult(rootNodes, errors) {
10262 this.rootNodes = rootNodes;
10263 this.errors = errors;
10264 }
10265 return ParseTreeResult;
10266}());
10267var Parser = /** @class */ (function () {
10268 function Parser(getTagDefinition) {
10269 this.getTagDefinition = getTagDefinition;
10270 }
10271 Parser.prototype.parse = function (source, url, options) {
10272 var tokensAndErrors = tokenize(source, url, this.getTagDefinition, options);
10273 var treeAndErrors = new _TreeBuilder(tokensAndErrors.tokens, this.getTagDefinition).build();
10274 return new ParseTreeResult(treeAndErrors.rootNodes, tokensAndErrors.errors.concat(treeAndErrors.errors));
10275 };
10276 return Parser;
10277}());
10278var _TreeBuilder = /** @class */ (function () {
10279 function _TreeBuilder(tokens, getTagDefinition) {
10280 this.tokens = tokens;
10281 this.getTagDefinition = getTagDefinition;
10282 this._index = -1;
10283 this._rootNodes = [];
10284 this._errors = [];
10285 this._elementStack = [];
10286 this._advance();
10287 }
10288 _TreeBuilder.prototype.build = function () {
10289 while (this._peek.type !== TokenType.EOF) {
10290 if (this._peek.type === TokenType.TAG_OPEN_START) {
10291 this._consumeStartTag(this._advance());
10292 }
10293 else if (this._peek.type === TokenType.TAG_CLOSE) {
10294 this._consumeEndTag(this._advance());
10295 }
10296 else if (this._peek.type === TokenType.CDATA_START) {
10297 this._closeVoidElement();
10298 this._consumeCdata(this._advance());
10299 }
10300 else if (this._peek.type === TokenType.COMMENT_START) {
10301 this._closeVoidElement();
10302 this._consumeComment(this._advance());
10303 }
10304 else if (this._peek.type === TokenType.TEXT || this._peek.type === TokenType.RAW_TEXT ||
10305 this._peek.type === TokenType.ESCAPABLE_RAW_TEXT) {
10306 this._closeVoidElement();
10307 this._consumeText(this._advance());
10308 }
10309 else if (this._peek.type === TokenType.EXPANSION_FORM_START) {
10310 this._consumeExpansion(this._advance());
10311 }
10312 else {
10313 // Skip all other tokens...
10314 this._advance();
10315 }
10316 }
10317 return new ParseTreeResult(this._rootNodes, this._errors);
10318 };
10319 _TreeBuilder.prototype._advance = function () {
10320 var prev = this._peek;
10321 if (this._index < this.tokens.length - 1) {
10322 // Note: there is always an EOF token at the end
10323 this._index++;
10324 }
10325 this._peek = this.tokens[this._index];
10326 return prev;
10327 };
10328 _TreeBuilder.prototype._advanceIf = function (type) {
10329 if (this._peek.type === type) {
10330 return this._advance();
10331 }
10332 return null;
10333 };
10334 _TreeBuilder.prototype._consumeCdata = function (startToken) {
10335 this._consumeText(this._advance());
10336 this._advanceIf(TokenType.CDATA_END);
10337 };
10338 _TreeBuilder.prototype._consumeComment = function (token) {
10339 var text = this._advanceIf(TokenType.RAW_TEXT);
10340 this._advanceIf(TokenType.COMMENT_END);
10341 var value = text != null ? text.parts[0].trim() : null;
10342 this._addToParent(new Comment(value, token.sourceSpan));
10343 };
10344 _TreeBuilder.prototype._consumeExpansion = function (token) {
10345 var switchValue = this._advance();
10346 var type = this._advance();
10347 var cases = [];
10348 // read =
10349 while (this._peek.type === TokenType.EXPANSION_CASE_VALUE) {
10350 var expCase = this._parseExpansionCase();
10351 if (!expCase)
10352 return; // error
10353 cases.push(expCase);
10354 }
10355 // read the final }
10356 if (this._peek.type !== TokenType.EXPANSION_FORM_END) {
10357 this._errors.push(TreeError.create(null, this._peek.sourceSpan, "Invalid ICU message. Missing '}'."));
10358 return;
10359 }
10360 var sourceSpan = new ParseSourceSpan(token.sourceSpan.start, this._peek.sourceSpan.end);
10361 this._addToParent(new Expansion(switchValue.parts[0], type.parts[0], cases, sourceSpan, switchValue.sourceSpan));
10362 this._advance();
10363 };
10364 _TreeBuilder.prototype._parseExpansionCase = function () {
10365 var value = this._advance();
10366 // read {
10367 if (this._peek.type !== TokenType.EXPANSION_CASE_EXP_START) {
10368 this._errors.push(TreeError.create(null, this._peek.sourceSpan, "Invalid ICU message. Missing '{'."));
10369 return null;
10370 }
10371 // read until }
10372 var start = this._advance();
10373 var exp = this._collectExpansionExpTokens(start);
10374 if (!exp)
10375 return null;
10376 var end = this._advance();
10377 exp.push(new Token(TokenType.EOF, [], end.sourceSpan));
10378 // parse everything in between { and }
10379 var parsedExp = new _TreeBuilder(exp, this.getTagDefinition).build();
10380 if (parsedExp.errors.length > 0) {
10381 this._errors = this._errors.concat(parsedExp.errors);
10382 return null;
10383 }
10384 var sourceSpan = new ParseSourceSpan(value.sourceSpan.start, end.sourceSpan.end);
10385 var expSourceSpan = new ParseSourceSpan(start.sourceSpan.start, end.sourceSpan.end);
10386 return new ExpansionCase(value.parts[0], parsedExp.rootNodes, sourceSpan, value.sourceSpan, expSourceSpan);
10387 };
10388 _TreeBuilder.prototype._collectExpansionExpTokens = function (start) {
10389 var exp = [];
10390 var expansionFormStack = [TokenType.EXPANSION_CASE_EXP_START];
10391 while (true) {
10392 if (this._peek.type === TokenType.EXPANSION_FORM_START ||
10393 this._peek.type === TokenType.EXPANSION_CASE_EXP_START) {
10394 expansionFormStack.push(this._peek.type);
10395 }
10396 if (this._peek.type === TokenType.EXPANSION_CASE_EXP_END) {
10397 if (lastOnStack(expansionFormStack, TokenType.EXPANSION_CASE_EXP_START)) {
10398 expansionFormStack.pop();
10399 if (expansionFormStack.length == 0)
10400 return exp;
10401 }
10402 else {
10403 this._errors.push(TreeError.create(null, start.sourceSpan, "Invalid ICU message. Missing '}'."));
10404 return null;
10405 }
10406 }
10407 if (this._peek.type === TokenType.EXPANSION_FORM_END) {
10408 if (lastOnStack(expansionFormStack, TokenType.EXPANSION_FORM_START)) {
10409 expansionFormStack.pop();
10410 }
10411 else {
10412 this._errors.push(TreeError.create(null, start.sourceSpan, "Invalid ICU message. Missing '}'."));
10413 return null;
10414 }
10415 }
10416 if (this._peek.type === TokenType.EOF) {
10417 this._errors.push(TreeError.create(null, start.sourceSpan, "Invalid ICU message. Missing '}'."));
10418 return null;
10419 }
10420 exp.push(this._advance());
10421 }
10422 };
10423 _TreeBuilder.prototype._consumeText = function (token) {
10424 var text = token.parts[0];
10425 if (text.length > 0 && text[0] == '\n') {
10426 var parent_1 = this._getParentElement();
10427 if (parent_1 != null && parent_1.children.length == 0 &&
10428 this.getTagDefinition(parent_1.name).ignoreFirstLf) {
10429 text = text.substring(1);
10430 }
10431 }
10432 if (text.length > 0) {
10433 this._addToParent(new Text$3(text, token.sourceSpan));
10434 }
10435 };
10436 _TreeBuilder.prototype._closeVoidElement = function () {
10437 var el = this._getParentElement();
10438 if (el && this.getTagDefinition(el.name).isVoid) {
10439 this._elementStack.pop();
10440 }
10441 };
10442 _TreeBuilder.prototype._consumeStartTag = function (startTagToken) {
10443 var prefix = startTagToken.parts[0];
10444 var name = startTagToken.parts[1];
10445 var attrs = [];
10446 while (this._peek.type === TokenType.ATTR_NAME) {
10447 attrs.push(this._consumeAttr(this._advance()));
10448 }
10449 var fullName = this._getElementFullName(prefix, name, this._getParentElement());
10450 var selfClosing = false;
10451 // Note: There could have been a tokenizer error
10452 // so that we don't get a token for the end tag...
10453 if (this._peek.type === TokenType.TAG_OPEN_END_VOID) {
10454 this._advance();
10455 selfClosing = true;
10456 var tagDef = this.getTagDefinition(fullName);
10457 if (!(tagDef.canSelfClose || getNsPrefix(fullName) !== null || tagDef.isVoid)) {
10458 this._errors.push(TreeError.create(fullName, startTagToken.sourceSpan, "Only void and foreign elements can be self closed \"" + startTagToken.parts[1] + "\""));
10459 }
10460 }
10461 else if (this._peek.type === TokenType.TAG_OPEN_END) {
10462 this._advance();
10463 selfClosing = false;
10464 }
10465 var end = this._peek.sourceSpan.start;
10466 var span = new ParseSourceSpan(startTagToken.sourceSpan.start, end);
10467 var el = new Element$1(fullName, attrs, [], span, span, undefined);
10468 this._pushElement(el);
10469 if (selfClosing) {
10470 this._popElement(fullName);
10471 el.endSourceSpan = span;
10472 }
10473 };
10474 _TreeBuilder.prototype._pushElement = function (el) {
10475 var parentEl = this._getParentElement();
10476 if (parentEl && this.getTagDefinition(parentEl.name).isClosedByChild(el.name)) {
10477 this._elementStack.pop();
10478 }
10479 this._addToParent(el);
10480 this._elementStack.push(el);
10481 };
10482 _TreeBuilder.prototype._consumeEndTag = function (endTagToken) {
10483 var fullName = this._getElementFullName(endTagToken.parts[0], endTagToken.parts[1], this._getParentElement());
10484 if (this._getParentElement()) {
10485 this._getParentElement().endSourceSpan = endTagToken.sourceSpan;
10486 }
10487 if (this.getTagDefinition(fullName).isVoid) {
10488 this._errors.push(TreeError.create(fullName, endTagToken.sourceSpan, "Void elements do not have end tags \"" + endTagToken.parts[1] + "\""));
10489 }
10490 else if (!this._popElement(fullName)) {
10491 var errMsg = "Unexpected closing tag \"" + fullName + "\". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags";
10492 this._errors.push(TreeError.create(fullName, endTagToken.sourceSpan, errMsg));
10493 }
10494 };
10495 _TreeBuilder.prototype._popElement = function (fullName) {
10496 for (var stackIndex = this._elementStack.length - 1; stackIndex >= 0; stackIndex--) {
10497 var el = this._elementStack[stackIndex];
10498 if (el.name == fullName) {
10499 this._elementStack.splice(stackIndex, this._elementStack.length - stackIndex);
10500 return true;
10501 }
10502 if (!this.getTagDefinition(el.name).closedByParent) {
10503 return false;
10504 }
10505 }
10506 return false;
10507 };
10508 _TreeBuilder.prototype._consumeAttr = function (attrName) {
10509 var fullName = mergeNsAndName(attrName.parts[0], attrName.parts[1]);
10510 var end = attrName.sourceSpan.end;
10511 var value = '';
10512 var valueSpan = undefined;
10513 if (this._peek.type === TokenType.ATTR_QUOTE) {
10514 this._advance();
10515 }
10516 if (this._peek.type === TokenType.ATTR_VALUE) {
10517 var valueToken = this._advance();
10518 value = valueToken.parts[0];
10519 end = valueToken.sourceSpan.end;
10520 valueSpan = valueToken.sourceSpan;
10521 }
10522 if (this._peek.type === TokenType.ATTR_QUOTE) {
10523 var quoteToken = this._advance();
10524 end = quoteToken.sourceSpan.end;
10525 }
10526 return new Attribute(fullName, value, new ParseSourceSpan(attrName.sourceSpan.start, end), valueSpan);
10527 };
10528 _TreeBuilder.prototype._getParentElement = function () {
10529 return this._elementStack.length > 0 ? this._elementStack[this._elementStack.length - 1] : null;
10530 };
10531 /**
10532 * Returns the parent in the DOM and the container.
10533 *
10534 * `<ng-container>` elements are skipped as they are not rendered as DOM element.
10535 */
10536 _TreeBuilder.prototype._getParentElementSkippingContainers = function () {
10537 var container = null;
10538 for (var i = this._elementStack.length - 1; i >= 0; i--) {
10539 if (!isNgContainer(this._elementStack[i].name)) {
10540 return { parent: this._elementStack[i], container: container };
10541 }
10542 container = this._elementStack[i];
10543 }
10544 return { parent: null, container: container };
10545 };
10546 _TreeBuilder.prototype._addToParent = function (node) {
10547 var parent = this._getParentElement();
10548 if (parent != null) {
10549 parent.children.push(node);
10550 }
10551 else {
10552 this._rootNodes.push(node);
10553 }
10554 };
10555 /**
10556 * Insert a node between the parent and the container.
10557 * When no container is given, the node is appended as a child of the parent.
10558 * Also updates the element stack accordingly.
10559 *
10560 * @internal
10561 */
10562 _TreeBuilder.prototype._insertBeforeContainer = function (parent, container, node) {
10563 if (!container) {
10564 this._addToParent(node);
10565 this._elementStack.push(node);
10566 }
10567 else {
10568 if (parent) {
10569 // replace the container with the new node in the children
10570 var index = parent.children.indexOf(container);
10571 parent.children[index] = node;
10572 }
10573 else {
10574 this._rootNodes.push(node);
10575 }
10576 node.children.push(container);
10577 this._elementStack.splice(this._elementStack.indexOf(container), 0, node);
10578 }
10579 };
10580 _TreeBuilder.prototype._getElementFullName = function (prefix, localName, parentElement) {
10581 if (prefix === '') {
10582 prefix = this.getTagDefinition(localName).implicitNamespacePrefix || '';
10583 if (prefix === '' && parentElement != null) {
10584 prefix = getNsPrefix(parentElement.name);
10585 }
10586 }
10587 return mergeNsAndName(prefix, localName);
10588 };
10589 return _TreeBuilder;
10590}());
10591function lastOnStack(stack, element) {
10592 return stack.length > 0 && stack[stack.length - 1] === element;
10593}
10594
10595/**
10596 * @license
10597 * Copyright Google Inc. All Rights Reserved.
10598 *
10599 * Use of this source code is governed by an MIT-style license that can be
10600 * found in the LICENSE file at https://angular.io/license
10601 */
10602var HtmlParser = /** @class */ (function (_super) {
10603 __extends(HtmlParser, _super);
10604 function HtmlParser() {
10605 return _super.call(this, getHtmlTagDefinition) || this;
10606 }
10607 HtmlParser.prototype.parse = function (source, url, options) {
10608 return _super.prototype.parse.call(this, source, url, options);
10609 };
10610 return HtmlParser;
10611}(Parser));
10612
10613/**
10614 * @license
10615 * Copyright Google Inc. All Rights Reserved.
10616 *
10617 * Use of this source code is governed by an MIT-style license that can be
10618 * found in the LICENSE file at https://angular.io/license
10619 */
10620var PRESERVE_WS_ATTR_NAME = 'ngPreserveWhitespaces';
10621var SKIP_WS_TRIM_TAGS = new Set(['pre', 'template', 'textarea', 'script', 'style']);
10622// Equivalent to \s with \u00a0 (non-breaking space) excluded.
10623// Based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
10624var WS_CHARS = ' \f\n\r\t\v\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff';
10625var NO_WS_REGEXP = new RegExp("[^" + WS_CHARS + "]");
10626var WS_REPLACE_REGEXP = new RegExp("[" + WS_CHARS + "]{2,}", 'g');
10627function hasPreserveWhitespacesAttr(attrs) {
10628 return attrs.some(function (attr) { return attr.name === PRESERVE_WS_ATTR_NAME; });
10629}
10630/**
10631 * Angular Dart introduced &ngsp; as a placeholder for non-removable space, see:
10632 * https://github.com/dart-lang/angular/blob/0bb611387d29d65b5af7f9d2515ab571fd3fbee4/_tests/test/compiler/preserve_whitespace_test.dart#L25-L32
10633 * In Angular Dart &ngsp; is converted to the 0xE500 PUA (Private Use Areas) unicode character
10634 * and later on replaced by a space. We are re-implementing the same idea here.
10635 */
10636function replaceNgsp(value) {
10637 // lexer is replacing the &ngsp; pseudo-entity with NGSP_UNICODE
10638 return value.replace(new RegExp(NGSP_UNICODE, 'g'), ' ');
10639}
10640/**
10641 * This visitor can walk HTML parse tree and remove / trim text nodes using the following rules:
10642 * - consider spaces, tabs and new lines as whitespace characters;
10643 * - drop text nodes consisting of whitespace characters only;
10644 * - for all other text nodes replace consecutive whitespace characters with one space;
10645 * - convert &ngsp; pseudo-entity to a single space;
10646 *
10647 * Removal and trimming of whitespaces have positive performance impact (less code to generate
10648 * while compiling templates, faster view creation). At the same time it can be "destructive"
10649 * in some cases (whitespaces can influence layout). Because of the potential of breaking layout
10650 * this visitor is not activated by default in Angular 5 and people need to explicitly opt-in for
10651 * whitespace removal. The default option for whitespace removal will be revisited in Angular 6
10652 * and might be changed to "on" by default.
10653 */
10654var WhitespaceVisitor = /** @class */ (function () {
10655 function WhitespaceVisitor() {
10656 }
10657 WhitespaceVisitor.prototype.visitElement = function (element, context) {
10658 if (SKIP_WS_TRIM_TAGS.has(element.name) || hasPreserveWhitespacesAttr(element.attrs)) {
10659 // don't descent into elements where we need to preserve whitespaces
10660 // but still visit all attributes to eliminate one used as a market to preserve WS
10661 return new Element$1(element.name, visitAll$1(this, element.attrs), element.children, element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
10662 }
10663 return new Element$1(element.name, element.attrs, visitAll$1(this, element.children), element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
10664 };
10665 WhitespaceVisitor.prototype.visitAttribute = function (attribute, context) {
10666 return attribute.name !== PRESERVE_WS_ATTR_NAME ? attribute : null;
10667 };
10668 WhitespaceVisitor.prototype.visitText = function (text, context) {
10669 var isNotBlank = text.value.match(NO_WS_REGEXP);
10670 if (isNotBlank) {
10671 return new Text$3(replaceNgsp(text.value).replace(WS_REPLACE_REGEXP, ' '), text.sourceSpan, text.i18n);
10672 }
10673 return null;
10674 };
10675 WhitespaceVisitor.prototype.visitComment = function (comment, context) { return comment; };
10676 WhitespaceVisitor.prototype.visitExpansion = function (expansion, context) { return expansion; };
10677 WhitespaceVisitor.prototype.visitExpansionCase = function (expansionCase, context) { return expansionCase; };
10678 return WhitespaceVisitor;
10679}());
10680function removeWhitespaces(htmlAstWithErrors) {
10681 return new ParseTreeResult(visitAll$1(new WhitespaceVisitor(), htmlAstWithErrors.rootNodes), htmlAstWithErrors.errors);
10682}
10683
10684/**
10685 * @license
10686 * Copyright Google Inc. All Rights Reserved.
10687 *
10688 * Use of this source code is governed by an MIT-style license that can be
10689 * found in the LICENSE file at https://angular.io/license
10690 */
10691// http://cldr.unicode.org/index/cldr-spec/plural-rules
10692var PLURAL_CASES = ['zero', 'one', 'two', 'few', 'many', 'other'];
10693/**
10694 * Expands special forms into elements.
10695 *
10696 * For example,
10697 *
10698 * ```
10699 * { messages.length, plural,
10700 * =0 {zero}
10701 * =1 {one}
10702 * other {more than one}
10703 * }
10704 * ```
10705 *
10706 * will be expanded into
10707 *
10708 * ```
10709 * <ng-container [ngPlural]="messages.length">
10710 * <ng-template ngPluralCase="=0">zero</ng-template>
10711 * <ng-template ngPluralCase="=1">one</ng-template>
10712 * <ng-template ngPluralCase="other">more than one</ng-template>
10713 * </ng-container>
10714 * ```
10715 */
10716function expandNodes(nodes) {
10717 var expander = new _Expander();
10718 return new ExpansionResult(visitAll$1(expander, nodes), expander.isExpanded, expander.errors);
10719}
10720var ExpansionResult = /** @class */ (function () {
10721 function ExpansionResult(nodes, expanded, errors) {
10722 this.nodes = nodes;
10723 this.expanded = expanded;
10724 this.errors = errors;
10725 }
10726 return ExpansionResult;
10727}());
10728var ExpansionError = /** @class */ (function (_super) {
10729 __extends(ExpansionError, _super);
10730 function ExpansionError(span, errorMsg) {
10731 return _super.call(this, span, errorMsg) || this;
10732 }
10733 return ExpansionError;
10734}(ParseError));
10735/**
10736 * Expand expansion forms (plural, select) to directives
10737 *
10738 * @internal
10739 */
10740var _Expander = /** @class */ (function () {
10741 function _Expander() {
10742 this.isExpanded = false;
10743 this.errors = [];
10744 }
10745 _Expander.prototype.visitElement = function (element, context) {
10746 return new Element$1(element.name, element.attrs, visitAll$1(this, element.children), element.sourceSpan, element.startSourceSpan, element.endSourceSpan);
10747 };
10748 _Expander.prototype.visitAttribute = function (attribute, context) { return attribute; };
10749 _Expander.prototype.visitText = function (text, context) { return text; };
10750 _Expander.prototype.visitComment = function (comment, context) { return comment; };
10751 _Expander.prototype.visitExpansion = function (icu, context) {
10752 this.isExpanded = true;
10753 return icu.type == 'plural' ? _expandPluralForm(icu, this.errors) :
10754 _expandDefaultForm(icu, this.errors);
10755 };
10756 _Expander.prototype.visitExpansionCase = function (icuCase, context) {
10757 throw new Error('Should not be reached');
10758 };
10759 return _Expander;
10760}());
10761// Plural forms are expanded to `NgPlural` and `NgPluralCase`s
10762function _expandPluralForm(ast, errors) {
10763 var children = ast.cases.map(function (c) {
10764 if (PLURAL_CASES.indexOf(c.value) == -1 && !c.value.match(/^=\d+$/)) {
10765 errors.push(new ExpansionError(c.valueSourceSpan, "Plural cases should be \"=<number>\" or one of " + PLURAL_CASES.join(", ")));
10766 }
10767 var expansionResult = expandNodes(c.expression);
10768 errors.push.apply(errors, __spread(expansionResult.errors));
10769 return new Element$1("ng-template", [new Attribute('ngPluralCase', "" + c.value, c.valueSourceSpan)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan);
10770 });
10771 var switchAttr = new Attribute('[ngPlural]', ast.switchValue, ast.switchValueSourceSpan);
10772 return new Element$1('ng-container', [switchAttr], children, ast.sourceSpan, ast.sourceSpan, ast.sourceSpan);
10773}
10774// ICU messages (excluding plural form) are expanded to `NgSwitch` and `NgSwitchCase`s
10775function _expandDefaultForm(ast, errors) {
10776 var children = ast.cases.map(function (c) {
10777 var expansionResult = expandNodes(c.expression);
10778 errors.push.apply(errors, __spread(expansionResult.errors));
10779 if (c.value === 'other') {
10780 // other is the default case when no values match
10781 return new Element$1("ng-template", [new Attribute('ngSwitchDefault', '', c.valueSourceSpan)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan);
10782 }
10783 return new Element$1("ng-template", [new Attribute('ngSwitchCase', "" + c.value, c.valueSourceSpan)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan);
10784 });
10785 var switchAttr = new Attribute('[ngSwitch]', ast.switchValue, ast.switchValueSourceSpan);
10786 return new Element$1('ng-container', [switchAttr], children, ast.sourceSpan, ast.sourceSpan, ast.sourceSpan);
10787}
10788
10789/**
10790 * @license
10791 * Copyright Google Inc. All Rights Reserved.
10792 *
10793 * Use of this source code is governed by an MIT-style license that can be
10794 * found in the LICENSE file at https://angular.io/license
10795 */
10796var _a;
10797/**
10798 * A segment of text within the template.
10799 */
10800var TextAst = /** @class */ (function () {
10801 function TextAst(value, ngContentIndex, sourceSpan) {
10802 this.value = value;
10803 this.ngContentIndex = ngContentIndex;
10804 this.sourceSpan = sourceSpan;
10805 }
10806 TextAst.prototype.visit = function (visitor, context) { return visitor.visitText(this, context); };
10807 return TextAst;
10808}());
10809/**
10810 * A bound expression within the text of a template.
10811 */
10812var BoundTextAst = /** @class */ (function () {
10813 function BoundTextAst(value, ngContentIndex, sourceSpan) {
10814 this.value = value;
10815 this.ngContentIndex = ngContentIndex;
10816 this.sourceSpan = sourceSpan;
10817 }
10818 BoundTextAst.prototype.visit = function (visitor, context) {
10819 return visitor.visitBoundText(this, context);
10820 };
10821 return BoundTextAst;
10822}());
10823/**
10824 * A plain attribute on an element.
10825 */
10826var AttrAst = /** @class */ (function () {
10827 function AttrAst(name, value, sourceSpan) {
10828 this.name = name;
10829 this.value = value;
10830 this.sourceSpan = sourceSpan;
10831 }
10832 AttrAst.prototype.visit = function (visitor, context) { return visitor.visitAttr(this, context); };
10833 return AttrAst;
10834}());
10835var BoundPropertyMapping = (_a = {},
10836 _a[4 /* Animation */] = 4 /* Animation */,
10837 _a[1 /* Attribute */] = 1 /* Attribute */,
10838 _a[2 /* Class */] = 2 /* Class */,
10839 _a[0 /* Property */] = 0 /* Property */,
10840 _a[3 /* Style */] = 3 /* Style */,
10841 _a);
10842/**
10843 * A binding for an element property (e.g. `[property]="expression"`) or an animation trigger (e.g.
10844 * `[@trigger]="stateExp"`)
10845 */
10846var BoundElementPropertyAst = /** @class */ (function () {
10847 function BoundElementPropertyAst(name, type, securityContext, value, unit, sourceSpan) {
10848 this.name = name;
10849 this.type = type;
10850 this.securityContext = securityContext;
10851 this.value = value;
10852 this.unit = unit;
10853 this.sourceSpan = sourceSpan;
10854 this.isAnimation = this.type === 4 /* Animation */;
10855 }
10856 BoundElementPropertyAst.fromBoundProperty = function (prop) {
10857 var type = BoundPropertyMapping[prop.type];
10858 return new BoundElementPropertyAst(prop.name, type, prop.securityContext, prop.value, prop.unit, prop.sourceSpan);
10859 };
10860 BoundElementPropertyAst.prototype.visit = function (visitor, context) {
10861 return visitor.visitElementProperty(this, context);
10862 };
10863 return BoundElementPropertyAst;
10864}());
10865/**
10866 * A binding for an element event (e.g. `(event)="handler()"`) or an animation trigger event (e.g.
10867 * `(@trigger.phase)="callback($event)"`).
10868 */
10869var BoundEventAst = /** @class */ (function () {
10870 function BoundEventAst(name, target, phase, handler, sourceSpan, handlerSpan) {
10871 this.name = name;
10872 this.target = target;
10873 this.phase = phase;
10874 this.handler = handler;
10875 this.sourceSpan = sourceSpan;
10876 this.handlerSpan = handlerSpan;
10877 this.fullName = BoundEventAst.calcFullName(this.name, this.target, this.phase);
10878 this.isAnimation = !!this.phase;
10879 }
10880 BoundEventAst.calcFullName = function (name, target, phase) {
10881 if (target) {
10882 return target + ":" + name;
10883 }
10884 if (phase) {
10885 return "@" + name + "." + phase;
10886 }
10887 return name;
10888 };
10889 BoundEventAst.fromParsedEvent = function (event) {
10890 var target = event.type === 0 /* Regular */ ? event.targetOrPhase : null;
10891 var phase = event.type === 1 /* Animation */ ? event.targetOrPhase : null;
10892 return new BoundEventAst(event.name, target, phase, event.handler, event.sourceSpan, event.handlerSpan);
10893 };
10894 BoundEventAst.prototype.visit = function (visitor, context) {
10895 return visitor.visitEvent(this, context);
10896 };
10897 return BoundEventAst;
10898}());
10899/**
10900 * A reference declaration on an element (e.g. `let someName="expression"`).
10901 */
10902var ReferenceAst = /** @class */ (function () {
10903 function ReferenceAst(name, value, originalValue, sourceSpan) {
10904 this.name = name;
10905 this.value = value;
10906 this.originalValue = originalValue;
10907 this.sourceSpan = sourceSpan;
10908 }
10909 ReferenceAst.prototype.visit = function (visitor, context) {
10910 return visitor.visitReference(this, context);
10911 };
10912 return ReferenceAst;
10913}());
10914/**
10915 * A variable declaration on a <ng-template> (e.g. `var-someName="someLocalName"`).
10916 */
10917var VariableAst = /** @class */ (function () {
10918 function VariableAst(name, value, sourceSpan) {
10919 this.name = name;
10920 this.value = value;
10921 this.sourceSpan = sourceSpan;
10922 }
10923 VariableAst.fromParsedVariable = function (v) {
10924 return new VariableAst(v.name, v.value, v.sourceSpan);
10925 };
10926 VariableAst.prototype.visit = function (visitor, context) {
10927 return visitor.visitVariable(this, context);
10928 };
10929 return VariableAst;
10930}());
10931/**
10932 * An element declaration in a template.
10933 */
10934var ElementAst = /** @class */ (function () {
10935 function ElementAst(name, attrs, inputs, outputs, references, directives, providers, hasViewContainer, queryMatches, children, ngContentIndex, sourceSpan, endSourceSpan) {
10936 this.name = name;
10937 this.attrs = attrs;
10938 this.inputs = inputs;
10939 this.outputs = outputs;
10940 this.references = references;
10941 this.directives = directives;
10942 this.providers = providers;
10943 this.hasViewContainer = hasViewContainer;
10944 this.queryMatches = queryMatches;
10945 this.children = children;
10946 this.ngContentIndex = ngContentIndex;
10947 this.sourceSpan = sourceSpan;
10948 this.endSourceSpan = endSourceSpan;
10949 }
10950 ElementAst.prototype.visit = function (visitor, context) {
10951 return visitor.visitElement(this, context);
10952 };
10953 return ElementAst;
10954}());
10955/**
10956 * A `<ng-template>` element included in an Angular template.
10957 */
10958var EmbeddedTemplateAst = /** @class */ (function () {
10959 function EmbeddedTemplateAst(attrs, outputs, references, variables, directives, providers, hasViewContainer, queryMatches, children, ngContentIndex, sourceSpan) {
10960 this.attrs = attrs;
10961 this.outputs = outputs;
10962 this.references = references;
10963 this.variables = variables;
10964 this.directives = directives;
10965 this.providers = providers;
10966 this.hasViewContainer = hasViewContainer;
10967 this.queryMatches = queryMatches;
10968 this.children = children;
10969 this.ngContentIndex = ngContentIndex;
10970 this.sourceSpan = sourceSpan;
10971 }
10972 EmbeddedTemplateAst.prototype.visit = function (visitor, context) {
10973 return visitor.visitEmbeddedTemplate(this, context);
10974 };
10975 return EmbeddedTemplateAst;
10976}());
10977/**
10978 * A directive property with a bound value (e.g. `*ngIf="condition").
10979 */
10980var BoundDirectivePropertyAst = /** @class */ (function () {
10981 function BoundDirectivePropertyAst(directiveName, templateName, value, sourceSpan) {
10982 this.directiveName = directiveName;
10983 this.templateName = templateName;
10984 this.value = value;
10985 this.sourceSpan = sourceSpan;
10986 }
10987 BoundDirectivePropertyAst.prototype.visit = function (visitor, context) {
10988 return visitor.visitDirectiveProperty(this, context);
10989 };
10990 return BoundDirectivePropertyAst;
10991}());
10992/**
10993 * A directive declared on an element.
10994 */
10995var DirectiveAst = /** @class */ (function () {
10996 function DirectiveAst(directive, inputs, hostProperties, hostEvents, contentQueryStartId, sourceSpan) {
10997 this.directive = directive;
10998 this.inputs = inputs;
10999 this.hostProperties = hostProperties;
11000 this.hostEvents = hostEvents;
11001 this.contentQueryStartId = contentQueryStartId;
11002 this.sourceSpan = sourceSpan;
11003 }
11004 DirectiveAst.prototype.visit = function (visitor, context) {
11005 return visitor.visitDirective(this, context);
11006 };
11007 return DirectiveAst;
11008}());
11009/**
11010 * A provider declared on an element
11011 */
11012var ProviderAst = /** @class */ (function () {
11013 function ProviderAst(token, multiProvider, eager, providers, providerType, lifecycleHooks, sourceSpan, isModule) {
11014 this.token = token;
11015 this.multiProvider = multiProvider;
11016 this.eager = eager;
11017 this.providers = providers;
11018 this.providerType = providerType;
11019 this.lifecycleHooks = lifecycleHooks;
11020 this.sourceSpan = sourceSpan;
11021 this.isModule = isModule;
11022 }
11023 ProviderAst.prototype.visit = function (visitor, context) {
11024 // No visit method in the visitor for now...
11025 return null;
11026 };
11027 return ProviderAst;
11028}());
11029var ProviderAstType;
11030(function (ProviderAstType) {
11031 ProviderAstType[ProviderAstType["PublicService"] = 0] = "PublicService";
11032 ProviderAstType[ProviderAstType["PrivateService"] = 1] = "PrivateService";
11033 ProviderAstType[ProviderAstType["Component"] = 2] = "Component";
11034 ProviderAstType[ProviderAstType["Directive"] = 3] = "Directive";
11035 ProviderAstType[ProviderAstType["Builtin"] = 4] = "Builtin";
11036})(ProviderAstType || (ProviderAstType = {}));
11037/**
11038 * Position where content is to be projected (instance of `<ng-content>` in a template).
11039 */
11040var NgContentAst = /** @class */ (function () {
11041 function NgContentAst(index, ngContentIndex, sourceSpan) {
11042 this.index = index;
11043 this.ngContentIndex = ngContentIndex;
11044 this.sourceSpan = sourceSpan;
11045 }
11046 NgContentAst.prototype.visit = function (visitor, context) {
11047 return visitor.visitNgContent(this, context);
11048 };
11049 return NgContentAst;
11050}());
11051/**
11052 * A visitor that accepts each node but doesn't do anything. It is intended to be used
11053 * as the base class for a visitor that is only interested in a subset of the node types.
11054 */
11055var NullTemplateVisitor = /** @class */ (function () {
11056 function NullTemplateVisitor() {
11057 }
11058 NullTemplateVisitor.prototype.visitNgContent = function (ast, context) { };
11059 NullTemplateVisitor.prototype.visitEmbeddedTemplate = function (ast, context) { };
11060 NullTemplateVisitor.prototype.visitElement = function (ast, context) { };
11061 NullTemplateVisitor.prototype.visitReference = function (ast, context) { };
11062 NullTemplateVisitor.prototype.visitVariable = function (ast, context) { };
11063 NullTemplateVisitor.prototype.visitEvent = function (ast, context) { };
11064 NullTemplateVisitor.prototype.visitElementProperty = function (ast, context) { };
11065 NullTemplateVisitor.prototype.visitAttr = function (ast, context) { };
11066 NullTemplateVisitor.prototype.visitBoundText = function (ast, context) { };
11067 NullTemplateVisitor.prototype.visitText = function (ast, context) { };
11068 NullTemplateVisitor.prototype.visitDirective = function (ast, context) { };
11069 NullTemplateVisitor.prototype.visitDirectiveProperty = function (ast, context) { };
11070 return NullTemplateVisitor;
11071}());
11072/**
11073 * Base class that can be used to build a visitor that visits each node
11074 * in an template ast recursively.
11075 */
11076var RecursiveTemplateAstVisitor = /** @class */ (function (_super) {
11077 __extends(RecursiveTemplateAstVisitor, _super);
11078 function RecursiveTemplateAstVisitor() {
11079 return _super.call(this) || this;
11080 }
11081 // Nodes with children
11082 RecursiveTemplateAstVisitor.prototype.visitEmbeddedTemplate = function (ast, context) {
11083 return this.visitChildren(context, function (visit) {
11084 visit(ast.attrs);
11085 visit(ast.references);
11086 visit(ast.variables);
11087 visit(ast.directives);
11088 visit(ast.providers);
11089 visit(ast.children);
11090 });
11091 };
11092 RecursiveTemplateAstVisitor.prototype.visitElement = function (ast, context) {
11093 return this.visitChildren(context, function (visit) {
11094 visit(ast.attrs);
11095 visit(ast.inputs);
11096 visit(ast.outputs);
11097 visit(ast.references);
11098 visit(ast.directives);
11099 visit(ast.providers);
11100 visit(ast.children);
11101 });
11102 };
11103 RecursiveTemplateAstVisitor.prototype.visitDirective = function (ast, context) {
11104 return this.visitChildren(context, function (visit) {
11105 visit(ast.inputs);
11106 visit(ast.hostProperties);
11107 visit(ast.hostEvents);
11108 });
11109 };
11110 RecursiveTemplateAstVisitor.prototype.visitChildren = function (context, cb) {
11111 var results = [];
11112 var t = this;
11113 function visit(children) {
11114 if (children && children.length)
11115 results.push(templateVisitAll(t, children, context));
11116 }
11117 cb(visit);
11118 return Array.prototype.concat.apply([], results);
11119 };
11120 return RecursiveTemplateAstVisitor;
11121}(NullTemplateVisitor));
11122/**
11123 * Visit every node in a list of {@link TemplateAst}s with the given {@link TemplateAstVisitor}.
11124 */
11125function templateVisitAll(visitor, asts, context) {
11126 if (context === void 0) { context = null; }
11127 var result = [];
11128 var visit = visitor.visit ?
11129 function (ast) { return visitor.visit(ast, context) || ast.visit(visitor, context); } :
11130 function (ast) { return ast.visit(visitor, context); };
11131 asts.forEach(function (ast) {
11132 var astResult = visit(ast);
11133 if (astResult) {
11134 result.push(astResult);
11135 }
11136 });
11137 return result;
11138}
11139
11140/**
11141 * @license
11142 * Copyright Google Inc. All Rights Reserved.
11143 *
11144 * Use of this source code is governed by an MIT-style license that can be
11145 * found in the LICENSE file at https://angular.io/license
11146 */
11147var ProviderError = /** @class */ (function (_super) {
11148 __extends(ProviderError, _super);
11149 function ProviderError(message, span) {
11150 return _super.call(this, span, message) || this;
11151 }
11152 return ProviderError;
11153}(ParseError));
11154var ProviderViewContext = /** @class */ (function () {
11155 function ProviderViewContext(reflector, component) {
11156 var _this = this;
11157 this.reflector = reflector;
11158 this.component = component;
11159 this.errors = [];
11160 this.viewQueries = _getViewQueries(component);
11161 this.viewProviders = new Map();
11162 component.viewProviders.forEach(function (provider) {
11163 if (_this.viewProviders.get(tokenReference(provider.token)) == null) {
11164 _this.viewProviders.set(tokenReference(provider.token), true);
11165 }
11166 });
11167 }
11168 return ProviderViewContext;
11169}());
11170var ProviderElementContext = /** @class */ (function () {
11171 function ProviderElementContext(viewContext, _parent, _isViewRoot, _directiveAsts, attrs, refs, isTemplate, contentQueryStartId, _sourceSpan) {
11172 var _this = this;
11173 this.viewContext = viewContext;
11174 this._parent = _parent;
11175 this._isViewRoot = _isViewRoot;
11176 this._directiveAsts = _directiveAsts;
11177 this._sourceSpan = _sourceSpan;
11178 this._transformedProviders = new Map();
11179 this._seenProviders = new Map();
11180 this._queriedTokens = new Map();
11181 this.transformedHasViewContainer = false;
11182 this._attrs = {};
11183 attrs.forEach(function (attrAst) { return _this._attrs[attrAst.name] = attrAst.value; });
11184 var directivesMeta = _directiveAsts.map(function (directiveAst) { return directiveAst.directive; });
11185 this._allProviders =
11186 _resolveProvidersFromDirectives(directivesMeta, _sourceSpan, viewContext.errors);
11187 this._contentQueries = _getContentQueries(contentQueryStartId, directivesMeta);
11188 Array.from(this._allProviders.values()).forEach(function (provider) {
11189 _this._addQueryReadsTo(provider.token, provider.token, _this._queriedTokens);
11190 });
11191 if (isTemplate) {
11192 var templateRefId = createTokenForExternalReference(this.viewContext.reflector, Identifiers.TemplateRef);
11193 this._addQueryReadsTo(templateRefId, templateRefId, this._queriedTokens);
11194 }
11195 refs.forEach(function (refAst) {
11196 var defaultQueryValue = refAst.value ||
11197 createTokenForExternalReference(_this.viewContext.reflector, Identifiers.ElementRef);
11198 _this._addQueryReadsTo({ value: refAst.name }, defaultQueryValue, _this._queriedTokens);
11199 });
11200 if (this._queriedTokens.get(this.viewContext.reflector.resolveExternalReference(Identifiers.ViewContainerRef))) {
11201 this.transformedHasViewContainer = true;
11202 }
11203 // create the providers that we know are eager first
11204 Array.from(this._allProviders.values()).forEach(function (provider) {
11205 var eager = provider.eager || _this._queriedTokens.get(tokenReference(provider.token));
11206 if (eager) {
11207 _this._getOrCreateLocalProvider(provider.providerType, provider.token, true);
11208 }
11209 });
11210 }
11211 ProviderElementContext.prototype.afterElement = function () {
11212 var _this = this;
11213 // collect lazy providers
11214 Array.from(this._allProviders.values()).forEach(function (provider) {
11215 _this._getOrCreateLocalProvider(provider.providerType, provider.token, false);
11216 });
11217 };
11218 Object.defineProperty(ProviderElementContext.prototype, "transformProviders", {
11219 get: function () {
11220 // Note: Maps keep their insertion order.
11221 var lazyProviders = [];
11222 var eagerProviders = [];
11223 this._transformedProviders.forEach(function (provider) {
11224 if (provider.eager) {
11225 eagerProviders.push(provider);
11226 }
11227 else {
11228 lazyProviders.push(provider);
11229 }
11230 });
11231 return lazyProviders.concat(eagerProviders);
11232 },
11233 enumerable: true,
11234 configurable: true
11235 });
11236 Object.defineProperty(ProviderElementContext.prototype, "transformedDirectiveAsts", {
11237 get: function () {
11238 var sortedProviderTypes = this.transformProviders.map(function (provider) { return provider.token.identifier; });
11239 var sortedDirectives = this._directiveAsts.slice();
11240 sortedDirectives.sort(function (dir1, dir2) { return sortedProviderTypes.indexOf(dir1.directive.type) -
11241 sortedProviderTypes.indexOf(dir2.directive.type); });
11242 return sortedDirectives;
11243 },
11244 enumerable: true,
11245 configurable: true
11246 });
11247 Object.defineProperty(ProviderElementContext.prototype, "queryMatches", {
11248 get: function () {
11249 var allMatches = [];
11250 this._queriedTokens.forEach(function (matches) { allMatches.push.apply(allMatches, __spread(matches)); });
11251 return allMatches;
11252 },
11253 enumerable: true,
11254 configurable: true
11255 });
11256 ProviderElementContext.prototype._addQueryReadsTo = function (token, defaultValue, queryReadTokens) {
11257 this._getQueriesFor(token).forEach(function (query) {
11258 var queryValue = query.meta.read || defaultValue;
11259 var tokenRef = tokenReference(queryValue);
11260 var queryMatches = queryReadTokens.get(tokenRef);
11261 if (!queryMatches) {
11262 queryMatches = [];
11263 queryReadTokens.set(tokenRef, queryMatches);
11264 }
11265 queryMatches.push({ queryId: query.queryId, value: queryValue });
11266 });
11267 };
11268 ProviderElementContext.prototype._getQueriesFor = function (token) {
11269 var result = [];
11270 var currentEl = this;
11271 var distance = 0;
11272 var queries;
11273 while (currentEl !== null) {
11274 queries = currentEl._contentQueries.get(tokenReference(token));
11275 if (queries) {
11276 result.push.apply(result, __spread(queries.filter(function (query) { return query.meta.descendants || distance <= 1; })));
11277 }
11278 if (currentEl._directiveAsts.length > 0) {
11279 distance++;
11280 }
11281 currentEl = currentEl._parent;
11282 }
11283 queries = this.viewContext.viewQueries.get(tokenReference(token));
11284 if (queries) {
11285 result.push.apply(result, __spread(queries));
11286 }
11287 return result;
11288 };
11289 ProviderElementContext.prototype._getOrCreateLocalProvider = function (requestingProviderType, token, eager) {
11290 var _this = this;
11291 var resolvedProvider = this._allProviders.get(tokenReference(token));
11292 if (!resolvedProvider || ((requestingProviderType === ProviderAstType.Directive ||
11293 requestingProviderType === ProviderAstType.PublicService) &&
11294 resolvedProvider.providerType === ProviderAstType.PrivateService) ||
11295 ((requestingProviderType === ProviderAstType.PrivateService ||
11296 requestingProviderType === ProviderAstType.PublicService) &&
11297 resolvedProvider.providerType === ProviderAstType.Builtin)) {
11298 return null;
11299 }
11300 var transformedProviderAst = this._transformedProviders.get(tokenReference(token));
11301 if (transformedProviderAst) {
11302 return transformedProviderAst;
11303 }
11304 if (this._seenProviders.get(tokenReference(token)) != null) {
11305 this.viewContext.errors.push(new ProviderError("Cannot instantiate cyclic dependency! " + tokenName(token), this._sourceSpan));
11306 return null;
11307 }
11308 this._seenProviders.set(tokenReference(token), true);
11309 var transformedProviders = resolvedProvider.providers.map(function (provider) {
11310 var transformedUseValue = provider.useValue;
11311 var transformedUseExisting = provider.useExisting;
11312 var transformedDeps = undefined;
11313 if (provider.useExisting != null) {
11314 var existingDiDep = _this._getDependency(resolvedProvider.providerType, { token: provider.useExisting }, eager);
11315 if (existingDiDep.token != null) {
11316 transformedUseExisting = existingDiDep.token;
11317 }
11318 else {
11319 transformedUseExisting = null;
11320 transformedUseValue = existingDiDep.value;
11321 }
11322 }
11323 else if (provider.useFactory) {
11324 var deps = provider.deps || provider.useFactory.diDeps;
11325 transformedDeps =
11326 deps.map(function (dep) { return _this._getDependency(resolvedProvider.providerType, dep, eager); });
11327 }
11328 else if (provider.useClass) {
11329 var deps = provider.deps || provider.useClass.diDeps;
11330 transformedDeps =
11331 deps.map(function (dep) { return _this._getDependency(resolvedProvider.providerType, dep, eager); });
11332 }
11333 return _transformProvider(provider, {
11334 useExisting: transformedUseExisting,
11335 useValue: transformedUseValue,
11336 deps: transformedDeps
11337 });
11338 });
11339 transformedProviderAst =
11340 _transformProviderAst(resolvedProvider, { eager: eager, providers: transformedProviders });
11341 this._transformedProviders.set(tokenReference(token), transformedProviderAst);
11342 return transformedProviderAst;
11343 };
11344 ProviderElementContext.prototype._getLocalDependency = function (requestingProviderType, dep, eager) {
11345 if (eager === void 0) { eager = false; }
11346 if (dep.isAttribute) {
11347 var attrValue = this._attrs[dep.token.value];
11348 return { isValue: true, value: attrValue == null ? null : attrValue };
11349 }
11350 if (dep.token != null) {
11351 // access builtints
11352 if ((requestingProviderType === ProviderAstType.Directive ||
11353 requestingProviderType === ProviderAstType.Component)) {
11354 if (tokenReference(dep.token) ===
11355 this.viewContext.reflector.resolveExternalReference(Identifiers.Renderer) ||
11356 tokenReference(dep.token) ===
11357 this.viewContext.reflector.resolveExternalReference(Identifiers.ElementRef) ||
11358 tokenReference(dep.token) ===
11359 this.viewContext.reflector.resolveExternalReference(Identifiers.ChangeDetectorRef) ||
11360 tokenReference(dep.token) ===
11361 this.viewContext.reflector.resolveExternalReference(Identifiers.TemplateRef)) {
11362 return dep;
11363 }
11364 if (tokenReference(dep.token) ===
11365 this.viewContext.reflector.resolveExternalReference(Identifiers.ViewContainerRef)) {
11366 this.transformedHasViewContainer = true;
11367 }
11368 }
11369 // access the injector
11370 if (tokenReference(dep.token) ===
11371 this.viewContext.reflector.resolveExternalReference(Identifiers.Injector)) {
11372 return dep;
11373 }
11374 // access providers
11375 if (this._getOrCreateLocalProvider(requestingProviderType, dep.token, eager) != null) {
11376 return dep;
11377 }
11378 }
11379 return null;
11380 };
11381 ProviderElementContext.prototype._getDependency = function (requestingProviderType, dep, eager) {
11382 if (eager === void 0) { eager = false; }
11383 var currElement = this;
11384 var currEager = eager;
11385 var result = null;
11386 if (!dep.isSkipSelf) {
11387 result = this._getLocalDependency(requestingProviderType, dep, eager);
11388 }
11389 if (dep.isSelf) {
11390 if (!result && dep.isOptional) {
11391 result = { isValue: true, value: null };
11392 }
11393 }
11394 else {
11395 // check parent elements
11396 while (!result && currElement._parent) {
11397 var prevElement = currElement;
11398 currElement = currElement._parent;
11399 if (prevElement._isViewRoot) {
11400 currEager = false;
11401 }
11402 result = currElement._getLocalDependency(ProviderAstType.PublicService, dep, currEager);
11403 }
11404 // check @Host restriction
11405 if (!result) {
11406 if (!dep.isHost || this.viewContext.component.isHost ||
11407 this.viewContext.component.type.reference === tokenReference(dep.token) ||
11408 this.viewContext.viewProviders.get(tokenReference(dep.token)) != null) {
11409 result = dep;
11410 }
11411 else {
11412 result = dep.isOptional ? { isValue: true, value: null } : null;
11413 }
11414 }
11415 }
11416 if (!result) {
11417 this.viewContext.errors.push(new ProviderError("No provider for " + tokenName(dep.token), this._sourceSpan));
11418 }
11419 return result;
11420 };
11421 return ProviderElementContext;
11422}());
11423var NgModuleProviderAnalyzer = /** @class */ (function () {
11424 function NgModuleProviderAnalyzer(reflector, ngModule, extraProviders, sourceSpan) {
11425 var _this = this;
11426 this.reflector = reflector;
11427 this._transformedProviders = new Map();
11428 this._seenProviders = new Map();
11429 this._errors = [];
11430 this._allProviders = new Map();
11431 ngModule.transitiveModule.modules.forEach(function (ngModuleType) {
11432 var ngModuleProvider = { token: { identifier: ngModuleType }, useClass: ngModuleType };
11433 _resolveProviders([ngModuleProvider], ProviderAstType.PublicService, true, sourceSpan, _this._errors, _this._allProviders, /* isModule */ true);
11434 });
11435 _resolveProviders(ngModule.transitiveModule.providers.map(function (entry) { return entry.provider; }).concat(extraProviders), ProviderAstType.PublicService, false, sourceSpan, this._errors, this._allProviders,
11436 /* isModule */ false);
11437 }
11438 NgModuleProviderAnalyzer.prototype.parse = function () {
11439 var _this = this;
11440 Array.from(this._allProviders.values()).forEach(function (provider) {
11441 _this._getOrCreateLocalProvider(provider.token, provider.eager);
11442 });
11443 if (this._errors.length > 0) {
11444 var errorString = this._errors.join('\n');
11445 throw new Error("Provider parse errors:\n" + errorString);
11446 }
11447 // Note: Maps keep their insertion order.
11448 var lazyProviders = [];
11449 var eagerProviders = [];
11450 this._transformedProviders.forEach(function (provider) {
11451 if (provider.eager) {
11452 eagerProviders.push(provider);
11453 }
11454 else {
11455 lazyProviders.push(provider);
11456 }
11457 });
11458 return lazyProviders.concat(eagerProviders);
11459 };
11460 NgModuleProviderAnalyzer.prototype._getOrCreateLocalProvider = function (token, eager) {
11461 var _this = this;
11462 var resolvedProvider = this._allProviders.get(tokenReference(token));
11463 if (!resolvedProvider) {
11464 return null;
11465 }
11466 var transformedProviderAst = this._transformedProviders.get(tokenReference(token));
11467 if (transformedProviderAst) {
11468 return transformedProviderAst;
11469 }
11470 if (this._seenProviders.get(tokenReference(token)) != null) {
11471 this._errors.push(new ProviderError("Cannot instantiate cyclic dependency! " + tokenName(token), resolvedProvider.sourceSpan));
11472 return null;
11473 }
11474 this._seenProviders.set(tokenReference(token), true);
11475 var transformedProviders = resolvedProvider.providers.map(function (provider) {
11476 var transformedUseValue = provider.useValue;
11477 var transformedUseExisting = provider.useExisting;
11478 var transformedDeps = undefined;
11479 if (provider.useExisting != null) {
11480 var existingDiDep = _this._getDependency({ token: provider.useExisting }, eager, resolvedProvider.sourceSpan);
11481 if (existingDiDep.token != null) {
11482 transformedUseExisting = existingDiDep.token;
11483 }
11484 else {
11485 transformedUseExisting = null;
11486 transformedUseValue = existingDiDep.value;
11487 }
11488 }
11489 else if (provider.useFactory) {
11490 var deps = provider.deps || provider.useFactory.diDeps;
11491 transformedDeps =
11492 deps.map(function (dep) { return _this._getDependency(dep, eager, resolvedProvider.sourceSpan); });
11493 }
11494 else if (provider.useClass) {
11495 var deps = provider.deps || provider.useClass.diDeps;
11496 transformedDeps =
11497 deps.map(function (dep) { return _this._getDependency(dep, eager, resolvedProvider.sourceSpan); });
11498 }
11499 return _transformProvider(provider, {
11500 useExisting: transformedUseExisting,
11501 useValue: transformedUseValue,
11502 deps: transformedDeps
11503 });
11504 });
11505 transformedProviderAst =
11506 _transformProviderAst(resolvedProvider, { eager: eager, providers: transformedProviders });
11507 this._transformedProviders.set(tokenReference(token), transformedProviderAst);
11508 return transformedProviderAst;
11509 };
11510 NgModuleProviderAnalyzer.prototype._getDependency = function (dep, eager, requestorSourceSpan) {
11511 if (eager === void 0) { eager = false; }
11512 var foundLocal = false;
11513 if (!dep.isSkipSelf && dep.token != null) {
11514 // access the injector
11515 if (tokenReference(dep.token) ===
11516 this.reflector.resolveExternalReference(Identifiers.Injector) ||
11517 tokenReference(dep.token) ===
11518 this.reflector.resolveExternalReference(Identifiers.ComponentFactoryResolver)) {
11519 foundLocal = true;
11520 // access providers
11521 }
11522 else if (this._getOrCreateLocalProvider(dep.token, eager) != null) {
11523 foundLocal = true;
11524 }
11525 }
11526 return dep;
11527 };
11528 return NgModuleProviderAnalyzer;
11529}());
11530function _transformProvider(provider, _a) {
11531 var useExisting = _a.useExisting, useValue = _a.useValue, deps = _a.deps;
11532 return {
11533 token: provider.token,
11534 useClass: provider.useClass,
11535 useExisting: useExisting,
11536 useFactory: provider.useFactory,
11537 useValue: useValue,
11538 deps: deps,
11539 multi: provider.multi
11540 };
11541}
11542function _transformProviderAst(provider, _a) {
11543 var eager = _a.eager, providers = _a.providers;
11544 return new ProviderAst(provider.token, provider.multiProvider, provider.eager || eager, providers, provider.providerType, provider.lifecycleHooks, provider.sourceSpan, provider.isModule);
11545}
11546function _resolveProvidersFromDirectives(directives, sourceSpan, targetErrors) {
11547 var providersByToken = new Map();
11548 directives.forEach(function (directive) {
11549 var dirProvider = { token: { identifier: directive.type }, useClass: directive.type };
11550 _resolveProviders([dirProvider], directive.isComponent ? ProviderAstType.Component : ProviderAstType.Directive, true, sourceSpan, targetErrors, providersByToken, /* isModule */ false);
11551 });
11552 // Note: directives need to be able to overwrite providers of a component!
11553 var directivesWithComponentFirst = directives.filter(function (dir) { return dir.isComponent; }).concat(directives.filter(function (dir) { return !dir.isComponent; }));
11554 directivesWithComponentFirst.forEach(function (directive) {
11555 _resolveProviders(directive.providers, ProviderAstType.PublicService, false, sourceSpan, targetErrors, providersByToken, /* isModule */ false);
11556 _resolveProviders(directive.viewProviders, ProviderAstType.PrivateService, false, sourceSpan, targetErrors, providersByToken, /* isModule */ false);
11557 });
11558 return providersByToken;
11559}
11560function _resolveProviders(providers, providerType, eager, sourceSpan, targetErrors, targetProvidersByToken, isModule) {
11561 providers.forEach(function (provider) {
11562 var resolvedProvider = targetProvidersByToken.get(tokenReference(provider.token));
11563 if (resolvedProvider != null && !!resolvedProvider.multiProvider !== !!provider.multi) {
11564 targetErrors.push(new ProviderError("Mixing multi and non multi provider is not possible for token " + tokenName(resolvedProvider.token), sourceSpan));
11565 }
11566 if (!resolvedProvider) {
11567 var lifecycleHooks = provider.token.identifier &&
11568 provider.token.identifier.lifecycleHooks ?
11569 provider.token.identifier.lifecycleHooks :
11570 [];
11571 var isUseValue = !(provider.useClass || provider.useExisting || provider.useFactory);
11572 resolvedProvider = new ProviderAst(provider.token, !!provider.multi, eager || isUseValue, [provider], providerType, lifecycleHooks, sourceSpan, isModule);
11573 targetProvidersByToken.set(tokenReference(provider.token), resolvedProvider);
11574 }
11575 else {
11576 if (!provider.multi) {
11577 resolvedProvider.providers.length = 0;
11578 }
11579 resolvedProvider.providers.push(provider);
11580 }
11581 });
11582}
11583function _getViewQueries(component) {
11584 // Note: queries start with id 1 so we can use the number in a Bloom filter!
11585 var viewQueryId = 1;
11586 var viewQueries = new Map();
11587 if (component.viewQueries) {
11588 component.viewQueries.forEach(function (query) { return _addQueryToTokenMap(viewQueries, { meta: query, queryId: viewQueryId++ }); });
11589 }
11590 return viewQueries;
11591}
11592function _getContentQueries(contentQueryStartId, directives) {
11593 var contentQueryId = contentQueryStartId;
11594 var contentQueries = new Map();
11595 directives.forEach(function (directive, directiveIndex) {
11596 if (directive.queries) {
11597 directive.queries.forEach(function (query) { return _addQueryToTokenMap(contentQueries, { meta: query, queryId: contentQueryId++ }); });
11598 }
11599 });
11600 return contentQueries;
11601}
11602function _addQueryToTokenMap(map, query) {
11603 query.meta.selectors.forEach(function (token) {
11604 var entry = map.get(tokenReference(token));
11605 if (!entry) {
11606 entry = [];
11607 map.set(tokenReference(token), entry);
11608 }
11609 entry.push(query);
11610 });
11611}
11612
11613/**
11614 * @license
11615 * Copyright Google Inc. All Rights Reserved.
11616 *
11617 * Use of this source code is governed by an MIT-style license that can be
11618 * found in the LICENSE file at https://angular.io/license
11619 */
11620var StyleWithImports = /** @class */ (function () {
11621 function StyleWithImports(style, styleUrls) {
11622 this.style = style;
11623 this.styleUrls = styleUrls;
11624 }
11625 return StyleWithImports;
11626}());
11627function isStyleUrlResolvable(url) {
11628 if (url == null || url.length === 0 || url[0] == '/')
11629 return false;
11630 var schemeMatch = url.match(URL_WITH_SCHEMA_REGEXP);
11631 return schemeMatch === null || schemeMatch[1] == 'package' || schemeMatch[1] == 'asset';
11632}
11633/**
11634 * Rewrites stylesheets by resolving and removing the @import urls that
11635 * are either relative or don't have a `package:` scheme
11636 */
11637function extractStyleUrls(resolver, baseUrl, cssText) {
11638 var foundUrls = [];
11639 var modifiedCssText = cssText.replace(CSS_STRIPPABLE_COMMENT_REGEXP, '')
11640 .replace(CSS_IMPORT_REGEXP, function () {
11641 var m = [];
11642 for (var _i = 0; _i < arguments.length; _i++) {
11643 m[_i] = arguments[_i];
11644 }
11645 var url = m[1] || m[2];
11646 if (!isStyleUrlResolvable(url)) {
11647 // Do not attempt to resolve non-package absolute URLs with URI
11648 // scheme
11649 return m[0];
11650 }
11651 foundUrls.push(resolver.resolve(baseUrl, url));
11652 return '';
11653 });
11654 return new StyleWithImports(modifiedCssText, foundUrls);
11655}
11656var CSS_IMPORT_REGEXP = /@import\s+(?:url\()?\s*(?:(?:['"]([^'"]*))|([^;\)\s]*))[^;]*;?/g;
11657var CSS_STRIPPABLE_COMMENT_REGEXP = /\/\*(?!#\s*(?:sourceURL|sourceMappingURL)=)[\s\S]+?\*\//g;
11658var URL_WITH_SCHEMA_REGEXP = /^([^:/?#]+):/;
11659
11660/**
11661 * @license
11662 * Copyright Google Inc. All Rights Reserved.
11663 *
11664 * Use of this source code is governed by an MIT-style license that can be
11665 * found in the LICENSE file at https://angular.io/license
11666 */
11667var PROPERTY_PARTS_SEPARATOR = '.';
11668var ATTRIBUTE_PREFIX = 'attr';
11669var CLASS_PREFIX = 'class';
11670var STYLE_PREFIX = 'style';
11671var ANIMATE_PROP_PREFIX = 'animate-';
11672/**
11673 * Parses bindings in templates and in the directive host area.
11674 */
11675var BindingParser = /** @class */ (function () {
11676 function BindingParser(_exprParser, _interpolationConfig, _schemaRegistry, pipes, errors) {
11677 this._exprParser = _exprParser;
11678 this._interpolationConfig = _interpolationConfig;
11679 this._schemaRegistry = _schemaRegistry;
11680 this.errors = errors;
11681 this.pipesByName = null;
11682 this._usedPipes = new Map();
11683 // When the `pipes` parameter is `null`, do not check for used pipes
11684 // This is used in IVY when we might not know the available pipes at compile time
11685 if (pipes) {
11686 var pipesByName_1 = new Map();
11687 pipes.forEach(function (pipe) { return pipesByName_1.set(pipe.name, pipe); });
11688 this.pipesByName = pipesByName_1;
11689 }
11690 }
11691 Object.defineProperty(BindingParser.prototype, "interpolationConfig", {
11692 get: function () { return this._interpolationConfig; },
11693 enumerable: true,
11694 configurable: true
11695 });
11696 BindingParser.prototype.getUsedPipes = function () { return Array.from(this._usedPipes.values()); };
11697 BindingParser.prototype.createBoundHostProperties = function (dirMeta, sourceSpan) {
11698 var _this = this;
11699 if (dirMeta.hostProperties) {
11700 var boundProps_1 = [];
11701 Object.keys(dirMeta.hostProperties).forEach(function (propName) {
11702 var expression = dirMeta.hostProperties[propName];
11703 if (typeof expression === 'string') {
11704 _this.parsePropertyBinding(propName, expression, true, sourceSpan, sourceSpan.start.offset, undefined, [], boundProps_1);
11705 }
11706 else {
11707 _this._reportError("Value of the host property binding \"" + propName + "\" needs to be a string representing an expression but got \"" + expression + "\" (" + typeof expression + ")", sourceSpan);
11708 }
11709 });
11710 return boundProps_1;
11711 }
11712 return null;
11713 };
11714 BindingParser.prototype.createDirectiveHostPropertyAsts = function (dirMeta, elementSelector, sourceSpan) {
11715 var _this = this;
11716 var boundProps = this.createBoundHostProperties(dirMeta, sourceSpan);
11717 return boundProps &&
11718 boundProps.map(function (prop) { return _this.createBoundElementProperty(elementSelector, prop); });
11719 };
11720 BindingParser.prototype.createDirectiveHostEventAsts = function (dirMeta, sourceSpan) {
11721 var _this = this;
11722 if (dirMeta.hostListeners) {
11723 var targetEvents_1 = [];
11724 Object.keys(dirMeta.hostListeners).forEach(function (propName) {
11725 var expression = dirMeta.hostListeners[propName];
11726 if (typeof expression === 'string') {
11727 // TODO: pass a more accurate handlerSpan for this event.
11728 _this.parseEvent(propName, expression, sourceSpan, sourceSpan, [], targetEvents_1);
11729 }
11730 else {
11731 _this._reportError("Value of the host listener \"" + propName + "\" needs to be a string representing an expression but got \"" + expression + "\" (" + typeof expression + ")", sourceSpan);
11732 }
11733 });
11734 return targetEvents_1;
11735 }
11736 return null;
11737 };
11738 BindingParser.prototype.parseInterpolation = function (value, sourceSpan) {
11739 var sourceInfo = sourceSpan.start.toString();
11740 try {
11741 var ast = this._exprParser.parseInterpolation(value, sourceInfo, sourceSpan.start.offset, this._interpolationConfig);
11742 if (ast)
11743 this._reportExpressionParserErrors(ast.errors, sourceSpan);
11744 this._checkPipes(ast, sourceSpan);
11745 return ast;
11746 }
11747 catch (e) {
11748 this._reportError("" + e, sourceSpan);
11749 return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo, sourceSpan.start.offset);
11750 }
11751 };
11752 // Parse an inline template binding. ie `<tag *tplKey="<tplValue>">`
11753 BindingParser.prototype.parseInlineTemplateBinding = function (tplKey, tplValue, sourceSpan, absoluteOffset, targetMatchableAttrs, targetProps, targetVars) {
11754 var bindings = this._parseTemplateBindings(tplKey, tplValue, sourceSpan);
11755 for (var i = 0; i < bindings.length; i++) {
11756 var binding = bindings[i];
11757 if (binding.keyIsVar) {
11758 targetVars.push(new ParsedVariable(binding.key, binding.name, sourceSpan));
11759 }
11760 else if (binding.expression) {
11761 this._parsePropertyAst(binding.key, binding.expression, sourceSpan, undefined, targetMatchableAttrs, targetProps);
11762 }
11763 else {
11764 targetMatchableAttrs.push([binding.key, '']);
11765 this.parseLiteralAttr(binding.key, null, sourceSpan, absoluteOffset, undefined, targetMatchableAttrs, targetProps);
11766 }
11767 }
11768 };
11769 BindingParser.prototype._parseTemplateBindings = function (tplKey, tplValue, sourceSpan) {
11770 var _this = this;
11771 var sourceInfo = sourceSpan.start.toString();
11772 try {
11773 var bindingsResult = this._exprParser.parseTemplateBindings(tplKey, tplValue, sourceInfo, sourceSpan.start.offset);
11774 this._reportExpressionParserErrors(bindingsResult.errors, sourceSpan);
11775 bindingsResult.templateBindings.forEach(function (binding) {
11776 if (binding.expression) {
11777 _this._checkPipes(binding.expression, sourceSpan);
11778 }
11779 });
11780 bindingsResult.warnings.forEach(function (warning) { _this._reportError(warning, sourceSpan, ParseErrorLevel.WARNING); });
11781 return bindingsResult.templateBindings;
11782 }
11783 catch (e) {
11784 this._reportError("" + e, sourceSpan);
11785 return [];
11786 }
11787 };
11788 BindingParser.prototype.parseLiteralAttr = function (name, value, sourceSpan, absoluteOffset, valueSpan, targetMatchableAttrs, targetProps) {
11789 if (isAnimationLabel(name)) {
11790 name = name.substring(1);
11791 if (value) {
11792 this._reportError("Assigning animation triggers via @prop=\"exp\" attributes with an expression is invalid." +
11793 " Use property bindings (e.g. [@prop]=\"exp\") or use an attribute without a value (e.g. @prop) instead.", sourceSpan, ParseErrorLevel.ERROR);
11794 }
11795 this._parseAnimation(name, value, sourceSpan, absoluteOffset, valueSpan, targetMatchableAttrs, targetProps);
11796 }
11797 else {
11798 targetProps.push(new ParsedProperty(name, this._exprParser.wrapLiteralPrimitive(value, '', absoluteOffset), ParsedPropertyType.LITERAL_ATTR, sourceSpan, valueSpan));
11799 }
11800 };
11801 BindingParser.prototype.parsePropertyBinding = function (name, expression, isHost, sourceSpan, absoluteOffset, valueSpan, targetMatchableAttrs, targetProps) {
11802 var isAnimationProp = false;
11803 if (name.startsWith(ANIMATE_PROP_PREFIX)) {
11804 isAnimationProp = true;
11805 name = name.substring(ANIMATE_PROP_PREFIX.length);
11806 }
11807 else if (isAnimationLabel(name)) {
11808 isAnimationProp = true;
11809 name = name.substring(1);
11810 }
11811 if (isAnimationProp) {
11812 this._parseAnimation(name, expression, sourceSpan, absoluteOffset, valueSpan, targetMatchableAttrs, targetProps);
11813 }
11814 else {
11815 this._parsePropertyAst(name, this._parseBinding(expression, isHost, valueSpan || sourceSpan, absoluteOffset), sourceSpan, valueSpan, targetMatchableAttrs, targetProps);
11816 }
11817 };
11818 BindingParser.prototype.parsePropertyInterpolation = function (name, value, sourceSpan, valueSpan, targetMatchableAttrs, targetProps) {
11819 var expr = this.parseInterpolation(value, valueSpan || sourceSpan);
11820 if (expr) {
11821 this._parsePropertyAst(name, expr, sourceSpan, valueSpan, targetMatchableAttrs, targetProps);
11822 return true;
11823 }
11824 return false;
11825 };
11826 BindingParser.prototype._parsePropertyAst = function (name, ast, sourceSpan, valueSpan, targetMatchableAttrs, targetProps) {
11827 targetMatchableAttrs.push([name, ast.source]);
11828 targetProps.push(new ParsedProperty(name, ast, ParsedPropertyType.DEFAULT, sourceSpan, valueSpan));
11829 };
11830 BindingParser.prototype._parseAnimation = function (name, expression, sourceSpan, absoluteOffset, valueSpan, targetMatchableAttrs, targetProps) {
11831 // This will occur when a @trigger is not paired with an expression.
11832 // For animations it is valid to not have an expression since */void
11833 // states will be applied by angular when the element is attached/detached
11834 var ast = this._parseBinding(expression || 'undefined', false, valueSpan || sourceSpan, absoluteOffset);
11835 targetMatchableAttrs.push([name, ast.source]);
11836 targetProps.push(new ParsedProperty(name, ast, ParsedPropertyType.ANIMATION, sourceSpan, valueSpan));
11837 };
11838 BindingParser.prototype._parseBinding = function (value, isHostBinding, sourceSpan, absoluteOffset) {
11839 var sourceInfo = (sourceSpan && sourceSpan.start || '(unknown)').toString();
11840 try {
11841 var ast = isHostBinding ?
11842 this._exprParser.parseSimpleBinding(value, sourceInfo, absoluteOffset, this._interpolationConfig) :
11843 this._exprParser.parseBinding(value, sourceInfo, absoluteOffset, this._interpolationConfig);
11844 if (ast)
11845 this._reportExpressionParserErrors(ast.errors, sourceSpan);
11846 this._checkPipes(ast, sourceSpan);
11847 return ast;
11848 }
11849 catch (e) {
11850 this._reportError("" + e, sourceSpan);
11851 return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo, absoluteOffset);
11852 }
11853 };
11854 BindingParser.prototype.createBoundElementProperty = function (elementSelector, boundProp, skipValidation, mapPropertyName) {
11855 if (skipValidation === void 0) { skipValidation = false; }
11856 if (mapPropertyName === void 0) { mapPropertyName = true; }
11857 if (boundProp.isAnimation) {
11858 return new BoundElementProperty(boundProp.name, 4 /* Animation */, SecurityContext.NONE, boundProp.expression, null, boundProp.sourceSpan, boundProp.valueSpan);
11859 }
11860 var unit = null;
11861 var bindingType = undefined;
11862 var boundPropertyName = null;
11863 var parts = boundProp.name.split(PROPERTY_PARTS_SEPARATOR);
11864 var securityContexts = undefined;
11865 // Check for special cases (prefix style, attr, class)
11866 if (parts.length > 1) {
11867 if (parts[0] == ATTRIBUTE_PREFIX) {
11868 boundPropertyName = parts[1];
11869 if (!skipValidation) {
11870 this._validatePropertyOrAttributeName(boundPropertyName, boundProp.sourceSpan, true);
11871 }
11872 securityContexts = calcPossibleSecurityContexts(this._schemaRegistry, elementSelector, boundPropertyName, true);
11873 var nsSeparatorIdx = boundPropertyName.indexOf(':');
11874 if (nsSeparatorIdx > -1) {
11875 var ns = boundPropertyName.substring(0, nsSeparatorIdx);
11876 var name_1 = boundPropertyName.substring(nsSeparatorIdx + 1);
11877 boundPropertyName = mergeNsAndName(ns, name_1);
11878 }
11879 bindingType = 1 /* Attribute */;
11880 }
11881 else if (parts[0] == CLASS_PREFIX) {
11882 boundPropertyName = parts[1];
11883 bindingType = 2 /* Class */;
11884 securityContexts = [SecurityContext.NONE];
11885 }
11886 else if (parts[0] == STYLE_PREFIX) {
11887 unit = parts.length > 2 ? parts[2] : null;
11888 boundPropertyName = parts[1];
11889 bindingType = 3 /* Style */;
11890 securityContexts = [SecurityContext.STYLE];
11891 }
11892 }
11893 // If not a special case, use the full property name
11894 if (boundPropertyName === null) {
11895 var mappedPropName = this._schemaRegistry.getMappedPropName(boundProp.name);
11896 boundPropertyName = mapPropertyName ? mappedPropName : boundProp.name;
11897 securityContexts = calcPossibleSecurityContexts(this._schemaRegistry, elementSelector, mappedPropName, false);
11898 bindingType = 0 /* Property */;
11899 if (!skipValidation) {
11900 this._validatePropertyOrAttributeName(mappedPropName, boundProp.sourceSpan, false);
11901 }
11902 }
11903 return new BoundElementProperty(boundPropertyName, bindingType, securityContexts[0], boundProp.expression, unit, boundProp.sourceSpan, boundProp.valueSpan);
11904 };
11905 BindingParser.prototype.parseEvent = function (name, expression, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents) {
11906 if (isAnimationLabel(name)) {
11907 name = name.substr(1);
11908 this._parseAnimationEvent(name, expression, sourceSpan, handlerSpan, targetEvents);
11909 }
11910 else {
11911 this._parseRegularEvent(name, expression, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents);
11912 }
11913 };
11914 BindingParser.prototype.calcPossibleSecurityContexts = function (selector, propName, isAttribute) {
11915 var prop = this._schemaRegistry.getMappedPropName(propName);
11916 return calcPossibleSecurityContexts(this._schemaRegistry, selector, prop, isAttribute);
11917 };
11918 BindingParser.prototype._parseAnimationEvent = function (name, expression, sourceSpan, handlerSpan, targetEvents) {
11919 var matches = splitAtPeriod(name, [name, '']);
11920 var eventName = matches[0];
11921 var phase = matches[1].toLowerCase();
11922 if (phase) {
11923 switch (phase) {
11924 case 'start':
11925 case 'done':
11926 var ast = this._parseAction(expression, handlerSpan);
11927 targetEvents.push(new ParsedEvent(eventName, phase, 1 /* Animation */, ast, sourceSpan, handlerSpan));
11928 break;
11929 default:
11930 this._reportError("The provided animation output phase value \"" + phase + "\" for \"@" + eventName + "\" is not supported (use start or done)", sourceSpan);
11931 break;
11932 }
11933 }
11934 else {
11935 this._reportError("The animation trigger output event (@" + eventName + ") is missing its phase value name (start or done are currently supported)", sourceSpan);
11936 }
11937 };
11938 BindingParser.prototype._parseRegularEvent = function (name, expression, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents) {
11939 // long format: 'target: eventName'
11940 var _a = __read(splitAtColon(name, [null, name]), 2), target = _a[0], eventName = _a[1];
11941 var ast = this._parseAction(expression, handlerSpan);
11942 targetMatchableAttrs.push([name, ast.source]);
11943 targetEvents.push(new ParsedEvent(eventName, target, 0 /* Regular */, ast, sourceSpan, handlerSpan));
11944 // Don't detect directives for event names for now,
11945 // so don't add the event name to the matchableAttrs
11946 };
11947 BindingParser.prototype._parseAction = function (value, sourceSpan) {
11948 var sourceInfo = (sourceSpan && sourceSpan.start || '(unknown').toString();
11949 var absoluteOffset = (sourceSpan && sourceSpan.start) ? sourceSpan.start.offset : 0;
11950 try {
11951 var ast = this._exprParser.parseAction(value, sourceInfo, absoluteOffset, this._interpolationConfig);
11952 if (ast) {
11953 this._reportExpressionParserErrors(ast.errors, sourceSpan);
11954 }
11955 if (!ast || ast.ast instanceof EmptyExpr) {
11956 this._reportError("Empty expressions are not allowed", sourceSpan);
11957 return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo, absoluteOffset);
11958 }
11959 this._checkPipes(ast, sourceSpan);
11960 return ast;
11961 }
11962 catch (e) {
11963 this._reportError("" + e, sourceSpan);
11964 return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo, absoluteOffset);
11965 }
11966 };
11967 BindingParser.prototype._reportError = function (message, sourceSpan, level) {
11968 if (level === void 0) { level = ParseErrorLevel.ERROR; }
11969 this.errors.push(new ParseError(sourceSpan, message, level));
11970 };
11971 BindingParser.prototype._reportExpressionParserErrors = function (errors, sourceSpan) {
11972 var e_1, _a;
11973 try {
11974 for (var errors_1 = __values(errors), errors_1_1 = errors_1.next(); !errors_1_1.done; errors_1_1 = errors_1.next()) {
11975 var error = errors_1_1.value;
11976 this._reportError(error.message, sourceSpan);
11977 }
11978 }
11979 catch (e_1_1) { e_1 = { error: e_1_1 }; }
11980 finally {
11981 try {
11982 if (errors_1_1 && !errors_1_1.done && (_a = errors_1.return)) _a.call(errors_1);
11983 }
11984 finally { if (e_1) throw e_1.error; }
11985 }
11986 };
11987 // Make sure all the used pipes are known in `this.pipesByName`
11988 BindingParser.prototype._checkPipes = function (ast, sourceSpan) {
11989 var _this = this;
11990 if (ast && this.pipesByName) {
11991 var collector = new PipeCollector();
11992 ast.visit(collector);
11993 collector.pipes.forEach(function (ast, pipeName) {
11994 var pipeMeta = _this.pipesByName.get(pipeName);
11995 if (!pipeMeta) {
11996 _this._reportError("The pipe '" + pipeName + "' could not be found", new ParseSourceSpan(sourceSpan.start.moveBy(ast.span.start), sourceSpan.start.moveBy(ast.span.end)));
11997 }
11998 else {
11999 _this._usedPipes.set(pipeName, pipeMeta);
12000 }
12001 });
12002 }
12003 };
12004 /**
12005 * @param propName the name of the property / attribute
12006 * @param sourceSpan
12007 * @param isAttr true when binding to an attribute
12008 */
12009 BindingParser.prototype._validatePropertyOrAttributeName = function (propName, sourceSpan, isAttr) {
12010 var report = isAttr ? this._schemaRegistry.validateAttribute(propName) :
12011 this._schemaRegistry.validateProperty(propName);
12012 if (report.error) {
12013 this._reportError(report.msg, sourceSpan, ParseErrorLevel.ERROR);
12014 }
12015 };
12016 return BindingParser;
12017}());
12018var PipeCollector = /** @class */ (function (_super) {
12019 __extends(PipeCollector, _super);
12020 function PipeCollector() {
12021 var _this = _super !== null && _super.apply(this, arguments) || this;
12022 _this.pipes = new Map();
12023 return _this;
12024 }
12025 PipeCollector.prototype.visitPipe = function (ast, context) {
12026 this.pipes.set(ast.name, ast);
12027 ast.exp.visit(this);
12028 this.visitAll(ast.args, context);
12029 return null;
12030 };
12031 return PipeCollector;
12032}(RecursiveAstVisitor$1));
12033function isAnimationLabel(name) {
12034 return name[0] == '@';
12035}
12036function calcPossibleSecurityContexts(registry, selector, propName, isAttribute) {
12037 var ctxs = [];
12038 CssSelector.parse(selector).forEach(function (selector) {
12039 var elementNames = selector.element ? [selector.element] : registry.allKnownElementNames();
12040 var notElementNames = new Set(selector.notSelectors.filter(function (selector) { return selector.isElementSelector(); })
12041 .map(function (selector) { return selector.element; }));
12042 var possibleElementNames = elementNames.filter(function (elementName) { return !notElementNames.has(elementName); });
12043 ctxs.push.apply(ctxs, __spread(possibleElementNames.map(function (elementName) { return registry.securityContext(elementName, propName, isAttribute); })));
12044 });
12045 return ctxs.length === 0 ? [SecurityContext.NONE] : Array.from(new Set(ctxs)).sort();
12046}
12047
12048/**
12049 * @license
12050 * Copyright Google Inc. 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 */
12055var NG_CONTENT_SELECT_ATTR = 'select';
12056var LINK_ELEMENT = 'link';
12057var LINK_STYLE_REL_ATTR = 'rel';
12058var LINK_STYLE_HREF_ATTR = 'href';
12059var LINK_STYLE_REL_VALUE = 'stylesheet';
12060var STYLE_ELEMENT = 'style';
12061var SCRIPT_ELEMENT = 'script';
12062var NG_NON_BINDABLE_ATTR = 'ngNonBindable';
12063var NG_PROJECT_AS = 'ngProjectAs';
12064function preparseElement(ast) {
12065 var selectAttr = null;
12066 var hrefAttr = null;
12067 var relAttr = null;
12068 var nonBindable = false;
12069 var projectAs = '';
12070 ast.attrs.forEach(function (attr) {
12071 var lcAttrName = attr.name.toLowerCase();
12072 if (lcAttrName == NG_CONTENT_SELECT_ATTR) {
12073 selectAttr = attr.value;
12074 }
12075 else if (lcAttrName == LINK_STYLE_HREF_ATTR) {
12076 hrefAttr = attr.value;
12077 }
12078 else if (lcAttrName == LINK_STYLE_REL_ATTR) {
12079 relAttr = attr.value;
12080 }
12081 else if (attr.name == NG_NON_BINDABLE_ATTR) {
12082 nonBindable = true;
12083 }
12084 else if (attr.name == NG_PROJECT_AS) {
12085 if (attr.value.length > 0) {
12086 projectAs = attr.value;
12087 }
12088 }
12089 });
12090 selectAttr = normalizeNgContentSelect(selectAttr);
12091 var nodeName = ast.name.toLowerCase();
12092 var type = PreparsedElementType.OTHER;
12093 if (isNgContent(nodeName)) {
12094 type = PreparsedElementType.NG_CONTENT;
12095 }
12096 else if (nodeName == STYLE_ELEMENT) {
12097 type = PreparsedElementType.STYLE;
12098 }
12099 else if (nodeName == SCRIPT_ELEMENT) {
12100 type = PreparsedElementType.SCRIPT;
12101 }
12102 else if (nodeName == LINK_ELEMENT && relAttr == LINK_STYLE_REL_VALUE) {
12103 type = PreparsedElementType.STYLESHEET;
12104 }
12105 return new PreparsedElement(type, selectAttr, hrefAttr, nonBindable, projectAs);
12106}
12107var PreparsedElementType;
12108(function (PreparsedElementType) {
12109 PreparsedElementType[PreparsedElementType["NG_CONTENT"] = 0] = "NG_CONTENT";
12110 PreparsedElementType[PreparsedElementType["STYLE"] = 1] = "STYLE";
12111 PreparsedElementType[PreparsedElementType["STYLESHEET"] = 2] = "STYLESHEET";
12112 PreparsedElementType[PreparsedElementType["SCRIPT"] = 3] = "SCRIPT";
12113 PreparsedElementType[PreparsedElementType["OTHER"] = 4] = "OTHER";
12114})(PreparsedElementType || (PreparsedElementType = {}));
12115var PreparsedElement = /** @class */ (function () {
12116 function PreparsedElement(type, selectAttr, hrefAttr, nonBindable, projectAs) {
12117 this.type = type;
12118 this.selectAttr = selectAttr;
12119 this.hrefAttr = hrefAttr;
12120 this.nonBindable = nonBindable;
12121 this.projectAs = projectAs;
12122 }
12123 return PreparsedElement;
12124}());
12125function normalizeNgContentSelect(selectAttr) {
12126 if (selectAttr === null || selectAttr.length === 0) {
12127 return '*';
12128 }
12129 return selectAttr;
12130}
12131
12132/**
12133 * @license
12134 * Copyright Google Inc. All Rights Reserved.
12135 *
12136 * Use of this source code is governed by an MIT-style license that can be
12137 * found in the LICENSE file at https://angular.io/license
12138 */
12139var BIND_NAME_REGEXP = /^(?:(?:(?:(bind-)|(let-)|(ref-|#)|(on-)|(bindon-)|(@))(.+))|\[\(([^\)]+)\)\]|\[([^\]]+)\]|\(([^\)]+)\))$/;
12140// Group 1 = "bind-"
12141var KW_BIND_IDX = 1;
12142// Group 2 = "let-"
12143var KW_LET_IDX = 2;
12144// Group 3 = "ref-/#"
12145var KW_REF_IDX = 3;
12146// Group 4 = "on-"
12147var KW_ON_IDX = 4;
12148// Group 5 = "bindon-"
12149var KW_BINDON_IDX = 5;
12150// Group 6 = "@"
12151var KW_AT_IDX = 6;
12152// Group 7 = the identifier after "bind-", "let-", "ref-/#", "on-", "bindon-" or "@"
12153var IDENT_KW_IDX = 7;
12154// Group 8 = identifier inside [()]
12155var IDENT_BANANA_BOX_IDX = 8;
12156// Group 9 = identifier inside []
12157var IDENT_PROPERTY_IDX = 9;
12158// Group 10 = identifier inside ()
12159var IDENT_EVENT_IDX = 10;
12160var TEMPLATE_ATTR_PREFIX = '*';
12161var CLASS_ATTR = 'class';
12162var _TEXT_CSS_SELECTOR;
12163function TEXT_CSS_SELECTOR() {
12164 if (!_TEXT_CSS_SELECTOR) {
12165 _TEXT_CSS_SELECTOR = CssSelector.parse('*')[0];
12166 }
12167 return _TEXT_CSS_SELECTOR;
12168}
12169var TemplateParseError = /** @class */ (function (_super) {
12170 __extends(TemplateParseError, _super);
12171 function TemplateParseError(message, span, level) {
12172 return _super.call(this, span, message, level) || this;
12173 }
12174 return TemplateParseError;
12175}(ParseError));
12176var TemplateParseResult = /** @class */ (function () {
12177 function TemplateParseResult(templateAst, usedPipes, errors) {
12178 this.templateAst = templateAst;
12179 this.usedPipes = usedPipes;
12180 this.errors = errors;
12181 }
12182 return TemplateParseResult;
12183}());
12184var TemplateParser = /** @class */ (function () {
12185 function TemplateParser(_config, _reflector, _exprParser, _schemaRegistry, _htmlParser, _console, transforms) {
12186 this._config = _config;
12187 this._reflector = _reflector;
12188 this._exprParser = _exprParser;
12189 this._schemaRegistry = _schemaRegistry;
12190 this._htmlParser = _htmlParser;
12191 this._console = _console;
12192 this.transforms = transforms;
12193 }
12194 Object.defineProperty(TemplateParser.prototype, "expressionParser", {
12195 get: function () { return this._exprParser; },
12196 enumerable: true,
12197 configurable: true
12198 });
12199 TemplateParser.prototype.parse = function (component, template, directives, pipes, schemas, templateUrl, preserveWhitespaces) {
12200 var result = this.tryParse(component, template, directives, pipes, schemas, templateUrl, preserveWhitespaces);
12201 var warnings = result.errors.filter(function (error) { return error.level === ParseErrorLevel.WARNING; });
12202 var errors = result.errors.filter(function (error) { return error.level === ParseErrorLevel.ERROR; });
12203 if (warnings.length > 0) {
12204 this._console.warn("Template parse warnings:\n" + warnings.join('\n'));
12205 }
12206 if (errors.length > 0) {
12207 var errorString = errors.join('\n');
12208 throw syntaxError("Template parse errors:\n" + errorString, errors);
12209 }
12210 return { template: result.templateAst, pipes: result.usedPipes };
12211 };
12212 TemplateParser.prototype.tryParse = function (component, template, directives, pipes, schemas, templateUrl, preserveWhitespaces) {
12213 var htmlParseResult = typeof template === 'string' ?
12214 this._htmlParser.parse(template, templateUrl, {
12215 tokenizeExpansionForms: true,
12216 interpolationConfig: this.getInterpolationConfig(component)
12217 }) :
12218 template;
12219 if (!preserveWhitespaces) {
12220 htmlParseResult = removeWhitespaces(htmlParseResult);
12221 }
12222 return this.tryParseHtml(this.expandHtml(htmlParseResult), component, directives, pipes, schemas);
12223 };
12224 TemplateParser.prototype.tryParseHtml = function (htmlAstWithErrors, component, directives, pipes, schemas) {
12225 var result;
12226 var errors = htmlAstWithErrors.errors;
12227 var usedPipes = [];
12228 if (htmlAstWithErrors.rootNodes.length > 0) {
12229 var uniqDirectives = removeSummaryDuplicates(directives);
12230 var uniqPipes = removeSummaryDuplicates(pipes);
12231 var providerViewContext = new ProviderViewContext(this._reflector, component);
12232 var interpolationConfig = undefined;
12233 if (component.template && component.template.interpolation) {
12234 interpolationConfig = {
12235 start: component.template.interpolation[0],
12236 end: component.template.interpolation[1]
12237 };
12238 }
12239 var bindingParser = new BindingParser(this._exprParser, interpolationConfig, this._schemaRegistry, uniqPipes, errors);
12240 var parseVisitor = new TemplateParseVisitor(this._reflector, this._config, providerViewContext, uniqDirectives, bindingParser, this._schemaRegistry, schemas, errors);
12241 result = visitAll$1(parseVisitor, htmlAstWithErrors.rootNodes, EMPTY_ELEMENT_CONTEXT);
12242 errors.push.apply(errors, __spread(providerViewContext.errors));
12243 usedPipes.push.apply(usedPipes, __spread(bindingParser.getUsedPipes()));
12244 }
12245 else {
12246 result = [];
12247 }
12248 this._assertNoReferenceDuplicationOnTemplate(result, errors);
12249 if (errors.length > 0) {
12250 return new TemplateParseResult(result, usedPipes, errors);
12251 }
12252 if (this.transforms) {
12253 this.transforms.forEach(function (transform) { result = templateVisitAll(transform, result); });
12254 }
12255 return new TemplateParseResult(result, usedPipes, errors);
12256 };
12257 TemplateParser.prototype.expandHtml = function (htmlAstWithErrors, forced) {
12258 if (forced === void 0) { forced = false; }
12259 var errors = htmlAstWithErrors.errors;
12260 if (errors.length == 0 || forced) {
12261 // Transform ICU messages to angular directives
12262 var expandedHtmlAst = expandNodes(htmlAstWithErrors.rootNodes);
12263 errors.push.apply(errors, __spread(expandedHtmlAst.errors));
12264 htmlAstWithErrors = new ParseTreeResult(expandedHtmlAst.nodes, errors);
12265 }
12266 return htmlAstWithErrors;
12267 };
12268 TemplateParser.prototype.getInterpolationConfig = function (component) {
12269 if (component.template) {
12270 return InterpolationConfig.fromArray(component.template.interpolation);
12271 }
12272 return undefined;
12273 };
12274 /** @internal */
12275 TemplateParser.prototype._assertNoReferenceDuplicationOnTemplate = function (result, errors) {
12276 var existingReferences = [];
12277 result.filter(function (element) { return !!element.references; })
12278 .forEach(function (element) { return element.references.forEach(function (reference) {
12279 var name = reference.name;
12280 if (existingReferences.indexOf(name) < 0) {
12281 existingReferences.push(name);
12282 }
12283 else {
12284 var error = new TemplateParseError("Reference \"#" + name + "\" is defined several times", reference.sourceSpan, ParseErrorLevel.ERROR);
12285 errors.push(error);
12286 }
12287 }); });
12288 };
12289 return TemplateParser;
12290}());
12291var TemplateParseVisitor = /** @class */ (function () {
12292 function TemplateParseVisitor(reflector, config, providerViewContext, directives, _bindingParser, _schemaRegistry, _schemas, _targetErrors) {
12293 var _this = this;
12294 this.reflector = reflector;
12295 this.config = config;
12296 this.providerViewContext = providerViewContext;
12297 this._bindingParser = _bindingParser;
12298 this._schemaRegistry = _schemaRegistry;
12299 this._schemas = _schemas;
12300 this._targetErrors = _targetErrors;
12301 this.selectorMatcher = new SelectorMatcher();
12302 this.directivesIndex = new Map();
12303 this.ngContentCount = 0;
12304 // Note: queries start with id 1 so we can use the number in a Bloom filter!
12305 this.contentQueryStartId = providerViewContext.component.viewQueries.length + 1;
12306 directives.forEach(function (directive, index) {
12307 var selector = CssSelector.parse(directive.selector);
12308 _this.selectorMatcher.addSelectables(selector, directive);
12309 _this.directivesIndex.set(directive, index);
12310 });
12311 }
12312 TemplateParseVisitor.prototype.visitExpansion = function (expansion, context) { return null; };
12313 TemplateParseVisitor.prototype.visitExpansionCase = function (expansionCase, context) { return null; };
12314 TemplateParseVisitor.prototype.visitText = function (text, parent) {
12315 var ngContentIndex = parent.findNgContentIndex(TEXT_CSS_SELECTOR());
12316 var valueNoNgsp = replaceNgsp(text.value);
12317 var expr = this._bindingParser.parseInterpolation(valueNoNgsp, text.sourceSpan);
12318 return expr ? new BoundTextAst(expr, ngContentIndex, text.sourceSpan) :
12319 new TextAst(valueNoNgsp, ngContentIndex, text.sourceSpan);
12320 };
12321 TemplateParseVisitor.prototype.visitAttribute = function (attribute, context) {
12322 return new AttrAst(attribute.name, attribute.value, attribute.sourceSpan);
12323 };
12324 TemplateParseVisitor.prototype.visitComment = function (comment, context) { return null; };
12325 TemplateParseVisitor.prototype.visitElement = function (element, parent) {
12326 var _this = this;
12327 var queryStartIndex = this.contentQueryStartId;
12328 var elName = element.name;
12329 var preparsedElement = preparseElement(element);
12330 if (preparsedElement.type === PreparsedElementType.SCRIPT ||
12331 preparsedElement.type === PreparsedElementType.STYLE) {
12332 // Skipping <script> for security reasons
12333 // Skipping <style> as we already processed them
12334 // in the StyleCompiler
12335 return null;
12336 }
12337 if (preparsedElement.type === PreparsedElementType.STYLESHEET &&
12338 isStyleUrlResolvable(preparsedElement.hrefAttr)) {
12339 // Skipping stylesheets with either relative urls or package scheme as we already processed
12340 // them in the StyleCompiler
12341 return null;
12342 }
12343 var matchableAttrs = [];
12344 var elementOrDirectiveProps = [];
12345 var elementOrDirectiveRefs = [];
12346 var elementVars = [];
12347 var events = [];
12348 var templateElementOrDirectiveProps = [];
12349 var templateMatchableAttrs = [];
12350 var templateElementVars = [];
12351 var hasInlineTemplates = false;
12352 var attrs = [];
12353 var isTemplateElement = isNgTemplate(element.name);
12354 element.attrs.forEach(function (attr) {
12355 var parsedVariables = [];
12356 var hasBinding = _this._parseAttr(isTemplateElement, attr, matchableAttrs, elementOrDirectiveProps, events, elementOrDirectiveRefs, elementVars);
12357 elementVars.push.apply(elementVars, __spread(parsedVariables.map(function (v) { return VariableAst.fromParsedVariable(v); })));
12358 var templateValue;
12359 var templateKey;
12360 var normalizedName = _this._normalizeAttributeName(attr.name);
12361 if (normalizedName.startsWith(TEMPLATE_ATTR_PREFIX)) {
12362 templateValue = attr.value;
12363 templateKey = normalizedName.substring(TEMPLATE_ATTR_PREFIX.length);
12364 }
12365 var hasTemplateBinding = templateValue != null;
12366 if (hasTemplateBinding) {
12367 if (hasInlineTemplates) {
12368 _this._reportError("Can't have multiple template bindings on one element. Use only one attribute prefixed with *", attr.sourceSpan);
12369 }
12370 hasInlineTemplates = true;
12371 var parsedVariables_1 = [];
12372 _this._bindingParser.parseInlineTemplateBinding(templateKey, templateValue, attr.sourceSpan, attr.sourceSpan.start.offset, templateMatchableAttrs, templateElementOrDirectiveProps, parsedVariables_1);
12373 templateElementVars.push.apply(templateElementVars, __spread(parsedVariables_1.map(function (v) { return VariableAst.fromParsedVariable(v); })));
12374 }
12375 if (!hasBinding && !hasTemplateBinding) {
12376 // don't include the bindings as attributes as well in the AST
12377 attrs.push(_this.visitAttribute(attr, null));
12378 matchableAttrs.push([attr.name, attr.value]);
12379 }
12380 });
12381 var elementCssSelector = createElementCssSelector(elName, matchableAttrs);
12382 var _a = this._parseDirectives(this.selectorMatcher, elementCssSelector), directiveMetas = _a.directives, matchElement = _a.matchElement;
12383 var references = [];
12384 var boundDirectivePropNames = new Set();
12385 var directiveAsts = this._createDirectiveAsts(isTemplateElement, element.name, directiveMetas, elementOrDirectiveProps, elementOrDirectiveRefs, element.sourceSpan, references, boundDirectivePropNames);
12386 var elementProps = this._createElementPropertyAsts(element.name, elementOrDirectiveProps, boundDirectivePropNames);
12387 var isViewRoot = parent.isTemplateElement || hasInlineTemplates;
12388 var providerContext = new ProviderElementContext(this.providerViewContext, parent.providerContext, isViewRoot, directiveAsts, attrs, references, isTemplateElement, queryStartIndex, element.sourceSpan);
12389 var children = visitAll$1(preparsedElement.nonBindable ? NON_BINDABLE_VISITOR : this, element.children, ElementContext.create(isTemplateElement, directiveAsts, isTemplateElement ? parent.providerContext : providerContext));
12390 providerContext.afterElement();
12391 // Override the actual selector when the `ngProjectAs` attribute is provided
12392 var projectionSelector = preparsedElement.projectAs != '' ?
12393 CssSelector.parse(preparsedElement.projectAs)[0] :
12394 elementCssSelector;
12395 var ngContentIndex = parent.findNgContentIndex(projectionSelector);
12396 var parsedElement;
12397 if (preparsedElement.type === PreparsedElementType.NG_CONTENT) {
12398 // `<ng-content>` element
12399 if (element.children && !element.children.every(_isEmptyTextNode)) {
12400 this._reportError("<ng-content> element cannot have content.", element.sourceSpan);
12401 }
12402 parsedElement = new NgContentAst(this.ngContentCount++, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan);
12403 }
12404 else if (isTemplateElement) {
12405 // `<ng-template>` element
12406 this._assertAllEventsPublishedByDirectives(directiveAsts, events);
12407 this._assertNoComponentsNorElementBindingsOnTemplate(directiveAsts, elementProps, element.sourceSpan);
12408 parsedElement = new EmbeddedTemplateAst(attrs, events, references, elementVars, providerContext.transformedDirectiveAsts, providerContext.transformProviders, providerContext.transformedHasViewContainer, providerContext.queryMatches, children, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan);
12409 }
12410 else {
12411 // element other than `<ng-content>` and `<ng-template>`
12412 this._assertElementExists(matchElement, element);
12413 this._assertOnlyOneComponent(directiveAsts, element.sourceSpan);
12414 var ngContentIndex_1 = hasInlineTemplates ? null : parent.findNgContentIndex(projectionSelector);
12415 parsedElement = new ElementAst(elName, attrs, elementProps, events, references, providerContext.transformedDirectiveAsts, providerContext.transformProviders, providerContext.transformedHasViewContainer, providerContext.queryMatches, children, hasInlineTemplates ? null : ngContentIndex_1, element.sourceSpan, element.endSourceSpan || null);
12416 }
12417 if (hasInlineTemplates) {
12418 // The element as a *-attribute
12419 var templateQueryStartIndex = this.contentQueryStartId;
12420 var templateSelector = createElementCssSelector('ng-template', templateMatchableAttrs);
12421 var directives = this._parseDirectives(this.selectorMatcher, templateSelector).directives;
12422 var templateBoundDirectivePropNames = new Set();
12423 var templateDirectiveAsts = this._createDirectiveAsts(true, elName, directives, templateElementOrDirectiveProps, [], element.sourceSpan, [], templateBoundDirectivePropNames);
12424 var templateElementProps = this._createElementPropertyAsts(elName, templateElementOrDirectiveProps, templateBoundDirectivePropNames);
12425 this._assertNoComponentsNorElementBindingsOnTemplate(templateDirectiveAsts, templateElementProps, element.sourceSpan);
12426 var templateProviderContext = new ProviderElementContext(this.providerViewContext, parent.providerContext, parent.isTemplateElement, templateDirectiveAsts, [], [], true, templateQueryStartIndex, element.sourceSpan);
12427 templateProviderContext.afterElement();
12428 parsedElement = new EmbeddedTemplateAst([], [], [], templateElementVars, templateProviderContext.transformedDirectiveAsts, templateProviderContext.transformProviders, templateProviderContext.transformedHasViewContainer, templateProviderContext.queryMatches, [parsedElement], ngContentIndex, element.sourceSpan);
12429 }
12430 return parsedElement;
12431 };
12432 TemplateParseVisitor.prototype._parseAttr = function (isTemplateElement, attr, targetMatchableAttrs, targetProps, targetEvents, targetRefs, targetVars) {
12433 var name = this._normalizeAttributeName(attr.name);
12434 var value = attr.value;
12435 var srcSpan = attr.sourceSpan;
12436 var absoluteOffset = attr.valueSpan ? attr.valueSpan.start.offset : srcSpan.start.offset;
12437 var boundEvents = [];
12438 var bindParts = name.match(BIND_NAME_REGEXP);
12439 var hasBinding = false;
12440 if (bindParts !== null) {
12441 hasBinding = true;
12442 if (bindParts[KW_BIND_IDX] != null) {
12443 this._bindingParser.parsePropertyBinding(bindParts[IDENT_KW_IDX], value, false, srcSpan, absoluteOffset, attr.valueSpan, targetMatchableAttrs, targetProps);
12444 }
12445 else if (bindParts[KW_LET_IDX]) {
12446 if (isTemplateElement) {
12447 var identifier = bindParts[IDENT_KW_IDX];
12448 this._parseVariable(identifier, value, srcSpan, targetVars);
12449 }
12450 else {
12451 this._reportError("\"let-\" is only supported on ng-template elements.", srcSpan);
12452 }
12453 }
12454 else if (bindParts[KW_REF_IDX]) {
12455 var identifier = bindParts[IDENT_KW_IDX];
12456 this._parseReference(identifier, value, srcSpan, targetRefs);
12457 }
12458 else if (bindParts[KW_ON_IDX]) {
12459 this._bindingParser.parseEvent(bindParts[IDENT_KW_IDX], value, srcSpan, attr.valueSpan || srcSpan, targetMatchableAttrs, boundEvents);
12460 }
12461 else if (bindParts[KW_BINDON_IDX]) {
12462 this._bindingParser.parsePropertyBinding(bindParts[IDENT_KW_IDX], value, false, srcSpan, absoluteOffset, attr.valueSpan, targetMatchableAttrs, targetProps);
12463 this._parseAssignmentEvent(bindParts[IDENT_KW_IDX], value, srcSpan, attr.valueSpan || srcSpan, targetMatchableAttrs, boundEvents);
12464 }
12465 else if (bindParts[KW_AT_IDX]) {
12466 this._bindingParser.parseLiteralAttr(name, value, srcSpan, absoluteOffset, attr.valueSpan, targetMatchableAttrs, targetProps);
12467 }
12468 else if (bindParts[IDENT_BANANA_BOX_IDX]) {
12469 this._bindingParser.parsePropertyBinding(bindParts[IDENT_BANANA_BOX_IDX], value, false, srcSpan, absoluteOffset, attr.valueSpan, targetMatchableAttrs, targetProps);
12470 this._parseAssignmentEvent(bindParts[IDENT_BANANA_BOX_IDX], value, srcSpan, attr.valueSpan || srcSpan, targetMatchableAttrs, boundEvents);
12471 }
12472 else if (bindParts[IDENT_PROPERTY_IDX]) {
12473 this._bindingParser.parsePropertyBinding(bindParts[IDENT_PROPERTY_IDX], value, false, srcSpan, absoluteOffset, attr.valueSpan, targetMatchableAttrs, targetProps);
12474 }
12475 else if (bindParts[IDENT_EVENT_IDX]) {
12476 this._bindingParser.parseEvent(bindParts[IDENT_EVENT_IDX], value, srcSpan, attr.valueSpan || srcSpan, targetMatchableAttrs, boundEvents);
12477 }
12478 }
12479 else {
12480 hasBinding = this._bindingParser.parsePropertyInterpolation(name, value, srcSpan, attr.valueSpan, targetMatchableAttrs, targetProps);
12481 }
12482 if (!hasBinding) {
12483 this._bindingParser.parseLiteralAttr(name, value, srcSpan, absoluteOffset, attr.valueSpan, targetMatchableAttrs, targetProps);
12484 }
12485 targetEvents.push.apply(targetEvents, __spread(boundEvents.map(function (e) { return BoundEventAst.fromParsedEvent(e); })));
12486 return hasBinding;
12487 };
12488 TemplateParseVisitor.prototype._normalizeAttributeName = function (attrName) {
12489 return /^data-/i.test(attrName) ? attrName.substring(5) : attrName;
12490 };
12491 TemplateParseVisitor.prototype._parseVariable = function (identifier, value, sourceSpan, targetVars) {
12492 if (identifier.indexOf('-') > -1) {
12493 this._reportError("\"-\" is not allowed in variable names", sourceSpan);
12494 }
12495 targetVars.push(new VariableAst(identifier, value, sourceSpan));
12496 };
12497 TemplateParseVisitor.prototype._parseReference = function (identifier, value, sourceSpan, targetRefs) {
12498 if (identifier.indexOf('-') > -1) {
12499 this._reportError("\"-\" is not allowed in reference names", sourceSpan);
12500 }
12501 targetRefs.push(new ElementOrDirectiveRef(identifier, value, sourceSpan));
12502 };
12503 TemplateParseVisitor.prototype._parseAssignmentEvent = function (name, expression, sourceSpan, valueSpan, targetMatchableAttrs, targetEvents) {
12504 this._bindingParser.parseEvent(name + "Change", expression + "=$event", sourceSpan, valueSpan, targetMatchableAttrs, targetEvents);
12505 };
12506 TemplateParseVisitor.prototype._parseDirectives = function (selectorMatcher, elementCssSelector) {
12507 var _this = this;
12508 // Need to sort the directives so that we get consistent results throughout,
12509 // as selectorMatcher uses Maps inside.
12510 // Also deduplicate directives as they might match more than one time!
12511 var directives = new Array(this.directivesIndex.size);
12512 // Whether any directive selector matches on the element name
12513 var matchElement = false;
12514 selectorMatcher.match(elementCssSelector, function (selector, directive) {
12515 directives[_this.directivesIndex.get(directive)] = directive;
12516 matchElement = matchElement || selector.hasElementSelector();
12517 });
12518 return {
12519 directives: directives.filter(function (dir) { return !!dir; }),
12520 matchElement: matchElement,
12521 };
12522 };
12523 TemplateParseVisitor.prototype._createDirectiveAsts = function (isTemplateElement, elementName, directives, props, elementOrDirectiveRefs, elementSourceSpan, targetReferences, targetBoundDirectivePropNames) {
12524 var _this = this;
12525 var matchedReferences = new Set();
12526 var component = null;
12527 var directiveAsts = directives.map(function (directive) {
12528 var sourceSpan = new ParseSourceSpan(elementSourceSpan.start, elementSourceSpan.end, "Directive " + identifierName(directive.type));
12529 if (directive.isComponent) {
12530 component = directive;
12531 }
12532 var directiveProperties = [];
12533 var boundProperties = _this._bindingParser.createDirectiveHostPropertyAsts(directive, elementName, sourceSpan);
12534 var hostProperties = boundProperties.map(function (prop) { return BoundElementPropertyAst.fromBoundProperty(prop); });
12535 // Note: We need to check the host properties here as well,
12536 // as we don't know the element name in the DirectiveWrapperCompiler yet.
12537 hostProperties = _this._checkPropertiesInSchema(elementName, hostProperties);
12538 var parsedEvents = _this._bindingParser.createDirectiveHostEventAsts(directive, sourceSpan);
12539 _this._createDirectivePropertyAsts(directive.inputs, props, directiveProperties, targetBoundDirectivePropNames);
12540 elementOrDirectiveRefs.forEach(function (elOrDirRef) {
12541 if ((elOrDirRef.value.length === 0 && directive.isComponent) ||
12542 (elOrDirRef.isReferenceToDirective(directive))) {
12543 targetReferences.push(new ReferenceAst(elOrDirRef.name, createTokenForReference(directive.type.reference), elOrDirRef.value, elOrDirRef.sourceSpan));
12544 matchedReferences.add(elOrDirRef.name);
12545 }
12546 });
12547 var hostEvents = parsedEvents.map(function (e) { return BoundEventAst.fromParsedEvent(e); });
12548 var contentQueryStartId = _this.contentQueryStartId;
12549 _this.contentQueryStartId += directive.queries.length;
12550 return new DirectiveAst(directive, directiveProperties, hostProperties, hostEvents, contentQueryStartId, sourceSpan);
12551 });
12552 elementOrDirectiveRefs.forEach(function (elOrDirRef) {
12553 if (elOrDirRef.value.length > 0) {
12554 if (!matchedReferences.has(elOrDirRef.name)) {
12555 _this._reportError("There is no directive with \"exportAs\" set to \"" + elOrDirRef.value + "\"", elOrDirRef.sourceSpan);
12556 }
12557 }
12558 else if (!component) {
12559 var refToken = null;
12560 if (isTemplateElement) {
12561 refToken = createTokenForExternalReference(_this.reflector, Identifiers.TemplateRef);
12562 }
12563 targetReferences.push(new ReferenceAst(elOrDirRef.name, refToken, elOrDirRef.value, elOrDirRef.sourceSpan));
12564 }
12565 });
12566 return directiveAsts;
12567 };
12568 TemplateParseVisitor.prototype._createDirectivePropertyAsts = function (directiveProperties, boundProps, targetBoundDirectiveProps, targetBoundDirectivePropNames) {
12569 if (directiveProperties) {
12570 var boundPropsByName_1 = new Map();
12571 boundProps.forEach(function (boundProp) {
12572 var prevValue = boundPropsByName_1.get(boundProp.name);
12573 if (!prevValue || prevValue.isLiteral) {
12574 // give [a]="b" a higher precedence than a="b" on the same element
12575 boundPropsByName_1.set(boundProp.name, boundProp);
12576 }
12577 });
12578 Object.keys(directiveProperties).forEach(function (dirProp) {
12579 var elProp = directiveProperties[dirProp];
12580 var boundProp = boundPropsByName_1.get(elProp);
12581 // Bindings are optional, so this binding only needs to be set up if an expression is given.
12582 if (boundProp) {
12583 targetBoundDirectivePropNames.add(boundProp.name);
12584 if (!isEmptyExpression(boundProp.expression)) {
12585 targetBoundDirectiveProps.push(new BoundDirectivePropertyAst(dirProp, boundProp.name, boundProp.expression, boundProp.sourceSpan));
12586 }
12587 }
12588 });
12589 }
12590 };
12591 TemplateParseVisitor.prototype._createElementPropertyAsts = function (elementName, props, boundDirectivePropNames) {
12592 var _this = this;
12593 var boundElementProps = [];
12594 props.forEach(function (prop) {
12595 if (!prop.isLiteral && !boundDirectivePropNames.has(prop.name)) {
12596 var boundProp = _this._bindingParser.createBoundElementProperty(elementName, prop);
12597 boundElementProps.push(BoundElementPropertyAst.fromBoundProperty(boundProp));
12598 }
12599 });
12600 return this._checkPropertiesInSchema(elementName, boundElementProps);
12601 };
12602 TemplateParseVisitor.prototype._findComponentDirectives = function (directives) {
12603 return directives.filter(function (directive) { return directive.directive.isComponent; });
12604 };
12605 TemplateParseVisitor.prototype._findComponentDirectiveNames = function (directives) {
12606 return this._findComponentDirectives(directives)
12607 .map(function (directive) { return identifierName(directive.directive.type); });
12608 };
12609 TemplateParseVisitor.prototype._assertOnlyOneComponent = function (directives, sourceSpan) {
12610 var componentTypeNames = this._findComponentDirectiveNames(directives);
12611 if (componentTypeNames.length > 1) {
12612 this._reportError("More than one component matched on this element.\n" +
12613 "Make sure that only one component's selector can match a given element.\n" +
12614 ("Conflicting components: " + componentTypeNames.join(',')), sourceSpan);
12615 }
12616 };
12617 /**
12618 * Make sure that non-angular tags conform to the schemas.
12619 *
12620 * Note: An element is considered an angular tag when at least one directive selector matches the
12621 * tag name.
12622 *
12623 * @param matchElement Whether any directive has matched on the tag name
12624 * @param element the html element
12625 */
12626 TemplateParseVisitor.prototype._assertElementExists = function (matchElement, element) {
12627 var elName = element.name.replace(/^:xhtml:/, '');
12628 if (!matchElement && !this._schemaRegistry.hasElement(elName, this._schemas)) {
12629 var errorMsg = "'" + elName + "' is not a known element:\n";
12630 errorMsg +=
12631 "1. If '" + elName + "' is an Angular component, then verify that it is part of this module.\n";
12632 if (elName.indexOf('-') > -1) {
12633 errorMsg +=
12634 "2. If '" + elName + "' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.";
12635 }
12636 else {
12637 errorMsg +=
12638 "2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.";
12639 }
12640 this._reportError(errorMsg, element.sourceSpan);
12641 }
12642 };
12643 TemplateParseVisitor.prototype._assertNoComponentsNorElementBindingsOnTemplate = function (directives, elementProps, sourceSpan) {
12644 var _this = this;
12645 var componentTypeNames = this._findComponentDirectiveNames(directives);
12646 if (componentTypeNames.length > 0) {
12647 this._reportError("Components on an embedded template: " + componentTypeNames.join(','), sourceSpan);
12648 }
12649 elementProps.forEach(function (prop) {
12650 _this._reportError("Property binding " + prop.name + " not used by any directive on an embedded template. Make sure that the property name is spelled correctly and all directives are listed in the \"@NgModule.declarations\".", sourceSpan);
12651 });
12652 };
12653 TemplateParseVisitor.prototype._assertAllEventsPublishedByDirectives = function (directives, events) {
12654 var _this = this;
12655 var allDirectiveEvents = new Set();
12656 directives.forEach(function (directive) {
12657 Object.keys(directive.directive.outputs).forEach(function (k) {
12658 var eventName = directive.directive.outputs[k];
12659 allDirectiveEvents.add(eventName);
12660 });
12661 });
12662 events.forEach(function (event) {
12663 if (event.target != null || !allDirectiveEvents.has(event.name)) {
12664 _this._reportError("Event binding " + event.fullName + " not emitted by any directive on an embedded template. Make sure that the event name is spelled correctly and all directives are listed in the \"@NgModule.declarations\".", event.sourceSpan);
12665 }
12666 });
12667 };
12668 TemplateParseVisitor.prototype._checkPropertiesInSchema = function (elementName, boundProps) {
12669 var _this = this;
12670 // Note: We can't filter out empty expressions before this method,
12671 // as we still want to validate them!
12672 return boundProps.filter(function (boundProp) {
12673 if (boundProp.type === 0 /* Property */ &&
12674 !_this._schemaRegistry.hasProperty(elementName, boundProp.name, _this._schemas)) {
12675 var errorMsg = "Can't bind to '" + boundProp.name + "' since it isn't a known property of '" + elementName + "'.";
12676 if (elementName.startsWith('ng-')) {
12677 errorMsg +=
12678 "\n1. If '" + boundProp.name + "' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component." +
12679 "\n2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.";
12680 }
12681 else if (elementName.indexOf('-') > -1) {
12682 errorMsg +=
12683 "\n1. If '" + elementName + "' is an Angular component and it has '" + boundProp.name + "' input, then verify that it is part of this module." +
12684 ("\n2. If '" + elementName + "' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.") +
12685 "\n3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.";
12686 }
12687 _this._reportError(errorMsg, boundProp.sourceSpan);
12688 }
12689 return !isEmptyExpression(boundProp.value);
12690 });
12691 };
12692 TemplateParseVisitor.prototype._reportError = function (message, sourceSpan, level) {
12693 if (level === void 0) { level = ParseErrorLevel.ERROR; }
12694 this._targetErrors.push(new ParseError(sourceSpan, message, level));
12695 };
12696 return TemplateParseVisitor;
12697}());
12698var NonBindableVisitor = /** @class */ (function () {
12699 function NonBindableVisitor() {
12700 }
12701 NonBindableVisitor.prototype.visitElement = function (ast, parent) {
12702 var preparsedElement = preparseElement(ast);
12703 if (preparsedElement.type === PreparsedElementType.SCRIPT ||
12704 preparsedElement.type === PreparsedElementType.STYLE ||
12705 preparsedElement.type === PreparsedElementType.STYLESHEET) {
12706 // Skipping <script> for security reasons
12707 // Skipping <style> and stylesheets as we already processed them
12708 // in the StyleCompiler
12709 return null;
12710 }
12711 var attrNameAndValues = ast.attrs.map(function (attr) { return [attr.name, attr.value]; });
12712 var selector = createElementCssSelector(ast.name, attrNameAndValues);
12713 var ngContentIndex = parent.findNgContentIndex(selector);
12714 var children = visitAll$1(this, ast.children, EMPTY_ELEMENT_CONTEXT);
12715 return new ElementAst(ast.name, visitAll$1(this, ast.attrs), [], [], [], [], [], false, [], children, ngContentIndex, ast.sourceSpan, ast.endSourceSpan);
12716 };
12717 NonBindableVisitor.prototype.visitComment = function (comment, context) { return null; };
12718 NonBindableVisitor.prototype.visitAttribute = function (attribute, context) {
12719 return new AttrAst(attribute.name, attribute.value, attribute.sourceSpan);
12720 };
12721 NonBindableVisitor.prototype.visitText = function (text, parent) {
12722 var ngContentIndex = parent.findNgContentIndex(TEXT_CSS_SELECTOR());
12723 return new TextAst(text.value, ngContentIndex, text.sourceSpan);
12724 };
12725 NonBindableVisitor.prototype.visitExpansion = function (expansion, context) { return expansion; };
12726 NonBindableVisitor.prototype.visitExpansionCase = function (expansionCase, context) { return expansionCase; };
12727 return NonBindableVisitor;
12728}());
12729/**
12730 * A reference to an element or directive in a template. E.g., the reference in this template:
12731 *
12732 * <div #myMenu="coolMenu">
12733 *
12734 * would be {name: 'myMenu', value: 'coolMenu', sourceSpan: ...}
12735 */
12736var ElementOrDirectiveRef = /** @class */ (function () {
12737 function ElementOrDirectiveRef(name, value, sourceSpan) {
12738 this.name = name;
12739 this.value = value;
12740 this.sourceSpan = sourceSpan;
12741 }
12742 /** Gets whether this is a reference to the given directive. */
12743 ElementOrDirectiveRef.prototype.isReferenceToDirective = function (directive) {
12744 return splitExportAs(directive.exportAs).indexOf(this.value) !== -1;
12745 };
12746 return ElementOrDirectiveRef;
12747}());
12748/** Splits a raw, potentially comma-delimited `exportAs` value into an array of names. */
12749function splitExportAs(exportAs) {
12750 return exportAs ? exportAs.split(',').map(function (e) { return e.trim(); }) : [];
12751}
12752function splitClasses(classAttrValue) {
12753 return classAttrValue.trim().split(/\s+/g);
12754}
12755var ElementContext = /** @class */ (function () {
12756 function ElementContext(isTemplateElement, _ngContentIndexMatcher, _wildcardNgContentIndex, providerContext) {
12757 this.isTemplateElement = isTemplateElement;
12758 this._ngContentIndexMatcher = _ngContentIndexMatcher;
12759 this._wildcardNgContentIndex = _wildcardNgContentIndex;
12760 this.providerContext = providerContext;
12761 }
12762 ElementContext.create = function (isTemplateElement, directives, providerContext) {
12763 var matcher = new SelectorMatcher();
12764 var wildcardNgContentIndex = null;
12765 var component = directives.find(function (directive) { return directive.directive.isComponent; });
12766 if (component) {
12767 var ngContentSelectors = component.directive.template.ngContentSelectors;
12768 for (var i = 0; i < ngContentSelectors.length; i++) {
12769 var selector = ngContentSelectors[i];
12770 if (selector === '*') {
12771 wildcardNgContentIndex = i;
12772 }
12773 else {
12774 matcher.addSelectables(CssSelector.parse(ngContentSelectors[i]), i);
12775 }
12776 }
12777 }
12778 return new ElementContext(isTemplateElement, matcher, wildcardNgContentIndex, providerContext);
12779 };
12780 ElementContext.prototype.findNgContentIndex = function (selector) {
12781 var ngContentIndices = [];
12782 this._ngContentIndexMatcher.match(selector, function (selector, ngContentIndex) { ngContentIndices.push(ngContentIndex); });
12783 ngContentIndices.sort();
12784 if (this._wildcardNgContentIndex != null) {
12785 ngContentIndices.push(this._wildcardNgContentIndex);
12786 }
12787 return ngContentIndices.length > 0 ? ngContentIndices[0] : null;
12788 };
12789 return ElementContext;
12790}());
12791function createElementCssSelector(elementName, attributes) {
12792 var cssSelector = new CssSelector();
12793 var elNameNoNs = splitNsName(elementName)[1];
12794 cssSelector.setElement(elNameNoNs);
12795 for (var i = 0; i < attributes.length; i++) {
12796 var attrName = attributes[i][0];
12797 var attrNameNoNs = splitNsName(attrName)[1];
12798 var attrValue = attributes[i][1];
12799 cssSelector.addAttribute(attrNameNoNs, attrValue);
12800 if (attrName.toLowerCase() == CLASS_ATTR) {
12801 var classes = splitClasses(attrValue);
12802 classes.forEach(function (className) { return cssSelector.addClassName(className); });
12803 }
12804 }
12805 return cssSelector;
12806}
12807var EMPTY_ELEMENT_CONTEXT = new ElementContext(true, new SelectorMatcher(), null, null);
12808var NON_BINDABLE_VISITOR = new NonBindableVisitor();
12809function _isEmptyTextNode(node) {
12810 return node instanceof Text$3 && node.value.trim().length == 0;
12811}
12812function removeSummaryDuplicates(items) {
12813 var map = new Map();
12814 items.forEach(function (item) {
12815 if (!map.get(item.type.reference)) {
12816 map.set(item.type.reference, item);
12817 }
12818 });
12819 return Array.from(map.values());
12820}
12821function isEmptyExpression(ast) {
12822 if (ast instanceof ASTWithSource) {
12823 ast = ast.ast;
12824 }
12825 return ast instanceof EmptyExpr;
12826}
12827
12828/**
12829 * @license
12830 * Copyright Google Inc. All Rights Reserved.
12831 *
12832 * Use of this source code is governed by an MIT-style license that can be
12833 * found in the LICENSE file at https://angular.io/license
12834 */
12835/**
12836 * Parses string representation of a style and converts it into object literal.
12837 *
12838 * @param value string representation of style as used in the `style` attribute in HTML.
12839 * Example: `color: red; height: auto`.
12840 * @returns An array of style property name and value pairs, e.g. `['color', 'red', 'height',
12841 * 'auto']`
12842 */
12843function parse(value) {
12844 // we use a string array here instead of a string map
12845 // because a string-map is not guaranteed to retain the
12846 // order of the entries whereas a string array can be
12847 // construted in a [key, value, key, value] format.
12848 var styles = [];
12849 var i = 0;
12850 var parenDepth = 0;
12851 var quote = 0 /* QuoteNone */;
12852 var valueStart = 0;
12853 var propStart = 0;
12854 var currentProp = null;
12855 var valueHasQuotes = false;
12856 while (i < value.length) {
12857 var token = value.charCodeAt(i++);
12858 switch (token) {
12859 case 40 /* OpenParen */:
12860 parenDepth++;
12861 break;
12862 case 41 /* CloseParen */:
12863 parenDepth--;
12864 break;
12865 case 39 /* QuoteSingle */:
12866 // valueStart needs to be there since prop values don't
12867 // have quotes in CSS
12868 valueHasQuotes = valueHasQuotes || valueStart > 0;
12869 if (quote === 0 /* QuoteNone */) {
12870 quote = 39 /* QuoteSingle */;
12871 }
12872 else if (quote === 39 /* QuoteSingle */ && value.charCodeAt(i - 1) !== 92 /* BackSlash */) {
12873 quote = 0 /* QuoteNone */;
12874 }
12875 break;
12876 case 34 /* QuoteDouble */:
12877 // same logic as above
12878 valueHasQuotes = valueHasQuotes || valueStart > 0;
12879 if (quote === 0 /* QuoteNone */) {
12880 quote = 34 /* QuoteDouble */;
12881 }
12882 else if (quote === 34 /* QuoteDouble */ && value.charCodeAt(i - 1) !== 92 /* BackSlash */) {
12883 quote = 0 /* QuoteNone */;
12884 }
12885 break;
12886 case 58 /* Colon */:
12887 if (!currentProp && parenDepth === 0 && quote === 0 /* QuoteNone */) {
12888 currentProp = hyphenate(value.substring(propStart, i - 1).trim());
12889 valueStart = i;
12890 }
12891 break;
12892 case 59 /* Semicolon */:
12893 if (currentProp && valueStart > 0 && parenDepth === 0 && quote === 0 /* QuoteNone */) {
12894 var styleVal = value.substring(valueStart, i - 1).trim();
12895 styles.push(currentProp, valueHasQuotes ? stripUnnecessaryQuotes(styleVal) : styleVal);
12896 propStart = i;
12897 valueStart = 0;
12898 currentProp = null;
12899 valueHasQuotes = false;
12900 }
12901 break;
12902 }
12903 }
12904 if (currentProp && valueStart) {
12905 var styleVal = value.substr(valueStart).trim();
12906 styles.push(currentProp, valueHasQuotes ? stripUnnecessaryQuotes(styleVal) : styleVal);
12907 }
12908 return styles;
12909}
12910function stripUnnecessaryQuotes(value) {
12911 var qS = value.charCodeAt(0);
12912 var qE = value.charCodeAt(value.length - 1);
12913 if (qS == qE && (qS == 39 /* QuoteSingle */ || qS == 34 /* QuoteDouble */)) {
12914 var tempValue = value.substring(1, value.length - 1);
12915 // special case to avoid using a multi-quoted string that was just chomped
12916 // (e.g. `font-family: "Verdana", "sans-serif"`)
12917 if (tempValue.indexOf('\'') == -1 && tempValue.indexOf('"') == -1) {
12918 value = tempValue;
12919 }
12920 }
12921 return value;
12922}
12923function hyphenate(value) {
12924 return value.replace(/[a-z][A-Z]/g, function (v) {
12925 return v.charAt(0) + '-' + v.charAt(1);
12926 }).toLowerCase();
12927}
12928
12929var IMPORTANT_FLAG = '!important';
12930/**
12931 * Produces creation/update instructions for all styling bindings (class and style)
12932 *
12933 * It also produces the creation instruction to register all initial styling values
12934 * (which are all the static class="..." and style="..." attribute values that exist
12935 * on an element within a template).
12936 *
12937 * The builder class below handles producing instructions for the following cases:
12938 *
12939 * - Static style/class attributes (style="..." and class="...")
12940 * - Dynamic style/class map bindings ([style]="map" and [class]="map|string")
12941 * - Dynamic style/class property bindings ([style.prop]="exp" and [class.name]="exp")
12942 *
12943 * Due to the complex relationship of all of these cases, the instructions generated
12944 * for these attributes/properties/bindings must be done so in the correct order. The
12945 * order which these must be generated is as follows:
12946 *
12947 * if (createMode) {
12948 * styling(...)
12949 * }
12950 * if (updateMode) {
12951 * styleMap(...)
12952 * classMap(...)
12953 * styleProp(...)
12954 * classProp(...)
12955 * stylingApply(...)
12956 * }
12957 *
12958 * The creation/update methods within the builder class produce these instructions.
12959 */
12960var StylingBuilder = /** @class */ (function () {
12961 function StylingBuilder(_elementIndexExpr, _directiveExpr) {
12962 this._elementIndexExpr = _elementIndexExpr;
12963 this._directiveExpr = _directiveExpr;
12964 /** Whether or not there are any static styling values present */
12965 this._hasInitialValues = false;
12966 /**
12967 * Whether or not there are any styling bindings present
12968 * (i.e. `[style]`, `[class]`, `[style.prop]` or `[class.name]`)
12969 */
12970 this.hasBindings = false;
12971 /** the input for [class] (if it exists) */
12972 this._classMapInput = null;
12973 /** the input for [style] (if it exists) */
12974 this._styleMapInput = null;
12975 /** an array of each [style.prop] input */
12976 this._singleStyleInputs = null;
12977 /** an array of each [class.name] input */
12978 this._singleClassInputs = null;
12979 this._lastStylingInput = null;
12980 this._firstStylingInput = null;
12981 // maps are used instead of hash maps because a Map will
12982 // retain the ordering of the keys
12983 /**
12984 * Represents the location of each style binding in the template
12985 * (e.g. `<div [style.width]="w" [style.height]="h">` implies
12986 * that `width=0` and `height=1`)
12987 */
12988 this._stylesIndex = new Map();
12989 /**
12990 * Represents the location of each class binding in the template
12991 * (e.g. `<div [class.big]="b" [class.hidden]="h">` implies
12992 * that `big=0` and `hidden=1`)
12993 */
12994 this._classesIndex = new Map();
12995 this._initialStyleValues = [];
12996 this._initialClassValues = [];
12997 // certain style properties ALWAYS need sanitization
12998 // this is checked each time new styles are encountered
12999 this._useDefaultSanitizer = false;
13000 }
13001 /**
13002 * Registers a given input to the styling builder to be later used when producing AOT code.
13003 *
13004 * The code below will only accept the input if it is somehow tied to styling (whether it be
13005 * style/class bindings or static style/class attributes).
13006 */
13007 StylingBuilder.prototype.registerBoundInput = function (input) {
13008 // [attr.style] or [attr.class] are skipped in the code below,
13009 // they should not be treated as styling-based bindings since
13010 // they are intended to be written directly to the attr and
13011 // will therefore skip all style/class resolution that is present
13012 // with style="", [style]="" and [style.prop]="", class="",
13013 // [class.prop]="". [class]="" assignments
13014 var binding = null;
13015 var name = input.name;
13016 switch (input.type) {
13017 case 0 /* Property */:
13018 binding = this.registerInputBasedOnName(name, input.value, input.sourceSpan);
13019 break;
13020 case 3 /* Style */:
13021 binding = this.registerStyleInput(name, false, input.value, input.sourceSpan, input.unit);
13022 break;
13023 case 2 /* Class */:
13024 binding = this.registerClassInput(name, false, input.value, input.sourceSpan);
13025 break;
13026 }
13027 return binding ? true : false;
13028 };
13029 StylingBuilder.prototype.registerInputBasedOnName = function (name, expression, sourceSpan) {
13030 var binding = null;
13031 var nameToMatch = name.substring(0, 5); // class | style
13032 var isStyle = nameToMatch === 'style';
13033 var isClass = isStyle ? false : (nameToMatch === 'class');
13034 if (isStyle || isClass) {
13035 var isMapBased = name.charAt(5) !== '.'; // style.prop or class.prop makes this a no
13036 var property = name.substr(isMapBased ? 5 : 6); // the dot explains why there's a +1
13037 if (isStyle) {
13038 binding = this.registerStyleInput(property, isMapBased, expression, sourceSpan);
13039 }
13040 else {
13041 binding = this.registerClassInput(property, isMapBased, expression, sourceSpan);
13042 }
13043 }
13044 return binding;
13045 };
13046 StylingBuilder.prototype.registerStyleInput = function (name, isMapBased, value, sourceSpan, unit) {
13047 if (isEmptyExpression(value)) {
13048 return null;
13049 }
13050 name = normalizePropName(name);
13051 var _a = parseProperty(name), property = _a.property, hasOverrideFlag = _a.hasOverrideFlag, bindingUnit = _a.unit;
13052 var entry = {
13053 name: property,
13054 unit: unit || bindingUnit, value: value, sourceSpan: sourceSpan, hasOverrideFlag: hasOverrideFlag
13055 };
13056 if (isMapBased) {
13057 this._useDefaultSanitizer = true;
13058 this._styleMapInput = entry;
13059 }
13060 else {
13061 (this._singleStyleInputs = this._singleStyleInputs || []).push(entry);
13062 this._useDefaultSanitizer = this._useDefaultSanitizer || isStyleSanitizable(name);
13063 registerIntoMap(this._stylesIndex, property);
13064 }
13065 this._lastStylingInput = entry;
13066 this._firstStylingInput = this._firstStylingInput || entry;
13067 this.hasBindings = true;
13068 return entry;
13069 };
13070 StylingBuilder.prototype.registerClassInput = function (name, isMapBased, value, sourceSpan) {
13071 if (isEmptyExpression(value)) {
13072 return null;
13073 }
13074 var _a = parseProperty(name), property = _a.property, hasOverrideFlag = _a.hasOverrideFlag;
13075 var entry = { name: property, value: value, sourceSpan: sourceSpan, hasOverrideFlag: hasOverrideFlag, unit: null };
13076 if (isMapBased) {
13077 this._classMapInput = entry;
13078 }
13079 else {
13080 (this._singleClassInputs = this._singleClassInputs || []).push(entry);
13081 registerIntoMap(this._classesIndex, property);
13082 }
13083 this._lastStylingInput = entry;
13084 this._firstStylingInput = this._firstStylingInput || entry;
13085 this.hasBindings = true;
13086 return entry;
13087 };
13088 /**
13089 * Registers the element's static style string value to the builder.
13090 *
13091 * @param value the style string (e.g. `width:100px; height:200px;`)
13092 */
13093 StylingBuilder.prototype.registerStyleAttr = function (value) {
13094 this._initialStyleValues = parse(value);
13095 this._hasInitialValues = true;
13096 };
13097 /**
13098 * Registers the element's static class string value to the builder.
13099 *
13100 * @param value the className string (e.g. `disabled gold zoom`)
13101 */
13102 StylingBuilder.prototype.registerClassAttr = function (value) {
13103 this._initialClassValues = value.trim().split(/\s+/g);
13104 this._hasInitialValues = true;
13105 };
13106 /**
13107 * Appends all styling-related expressions to the provided attrs array.
13108 *
13109 * @param attrs an existing array where each of the styling expressions
13110 * will be inserted into.
13111 */
13112 StylingBuilder.prototype.populateInitialStylingAttrs = function (attrs) {
13113 // [CLASS_MARKER, 'foo', 'bar', 'baz' ...]
13114 if (this._initialClassValues.length) {
13115 attrs.push(literal(1 /* Classes */));
13116 for (var i = 0; i < this._initialClassValues.length; i++) {
13117 attrs.push(literal(this._initialClassValues[i]));
13118 }
13119 }
13120 // [STYLE_MARKER, 'width', '200px', 'height', '100px', ...]
13121 if (this._initialStyleValues.length) {
13122 attrs.push(literal(2 /* Styles */));
13123 for (var i = 0; i < this._initialStyleValues.length; i += 2) {
13124 attrs.push(literal(this._initialStyleValues[i]), literal(this._initialStyleValues[i + 1]));
13125 }
13126 }
13127 };
13128 /**
13129 * Builds an instruction with all the expressions and parameters for `elementHostAttrs`.
13130 *
13131 * The instruction generation code below is used for producing the AOT statement code which is
13132 * responsible for registering initial styles (within a directive hostBindings' creation block),
13133 * as well as any of the provided attribute values, to the directive host element.
13134 */
13135 StylingBuilder.prototype.buildHostAttrsInstruction = function (sourceSpan, attrs, constantPool) {
13136 var _this = this;
13137 if (this._directiveExpr && (attrs.length || this._hasInitialValues)) {
13138 return {
13139 sourceSpan: sourceSpan,
13140 reference: Identifiers$1.elementHostAttrs,
13141 allocateBindingSlots: 0,
13142 params: function () {
13143 // params => elementHostAttrs(attrs)
13144 _this.populateInitialStylingAttrs(attrs);
13145 var attrArray = !attrs.some(function (attr) { return attr instanceof WrappedNodeExpr; }) ?
13146 getConstantLiteralFromArray(constantPool, attrs) :
13147 literalArr(attrs);
13148 return [attrArray];
13149 }
13150 };
13151 }
13152 return null;
13153 };
13154 /**
13155 * Builds an instruction with all the expressions and parameters for `styling`.
13156 *
13157 * The instruction generation code below is used for producing the AOT statement code which is
13158 * responsible for registering style/class bindings to an element.
13159 */
13160 StylingBuilder.prototype.buildStylingInstruction = function (sourceSpan, constantPool) {
13161 if (this.hasBindings) {
13162 return {
13163 sourceSpan: sourceSpan,
13164 allocateBindingSlots: 0,
13165 reference: Identifiers$1.styling,
13166 params: function () { return []; },
13167 };
13168 }
13169 return null;
13170 };
13171 /**
13172 * Builds an instruction with all the expressions and parameters for `classMap`.
13173 *
13174 * The instruction data will contain all expressions for `classMap` to function
13175 * which includes the `[class]` expression params.
13176 */
13177 StylingBuilder.prototype.buildClassMapInstruction = function (valueConverter) {
13178 if (this._classMapInput) {
13179 return this._buildMapBasedInstruction(valueConverter, true, this._classMapInput);
13180 }
13181 return null;
13182 };
13183 /**
13184 * Builds an instruction with all the expressions and parameters for `styleMap`.
13185 *
13186 * The instruction data will contain all expressions for `styleMap` to function
13187 * which includes the `[style]` expression params.
13188 */
13189 StylingBuilder.prototype.buildStyleMapInstruction = function (valueConverter) {
13190 if (this._styleMapInput) {
13191 return this._buildMapBasedInstruction(valueConverter, false, this._styleMapInput);
13192 }
13193 return null;
13194 };
13195 StylingBuilder.prototype._buildMapBasedInstruction = function (valueConverter, isClassBased, stylingInput) {
13196 // each styling binding value is stored in the LView
13197 var totalBindingSlotsRequired = 1;
13198 // these values must be outside of the update block so that they can
13199 // be evaluated (the AST visit call) during creation time so that any
13200 // pipes can be picked up in time before the template is built
13201 var mapValue = stylingInput.value.visit(valueConverter);
13202 var reference;
13203 if (mapValue instanceof Interpolation && isClassBased) {
13204 totalBindingSlotsRequired += mapValue.expressions.length;
13205 reference = getClassMapInterpolationExpression(mapValue);
13206 }
13207 else {
13208 reference = isClassBased ? Identifiers$1.classMap : Identifiers$1.styleMap;
13209 }
13210 return {
13211 sourceSpan: stylingInput.sourceSpan,
13212 reference: reference,
13213 allocateBindingSlots: totalBindingSlotsRequired,
13214 supportsInterpolation: isClassBased,
13215 params: function (convertFn) {
13216 var convertResult = convertFn(mapValue);
13217 return Array.isArray(convertResult) ? convertResult : [convertResult];
13218 }
13219 };
13220 };
13221 StylingBuilder.prototype._buildSingleInputs = function (reference, inputs, mapIndex, allowUnits, valueConverter, getInterpolationExpressionFn) {
13222 var totalBindingSlotsRequired = 0;
13223 return inputs.map(function (input) {
13224 var value = input.value.visit(valueConverter);
13225 // each styling binding value is stored in the LView
13226 var totalBindingSlotsRequired = 1;
13227 if (value instanceof Interpolation) {
13228 totalBindingSlotsRequired += value.expressions.length;
13229 if (getInterpolationExpressionFn) {
13230 reference = getInterpolationExpressionFn(value);
13231 }
13232 }
13233 return {
13234 sourceSpan: input.sourceSpan,
13235 supportsInterpolation: !!getInterpolationExpressionFn,
13236 allocateBindingSlots: totalBindingSlotsRequired, reference: reference,
13237 params: function (convertFn) {
13238 // params => stylingProp(propName, value)
13239 var params = [];
13240 params.push(literal(input.name));
13241 var convertResult = convertFn(value);
13242 if (Array.isArray(convertResult)) {
13243 params.push.apply(params, __spread(convertResult));
13244 }
13245 else {
13246 params.push(convertResult);
13247 }
13248 if (allowUnits && input.unit) {
13249 params.push(literal(input.unit));
13250 }
13251 return params;
13252 }
13253 };
13254 });
13255 };
13256 StylingBuilder.prototype._buildClassInputs = function (valueConverter) {
13257 if (this._singleClassInputs) {
13258 return this._buildSingleInputs(Identifiers$1.classProp, this._singleClassInputs, this._classesIndex, false, valueConverter);
13259 }
13260 return [];
13261 };
13262 StylingBuilder.prototype._buildStyleInputs = function (valueConverter) {
13263 if (this._singleStyleInputs) {
13264 return this._buildSingleInputs(Identifiers$1.styleProp, this._singleStyleInputs, this._stylesIndex, true, valueConverter, getStylePropInterpolationExpression);
13265 }
13266 return [];
13267 };
13268 StylingBuilder.prototype._buildApplyFn = function () {
13269 return {
13270 sourceSpan: this._lastStylingInput ? this._lastStylingInput.sourceSpan : null,
13271 reference: Identifiers$1.stylingApply,
13272 allocateBindingSlots: 0,
13273 params: function () { return []; }
13274 };
13275 };
13276 StylingBuilder.prototype._buildSanitizerFn = function () {
13277 return {
13278 sourceSpan: this._firstStylingInput ? this._firstStylingInput.sourceSpan : null,
13279 reference: Identifiers$1.styleSanitizer,
13280 allocateBindingSlots: 0,
13281 params: function () { return [importExpr(Identifiers$1.defaultStyleSanitizer)]; }
13282 };
13283 };
13284 /**
13285 * Constructs all instructions which contain the expressions that will be placed
13286 * into the update block of a template function or a directive hostBindings function.
13287 */
13288 StylingBuilder.prototype.buildUpdateLevelInstructions = function (valueConverter) {
13289 var instructions = [];
13290 if (this.hasBindings) {
13291 if (this._useDefaultSanitizer) {
13292 instructions.push(this._buildSanitizerFn());
13293 }
13294 var styleMapInstruction = this.buildStyleMapInstruction(valueConverter);
13295 if (styleMapInstruction) {
13296 instructions.push(styleMapInstruction);
13297 }
13298 var classMapInstruction = this.buildClassMapInstruction(valueConverter);
13299 if (classMapInstruction) {
13300 instructions.push(classMapInstruction);
13301 }
13302 instructions.push.apply(instructions, __spread(this._buildStyleInputs(valueConverter)));
13303 instructions.push.apply(instructions, __spread(this._buildClassInputs(valueConverter)));
13304 instructions.push(this._buildApplyFn());
13305 }
13306 return instructions;
13307 };
13308 return StylingBuilder;
13309}());
13310function registerIntoMap(map, key) {
13311 if (!map.has(key)) {
13312 map.set(key, map.size);
13313 }
13314}
13315function isStyleSanitizable(prop) {
13316 // Note that browsers support both the dash case and
13317 // camel case property names when setting through JS.
13318 return prop === 'background-image' || prop === 'backgroundImage' || prop === 'background' ||
13319 prop === 'border-image' || prop === 'borderImage' || prop === 'filter' ||
13320 prop === 'list-style' || prop === 'listStyle' || prop === 'list-style-image' ||
13321 prop === 'listStyleImage' || prop === 'clip-path' || prop === 'clipPath';
13322}
13323/**
13324 * Simple helper function to either provide the constant literal that will house the value
13325 * here or a null value if the provided values are empty.
13326 */
13327function getConstantLiteralFromArray(constantPool, values) {
13328 return values.length ? constantPool.getConstLiteral(literalArr(values), true) : NULL_EXPR;
13329}
13330/**
13331 * Simple helper function that adds a parameter or does nothing at all depending on the provided
13332 * predicate and totalExpectedArgs values
13333 */
13334function addParam(params, predicate, value, argNumber, totalExpectedArgs) {
13335 if (predicate && value) {
13336 params.push(value);
13337 }
13338 else if (argNumber < totalExpectedArgs) {
13339 params.push(NULL_EXPR);
13340 }
13341}
13342function parseProperty(name) {
13343 var hasOverrideFlag = false;
13344 var overrideIndex = name.indexOf(IMPORTANT_FLAG);
13345 if (overrideIndex !== -1) {
13346 name = overrideIndex > 0 ? name.substring(0, overrideIndex) : '';
13347 hasOverrideFlag = true;
13348 }
13349 var unit = '';
13350 var property = name;
13351 var unitIndex = name.lastIndexOf('.');
13352 if (unitIndex > 0) {
13353 unit = name.substr(unitIndex + 1);
13354 property = name.substring(0, unitIndex);
13355 }
13356 return { property: property, unit: unit, hasOverrideFlag: hasOverrideFlag };
13357}
13358/**
13359 * Gets the instruction to generate for an interpolated class map.
13360 * @param interpolation An Interpolation AST
13361 */
13362function getClassMapInterpolationExpression(interpolation) {
13363 switch (getInterpolationArgsLength(interpolation)) {
13364 case 1:
13365 return Identifiers$1.classMap;
13366 case 3:
13367 return Identifiers$1.classMapInterpolate1;
13368 case 5:
13369 return Identifiers$1.classMapInterpolate2;
13370 case 7:
13371 return Identifiers$1.classMapInterpolate3;
13372 case 9:
13373 return Identifiers$1.classMapInterpolate4;
13374 case 11:
13375 return Identifiers$1.classMapInterpolate5;
13376 case 13:
13377 return Identifiers$1.classMapInterpolate6;
13378 case 15:
13379 return Identifiers$1.classMapInterpolate7;
13380 case 17:
13381 return Identifiers$1.classMapInterpolate8;
13382 default:
13383 return Identifiers$1.classMapInterpolateV;
13384 }
13385}
13386/**
13387 * Gets the instruction to generate for an interpolated style prop.
13388 * @param interpolation An Interpolation AST
13389 */
13390function getStylePropInterpolationExpression(interpolation) {
13391 switch (getInterpolationArgsLength(interpolation)) {
13392 case 1:
13393 return Identifiers$1.styleProp;
13394 case 3:
13395 return Identifiers$1.stylePropInterpolate1;
13396 case 5:
13397 return Identifiers$1.stylePropInterpolate2;
13398 case 7:
13399 return Identifiers$1.stylePropInterpolate3;
13400 case 9:
13401 return Identifiers$1.stylePropInterpolate4;
13402 case 11:
13403 return Identifiers$1.stylePropInterpolate5;
13404 case 13:
13405 return Identifiers$1.stylePropInterpolate6;
13406 case 15:
13407 return Identifiers$1.stylePropInterpolate7;
13408 case 17:
13409 return Identifiers$1.stylePropInterpolate8;
13410 default:
13411 return Identifiers$1.stylePropInterpolateV;
13412 }
13413}
13414function normalizePropName(prop) {
13415 return hyphenate(prop);
13416}
13417
13418/**
13419 * @license
13420 * Copyright Google Inc. All Rights Reserved.
13421 *
13422 * Use of this source code is governed by an MIT-style license that can be
13423 * found in the LICENSE file at https://angular.io/license
13424 */
13425var TokenType$1;
13426(function (TokenType) {
13427 TokenType[TokenType["Character"] = 0] = "Character";
13428 TokenType[TokenType["Identifier"] = 1] = "Identifier";
13429 TokenType[TokenType["Keyword"] = 2] = "Keyword";
13430 TokenType[TokenType["String"] = 3] = "String";
13431 TokenType[TokenType["Operator"] = 4] = "Operator";
13432 TokenType[TokenType["Number"] = 5] = "Number";
13433 TokenType[TokenType["Error"] = 6] = "Error";
13434})(TokenType$1 || (TokenType$1 = {}));
13435var KEYWORDS = ['var', 'let', 'as', 'null', 'undefined', 'true', 'false', 'if', 'else', 'this'];
13436var Lexer = /** @class */ (function () {
13437 function Lexer() {
13438 }
13439 Lexer.prototype.tokenize = function (text) {
13440 var scanner = new _Scanner(text);
13441 var tokens = [];
13442 var token = scanner.scanToken();
13443 while (token != null) {
13444 tokens.push(token);
13445 token = scanner.scanToken();
13446 }
13447 return tokens;
13448 };
13449 return Lexer;
13450}());
13451var Token$1 = /** @class */ (function () {
13452 function Token(index, type, numValue, strValue) {
13453 this.index = index;
13454 this.type = type;
13455 this.numValue = numValue;
13456 this.strValue = strValue;
13457 }
13458 Token.prototype.isCharacter = function (code) {
13459 return this.type == TokenType$1.Character && this.numValue == code;
13460 };
13461 Token.prototype.isNumber = function () { return this.type == TokenType$1.Number; };
13462 Token.prototype.isString = function () { return this.type == TokenType$1.String; };
13463 Token.prototype.isOperator = function (operator) {
13464 return this.type == TokenType$1.Operator && this.strValue == operator;
13465 };
13466 Token.prototype.isIdentifier = function () { return this.type == TokenType$1.Identifier; };
13467 Token.prototype.isKeyword = function () { return this.type == TokenType$1.Keyword; };
13468 Token.prototype.isKeywordLet = function () { return this.type == TokenType$1.Keyword && this.strValue == 'let'; };
13469 Token.prototype.isKeywordAs = function () { return this.type == TokenType$1.Keyword && this.strValue == 'as'; };
13470 Token.prototype.isKeywordNull = function () { return this.type == TokenType$1.Keyword && this.strValue == 'null'; };
13471 Token.prototype.isKeywordUndefined = function () {
13472 return this.type == TokenType$1.Keyword && this.strValue == 'undefined';
13473 };
13474 Token.prototype.isKeywordTrue = function () { return this.type == TokenType$1.Keyword && this.strValue == 'true'; };
13475 Token.prototype.isKeywordFalse = function () { return this.type == TokenType$1.Keyword && this.strValue == 'false'; };
13476 Token.prototype.isKeywordThis = function () { return this.type == TokenType$1.Keyword && this.strValue == 'this'; };
13477 Token.prototype.isError = function () { return this.type == TokenType$1.Error; };
13478 Token.prototype.toNumber = function () { return this.type == TokenType$1.Number ? this.numValue : -1; };
13479 Token.prototype.toString = function () {
13480 switch (this.type) {
13481 case TokenType$1.Character:
13482 case TokenType$1.Identifier:
13483 case TokenType$1.Keyword:
13484 case TokenType$1.Operator:
13485 case TokenType$1.String:
13486 case TokenType$1.Error:
13487 return this.strValue;
13488 case TokenType$1.Number:
13489 return this.numValue.toString();
13490 default:
13491 return null;
13492 }
13493 };
13494 return Token;
13495}());
13496function newCharacterToken(index, code) {
13497 return new Token$1(index, TokenType$1.Character, code, String.fromCharCode(code));
13498}
13499function newIdentifierToken(index, text) {
13500 return new Token$1(index, TokenType$1.Identifier, 0, text);
13501}
13502function newKeywordToken(index, text) {
13503 return new Token$1(index, TokenType$1.Keyword, 0, text);
13504}
13505function newOperatorToken(index, text) {
13506 return new Token$1(index, TokenType$1.Operator, 0, text);
13507}
13508function newStringToken(index, text) {
13509 return new Token$1(index, TokenType$1.String, 0, text);
13510}
13511function newNumberToken(index, n) {
13512 return new Token$1(index, TokenType$1.Number, n, '');
13513}
13514function newErrorToken(index, message) {
13515 return new Token$1(index, TokenType$1.Error, 0, message);
13516}
13517var EOF = new Token$1(-1, TokenType$1.Character, 0, '');
13518var _Scanner = /** @class */ (function () {
13519 function _Scanner(input) {
13520 this.input = input;
13521 this.peek = 0;
13522 this.index = -1;
13523 this.length = input.length;
13524 this.advance();
13525 }
13526 _Scanner.prototype.advance = function () {
13527 this.peek = ++this.index >= this.length ? $EOF : this.input.charCodeAt(this.index);
13528 };
13529 _Scanner.prototype.scanToken = function () {
13530 var input = this.input, length = this.length;
13531 var peek = this.peek, index = this.index;
13532 // Skip whitespace.
13533 while (peek <= $SPACE) {
13534 if (++index >= length) {
13535 peek = $EOF;
13536 break;
13537 }
13538 else {
13539 peek = input.charCodeAt(index);
13540 }
13541 }
13542 this.peek = peek;
13543 this.index = index;
13544 if (index >= length) {
13545 return null;
13546 }
13547 // Handle identifiers and numbers.
13548 if (isIdentifierStart(peek))
13549 return this.scanIdentifier();
13550 if (isDigit(peek))
13551 return this.scanNumber(index);
13552 var start = index;
13553 switch (peek) {
13554 case $PERIOD:
13555 this.advance();
13556 return isDigit(this.peek) ? this.scanNumber(start) :
13557 newCharacterToken(start, $PERIOD);
13558 case $LPAREN:
13559 case $RPAREN:
13560 case $LBRACE:
13561 case $RBRACE:
13562 case $LBRACKET:
13563 case $RBRACKET:
13564 case $COMMA:
13565 case $COLON:
13566 case $SEMICOLON:
13567 return this.scanCharacter(start, peek);
13568 case $SQ:
13569 case $DQ:
13570 return this.scanString();
13571 case $HASH:
13572 case $PLUS:
13573 case $MINUS:
13574 case $STAR:
13575 case $SLASH:
13576 case $PERCENT:
13577 case $CARET:
13578 return this.scanOperator(start, String.fromCharCode(peek));
13579 case $QUESTION:
13580 return this.scanComplexOperator(start, '?', $PERIOD, '.');
13581 case $LT:
13582 case $GT:
13583 return this.scanComplexOperator(start, String.fromCharCode(peek), $EQ, '=');
13584 case $BANG:
13585 case $EQ:
13586 return this.scanComplexOperator(start, String.fromCharCode(peek), $EQ, '=', $EQ, '=');
13587 case $AMPERSAND:
13588 return this.scanComplexOperator(start, '&', $AMPERSAND, '&');
13589 case $BAR:
13590 return this.scanComplexOperator(start, '|', $BAR, '|');
13591 case $NBSP:
13592 while (isWhitespace(this.peek))
13593 this.advance();
13594 return this.scanToken();
13595 }
13596 this.advance();
13597 return this.error("Unexpected character [" + String.fromCharCode(peek) + "]", 0);
13598 };
13599 _Scanner.prototype.scanCharacter = function (start, code) {
13600 this.advance();
13601 return newCharacterToken(start, code);
13602 };
13603 _Scanner.prototype.scanOperator = function (start, str) {
13604 this.advance();
13605 return newOperatorToken(start, str);
13606 };
13607 /**
13608 * Tokenize a 2/3 char long operator
13609 *
13610 * @param start start index in the expression
13611 * @param one first symbol (always part of the operator)
13612 * @param twoCode code point for the second symbol
13613 * @param two second symbol (part of the operator when the second code point matches)
13614 * @param threeCode code point for the third symbol
13615 * @param three third symbol (part of the operator when provided and matches source expression)
13616 */
13617 _Scanner.prototype.scanComplexOperator = function (start, one, twoCode, two, threeCode, three) {
13618 this.advance();
13619 var str = one;
13620 if (this.peek == twoCode) {
13621 this.advance();
13622 str += two;
13623 }
13624 if (threeCode != null && this.peek == threeCode) {
13625 this.advance();
13626 str += three;
13627 }
13628 return newOperatorToken(start, str);
13629 };
13630 _Scanner.prototype.scanIdentifier = function () {
13631 var start = this.index;
13632 this.advance();
13633 while (isIdentifierPart(this.peek))
13634 this.advance();
13635 var str = this.input.substring(start, this.index);
13636 return KEYWORDS.indexOf(str) > -1 ? newKeywordToken(start, str) :
13637 newIdentifierToken(start, str);
13638 };
13639 _Scanner.prototype.scanNumber = function (start) {
13640 var simple = (this.index === start);
13641 this.advance(); // Skip initial digit.
13642 while (true) {
13643 if (isDigit(this.peek)) {
13644 // Do nothing.
13645 }
13646 else if (this.peek == $PERIOD) {
13647 simple = false;
13648 }
13649 else if (isExponentStart(this.peek)) {
13650 this.advance();
13651 if (isExponentSign(this.peek))
13652 this.advance();
13653 if (!isDigit(this.peek))
13654 return this.error('Invalid exponent', -1);
13655 simple = false;
13656 }
13657 else {
13658 break;
13659 }
13660 this.advance();
13661 }
13662 var str = this.input.substring(start, this.index);
13663 var value = simple ? parseIntAutoRadix(str) : parseFloat(str);
13664 return newNumberToken(start, value);
13665 };
13666 _Scanner.prototype.scanString = function () {
13667 var start = this.index;
13668 var quote = this.peek;
13669 this.advance(); // Skip initial quote.
13670 var buffer = '';
13671 var marker = this.index;
13672 var input = this.input;
13673 while (this.peek != quote) {
13674 if (this.peek == $BACKSLASH) {
13675 buffer += input.substring(marker, this.index);
13676 this.advance();
13677 var unescapedCode = void 0;
13678 // Workaround for TS2.1-introduced type strictness
13679 this.peek = this.peek;
13680 if (this.peek == $u) {
13681 // 4 character hex code for unicode character.
13682 var hex = input.substring(this.index + 1, this.index + 5);
13683 if (/^[0-9a-f]+$/i.test(hex)) {
13684 unescapedCode = parseInt(hex, 16);
13685 }
13686 else {
13687 return this.error("Invalid unicode escape [\\u" + hex + "]", 0);
13688 }
13689 for (var i = 0; i < 5; i++) {
13690 this.advance();
13691 }
13692 }
13693 else {
13694 unescapedCode = unescape(this.peek);
13695 this.advance();
13696 }
13697 buffer += String.fromCharCode(unescapedCode);
13698 marker = this.index;
13699 }
13700 else if (this.peek == $EOF) {
13701 return this.error('Unterminated quote', 0);
13702 }
13703 else {
13704 this.advance();
13705 }
13706 }
13707 var last = input.substring(marker, this.index);
13708 this.advance(); // Skip terminating quote.
13709 return newStringToken(start, buffer + last);
13710 };
13711 _Scanner.prototype.error = function (message, offset) {
13712 var position = this.index + offset;
13713 return newErrorToken(position, "Lexer Error: " + message + " at column " + position + " in expression [" + this.input + "]");
13714 };
13715 return _Scanner;
13716}());
13717function isIdentifierStart(code) {
13718 return ($a <= code && code <= $z) || ($A <= code && code <= $Z) ||
13719 (code == $_) || (code == $$);
13720}
13721function isIdentifier(input) {
13722 if (input.length == 0)
13723 return false;
13724 var scanner = new _Scanner(input);
13725 if (!isIdentifierStart(scanner.peek))
13726 return false;
13727 scanner.advance();
13728 while (scanner.peek !== $EOF) {
13729 if (!isIdentifierPart(scanner.peek))
13730 return false;
13731 scanner.advance();
13732 }
13733 return true;
13734}
13735function isIdentifierPart(code) {
13736 return isAsciiLetter(code) || isDigit(code) || (code == $_) ||
13737 (code == $$);
13738}
13739function isExponentStart(code) {
13740 return code == $e || code == $E;
13741}
13742function isExponentSign(code) {
13743 return code == $MINUS || code == $PLUS;
13744}
13745function isQuote(code) {
13746 return code === $SQ || code === $DQ || code === $BT;
13747}
13748function unescape(code) {
13749 switch (code) {
13750 case $n:
13751 return $LF;
13752 case $f:
13753 return $FF;
13754 case $r:
13755 return $CR;
13756 case $t:
13757 return $TAB;
13758 case $v:
13759 return $VTAB;
13760 default:
13761 return code;
13762 }
13763}
13764function parseIntAutoRadix(text) {
13765 var result = parseInt(text);
13766 if (isNaN(result)) {
13767 throw new Error('Invalid integer literal when parsing ' + text);
13768 }
13769 return result;
13770}
13771
13772/**
13773 * @license
13774 * Copyright Google Inc. All Rights Reserved.
13775 *
13776 * Use of this source code is governed by an MIT-style license that can be
13777 * found in the LICENSE file at https://angular.io/license
13778 */
13779var SplitInterpolation = /** @class */ (function () {
13780 function SplitInterpolation(strings, expressions, offsets) {
13781 this.strings = strings;
13782 this.expressions = expressions;
13783 this.offsets = offsets;
13784 }
13785 return SplitInterpolation;
13786}());
13787var TemplateBindingParseResult = /** @class */ (function () {
13788 function TemplateBindingParseResult(templateBindings, warnings, errors) {
13789 this.templateBindings = templateBindings;
13790 this.warnings = warnings;
13791 this.errors = errors;
13792 }
13793 return TemplateBindingParseResult;
13794}());
13795function _createInterpolateRegExp(config) {
13796 var pattern = escapeRegExp(config.start) + '([\\s\\S]*?)' + escapeRegExp(config.end);
13797 return new RegExp(pattern, 'g');
13798}
13799var Parser$1 = /** @class */ (function () {
13800 function Parser(_lexer) {
13801 this._lexer = _lexer;
13802 this.errors = [];
13803 }
13804 Parser.prototype.parseAction = function (input, location, absoluteOffset, interpolationConfig) {
13805 if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
13806 this._checkNoInterpolation(input, location, interpolationConfig);
13807 var sourceToLex = this._stripComments(input);
13808 var tokens = this._lexer.tokenize(this._stripComments(input));
13809 var ast = new _ParseAST(input, location, absoluteOffset, tokens, sourceToLex.length, true, this.errors, input.length - sourceToLex.length)
13810 .parseChain();
13811 return new ASTWithSource(ast, input, location, absoluteOffset, this.errors);
13812 };
13813 Parser.prototype.parseBinding = function (input, location, absoluteOffset, interpolationConfig) {
13814 if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
13815 var ast = this._parseBindingAst(input, location, absoluteOffset, interpolationConfig);
13816 return new ASTWithSource(ast, input, location, absoluteOffset, this.errors);
13817 };
13818 Parser.prototype.parseSimpleBinding = function (input, location, absoluteOffset, interpolationConfig) {
13819 if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
13820 var ast = this._parseBindingAst(input, location, absoluteOffset, interpolationConfig);
13821 var errors = SimpleExpressionChecker.check(ast);
13822 if (errors.length > 0) {
13823 this._reportError("Host binding expression cannot contain " + errors.join(' '), input, location);
13824 }
13825 return new ASTWithSource(ast, input, location, absoluteOffset, this.errors);
13826 };
13827 Parser.prototype._reportError = function (message, input, errLocation, ctxLocation) {
13828 this.errors.push(new ParserError(message, input, errLocation, ctxLocation));
13829 };
13830 Parser.prototype._parseBindingAst = function (input, location, absoluteOffset, interpolationConfig) {
13831 // Quotes expressions use 3rd-party expression language. We don't want to use
13832 // our lexer or parser for that, so we check for that ahead of time.
13833 var quote = this._parseQuote(input, location);
13834 if (quote != null) {
13835 return quote;
13836 }
13837 this._checkNoInterpolation(input, location, interpolationConfig);
13838 var sourceToLex = this._stripComments(input);
13839 var tokens = this._lexer.tokenize(sourceToLex);
13840 return new _ParseAST(input, location, absoluteOffset, tokens, sourceToLex.length, false, this.errors, input.length - sourceToLex.length)
13841 .parseChain();
13842 };
13843 Parser.prototype._parseQuote = function (input, location) {
13844 if (input == null)
13845 return null;
13846 var prefixSeparatorIndex = input.indexOf(':');
13847 if (prefixSeparatorIndex == -1)
13848 return null;
13849 var prefix = input.substring(0, prefixSeparatorIndex).trim();
13850 if (!isIdentifier(prefix))
13851 return null;
13852 var uninterpretedExpression = input.substring(prefixSeparatorIndex + 1);
13853 return new Quote(new ParseSpan(0, input.length), prefix, uninterpretedExpression, location);
13854 };
13855 Parser.prototype.parseTemplateBindings = function (tplKey, tplValue, location, absoluteOffset) {
13856 var tokens = this._lexer.tokenize(tplValue);
13857 return new _ParseAST(tplValue, location, absoluteOffset, tokens, tplValue.length, false, this.errors, 0)
13858 .parseTemplateBindings(tplKey);
13859 };
13860 Parser.prototype.parseInterpolation = function (input, location, absoluteOffset, interpolationConfig) {
13861 if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
13862 var split = this.splitInterpolation(input, location, interpolationConfig);
13863 if (split == null)
13864 return null;
13865 var expressions = [];
13866 for (var i = 0; i < split.expressions.length; ++i) {
13867 var expressionText = split.expressions[i];
13868 var sourceToLex = this._stripComments(expressionText);
13869 var tokens = this._lexer.tokenize(sourceToLex);
13870 var ast = new _ParseAST(input, location, absoluteOffset, tokens, sourceToLex.length, false, this.errors, split.offsets[i] + (expressionText.length - sourceToLex.length))
13871 .parseChain();
13872 expressions.push(ast);
13873 }
13874 return new ASTWithSource(new Interpolation(new ParseSpan(0, input == null ? 0 : input.length), split.strings, expressions), input, location, absoluteOffset, this.errors);
13875 };
13876 Parser.prototype.splitInterpolation = function (input, location, interpolationConfig) {
13877 if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
13878 var regexp = _createInterpolateRegExp(interpolationConfig);
13879 var parts = input.split(regexp);
13880 if (parts.length <= 1) {
13881 return null;
13882 }
13883 var strings = [];
13884 var expressions = [];
13885 var offsets = [];
13886 var offset = 0;
13887 for (var i = 0; i < parts.length; i++) {
13888 var part = parts[i];
13889 if (i % 2 === 0) {
13890 // fixed string
13891 strings.push(part);
13892 offset += part.length;
13893 }
13894 else if (part.trim().length > 0) {
13895 offset += interpolationConfig.start.length;
13896 expressions.push(part);
13897 offsets.push(offset);
13898 offset += part.length + interpolationConfig.end.length;
13899 }
13900 else {
13901 this._reportError('Blank expressions are not allowed in interpolated strings', input, "at column " + this._findInterpolationErrorColumn(parts, i, interpolationConfig) + " in", location);
13902 expressions.push('$implict');
13903 offsets.push(offset);
13904 }
13905 }
13906 return new SplitInterpolation(strings, expressions, offsets);
13907 };
13908 Parser.prototype.wrapLiteralPrimitive = function (input, location, absoluteOffset) {
13909 return new ASTWithSource(new LiteralPrimitive(new ParseSpan(0, input == null ? 0 : input.length), input), input, location, absoluteOffset, this.errors);
13910 };
13911 Parser.prototype._stripComments = function (input) {
13912 var i = this._commentStart(input);
13913 return i != null ? input.substring(0, i).trim() : input;
13914 };
13915 Parser.prototype._commentStart = function (input) {
13916 var outerQuote = null;
13917 for (var i = 0; i < input.length - 1; i++) {
13918 var char = input.charCodeAt(i);
13919 var nextChar = input.charCodeAt(i + 1);
13920 if (char === $SLASH && nextChar == $SLASH && outerQuote == null)
13921 return i;
13922 if (outerQuote === char) {
13923 outerQuote = null;
13924 }
13925 else if (outerQuote == null && isQuote(char)) {
13926 outerQuote = char;
13927 }
13928 }
13929 return null;
13930 };
13931 Parser.prototype._checkNoInterpolation = function (input, location, interpolationConfig) {
13932 var regexp = _createInterpolateRegExp(interpolationConfig);
13933 var parts = input.split(regexp);
13934 if (parts.length > 1) {
13935 this._reportError("Got interpolation (" + interpolationConfig.start + interpolationConfig.end + ") where expression was expected", input, "at column " + this._findInterpolationErrorColumn(parts, 1, interpolationConfig) + " in", location);
13936 }
13937 };
13938 Parser.prototype._findInterpolationErrorColumn = function (parts, partInErrIdx, interpolationConfig) {
13939 var errLocation = '';
13940 for (var j = 0; j < partInErrIdx; j++) {
13941 errLocation += j % 2 === 0 ?
13942 parts[j] :
13943 "" + interpolationConfig.start + parts[j] + interpolationConfig.end;
13944 }
13945 return errLocation.length;
13946 };
13947 return Parser;
13948}());
13949var _ParseAST = /** @class */ (function () {
13950 function _ParseAST(input, location, absoluteOffset, tokens, inputLength, parseAction, errors, offset) {
13951 this.input = input;
13952 this.location = location;
13953 this.absoluteOffset = absoluteOffset;
13954 this.tokens = tokens;
13955 this.inputLength = inputLength;
13956 this.parseAction = parseAction;
13957 this.errors = errors;
13958 this.offset = offset;
13959 this.rparensExpected = 0;
13960 this.rbracketsExpected = 0;
13961 this.rbracesExpected = 0;
13962 this.index = 0;
13963 }
13964 _ParseAST.prototype.peek = function (offset) {
13965 var i = this.index + offset;
13966 return i < this.tokens.length ? this.tokens[i] : EOF;
13967 };
13968 Object.defineProperty(_ParseAST.prototype, "next", {
13969 get: function () { return this.peek(0); },
13970 enumerable: true,
13971 configurable: true
13972 });
13973 Object.defineProperty(_ParseAST.prototype, "inputIndex", {
13974 get: function () {
13975 return (this.index < this.tokens.length) ? this.next.index + this.offset :
13976 this.inputLength + this.offset;
13977 },
13978 enumerable: true,
13979 configurable: true
13980 });
13981 _ParseAST.prototype.span = function (start) { return new ParseSpan(start, this.inputIndex); };
13982 _ParseAST.prototype.advance = function () { this.index++; };
13983 _ParseAST.prototype.optionalCharacter = function (code) {
13984 if (this.next.isCharacter(code)) {
13985 this.advance();
13986 return true;
13987 }
13988 else {
13989 return false;
13990 }
13991 };
13992 _ParseAST.prototype.peekKeywordLet = function () { return this.next.isKeywordLet(); };
13993 _ParseAST.prototype.peekKeywordAs = function () { return this.next.isKeywordAs(); };
13994 _ParseAST.prototype.expectCharacter = function (code) {
13995 if (this.optionalCharacter(code))
13996 return;
13997 this.error("Missing expected " + String.fromCharCode(code));
13998 };
13999 _ParseAST.prototype.optionalOperator = function (op) {
14000 if (this.next.isOperator(op)) {
14001 this.advance();
14002 return true;
14003 }
14004 else {
14005 return false;
14006 }
14007 };
14008 _ParseAST.prototype.expectOperator = function (operator) {
14009 if (this.optionalOperator(operator))
14010 return;
14011 this.error("Missing expected operator " + operator);
14012 };
14013 _ParseAST.prototype.expectIdentifierOrKeyword = function () {
14014 var n = this.next;
14015 if (!n.isIdentifier() && !n.isKeyword()) {
14016 this.error("Unexpected token " + n + ", expected identifier or keyword");
14017 return '';
14018 }
14019 this.advance();
14020 return n.toString();
14021 };
14022 _ParseAST.prototype.expectIdentifierOrKeywordOrString = function () {
14023 var n = this.next;
14024 if (!n.isIdentifier() && !n.isKeyword() && !n.isString()) {
14025 this.error("Unexpected token " + n + ", expected identifier, keyword, or string");
14026 return '';
14027 }
14028 this.advance();
14029 return n.toString();
14030 };
14031 _ParseAST.prototype.parseChain = function () {
14032 var exprs = [];
14033 var start = this.inputIndex;
14034 while (this.index < this.tokens.length) {
14035 var expr = this.parsePipe();
14036 exprs.push(expr);
14037 if (this.optionalCharacter($SEMICOLON)) {
14038 if (!this.parseAction) {
14039 this.error('Binding expression cannot contain chained expression');
14040 }
14041 while (this.optionalCharacter($SEMICOLON)) {
14042 } // read all semicolons
14043 }
14044 else if (this.index < this.tokens.length) {
14045 this.error("Unexpected token '" + this.next + "'");
14046 }
14047 }
14048 if (exprs.length == 0)
14049 return new EmptyExpr(this.span(start));
14050 if (exprs.length == 1)
14051 return exprs[0];
14052 return new Chain(this.span(start), exprs);
14053 };
14054 _ParseAST.prototype.parsePipe = function () {
14055 var result = this.parseExpression();
14056 if (this.optionalOperator('|')) {
14057 if (this.parseAction) {
14058 this.error('Cannot have a pipe in an action expression');
14059 }
14060 do {
14061 var name_1 = this.expectIdentifierOrKeyword();
14062 var args = [];
14063 while (this.optionalCharacter($COLON)) {
14064 args.push(this.parseExpression());
14065 }
14066 result = new BindingPipe(this.span(result.span.start), result, name_1, args);
14067 } while (this.optionalOperator('|'));
14068 }
14069 return result;
14070 };
14071 _ParseAST.prototype.parseExpression = function () { return this.parseConditional(); };
14072 _ParseAST.prototype.parseConditional = function () {
14073 var start = this.inputIndex;
14074 var result = this.parseLogicalOr();
14075 if (this.optionalOperator('?')) {
14076 var yes = this.parsePipe();
14077 var no = void 0;
14078 if (!this.optionalCharacter($COLON)) {
14079 var end = this.inputIndex;
14080 var expression = this.input.substring(start, end);
14081 this.error("Conditional expression " + expression + " requires all 3 expressions");
14082 no = new EmptyExpr(this.span(start));
14083 }
14084 else {
14085 no = this.parsePipe();
14086 }
14087 return new Conditional(this.span(start), result, yes, no);
14088 }
14089 else {
14090 return result;
14091 }
14092 };
14093 _ParseAST.prototype.parseLogicalOr = function () {
14094 // '||'
14095 var result = this.parseLogicalAnd();
14096 while (this.optionalOperator('||')) {
14097 var right = this.parseLogicalAnd();
14098 result = new Binary(this.span(result.span.start), '||', result, right);
14099 }
14100 return result;
14101 };
14102 _ParseAST.prototype.parseLogicalAnd = function () {
14103 // '&&'
14104 var result = this.parseEquality();
14105 while (this.optionalOperator('&&')) {
14106 var right = this.parseEquality();
14107 result = new Binary(this.span(result.span.start), '&&', result, right);
14108 }
14109 return result;
14110 };
14111 _ParseAST.prototype.parseEquality = function () {
14112 // '==','!=','===','!=='
14113 var result = this.parseRelational();
14114 while (this.next.type == TokenType$1.Operator) {
14115 var operator = this.next.strValue;
14116 switch (operator) {
14117 case '==':
14118 case '===':
14119 case '!=':
14120 case '!==':
14121 this.advance();
14122 var right = this.parseRelational();
14123 result = new Binary(this.span(result.span.start), operator, result, right);
14124 continue;
14125 }
14126 break;
14127 }
14128 return result;
14129 };
14130 _ParseAST.prototype.parseRelational = function () {
14131 // '<', '>', '<=', '>='
14132 var result = this.parseAdditive();
14133 while (this.next.type == TokenType$1.Operator) {
14134 var operator = this.next.strValue;
14135 switch (operator) {
14136 case '<':
14137 case '>':
14138 case '<=':
14139 case '>=':
14140 this.advance();
14141 var right = this.parseAdditive();
14142 result = new Binary(this.span(result.span.start), operator, result, right);
14143 continue;
14144 }
14145 break;
14146 }
14147 return result;
14148 };
14149 _ParseAST.prototype.parseAdditive = function () {
14150 // '+', '-'
14151 var result = this.parseMultiplicative();
14152 while (this.next.type == TokenType$1.Operator) {
14153 var operator = this.next.strValue;
14154 switch (operator) {
14155 case '+':
14156 case '-':
14157 this.advance();
14158 var right = this.parseMultiplicative();
14159 result = new Binary(this.span(result.span.start), operator, result, right);
14160 continue;
14161 }
14162 break;
14163 }
14164 return result;
14165 };
14166 _ParseAST.prototype.parseMultiplicative = function () {
14167 // '*', '%', '/'
14168 var result = this.parsePrefix();
14169 while (this.next.type == TokenType$1.Operator) {
14170 var operator = this.next.strValue;
14171 switch (operator) {
14172 case '*':
14173 case '%':
14174 case '/':
14175 this.advance();
14176 var right = this.parsePrefix();
14177 result = new Binary(this.span(result.span.start), operator, result, right);
14178 continue;
14179 }
14180 break;
14181 }
14182 return result;
14183 };
14184 _ParseAST.prototype.parsePrefix = function () {
14185 if (this.next.type == TokenType$1.Operator) {
14186 var start = this.inputIndex;
14187 var operator = this.next.strValue;
14188 var result = void 0;
14189 switch (operator) {
14190 case '+':
14191 this.advance();
14192 result = this.parsePrefix();
14193 return new Binary(this.span(start), '-', result, new LiteralPrimitive(new ParseSpan(start, start), 0));
14194 case '-':
14195 this.advance();
14196 result = this.parsePrefix();
14197 return new Binary(this.span(start), operator, new LiteralPrimitive(new ParseSpan(start, start), 0), result);
14198 case '!':
14199 this.advance();
14200 result = this.parsePrefix();
14201 return new PrefixNot(this.span(start), result);
14202 }
14203 }
14204 return this.parseCallChain();
14205 };
14206 _ParseAST.prototype.parseCallChain = function () {
14207 var result = this.parsePrimary();
14208 while (true) {
14209 if (this.optionalCharacter($PERIOD)) {
14210 result = this.parseAccessMemberOrMethodCall(result, false);
14211 }
14212 else if (this.optionalOperator('?.')) {
14213 result = this.parseAccessMemberOrMethodCall(result, true);
14214 }
14215 else if (this.optionalCharacter($LBRACKET)) {
14216 this.rbracketsExpected++;
14217 var key = this.parsePipe();
14218 this.rbracketsExpected--;
14219 this.expectCharacter($RBRACKET);
14220 if (this.optionalOperator('=')) {
14221 var value = this.parseConditional();
14222 result = new KeyedWrite(this.span(result.span.start), result, key, value);
14223 }
14224 else {
14225 result = new KeyedRead(this.span(result.span.start), result, key);
14226 }
14227 }
14228 else if (this.optionalCharacter($LPAREN)) {
14229 this.rparensExpected++;
14230 var args = this.parseCallArguments();
14231 this.rparensExpected--;
14232 this.expectCharacter($RPAREN);
14233 result = new FunctionCall(this.span(result.span.start), result, args);
14234 }
14235 else if (this.optionalOperator('!')) {
14236 result = new NonNullAssert(this.span(result.span.start), result);
14237 }
14238 else {
14239 return result;
14240 }
14241 }
14242 };
14243 _ParseAST.prototype.parsePrimary = function () {
14244 var start = this.inputIndex;
14245 if (this.optionalCharacter($LPAREN)) {
14246 this.rparensExpected++;
14247 var result = this.parsePipe();
14248 this.rparensExpected--;
14249 this.expectCharacter($RPAREN);
14250 return result;
14251 }
14252 else if (this.next.isKeywordNull()) {
14253 this.advance();
14254 return new LiteralPrimitive(this.span(start), null);
14255 }
14256 else if (this.next.isKeywordUndefined()) {
14257 this.advance();
14258 return new LiteralPrimitive(this.span(start), void 0);
14259 }
14260 else if (this.next.isKeywordTrue()) {
14261 this.advance();
14262 return new LiteralPrimitive(this.span(start), true);
14263 }
14264 else if (this.next.isKeywordFalse()) {
14265 this.advance();
14266 return new LiteralPrimitive(this.span(start), false);
14267 }
14268 else if (this.next.isKeywordThis()) {
14269 this.advance();
14270 return new ImplicitReceiver(this.span(start));
14271 }
14272 else if (this.optionalCharacter($LBRACKET)) {
14273 this.rbracketsExpected++;
14274 var elements = this.parseExpressionList($RBRACKET);
14275 this.rbracketsExpected--;
14276 this.expectCharacter($RBRACKET);
14277 return new LiteralArray(this.span(start), elements);
14278 }
14279 else if (this.next.isCharacter($LBRACE)) {
14280 return this.parseLiteralMap();
14281 }
14282 else if (this.next.isIdentifier()) {
14283 return this.parseAccessMemberOrMethodCall(new ImplicitReceiver(this.span(start)), false);
14284 }
14285 else if (this.next.isNumber()) {
14286 var value = this.next.toNumber();
14287 this.advance();
14288 return new LiteralPrimitive(this.span(start), value);
14289 }
14290 else if (this.next.isString()) {
14291 var literalValue = this.next.toString();
14292 this.advance();
14293 return new LiteralPrimitive(this.span(start), literalValue);
14294 }
14295 else if (this.index >= this.tokens.length) {
14296 this.error("Unexpected end of expression: " + this.input);
14297 return new EmptyExpr(this.span(start));
14298 }
14299 else {
14300 this.error("Unexpected token " + this.next);
14301 return new EmptyExpr(this.span(start));
14302 }
14303 };
14304 _ParseAST.prototype.parseExpressionList = function (terminator) {
14305 var result = [];
14306 if (!this.next.isCharacter(terminator)) {
14307 do {
14308 result.push(this.parsePipe());
14309 } while (this.optionalCharacter($COMMA));
14310 }
14311 return result;
14312 };
14313 _ParseAST.prototype.parseLiteralMap = function () {
14314 var keys = [];
14315 var values = [];
14316 var start = this.inputIndex;
14317 this.expectCharacter($LBRACE);
14318 if (!this.optionalCharacter($RBRACE)) {
14319 this.rbracesExpected++;
14320 do {
14321 var quoted = this.next.isString();
14322 var key = this.expectIdentifierOrKeywordOrString();
14323 keys.push({ key: key, quoted: quoted });
14324 this.expectCharacter($COLON);
14325 values.push(this.parsePipe());
14326 } while (this.optionalCharacter($COMMA));
14327 this.rbracesExpected--;
14328 this.expectCharacter($RBRACE);
14329 }
14330 return new LiteralMap(this.span(start), keys, values);
14331 };
14332 _ParseAST.prototype.parseAccessMemberOrMethodCall = function (receiver, isSafe) {
14333 if (isSafe === void 0) { isSafe = false; }
14334 var start = receiver.span.start;
14335 var id = this.expectIdentifierOrKeyword();
14336 if (this.optionalCharacter($LPAREN)) {
14337 this.rparensExpected++;
14338 var args = this.parseCallArguments();
14339 this.expectCharacter($RPAREN);
14340 this.rparensExpected--;
14341 var span = this.span(start);
14342 return isSafe ? new SafeMethodCall(span, receiver, id, args) :
14343 new MethodCall(span, receiver, id, args);
14344 }
14345 else {
14346 if (isSafe) {
14347 if (this.optionalOperator('=')) {
14348 this.error('The \'?.\' operator cannot be used in the assignment');
14349 return new EmptyExpr(this.span(start));
14350 }
14351 else {
14352 return new SafePropertyRead(this.span(start), receiver, id);
14353 }
14354 }
14355 else {
14356 if (this.optionalOperator('=')) {
14357 if (!this.parseAction) {
14358 this.error('Bindings cannot contain assignments');
14359 return new EmptyExpr(this.span(start));
14360 }
14361 var value = this.parseConditional();
14362 return new PropertyWrite(this.span(start), receiver, id, value);
14363 }
14364 else {
14365 return new PropertyRead(this.span(start), receiver, id);
14366 }
14367 }
14368 }
14369 };
14370 _ParseAST.prototype.parseCallArguments = function () {
14371 if (this.next.isCharacter($RPAREN))
14372 return [];
14373 var positionals = [];
14374 do {
14375 positionals.push(this.parsePipe());
14376 } while (this.optionalCharacter($COMMA));
14377 return positionals;
14378 };
14379 /**
14380 * An identifier, a keyword, a string with an optional `-` in between.
14381 */
14382 _ParseAST.prototype.expectTemplateBindingKey = function () {
14383 var result = '';
14384 var operatorFound = false;
14385 do {
14386 result += this.expectIdentifierOrKeywordOrString();
14387 operatorFound = this.optionalOperator('-');
14388 if (operatorFound) {
14389 result += '-';
14390 }
14391 } while (operatorFound);
14392 return result.toString();
14393 };
14394 // Parses the AST for `<some-tag *tplKey=AST>`
14395 _ParseAST.prototype.parseTemplateBindings = function (tplKey) {
14396 var firstBinding = true;
14397 var bindings = [];
14398 var warnings = [];
14399 do {
14400 var start = this.inputIndex;
14401 var rawKey = void 0;
14402 var key = void 0;
14403 var isVar = false;
14404 if (firstBinding) {
14405 rawKey = key = tplKey;
14406 firstBinding = false;
14407 }
14408 else {
14409 isVar = this.peekKeywordLet();
14410 if (isVar)
14411 this.advance();
14412 rawKey = this.expectTemplateBindingKey();
14413 key = isVar ? rawKey : tplKey + rawKey[0].toUpperCase() + rawKey.substring(1);
14414 this.optionalCharacter($COLON);
14415 }
14416 var name_2 = null;
14417 var expression = null;
14418 if (isVar) {
14419 if (this.optionalOperator('=')) {
14420 name_2 = this.expectTemplateBindingKey();
14421 }
14422 else {
14423 name_2 = '\$implicit';
14424 }
14425 }
14426 else if (this.peekKeywordAs()) {
14427 this.advance(); // consume `as`
14428 name_2 = rawKey;
14429 key = this.expectTemplateBindingKey(); // read local var name
14430 isVar = true;
14431 }
14432 else if (this.next !== EOF && !this.peekKeywordLet()) {
14433 var start_1 = this.inputIndex;
14434 var ast = this.parsePipe();
14435 var source = this.input.substring(start_1 - this.offset, this.inputIndex - this.offset);
14436 expression =
14437 new ASTWithSource(ast, source, this.location, this.absoluteOffset, this.errors);
14438 }
14439 bindings.push(new TemplateBinding(this.span(start), key, isVar, name_2, expression));
14440 if (this.peekKeywordAs() && !isVar) {
14441 var letStart = this.inputIndex;
14442 this.advance(); // consume `as`
14443 var letName = this.expectTemplateBindingKey(); // read local var name
14444 bindings.push(new TemplateBinding(this.span(letStart), letName, true, key, null));
14445 }
14446 if (!this.optionalCharacter($SEMICOLON)) {
14447 this.optionalCharacter($COMMA);
14448 }
14449 } while (this.index < this.tokens.length);
14450 return new TemplateBindingParseResult(bindings, warnings, this.errors);
14451 };
14452 _ParseAST.prototype.error = function (message, index) {
14453 if (index === void 0) { index = null; }
14454 this.errors.push(new ParserError(message, this.input, this.locationText(index), this.location));
14455 this.skip();
14456 };
14457 _ParseAST.prototype.locationText = function (index) {
14458 if (index === void 0) { index = null; }
14459 if (index == null)
14460 index = this.index;
14461 return (index < this.tokens.length) ? "at column " + (this.tokens[index].index + 1) + " in" :
14462 "at the end of the expression";
14463 };
14464 // Error recovery should skip tokens until it encounters a recovery point. skip() treats
14465 // the end of input and a ';' as unconditionally a recovery point. It also treats ')',
14466 // '}' and ']' as conditional recovery points if one of calling productions is expecting
14467 // one of these symbols. This allows skip() to recover from errors such as '(a.) + 1' allowing
14468 // more of the AST to be retained (it doesn't skip any tokens as the ')' is retained because
14469 // of the '(' begins an '(' <expr> ')' production). The recovery points of grouping symbols
14470 // must be conditional as they must be skipped if none of the calling productions are not
14471 // expecting the closing token else we will never make progress in the case of an
14472 // extraneous group closing symbol (such as a stray ')'). This is not the case for ';' because
14473 // parseChain() is always the root production and it expects a ';'.
14474 // If a production expects one of these token it increments the corresponding nesting count,
14475 // and then decrements it just prior to checking if the token is in the input.
14476 _ParseAST.prototype.skip = function () {
14477 var n = this.next;
14478 while (this.index < this.tokens.length && !n.isCharacter($SEMICOLON) &&
14479 (this.rparensExpected <= 0 || !n.isCharacter($RPAREN)) &&
14480 (this.rbracesExpected <= 0 || !n.isCharacter($RBRACE)) &&
14481 (this.rbracketsExpected <= 0 || !n.isCharacter($RBRACKET))) {
14482 if (this.next.isError()) {
14483 this.errors.push(new ParserError(this.next.toString(), this.input, this.locationText(), this.location));
14484 }
14485 this.advance();
14486 n = this.next;
14487 }
14488 };
14489 return _ParseAST;
14490}());
14491var SimpleExpressionChecker = /** @class */ (function () {
14492 function SimpleExpressionChecker() {
14493 this.errors = [];
14494 }
14495 SimpleExpressionChecker.check = function (ast) {
14496 var s = new SimpleExpressionChecker();
14497 ast.visit(s);
14498 return s.errors;
14499 };
14500 SimpleExpressionChecker.prototype.visitImplicitReceiver = function (ast, context) { };
14501 SimpleExpressionChecker.prototype.visitInterpolation = function (ast, context) { };
14502 SimpleExpressionChecker.prototype.visitLiteralPrimitive = function (ast, context) { };
14503 SimpleExpressionChecker.prototype.visitPropertyRead = function (ast, context) { };
14504 SimpleExpressionChecker.prototype.visitPropertyWrite = function (ast, context) { };
14505 SimpleExpressionChecker.prototype.visitSafePropertyRead = function (ast, context) { };
14506 SimpleExpressionChecker.prototype.visitMethodCall = function (ast, context) { };
14507 SimpleExpressionChecker.prototype.visitSafeMethodCall = function (ast, context) { };
14508 SimpleExpressionChecker.prototype.visitFunctionCall = function (ast, context) { };
14509 SimpleExpressionChecker.prototype.visitLiteralArray = function (ast, context) { this.visitAll(ast.expressions); };
14510 SimpleExpressionChecker.prototype.visitLiteralMap = function (ast, context) { this.visitAll(ast.values); };
14511 SimpleExpressionChecker.prototype.visitBinary = function (ast, context) { };
14512 SimpleExpressionChecker.prototype.visitPrefixNot = function (ast, context) { };
14513 SimpleExpressionChecker.prototype.visitNonNullAssert = function (ast, context) { };
14514 SimpleExpressionChecker.prototype.visitConditional = function (ast, context) { };
14515 SimpleExpressionChecker.prototype.visitPipe = function (ast, context) { this.errors.push('pipes'); };
14516 SimpleExpressionChecker.prototype.visitKeyedRead = function (ast, context) { };
14517 SimpleExpressionChecker.prototype.visitKeyedWrite = function (ast, context) { };
14518 SimpleExpressionChecker.prototype.visitAll = function (asts) {
14519 var _this = this;
14520 return asts.map(function (node) { return node.visit(_this); });
14521 };
14522 SimpleExpressionChecker.prototype.visitChain = function (ast, context) { };
14523 SimpleExpressionChecker.prototype.visitQuote = function (ast, context) { };
14524 return SimpleExpressionChecker;
14525}());
14526
14527/**
14528 * @license
14529 * Copyright Google Inc. All Rights Reserved.
14530 *
14531 * Use of this source code is governed by an MIT-style license that can be
14532 * found in the LICENSE file at https://angular.io/license
14533 */
14534// =================================================================================================
14535// =================================================================================================
14536// =========== S T O P - S T O P - S T O P - S T O P - S T O P - S T O P ===========
14537// =================================================================================================
14538// =================================================================================================
14539//
14540// DO NOT EDIT THIS LIST OF SECURITY SENSITIVE PROPERTIES WITHOUT A SECURITY REVIEW!
14541// Reach out to mprobst for details.
14542//
14543// =================================================================================================
14544/** Map from tagName|propertyName SecurityContext. Properties applying to all tags use '*'. */
14545var _SECURITY_SCHEMA;
14546function SECURITY_SCHEMA() {
14547 if (!_SECURITY_SCHEMA) {
14548 _SECURITY_SCHEMA = {};
14549 // Case is insignificant below, all element and attribute names are lower-cased for lookup.
14550 registerContext(SecurityContext.HTML, [
14551 'iframe|srcdoc',
14552 '*|innerHTML',
14553 '*|outerHTML',
14554 ]);
14555 registerContext(SecurityContext.STYLE, ['*|style']);
14556 // NB: no SCRIPT contexts here, they are never allowed due to the parser stripping them.
14557 registerContext(SecurityContext.URL, [
14558 '*|formAction', 'area|href', 'area|ping', 'audio|src', 'a|href',
14559 'a|ping', 'blockquote|cite', 'body|background', 'del|cite', 'form|action',
14560 'img|src', 'img|srcset', 'input|src', 'ins|cite', 'q|cite',
14561 'source|src', 'source|srcset', 'track|src', 'video|poster', 'video|src',
14562 ]);
14563 registerContext(SecurityContext.RESOURCE_URL, [
14564 'applet|code',
14565 'applet|codebase',
14566 'base|href',
14567 'embed|src',
14568 'frame|src',
14569 'head|profile',
14570 'html|manifest',
14571 'iframe|src',
14572 'link|href',
14573 'media|src',
14574 'object|codebase',
14575 'object|data',
14576 'script|src',
14577 ]);
14578 }
14579 return _SECURITY_SCHEMA;
14580}
14581function registerContext(ctx, specs) {
14582 var e_1, _a;
14583 try {
14584 for (var specs_1 = __values(specs), specs_1_1 = specs_1.next(); !specs_1_1.done; specs_1_1 = specs_1.next()) {
14585 var spec = specs_1_1.value;
14586 _SECURITY_SCHEMA[spec.toLowerCase()] = ctx;
14587 }
14588 }
14589 catch (e_1_1) { e_1 = { error: e_1_1 }; }
14590 finally {
14591 try {
14592 if (specs_1_1 && !specs_1_1.done && (_a = specs_1.return)) _a.call(specs_1);
14593 }
14594 finally { if (e_1) throw e_1.error; }
14595 }
14596}
14597
14598/**
14599 * @license
14600 * Copyright Google Inc. All Rights Reserved.
14601 *
14602 * Use of this source code is governed by an MIT-style license that can be
14603 * found in the LICENSE file at https://angular.io/license
14604 */
14605var ElementSchemaRegistry = /** @class */ (function () {
14606 function ElementSchemaRegistry() {
14607 }
14608 return ElementSchemaRegistry;
14609}());
14610
14611/**
14612 * @license
14613 * Copyright Google Inc. All Rights Reserved.
14614 *
14615 * Use of this source code is governed by an MIT-style license that can be
14616 * found in the LICENSE file at https://angular.io/license
14617 */
14618var BOOLEAN = 'boolean';
14619var NUMBER = 'number';
14620var STRING = 'string';
14621var OBJECT = 'object';
14622/**
14623 * This array represents the DOM schema. It encodes inheritance, properties, and events.
14624 *
14625 * ## Overview
14626 *
14627 * Each line represents one kind of element. The `element_inheritance` and properties are joined
14628 * using `element_inheritance|properties` syntax.
14629 *
14630 * ## Element Inheritance
14631 *
14632 * The `element_inheritance` can be further subdivided as `element1,element2,...^parentElement`.
14633 * Here the individual elements are separated by `,` (commas). Every element in the list
14634 * has identical properties.
14635 *
14636 * An `element` may inherit additional properties from `parentElement` If no `^parentElement` is
14637 * specified then `""` (blank) element is assumed.
14638 *
14639 * NOTE: The blank element inherits from root `[Element]` element, the super element of all
14640 * elements.
14641 *
14642 * NOTE an element prefix such as `:svg:` has no special meaning to the schema.
14643 *
14644 * ## Properties
14645 *
14646 * Each element has a set of properties separated by `,` (commas). Each property can be prefixed
14647 * by a special character designating its type:
14648 *
14649 * - (no prefix): property is a string.
14650 * - `*`: property represents an event.
14651 * - `!`: property is a boolean.
14652 * - `#`: property is a number.
14653 * - `%`: property is an object.
14654 *
14655 * ## Query
14656 *
14657 * The class creates an internal squas representation which allows to easily answer the query of
14658 * if a given property exist on a given element.
14659 *
14660 * NOTE: We don't yet support querying for types or events.
14661 * NOTE: This schema is auto extracted from `schema_extractor.ts` located in the test folder,
14662 * see dom_element_schema_registry_spec.ts
14663 */
14664// =================================================================================================
14665// =================================================================================================
14666// =========== S T O P - S T O P - S T O P - S T O P - S T O P - S T O P ===========
14667// =================================================================================================
14668// =================================================================================================
14669//
14670// DO NOT EDIT THIS DOM SCHEMA WITHOUT A SECURITY REVIEW!
14671//
14672// Newly added properties must be security reviewed and assigned an appropriate SecurityContext in
14673// dom_security_schema.ts. Reach out to mprobst & rjamet for details.
14674//
14675// =================================================================================================
14676var SCHEMA = [
14677 '[Element]|textContent,%classList,className,id,innerHTML,*beforecopy,*beforecut,*beforepaste,*copy,*cut,*paste,*search,*selectstart,*webkitfullscreenchange,*webkitfullscreenerror,*wheel,outerHTML,#scrollLeft,#scrollTop,slot' +
14678 /* added manually to avoid breaking changes */
14679 ',*message,*mozfullscreenchange,*mozfullscreenerror,*mozpointerlockchange,*mozpointerlockerror,*webglcontextcreationerror,*webglcontextlost,*webglcontextrestored',
14680 '[HTMLElement]^[Element]|accessKey,contentEditable,dir,!draggable,!hidden,innerText,lang,*abort,*auxclick,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*cuechange,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*gotpointercapture,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*lostpointercapture,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*pause,*play,*playing,*pointercancel,*pointerdown,*pointerenter,*pointerleave,*pointermove,*pointerout,*pointerover,*pointerup,*progress,*ratechange,*reset,*resize,*scroll,*seeked,*seeking,*select,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,outerText,!spellcheck,%style,#tabIndex,title,!translate',
14681 'abbr,address,article,aside,b,bdi,bdo,cite,code,dd,dfn,dt,em,figcaption,figure,footer,header,i,kbd,main,mark,nav,noscript,rb,rp,rt,rtc,ruby,s,samp,section,small,strong,sub,sup,u,var,wbr^[HTMLElement]|accessKey,contentEditable,dir,!draggable,!hidden,innerText,lang,*abort,*auxclick,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*cuechange,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*gotpointercapture,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*lostpointercapture,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*pause,*play,*playing,*pointercancel,*pointerdown,*pointerenter,*pointerleave,*pointermove,*pointerout,*pointerover,*pointerup,*progress,*ratechange,*reset,*resize,*scroll,*seeked,*seeking,*select,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,outerText,!spellcheck,%style,#tabIndex,title,!translate',
14682 'media^[HTMLElement]|!autoplay,!controls,%controlsList,%crossOrigin,#currentTime,!defaultMuted,#defaultPlaybackRate,!disableRemotePlayback,!loop,!muted,*encrypted,*waitingforkey,#playbackRate,preload,src,%srcObject,#volume',
14683 ':svg:^[HTMLElement]|*abort,*auxclick,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*cuechange,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*gotpointercapture,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*lostpointercapture,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*pause,*play,*playing,*pointercancel,*pointerdown,*pointerenter,*pointerleave,*pointermove,*pointerout,*pointerover,*pointerup,*progress,*ratechange,*reset,*resize,*scroll,*seeked,*seeking,*select,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,%style,#tabIndex',
14684 ':svg:graphics^:svg:|',
14685 ':svg:animation^:svg:|*begin,*end,*repeat',
14686 ':svg:geometry^:svg:|',
14687 ':svg:componentTransferFunction^:svg:|',
14688 ':svg:gradient^:svg:|',
14689 ':svg:textContent^:svg:graphics|',
14690 ':svg:textPositioning^:svg:textContent|',
14691 'a^[HTMLElement]|charset,coords,download,hash,host,hostname,href,hreflang,name,password,pathname,ping,port,protocol,referrerPolicy,rel,rev,search,shape,target,text,type,username',
14692 'area^[HTMLElement]|alt,coords,download,hash,host,hostname,href,!noHref,password,pathname,ping,port,protocol,referrerPolicy,rel,search,shape,target,username',
14693 'audio^media|',
14694 'br^[HTMLElement]|clear',
14695 'base^[HTMLElement]|href,target',
14696 'body^[HTMLElement]|aLink,background,bgColor,link,*beforeunload,*blur,*error,*focus,*hashchange,*languagechange,*load,*message,*offline,*online,*pagehide,*pageshow,*popstate,*rejectionhandled,*resize,*scroll,*storage,*unhandledrejection,*unload,text,vLink',
14697 'button^[HTMLElement]|!autofocus,!disabled,formAction,formEnctype,formMethod,!formNoValidate,formTarget,name,type,value',
14698 'canvas^[HTMLElement]|#height,#width',
14699 'content^[HTMLElement]|select',
14700 'dl^[HTMLElement]|!compact',
14701 'datalist^[HTMLElement]|',
14702 'details^[HTMLElement]|!open',
14703 'dialog^[HTMLElement]|!open,returnValue',
14704 'dir^[HTMLElement]|!compact',
14705 'div^[HTMLElement]|align',
14706 'embed^[HTMLElement]|align,height,name,src,type,width',
14707 'fieldset^[HTMLElement]|!disabled,name',
14708 'font^[HTMLElement]|color,face,size',
14709 'form^[HTMLElement]|acceptCharset,action,autocomplete,encoding,enctype,method,name,!noValidate,target',
14710 'frame^[HTMLElement]|frameBorder,longDesc,marginHeight,marginWidth,name,!noResize,scrolling,src',
14711 'frameset^[HTMLElement]|cols,*beforeunload,*blur,*error,*focus,*hashchange,*languagechange,*load,*message,*offline,*online,*pagehide,*pageshow,*popstate,*rejectionhandled,*resize,*scroll,*storage,*unhandledrejection,*unload,rows',
14712 'hr^[HTMLElement]|align,color,!noShade,size,width',
14713 'head^[HTMLElement]|',
14714 'h1,h2,h3,h4,h5,h6^[HTMLElement]|align',
14715 'html^[HTMLElement]|version',
14716 'iframe^[HTMLElement]|align,!allowFullscreen,frameBorder,height,longDesc,marginHeight,marginWidth,name,referrerPolicy,%sandbox,scrolling,src,srcdoc,width',
14717 'img^[HTMLElement]|align,alt,border,%crossOrigin,#height,#hspace,!isMap,longDesc,lowsrc,name,referrerPolicy,sizes,src,srcset,useMap,#vspace,#width',
14718 'input^[HTMLElement]|accept,align,alt,autocapitalize,autocomplete,!autofocus,!checked,!defaultChecked,defaultValue,dirName,!disabled,%files,formAction,formEnctype,formMethod,!formNoValidate,formTarget,#height,!incremental,!indeterminate,max,#maxLength,min,#minLength,!multiple,name,pattern,placeholder,!readOnly,!required,selectionDirection,#selectionEnd,#selectionStart,#size,src,step,type,useMap,value,%valueAsDate,#valueAsNumber,#width',
14719 'li^[HTMLElement]|type,#value',
14720 'label^[HTMLElement]|htmlFor',
14721 'legend^[HTMLElement]|align',
14722 'link^[HTMLElement]|as,charset,%crossOrigin,!disabled,href,hreflang,integrity,media,referrerPolicy,rel,%relList,rev,%sizes,target,type',
14723 'map^[HTMLElement]|name',
14724 'marquee^[HTMLElement]|behavior,bgColor,direction,height,#hspace,#loop,#scrollAmount,#scrollDelay,!trueSpeed,#vspace,width',
14725 'menu^[HTMLElement]|!compact',
14726 'meta^[HTMLElement]|content,httpEquiv,name,scheme',
14727 'meter^[HTMLElement]|#high,#low,#max,#min,#optimum,#value',
14728 'ins,del^[HTMLElement]|cite,dateTime',
14729 'ol^[HTMLElement]|!compact,!reversed,#start,type',
14730 'object^[HTMLElement]|align,archive,border,code,codeBase,codeType,data,!declare,height,#hspace,name,standby,type,useMap,#vspace,width',
14731 'optgroup^[HTMLElement]|!disabled,label',
14732 'option^[HTMLElement]|!defaultSelected,!disabled,label,!selected,text,value',
14733 'output^[HTMLElement]|defaultValue,%htmlFor,name,value',
14734 'p^[HTMLElement]|align',
14735 'param^[HTMLElement]|name,type,value,valueType',
14736 'picture^[HTMLElement]|',
14737 'pre^[HTMLElement]|#width',
14738 'progress^[HTMLElement]|#max,#value',
14739 'q,blockquote,cite^[HTMLElement]|',
14740 'script^[HTMLElement]|!async,charset,%crossOrigin,!defer,event,htmlFor,integrity,src,text,type',
14741 'select^[HTMLElement]|!autofocus,!disabled,#length,!multiple,name,!required,#selectedIndex,#size,value',
14742 'shadow^[HTMLElement]|',
14743 'slot^[HTMLElement]|name',
14744 'source^[HTMLElement]|media,sizes,src,srcset,type',
14745 'span^[HTMLElement]|',
14746 'style^[HTMLElement]|!disabled,media,type',
14747 'caption^[HTMLElement]|align',
14748 'th,td^[HTMLElement]|abbr,align,axis,bgColor,ch,chOff,#colSpan,headers,height,!noWrap,#rowSpan,scope,vAlign,width',
14749 'col,colgroup^[HTMLElement]|align,ch,chOff,#span,vAlign,width',
14750 'table^[HTMLElement]|align,bgColor,border,%caption,cellPadding,cellSpacing,frame,rules,summary,%tFoot,%tHead,width',
14751 'tr^[HTMLElement]|align,bgColor,ch,chOff,vAlign',
14752 'tfoot,thead,tbody^[HTMLElement]|align,ch,chOff,vAlign',
14753 'template^[HTMLElement]|',
14754 'textarea^[HTMLElement]|autocapitalize,!autofocus,#cols,defaultValue,dirName,!disabled,#maxLength,#minLength,name,placeholder,!readOnly,!required,#rows,selectionDirection,#selectionEnd,#selectionStart,value,wrap',
14755 'title^[HTMLElement]|text',
14756 'track^[HTMLElement]|!default,kind,label,src,srclang',
14757 'ul^[HTMLElement]|!compact,type',
14758 'unknown^[HTMLElement]|',
14759 'video^media|#height,poster,#width',
14760 ':svg:a^:svg:graphics|',
14761 ':svg:animate^:svg:animation|',
14762 ':svg:animateMotion^:svg:animation|',
14763 ':svg:animateTransform^:svg:animation|',
14764 ':svg:circle^:svg:geometry|',
14765 ':svg:clipPath^:svg:graphics|',
14766 ':svg:defs^:svg:graphics|',
14767 ':svg:desc^:svg:|',
14768 ':svg:discard^:svg:|',
14769 ':svg:ellipse^:svg:geometry|',
14770 ':svg:feBlend^:svg:|',
14771 ':svg:feColorMatrix^:svg:|',
14772 ':svg:feComponentTransfer^:svg:|',
14773 ':svg:feComposite^:svg:|',
14774 ':svg:feConvolveMatrix^:svg:|',
14775 ':svg:feDiffuseLighting^:svg:|',
14776 ':svg:feDisplacementMap^:svg:|',
14777 ':svg:feDistantLight^:svg:|',
14778 ':svg:feDropShadow^:svg:|',
14779 ':svg:feFlood^:svg:|',
14780 ':svg:feFuncA^:svg:componentTransferFunction|',
14781 ':svg:feFuncB^:svg:componentTransferFunction|',
14782 ':svg:feFuncG^:svg:componentTransferFunction|',
14783 ':svg:feFuncR^:svg:componentTransferFunction|',
14784 ':svg:feGaussianBlur^:svg:|',
14785 ':svg:feImage^:svg:|',
14786 ':svg:feMerge^:svg:|',
14787 ':svg:feMergeNode^:svg:|',
14788 ':svg:feMorphology^:svg:|',
14789 ':svg:feOffset^:svg:|',
14790 ':svg:fePointLight^:svg:|',
14791 ':svg:feSpecularLighting^:svg:|',
14792 ':svg:feSpotLight^:svg:|',
14793 ':svg:feTile^:svg:|',
14794 ':svg:feTurbulence^:svg:|',
14795 ':svg:filter^:svg:|',
14796 ':svg:foreignObject^:svg:graphics|',
14797 ':svg:g^:svg:graphics|',
14798 ':svg:image^:svg:graphics|',
14799 ':svg:line^:svg:geometry|',
14800 ':svg:linearGradient^:svg:gradient|',
14801 ':svg:mpath^:svg:|',
14802 ':svg:marker^:svg:|',
14803 ':svg:mask^:svg:|',
14804 ':svg:metadata^:svg:|',
14805 ':svg:path^:svg:geometry|',
14806 ':svg:pattern^:svg:|',
14807 ':svg:polygon^:svg:geometry|',
14808 ':svg:polyline^:svg:geometry|',
14809 ':svg:radialGradient^:svg:gradient|',
14810 ':svg:rect^:svg:geometry|',
14811 ':svg:svg^:svg:graphics|#currentScale,#zoomAndPan',
14812 ':svg:script^:svg:|type',
14813 ':svg:set^:svg:animation|',
14814 ':svg:stop^:svg:|',
14815 ':svg:style^:svg:|!disabled,media,title,type',
14816 ':svg:switch^:svg:graphics|',
14817 ':svg:symbol^:svg:|',
14818 ':svg:tspan^:svg:textPositioning|',
14819 ':svg:text^:svg:textPositioning|',
14820 ':svg:textPath^:svg:textContent|',
14821 ':svg:title^:svg:|',
14822 ':svg:use^:svg:graphics|',
14823 ':svg:view^:svg:|#zoomAndPan',
14824 'data^[HTMLElement]|value',
14825 'keygen^[HTMLElement]|!autofocus,challenge,!disabled,form,keytype,name',
14826 'menuitem^[HTMLElement]|type,label,icon,!disabled,!checked,radiogroup,!default',
14827 'summary^[HTMLElement]|',
14828 'time^[HTMLElement]|dateTime',
14829 ':svg:cursor^:svg:|',
14830];
14831var _ATTR_TO_PROP = {
14832 'class': 'className',
14833 'for': 'htmlFor',
14834 'formaction': 'formAction',
14835 'innerHtml': 'innerHTML',
14836 'readonly': 'readOnly',
14837 'tabindex': 'tabIndex',
14838};
14839var DomElementSchemaRegistry = /** @class */ (function (_super) {
14840 __extends(DomElementSchemaRegistry, _super);
14841 function DomElementSchemaRegistry() {
14842 var _this = _super.call(this) || this;
14843 _this._schema = {};
14844 SCHEMA.forEach(function (encodedType) {
14845 var type = {};
14846 var _a = __read(encodedType.split('|'), 2), strType = _a[0], strProperties = _a[1];
14847 var properties = strProperties.split(',');
14848 var _b = __read(strType.split('^'), 2), typeNames = _b[0], superName = _b[1];
14849 typeNames.split(',').forEach(function (tag) { return _this._schema[tag.toLowerCase()] = type; });
14850 var superType = superName && _this._schema[superName.toLowerCase()];
14851 if (superType) {
14852 Object.keys(superType).forEach(function (prop) { type[prop] = superType[prop]; });
14853 }
14854 properties.forEach(function (property) {
14855 if (property.length > 0) {
14856 switch (property[0]) {
14857 case '*':
14858 // We don't yet support events.
14859 // If ever allowing to bind to events, GO THROUGH A SECURITY REVIEW, allowing events
14860 // will
14861 // almost certainly introduce bad XSS vulnerabilities.
14862 // type[property.substring(1)] = EVENT;
14863 break;
14864 case '!':
14865 type[property.substring(1)] = BOOLEAN;
14866 break;
14867 case '#':
14868 type[property.substring(1)] = NUMBER;
14869 break;
14870 case '%':
14871 type[property.substring(1)] = OBJECT;
14872 break;
14873 default:
14874 type[property] = STRING;
14875 }
14876 }
14877 });
14878 });
14879 return _this;
14880 }
14881 DomElementSchemaRegistry.prototype.hasProperty = function (tagName, propName, schemaMetas) {
14882 if (schemaMetas.some(function (schema) { return schema.name === NO_ERRORS_SCHEMA.name; })) {
14883 return true;
14884 }
14885 if (tagName.indexOf('-') > -1) {
14886 if (isNgContainer(tagName) || isNgContent(tagName)) {
14887 return false;
14888 }
14889 if (schemaMetas.some(function (schema) { return schema.name === CUSTOM_ELEMENTS_SCHEMA.name; })) {
14890 // Can't tell now as we don't know which properties a custom element will get
14891 // once it is instantiated
14892 return true;
14893 }
14894 }
14895 var elementProperties = this._schema[tagName.toLowerCase()] || this._schema['unknown'];
14896 return !!elementProperties[propName];
14897 };
14898 DomElementSchemaRegistry.prototype.hasElement = function (tagName, schemaMetas) {
14899 if (schemaMetas.some(function (schema) { return schema.name === NO_ERRORS_SCHEMA.name; })) {
14900 return true;
14901 }
14902 if (tagName.indexOf('-') > -1) {
14903 if (isNgContainer(tagName) || isNgContent(tagName)) {
14904 return true;
14905 }
14906 if (schemaMetas.some(function (schema) { return schema.name === CUSTOM_ELEMENTS_SCHEMA.name; })) {
14907 // Allow any custom elements
14908 return true;
14909 }
14910 }
14911 return !!this._schema[tagName.toLowerCase()];
14912 };
14913 /**
14914 * securityContext returns the security context for the given property on the given DOM tag.
14915 *
14916 * Tag and property name are statically known and cannot change at runtime, i.e. it is not
14917 * possible to bind a value into a changing attribute or tag name.
14918 *
14919 * The filtering is based on a list of allowed tags|attributes. All attributes in the schema
14920 * above are assumed to have the 'NONE' security context, i.e. that they are safe inert
14921 * string values. Only specific well known attack vectors are assigned their appropriate context.
14922 */
14923 DomElementSchemaRegistry.prototype.securityContext = function (tagName, propName, isAttribute) {
14924 if (isAttribute) {
14925 // NB: For security purposes, use the mapped property name, not the attribute name.
14926 propName = this.getMappedPropName(propName);
14927 }
14928 // Make sure comparisons are case insensitive, so that case differences between attribute and
14929 // property names do not have a security impact.
14930 tagName = tagName.toLowerCase();
14931 propName = propName.toLowerCase();
14932 var ctx = SECURITY_SCHEMA()[tagName + '|' + propName];
14933 if (ctx) {
14934 return ctx;
14935 }
14936 ctx = SECURITY_SCHEMA()['*|' + propName];
14937 return ctx ? ctx : SecurityContext.NONE;
14938 };
14939 DomElementSchemaRegistry.prototype.getMappedPropName = function (propName) { return _ATTR_TO_PROP[propName] || propName; };
14940 DomElementSchemaRegistry.prototype.getDefaultComponentElementName = function () { return 'ng-component'; };
14941 DomElementSchemaRegistry.prototype.validateProperty = function (name) {
14942 if (name.toLowerCase().startsWith('on')) {
14943 var msg = "Binding to event property '" + name + "' is disallowed for security reasons, " +
14944 ("please use (" + name.slice(2) + ")=...") +
14945 ("\nIf '" + name + "' is a directive input, make sure the directive is imported by the") +
14946 " current module.";
14947 return { error: true, msg: msg };
14948 }
14949 else {
14950 return { error: false };
14951 }
14952 };
14953 DomElementSchemaRegistry.prototype.validateAttribute = function (name) {
14954 if (name.toLowerCase().startsWith('on')) {
14955 var msg = "Binding to event attribute '" + name + "' is disallowed for security reasons, " +
14956 ("please use (" + name.slice(2) + ")=...");
14957 return { error: true, msg: msg };
14958 }
14959 else {
14960 return { error: false };
14961 }
14962 };
14963 DomElementSchemaRegistry.prototype.allKnownElementNames = function () { return Object.keys(this._schema); };
14964 DomElementSchemaRegistry.prototype.normalizeAnimationStyleProperty = function (propName) {
14965 return dashCaseToCamelCase(propName);
14966 };
14967 DomElementSchemaRegistry.prototype.normalizeAnimationStyleValue = function (camelCaseProp, userProvidedProp, val) {
14968 var unit = '';
14969 var strVal = val.toString().trim();
14970 var errorMsg = null;
14971 if (_isPixelDimensionStyle(camelCaseProp) && val !== 0 && val !== '0') {
14972 if (typeof val === 'number') {
14973 unit = 'px';
14974 }
14975 else {
14976 var valAndSuffixMatch = val.match(/^[+-]?[\d\.]+([a-z]*)$/);
14977 if (valAndSuffixMatch && valAndSuffixMatch[1].length == 0) {
14978 errorMsg = "Please provide a CSS unit value for " + userProvidedProp + ":" + val;
14979 }
14980 }
14981 }
14982 return { error: errorMsg, value: strVal + unit };
14983 };
14984 return DomElementSchemaRegistry;
14985}(ElementSchemaRegistry));
14986function _isPixelDimensionStyle(prop) {
14987 switch (prop) {
14988 case 'width':
14989 case 'height':
14990 case 'minWidth':
14991 case 'minHeight':
14992 case 'maxWidth':
14993 case 'maxHeight':
14994 case 'left':
14995 case 'top':
14996 case 'bottom':
14997 case 'right':
14998 case 'fontSize':
14999 case 'outlineWidth':
15000 case 'outlineOffset':
15001 case 'paddingTop':
15002 case 'paddingLeft':
15003 case 'paddingBottom':
15004 case 'paddingRight':
15005 case 'marginTop':
15006 case 'marginLeft':
15007 case 'marginBottom':
15008 case 'marginRight':
15009 case 'borderRadius':
15010 case 'borderWidth':
15011 case 'borderTopWidth':
15012 case 'borderLeftWidth':
15013 case 'borderRightWidth':
15014 case 'borderBottomWidth':
15015 case 'textIndent':
15016 return true;
15017 default:
15018 return false;
15019 }
15020}
15021
15022/**
15023 * @license
15024 * Copyright Google Inc. All Rights Reserved.
15025 *
15026 * Use of this source code is governed by an MIT-style license that can be
15027 * found in the LICENSE file at https://angular.io/license
15028 */
15029var BIND_NAME_REGEXP$1 = /^(?:(?:(?:(bind-)|(let-)|(ref-|#)|(on-)|(bindon-)|(@))(.+))|\[\(([^\)]+)\)\]|\[([^\]]+)\]|\(([^\)]+)\))$/;
15030// Group 1 = "bind-"
15031var KW_BIND_IDX$1 = 1;
15032// Group 2 = "let-"
15033var KW_LET_IDX$1 = 2;
15034// Group 3 = "ref-/#"
15035var KW_REF_IDX$1 = 3;
15036// Group 4 = "on-"
15037var KW_ON_IDX$1 = 4;
15038// Group 5 = "bindon-"
15039var KW_BINDON_IDX$1 = 5;
15040// Group 6 = "@"
15041var KW_AT_IDX$1 = 6;
15042// Group 7 = the identifier after "bind-", "let-", "ref-/#", "on-", "bindon-" or "@"
15043var IDENT_KW_IDX$1 = 7;
15044// Group 8 = identifier inside [()]
15045var IDENT_BANANA_BOX_IDX$1 = 8;
15046// Group 9 = identifier inside []
15047var IDENT_PROPERTY_IDX$1 = 9;
15048// Group 10 = identifier inside ()
15049var IDENT_EVENT_IDX$1 = 10;
15050var TEMPLATE_ATTR_PREFIX$1 = '*';
15051function htmlAstToRender3Ast(htmlNodes, bindingParser) {
15052 var transformer = new HtmlAstToIvyAst(bindingParser);
15053 var ivyNodes = visitAll$1(transformer, htmlNodes);
15054 // Errors might originate in either the binding parser or the html to ivy transformer
15055 var allErrors = bindingParser.errors.concat(transformer.errors);
15056 var errors = allErrors.filter(function (e) { return e.level === ParseErrorLevel.ERROR; });
15057 if (errors.length > 0) {
15058 var errorString = errors.join('\n');
15059 throw syntaxError("Template parse errors:\n" + errorString, errors);
15060 }
15061 return {
15062 nodes: ivyNodes,
15063 errors: allErrors,
15064 styleUrls: transformer.styleUrls,
15065 styles: transformer.styles,
15066 };
15067}
15068var HtmlAstToIvyAst = /** @class */ (function () {
15069 function HtmlAstToIvyAst(bindingParser) {
15070 this.bindingParser = bindingParser;
15071 this.errors = [];
15072 this.styles = [];
15073 this.styleUrls = [];
15074 }
15075 // HTML visitor
15076 HtmlAstToIvyAst.prototype.visitElement = function (element) {
15077 var e_1, _a;
15078 var _this = this;
15079 var preparsedElement = preparseElement(element);
15080 if (preparsedElement.type === PreparsedElementType.SCRIPT) {
15081 return null;
15082 }
15083 else if (preparsedElement.type === PreparsedElementType.STYLE) {
15084 var contents = textContents(element);
15085 if (contents !== null) {
15086 this.styles.push(contents);
15087 }
15088 return null;
15089 }
15090 else if (preparsedElement.type === PreparsedElementType.STYLESHEET &&
15091 isStyleUrlResolvable(preparsedElement.hrefAttr)) {
15092 this.styleUrls.push(preparsedElement.hrefAttr);
15093 return null;
15094 }
15095 // Whether the element is a `<ng-template>`
15096 var isTemplateElement = isNgTemplate(element.name);
15097 var parsedProperties = [];
15098 var boundEvents = [];
15099 var variables = [];
15100 var references = [];
15101 var attributes = [];
15102 var i18nAttrsMeta = {};
15103 var templateParsedProperties = [];
15104 var templateVariables = [];
15105 // Whether the element has any *-attribute
15106 var elementHasInlineTemplate = false;
15107 try {
15108 for (var _b = __values(element.attrs), _c = _b.next(); !_c.done; _c = _b.next()) {
15109 var attribute = _c.value;
15110 var hasBinding = false;
15111 var normalizedName = normalizeAttributeName(attribute.name);
15112 // `*attr` defines template bindings
15113 var isTemplateBinding = false;
15114 if (attribute.i18n) {
15115 i18nAttrsMeta[attribute.name] = attribute.i18n;
15116 }
15117 if (normalizedName.startsWith(TEMPLATE_ATTR_PREFIX$1)) {
15118 // *-attributes
15119 if (elementHasInlineTemplate) {
15120 this.reportError("Can't have multiple template bindings on one element. Use only one attribute prefixed with *", attribute.sourceSpan);
15121 }
15122 isTemplateBinding = true;
15123 elementHasInlineTemplate = true;
15124 var templateValue = attribute.value;
15125 var templateKey = normalizedName.substring(TEMPLATE_ATTR_PREFIX$1.length);
15126 var parsedVariables = [];
15127 var absoluteOffset = attribute.valueSpan ? attribute.valueSpan.start.offset :
15128 attribute.sourceSpan.start.offset;
15129 this.bindingParser.parseInlineTemplateBinding(templateKey, templateValue, attribute.sourceSpan, absoluteOffset, [], templateParsedProperties, parsedVariables);
15130 templateVariables.push.apply(templateVariables, __spread(parsedVariables.map(function (v) { return new Variable(v.name, v.value, v.sourceSpan); })));
15131 }
15132 else {
15133 // Check for variables, events, property bindings, interpolation
15134 hasBinding = this.parseAttribute(isTemplateElement, attribute, [], parsedProperties, boundEvents, variables, references);
15135 }
15136 if (!hasBinding && !isTemplateBinding) {
15137 // don't include the bindings as attributes as well in the AST
15138 attributes.push(this.visitAttribute(attribute));
15139 }
15140 }
15141 }
15142 catch (e_1_1) { e_1 = { error: e_1_1 }; }
15143 finally {
15144 try {
15145 if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
15146 }
15147 finally { if (e_1) throw e_1.error; }
15148 }
15149 var children = visitAll$1(preparsedElement.nonBindable ? NON_BINDABLE_VISITOR$1 : this, element.children);
15150 var parsedElement;
15151 if (preparsedElement.type === PreparsedElementType.NG_CONTENT) {
15152 // `<ng-content>`
15153 if (element.children &&
15154 !element.children.every(function (node) { return isEmptyTextNode(node) || isCommentNode(node); })) {
15155 this.reportError("<ng-content> element cannot have content.", element.sourceSpan);
15156 }
15157 var selector = preparsedElement.selectAttr;
15158 var attrs = element.attrs.map(function (attr) { return _this.visitAttribute(attr); });
15159 parsedElement = new Content(selector, attrs, element.sourceSpan, element.i18n);
15160 }
15161 else if (isTemplateElement) {
15162 // `<ng-template>`
15163 var attrs = this.extractAttributes(element.name, parsedProperties, i18nAttrsMeta);
15164 parsedElement = new Template(element.name, attributes, attrs.bound, boundEvents, [ /* no template attributes */], children, references, variables, element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
15165 }
15166 else {
15167 var attrs = this.extractAttributes(element.name, parsedProperties, i18nAttrsMeta);
15168 parsedElement = new Element(element.name, attributes, attrs.bound, boundEvents, children, references, element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
15169 }
15170 if (elementHasInlineTemplate) {
15171 // If this node is an inline-template (e.g. has *ngFor) then we need to create a template
15172 // node that contains this node.
15173 // Moreover, if the node is an element, then we need to hoist its attributes to the template
15174 // node for matching against content projection selectors.
15175 var attrs = this.extractAttributes('ng-template', templateParsedProperties, i18nAttrsMeta);
15176 var templateAttrs_1 = [];
15177 attrs.literal.forEach(function (attr) { return templateAttrs_1.push(attr); });
15178 attrs.bound.forEach(function (attr) { return templateAttrs_1.push(attr); });
15179 var hoistedAttrs = parsedElement instanceof Element ?
15180 {
15181 attributes: parsedElement.attributes,
15182 inputs: parsedElement.inputs,
15183 outputs: parsedElement.outputs,
15184 } :
15185 { attributes: [], inputs: [], outputs: [] };
15186 // TODO(pk): test for this case
15187 parsedElement = new Template(parsedElement.name, hoistedAttrs.attributes, hoistedAttrs.inputs, hoistedAttrs.outputs, templateAttrs_1, [parsedElement], [ /* no references */], templateVariables, element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
15188 }
15189 return parsedElement;
15190 };
15191 HtmlAstToIvyAst.prototype.visitAttribute = function (attribute) {
15192 return new TextAttribute(attribute.name, attribute.value, attribute.sourceSpan, attribute.valueSpan, attribute.i18n);
15193 };
15194 HtmlAstToIvyAst.prototype.visitText = function (text) {
15195 return this._visitTextWithInterpolation(text.value, text.sourceSpan, text.i18n);
15196 };
15197 HtmlAstToIvyAst.prototype.visitExpansion = function (expansion) {
15198 var _this = this;
15199 var meta = expansion.i18n;
15200 // do not generate Icu in case it was created
15201 // outside of i18n block in a template
15202 if (!meta) {
15203 return null;
15204 }
15205 var vars = {};
15206 var placeholders = {};
15207 // extract VARs from ICUs - we process them separately while
15208 // assembling resulting message via goog.getMsg function, since
15209 // we need to pass them to top-level goog.getMsg call
15210 Object.keys(meta.placeholders).forEach(function (key) {
15211 var value = meta.placeholders[key];
15212 if (key.startsWith(I18N_ICU_VAR_PREFIX)) {
15213 var config = _this.bindingParser.interpolationConfig;
15214 // ICU expression is a plain string, not wrapped into start
15215 // and end tags, so we wrap it before passing to binding parser
15216 var wrapped = "" + config.start + value + config.end;
15217 vars[key] = _this._visitTextWithInterpolation(wrapped, expansion.sourceSpan);
15218 }
15219 else {
15220 placeholders[key] = _this._visitTextWithInterpolation(value, expansion.sourceSpan);
15221 }
15222 });
15223 return new Icu(vars, placeholders, expansion.sourceSpan, meta);
15224 };
15225 HtmlAstToIvyAst.prototype.visitExpansionCase = function (expansionCase) { return null; };
15226 HtmlAstToIvyAst.prototype.visitComment = function (comment) { return null; };
15227 // convert view engine `ParsedProperty` to a format suitable for IVY
15228 HtmlAstToIvyAst.prototype.extractAttributes = function (elementName, properties, i18nPropsMeta) {
15229 var _this = this;
15230 var bound = [];
15231 var literal = [];
15232 properties.forEach(function (prop) {
15233 var i18n = i18nPropsMeta[prop.name];
15234 if (prop.isLiteral) {
15235 literal.push(new TextAttribute(prop.name, prop.expression.source || '', prop.sourceSpan, undefined, i18n));
15236 }
15237 else {
15238 // Note that validation is skipped and property mapping is disabled
15239 // due to the fact that we need to make sure a given prop is not an
15240 // input of a directive and directive matching happens at runtime.
15241 var bep = _this.bindingParser.createBoundElementProperty(elementName, prop, /* skipValidation */ true, /* mapPropertyName */ false);
15242 bound.push(BoundAttribute.fromBoundElementProperty(bep, i18n));
15243 }
15244 });
15245 return { bound: bound, literal: literal };
15246 };
15247 HtmlAstToIvyAst.prototype.parseAttribute = function (isTemplateElement, attribute, matchableAttributes, parsedProperties, boundEvents, variables, references) {
15248 var name = normalizeAttributeName(attribute.name);
15249 var value = attribute.value;
15250 var srcSpan = attribute.sourceSpan;
15251 var absoluteOffset = attribute.valueSpan ? attribute.valueSpan.start.offset : srcSpan.start.offset;
15252 var bindParts = name.match(BIND_NAME_REGEXP$1);
15253 var hasBinding = false;
15254 if (bindParts) {
15255 hasBinding = true;
15256 if (bindParts[KW_BIND_IDX$1] != null) {
15257 this.bindingParser.parsePropertyBinding(bindParts[IDENT_KW_IDX$1], value, false, srcSpan, absoluteOffset, attribute.valueSpan, matchableAttributes, parsedProperties);
15258 }
15259 else if (bindParts[KW_LET_IDX$1]) {
15260 if (isTemplateElement) {
15261 var identifier = bindParts[IDENT_KW_IDX$1];
15262 this.parseVariable(identifier, value, srcSpan, attribute.valueSpan, variables);
15263 }
15264 else {
15265 this.reportError("\"let-\" is only supported on ng-template elements.", srcSpan);
15266 }
15267 }
15268 else if (bindParts[KW_REF_IDX$1]) {
15269 var identifier = bindParts[IDENT_KW_IDX$1];
15270 this.parseReference(identifier, value, srcSpan, attribute.valueSpan, references);
15271 }
15272 else if (bindParts[KW_ON_IDX$1]) {
15273 var events = [];
15274 this.bindingParser.parseEvent(bindParts[IDENT_KW_IDX$1], value, srcSpan, attribute.valueSpan || srcSpan, matchableAttributes, events);
15275 addEvents(events, boundEvents);
15276 }
15277 else if (bindParts[KW_BINDON_IDX$1]) {
15278 this.bindingParser.parsePropertyBinding(bindParts[IDENT_KW_IDX$1], value, false, srcSpan, absoluteOffset, attribute.valueSpan, matchableAttributes, parsedProperties);
15279 this.parseAssignmentEvent(bindParts[IDENT_KW_IDX$1], value, srcSpan, attribute.valueSpan, matchableAttributes, boundEvents);
15280 }
15281 else if (bindParts[KW_AT_IDX$1]) {
15282 this.bindingParser.parseLiteralAttr(name, value, srcSpan, absoluteOffset, attribute.valueSpan, matchableAttributes, parsedProperties);
15283 }
15284 else if (bindParts[IDENT_BANANA_BOX_IDX$1]) {
15285 this.bindingParser.parsePropertyBinding(bindParts[IDENT_BANANA_BOX_IDX$1], value, false, srcSpan, absoluteOffset, attribute.valueSpan, matchableAttributes, parsedProperties);
15286 this.parseAssignmentEvent(bindParts[IDENT_BANANA_BOX_IDX$1], value, srcSpan, attribute.valueSpan, matchableAttributes, boundEvents);
15287 }
15288 else if (bindParts[IDENT_PROPERTY_IDX$1]) {
15289 this.bindingParser.parsePropertyBinding(bindParts[IDENT_PROPERTY_IDX$1], value, false, srcSpan, absoluteOffset, attribute.valueSpan, matchableAttributes, parsedProperties);
15290 }
15291 else if (bindParts[IDENT_EVENT_IDX$1]) {
15292 var events = [];
15293 this.bindingParser.parseEvent(bindParts[IDENT_EVENT_IDX$1], value, srcSpan, attribute.valueSpan || srcSpan, matchableAttributes, events);
15294 addEvents(events, boundEvents);
15295 }
15296 }
15297 else {
15298 hasBinding = this.bindingParser.parsePropertyInterpolation(name, value, srcSpan, attribute.valueSpan, matchableAttributes, parsedProperties);
15299 }
15300 return hasBinding;
15301 };
15302 HtmlAstToIvyAst.prototype._visitTextWithInterpolation = function (value, sourceSpan, i18n) {
15303 var valueNoNgsp = replaceNgsp(value);
15304 var expr = this.bindingParser.parseInterpolation(valueNoNgsp, sourceSpan);
15305 return expr ? new BoundText(expr, sourceSpan, i18n) : new Text(valueNoNgsp, sourceSpan);
15306 };
15307 HtmlAstToIvyAst.prototype.parseVariable = function (identifier, value, sourceSpan, valueSpan, variables) {
15308 if (identifier.indexOf('-') > -1) {
15309 this.reportError("\"-\" is not allowed in variable names", sourceSpan);
15310 }
15311 variables.push(new Variable(identifier, value, sourceSpan, valueSpan));
15312 };
15313 HtmlAstToIvyAst.prototype.parseReference = function (identifier, value, sourceSpan, valueSpan, references) {
15314 if (identifier.indexOf('-') > -1) {
15315 this.reportError("\"-\" is not allowed in reference names", sourceSpan);
15316 }
15317 references.push(new Reference(identifier, value, sourceSpan, valueSpan));
15318 };
15319 HtmlAstToIvyAst.prototype.parseAssignmentEvent = function (name, expression, sourceSpan, valueSpan, targetMatchableAttrs, boundEvents) {
15320 var events = [];
15321 this.bindingParser.parseEvent(name + "Change", expression + "=$event", sourceSpan, valueSpan || sourceSpan, targetMatchableAttrs, events);
15322 addEvents(events, boundEvents);
15323 };
15324 HtmlAstToIvyAst.prototype.reportError = function (message, sourceSpan, level) {
15325 if (level === void 0) { level = ParseErrorLevel.ERROR; }
15326 this.errors.push(new ParseError(sourceSpan, message, level));
15327 };
15328 return HtmlAstToIvyAst;
15329}());
15330var NonBindableVisitor$1 = /** @class */ (function () {
15331 function NonBindableVisitor() {
15332 }
15333 NonBindableVisitor.prototype.visitElement = function (ast) {
15334 var preparsedElement = preparseElement(ast);
15335 if (preparsedElement.type === PreparsedElementType.SCRIPT ||
15336 preparsedElement.type === PreparsedElementType.STYLE ||
15337 preparsedElement.type === PreparsedElementType.STYLESHEET) {
15338 // Skipping <script> for security reasons
15339 // Skipping <style> and stylesheets as we already processed them
15340 // in the StyleCompiler
15341 return null;
15342 }
15343 var children = visitAll$1(this, ast.children, null);
15344 return new Element(ast.name, visitAll$1(this, ast.attrs),
15345 /* inputs */ [], /* outputs */ [], children, /* references */ [], ast.sourceSpan, ast.startSourceSpan, ast.endSourceSpan);
15346 };
15347 NonBindableVisitor.prototype.visitComment = function (comment) { return null; };
15348 NonBindableVisitor.prototype.visitAttribute = function (attribute) {
15349 return new TextAttribute(attribute.name, attribute.value, attribute.sourceSpan, undefined, attribute.i18n);
15350 };
15351 NonBindableVisitor.prototype.visitText = function (text) { return new Text(text.value, text.sourceSpan); };
15352 NonBindableVisitor.prototype.visitExpansion = function (expansion) { return null; };
15353 NonBindableVisitor.prototype.visitExpansionCase = function (expansionCase) { return null; };
15354 return NonBindableVisitor;
15355}());
15356var NON_BINDABLE_VISITOR$1 = new NonBindableVisitor$1();
15357function normalizeAttributeName(attrName) {
15358 return /^data-/i.test(attrName) ? attrName.substring(5) : attrName;
15359}
15360function addEvents(events, boundEvents) {
15361 boundEvents.push.apply(boundEvents, __spread(events.map(function (e) { return BoundEvent.fromParsedEvent(e); })));
15362}
15363function isEmptyTextNode(node) {
15364 return node instanceof Text$3 && node.value.trim().length == 0;
15365}
15366function isCommentNode(node) {
15367 return node instanceof Comment;
15368}
15369function textContents(node) {
15370 if (node.children.length !== 1 || !(node.children[0] instanceof Text$3)) {
15371 return null;
15372 }
15373 else {
15374 return node.children[0].value;
15375 }
15376}
15377
15378/**
15379 * @license
15380 * Copyright Google Inc. All Rights Reserved.
15381 *
15382 * Use of this source code is governed by an MIT-style license that can be
15383 * found in the LICENSE file at https://angular.io/license
15384 */
15385var TagType;
15386(function (TagType) {
15387 TagType[TagType["ELEMENT"] = 0] = "ELEMENT";
15388 TagType[TagType["TEMPLATE"] = 1] = "TEMPLATE";
15389 TagType[TagType["PROJECTION"] = 2] = "PROJECTION";
15390})(TagType || (TagType = {}));
15391/**
15392 * Generates an object that is used as a shared state between parent and all child contexts.
15393 */
15394function setupRegistry() {
15395 return { getUniqueId: getSeqNumberGenerator(), icus: new Map() };
15396}
15397/**
15398 * I18nContext is a helper class which keeps track of all i18n-related aspects
15399 * (accumulates placeholders, bindings, etc) between i18nStart and i18nEnd instructions.
15400 *
15401 * When we enter a nested template, the top-level context is being passed down
15402 * to the nested component, which uses this context to generate a child instance
15403 * of I18nContext class (to handle nested template) and at the end, reconciles it back
15404 * with the parent context.
15405 *
15406 * @param index Instruction index of i18nStart, which initiates this context
15407 * @param ref Reference to a translation const that represents the content if thus context
15408 * @param level Nestng level defined for child contexts
15409 * @param templateIndex Instruction index of a template which this context belongs to
15410 * @param meta Meta information (id, meaning, description, etc) associated with this context
15411 */
15412var I18nContext = /** @class */ (function () {
15413 function I18nContext(index, ref, level, templateIndex, meta, registry) {
15414 if (level === void 0) { level = 0; }
15415 if (templateIndex === void 0) { templateIndex = null; }
15416 this.index = index;
15417 this.ref = ref;
15418 this.level = level;
15419 this.templateIndex = templateIndex;
15420 this.meta = meta;
15421 this.registry = registry;
15422 this.bindings = new Set();
15423 this.placeholders = new Map();
15424 this.isEmitted = false;
15425 this._unresolvedCtxCount = 0;
15426 this._registry = registry || setupRegistry();
15427 this.id = this._registry.getUniqueId();
15428 }
15429 I18nContext.prototype.appendTag = function (type, node, index, closed) {
15430 if (node.isVoid && closed) {
15431 return; // ignore "close" for void tags
15432 }
15433 var ph = node.isVoid || !closed ? node.startName : node.closeName;
15434 var content = { type: type, index: index, ctx: this.id, isVoid: node.isVoid, closed: closed };
15435 updatePlaceholderMap(this.placeholders, ph, content);
15436 };
15437 Object.defineProperty(I18nContext.prototype, "icus", {
15438 get: function () { return this._registry.icus; },
15439 enumerable: true,
15440 configurable: true
15441 });
15442 Object.defineProperty(I18nContext.prototype, "isRoot", {
15443 get: function () { return this.level === 0; },
15444 enumerable: true,
15445 configurable: true
15446 });
15447 Object.defineProperty(I18nContext.prototype, "isResolved", {
15448 get: function () { return this._unresolvedCtxCount === 0; },
15449 enumerable: true,
15450 configurable: true
15451 });
15452 I18nContext.prototype.getSerializedPlaceholders = function () {
15453 var result = new Map();
15454 this.placeholders.forEach(function (values, key) { return result.set(key, values.map(serializePlaceholderValue)); });
15455 return result;
15456 };
15457 // public API to accumulate i18n-related content
15458 I18nContext.prototype.appendBinding = function (binding) { this.bindings.add(binding); };
15459 I18nContext.prototype.appendIcu = function (name, ref) {
15460 updatePlaceholderMap(this._registry.icus, name, ref);
15461 };
15462 I18nContext.prototype.appendBoundText = function (node) {
15463 var _this = this;
15464 var phs = assembleBoundTextPlaceholders(node, this.bindings.size, this.id);
15465 phs.forEach(function (values, key) { return updatePlaceholderMap.apply(void 0, __spread([_this.placeholders, key], values)); });
15466 };
15467 I18nContext.prototype.appendTemplate = function (node, index) {
15468 // add open and close tags at the same time,
15469 // since we process nested templates separately
15470 this.appendTag(TagType.TEMPLATE, node, index, false);
15471 this.appendTag(TagType.TEMPLATE, node, index, true);
15472 this._unresolvedCtxCount++;
15473 };
15474 I18nContext.prototype.appendElement = function (node, index, closed) {
15475 this.appendTag(TagType.ELEMENT, node, index, closed);
15476 };
15477 I18nContext.prototype.appendProjection = function (node, index) {
15478 // add open and close tags at the same time,
15479 // since we process projected content separately
15480 this.appendTag(TagType.PROJECTION, node, index, false);
15481 this.appendTag(TagType.PROJECTION, node, index, true);
15482 };
15483 /**
15484 * Generates an instance of a child context based on the root one,
15485 * when we enter a nested template within I18n section.
15486 *
15487 * @param index Instruction index of corresponding i18nStart, which initiates this context
15488 * @param templateIndex Instruction index of a template which this context belongs to
15489 * @param meta Meta information (id, meaning, description, etc) associated with this context
15490 *
15491 * @returns I18nContext instance
15492 */
15493 I18nContext.prototype.forkChildContext = function (index, templateIndex, meta) {
15494 return new I18nContext(index, this.ref, this.level + 1, templateIndex, meta, this._registry);
15495 };
15496 /**
15497 * Reconciles child context into parent one once the end of the i18n block is reached (i18nEnd).
15498 *
15499 * @param context Child I18nContext instance to be reconciled with parent context.
15500 */
15501 I18nContext.prototype.reconcileChildContext = function (context) {
15502 var _this = this;
15503 // set the right context id for open and close
15504 // template tags, so we can use it as sub-block ids
15505 ['start', 'close'].forEach(function (op) {
15506 var key = context.meta[op + "Name"];
15507 var phs = _this.placeholders.get(key) || [];
15508 var tag = phs.find(findTemplateFn(_this.id, context.templateIndex));
15509 if (tag) {
15510 tag.ctx = context.id;
15511 }
15512 });
15513 // reconcile placeholders
15514 var childPhs = context.placeholders;
15515 childPhs.forEach(function (values, key) {
15516 var phs = _this.placeholders.get(key);
15517 if (!phs) {
15518 _this.placeholders.set(key, values);
15519 return;
15520 }
15521 // try to find matching template...
15522 var tmplIdx = findIndex(phs, findTemplateFn(context.id, context.templateIndex));
15523 if (tmplIdx >= 0) {
15524 // ... if found - replace it with nested template content
15525 var isCloseTag = key.startsWith('CLOSE');
15526 var isTemplateTag = key.endsWith('NG-TEMPLATE');
15527 if (isTemplateTag) {
15528 // current template's content is placed before or after
15529 // parent template tag, depending on the open/close atrribute
15530 phs.splice.apply(phs, __spread([tmplIdx + (isCloseTag ? 0 : 1), 0], values));
15531 }
15532 else {
15533 var idx = isCloseTag ? values.length - 1 : 0;
15534 values[idx].tmpl = phs[tmplIdx];
15535 phs.splice.apply(phs, __spread([tmplIdx, 1], values));
15536 }
15537 }
15538 else {
15539 // ... otherwise just append content to placeholder value
15540 phs.push.apply(phs, __spread(values));
15541 }
15542 _this.placeholders.set(key, phs);
15543 });
15544 this._unresolvedCtxCount--;
15545 };
15546 return I18nContext;
15547}());
15548//
15549// Helper methods
15550//
15551function wrap(symbol, index, contextId, closed) {
15552 var state = closed ? '/' : '';
15553 return wrapI18nPlaceholder("" + state + symbol + index, contextId);
15554}
15555function wrapTag(symbol, _a, closed) {
15556 var index = _a.index, ctx = _a.ctx, isVoid = _a.isVoid;
15557 return isVoid ? wrap(symbol, index, ctx) + wrap(symbol, index, ctx, true) :
15558 wrap(symbol, index, ctx, closed);
15559}
15560function findTemplateFn(ctx, templateIndex) {
15561 return function (token) { return typeof token === 'object' && token.type === TagType.TEMPLATE &&
15562 token.index === templateIndex && token.ctx === ctx; };
15563}
15564function serializePlaceholderValue(value) {
15565 var element = function (data, closed) { return wrapTag('#', data, closed); };
15566 var template = function (data, closed) { return wrapTag('*', data, closed); };
15567 var projection = function (data, closed) { return wrapTag('!', data, closed); };
15568 switch (value.type) {
15569 case TagType.ELEMENT:
15570 // close element tag
15571 if (value.closed) {
15572 return element(value, true) + (value.tmpl ? template(value.tmpl, true) : '');
15573 }
15574 // open element tag that also initiates a template
15575 if (value.tmpl) {
15576 return template(value.tmpl) + element(value) +
15577 (value.isVoid ? template(value.tmpl, true) : '');
15578 }
15579 return element(value);
15580 case TagType.TEMPLATE:
15581 return template(value, value.closed);
15582 case TagType.PROJECTION:
15583 return projection(value, value.closed);
15584 default:
15585 return value;
15586 }
15587}
15588
15589/**
15590 * @license
15591 * Copyright Google Inc. All Rights Reserved.
15592 *
15593 * Use of this source code is governed by an MIT-style license that can be
15594 * found in the LICENSE file at https://angular.io/license
15595 */
15596var TAG_TO_PLACEHOLDER_NAMES = {
15597 'A': 'LINK',
15598 'B': 'BOLD_TEXT',
15599 'BR': 'LINE_BREAK',
15600 'EM': 'EMPHASISED_TEXT',
15601 'H1': 'HEADING_LEVEL1',
15602 'H2': 'HEADING_LEVEL2',
15603 'H3': 'HEADING_LEVEL3',
15604 'H4': 'HEADING_LEVEL4',
15605 'H5': 'HEADING_LEVEL5',
15606 'H6': 'HEADING_LEVEL6',
15607 'HR': 'HORIZONTAL_RULE',
15608 'I': 'ITALIC_TEXT',
15609 'LI': 'LIST_ITEM',
15610 'LINK': 'MEDIA_LINK',
15611 'OL': 'ORDERED_LIST',
15612 'P': 'PARAGRAPH',
15613 'Q': 'QUOTATION',
15614 'S': 'STRIKETHROUGH_TEXT',
15615 'SMALL': 'SMALL_TEXT',
15616 'SUB': 'SUBSTRIPT',
15617 'SUP': 'SUPERSCRIPT',
15618 'TBODY': 'TABLE_BODY',
15619 'TD': 'TABLE_CELL',
15620 'TFOOT': 'TABLE_FOOTER',
15621 'TH': 'TABLE_HEADER_CELL',
15622 'THEAD': 'TABLE_HEADER',
15623 'TR': 'TABLE_ROW',
15624 'TT': 'MONOSPACED_TEXT',
15625 'U': 'UNDERLINED_TEXT',
15626 'UL': 'UNORDERED_LIST',
15627};
15628/**
15629 * Creates unique names for placeholder with different content.
15630 *
15631 * Returns the same placeholder name when the content is identical.
15632 */
15633var PlaceholderRegistry = /** @class */ (function () {
15634 function PlaceholderRegistry() {
15635 // Count the occurrence of the base name top generate a unique name
15636 this._placeHolderNameCounts = {};
15637 // Maps signature to placeholder names
15638 this._signatureToName = {};
15639 }
15640 PlaceholderRegistry.prototype.getStartTagPlaceholderName = function (tag, attrs, isVoid) {
15641 var signature = this._hashTag(tag, attrs, isVoid);
15642 if (this._signatureToName[signature]) {
15643 return this._signatureToName[signature];
15644 }
15645 var upperTag = tag.toUpperCase();
15646 var baseName = TAG_TO_PLACEHOLDER_NAMES[upperTag] || "TAG_" + upperTag;
15647 var name = this._generateUniqueName(isVoid ? baseName : "START_" + baseName);
15648 this._signatureToName[signature] = name;
15649 return name;
15650 };
15651 PlaceholderRegistry.prototype.getCloseTagPlaceholderName = function (tag) {
15652 var signature = this._hashClosingTag(tag);
15653 if (this._signatureToName[signature]) {
15654 return this._signatureToName[signature];
15655 }
15656 var upperTag = tag.toUpperCase();
15657 var baseName = TAG_TO_PLACEHOLDER_NAMES[upperTag] || "TAG_" + upperTag;
15658 var name = this._generateUniqueName("CLOSE_" + baseName);
15659 this._signatureToName[signature] = name;
15660 return name;
15661 };
15662 PlaceholderRegistry.prototype.getPlaceholderName = function (name, content) {
15663 var upperName = name.toUpperCase();
15664 var signature = "PH: " + upperName + "=" + content;
15665 if (this._signatureToName[signature]) {
15666 return this._signatureToName[signature];
15667 }
15668 var uniqueName = this._generateUniqueName(upperName);
15669 this._signatureToName[signature] = uniqueName;
15670 return uniqueName;
15671 };
15672 PlaceholderRegistry.prototype.getUniquePlaceholder = function (name) {
15673 return this._generateUniqueName(name.toUpperCase());
15674 };
15675 // Generate a hash for a tag - does not take attribute order into account
15676 PlaceholderRegistry.prototype._hashTag = function (tag, attrs, isVoid) {
15677 var start = "<" + tag;
15678 var strAttrs = Object.keys(attrs).sort().map(function (name) { return " " + name + "=" + attrs[name]; }).join('');
15679 var end = isVoid ? '/>' : "></" + tag + ">";
15680 return start + strAttrs + end;
15681 };
15682 PlaceholderRegistry.prototype._hashClosingTag = function (tag) { return this._hashTag("/" + tag, {}, false); };
15683 PlaceholderRegistry.prototype._generateUniqueName = function (base) {
15684 var seen = this._placeHolderNameCounts.hasOwnProperty(base);
15685 if (!seen) {
15686 this._placeHolderNameCounts[base] = 1;
15687 return base;
15688 }
15689 var id = this._placeHolderNameCounts[base];
15690 this._placeHolderNameCounts[base] = id + 1;
15691 return base + "_" + id;
15692 };
15693 return PlaceholderRegistry;
15694}());
15695
15696/**
15697 * @license
15698 * Copyright Google Inc. All Rights Reserved.
15699 *
15700 * Use of this source code is governed by an MIT-style license that can be
15701 * found in the LICENSE file at https://angular.io/license
15702 */
15703var _expParser = new Parser$1(new Lexer());
15704/**
15705 * Returns a function converting html nodes to an i18n Message given an interpolationConfig
15706 */
15707function createI18nMessageFactory(interpolationConfig) {
15708 var visitor = new _I18nVisitor(_expParser, interpolationConfig);
15709 return function (nodes, meaning, description, id, visitNodeFn) {
15710 return visitor.toI18nMessage(nodes, meaning, description, id, visitNodeFn);
15711 };
15712}
15713var _I18nVisitor = /** @class */ (function () {
15714 function _I18nVisitor(_expressionParser, _interpolationConfig) {
15715 this._expressionParser = _expressionParser;
15716 this._interpolationConfig = _interpolationConfig;
15717 }
15718 _I18nVisitor.prototype.toI18nMessage = function (nodes, meaning, description, id, visitNodeFn) {
15719 this._isIcu = nodes.length == 1 && nodes[0] instanceof Expansion;
15720 this._icuDepth = 0;
15721 this._placeholderRegistry = new PlaceholderRegistry();
15722 this._placeholderToContent = {};
15723 this._placeholderToMessage = {};
15724 this._visitNodeFn = visitNodeFn;
15725 var i18nodes = visitAll$1(this, nodes, {});
15726 return new Message(i18nodes, this._placeholderToContent, this._placeholderToMessage, meaning, description, id);
15727 };
15728 _I18nVisitor.prototype._visitNode = function (html, i18n) {
15729 if (this._visitNodeFn) {
15730 this._visitNodeFn(html, i18n);
15731 }
15732 return i18n;
15733 };
15734 _I18nVisitor.prototype.visitElement = function (el, context) {
15735 var children = visitAll$1(this, el.children);
15736 var attrs = {};
15737 el.attrs.forEach(function (attr) {
15738 // Do not visit the attributes, translatable ones are top-level ASTs
15739 attrs[attr.name] = attr.value;
15740 });
15741 var isVoid = getHtmlTagDefinition(el.name).isVoid;
15742 var startPhName = this._placeholderRegistry.getStartTagPlaceholderName(el.name, attrs, isVoid);
15743 this._placeholderToContent[startPhName] = el.sourceSpan.toString();
15744 var closePhName = '';
15745 if (!isVoid) {
15746 closePhName = this._placeholderRegistry.getCloseTagPlaceholderName(el.name);
15747 this._placeholderToContent[closePhName] = "</" + el.name + ">";
15748 }
15749 var node = new TagPlaceholder(el.name, attrs, startPhName, closePhName, children, isVoid, el.sourceSpan);
15750 return this._visitNode(el, node);
15751 };
15752 _I18nVisitor.prototype.visitAttribute = function (attribute, context) {
15753 var node = this._visitTextWithInterpolation(attribute.value, attribute.sourceSpan);
15754 return this._visitNode(attribute, node);
15755 };
15756 _I18nVisitor.prototype.visitText = function (text, context) {
15757 var node = this._visitTextWithInterpolation(text.value, text.sourceSpan);
15758 return this._visitNode(text, node);
15759 };
15760 _I18nVisitor.prototype.visitComment = function (comment, context) { return null; };
15761 _I18nVisitor.prototype.visitExpansion = function (icu, context) {
15762 var _this = this;
15763 this._icuDepth++;
15764 var i18nIcuCases = {};
15765 var i18nIcu = new Icu$1(icu.switchValue, icu.type, i18nIcuCases, icu.sourceSpan);
15766 icu.cases.forEach(function (caze) {
15767 i18nIcuCases[caze.value] = new Container(caze.expression.map(function (node) { return node.visit(_this, {}); }), caze.expSourceSpan);
15768 });
15769 this._icuDepth--;
15770 if (this._isIcu || this._icuDepth > 0) {
15771 // Returns an ICU node when:
15772 // - the message (vs a part of the message) is an ICU message, or
15773 // - the ICU message is nested.
15774 var expPh = this._placeholderRegistry.getUniquePlaceholder("VAR_" + icu.type);
15775 i18nIcu.expressionPlaceholder = expPh;
15776 this._placeholderToContent[expPh] = icu.switchValue;
15777 return this._visitNode(icu, i18nIcu);
15778 }
15779 // Else returns a placeholder
15780 // ICU placeholders should not be replaced with their original content but with the their
15781 // translations. We need to create a new visitor (they are not re-entrant) to compute the
15782 // message id.
15783 // TODO(vicb): add a html.Node -> i18n.Message cache to avoid having to re-create the msg
15784 var phName = this._placeholderRegistry.getPlaceholderName('ICU', icu.sourceSpan.toString());
15785 var visitor = new _I18nVisitor(this._expressionParser, this._interpolationConfig);
15786 this._placeholderToMessage[phName] = visitor.toI18nMessage([icu], '', '', '');
15787 var node = new IcuPlaceholder(i18nIcu, phName, icu.sourceSpan);
15788 return this._visitNode(icu, node);
15789 };
15790 _I18nVisitor.prototype.visitExpansionCase = function (icuCase, context) {
15791 throw new Error('Unreachable code');
15792 };
15793 _I18nVisitor.prototype._visitTextWithInterpolation = function (text, sourceSpan) {
15794 var splitInterpolation = this._expressionParser.splitInterpolation(text, sourceSpan.start.toString(), this._interpolationConfig);
15795 if (!splitInterpolation) {
15796 // No expression, return a single text
15797 return new Text$1(text, sourceSpan);
15798 }
15799 // Return a group of text + expressions
15800 var nodes = [];
15801 var container = new Container(nodes, sourceSpan);
15802 var _a = this._interpolationConfig, sDelimiter = _a.start, eDelimiter = _a.end;
15803 for (var i = 0; i < splitInterpolation.strings.length - 1; i++) {
15804 var expression = splitInterpolation.expressions[i];
15805 var baseName = _extractPlaceholderName(expression) || 'INTERPOLATION';
15806 var phName = this._placeholderRegistry.getPlaceholderName(baseName, expression);
15807 if (splitInterpolation.strings[i].length) {
15808 // No need to add empty strings
15809 nodes.push(new Text$1(splitInterpolation.strings[i], sourceSpan));
15810 }
15811 nodes.push(new Placeholder(expression, phName, sourceSpan));
15812 this._placeholderToContent[phName] = sDelimiter + expression + eDelimiter;
15813 }
15814 // The last index contains no expression
15815 var lastStringIdx = splitInterpolation.strings.length - 1;
15816 if (splitInterpolation.strings[lastStringIdx].length) {
15817 nodes.push(new Text$1(splitInterpolation.strings[lastStringIdx], sourceSpan));
15818 }
15819 return container;
15820 };
15821 return _I18nVisitor;
15822}());
15823var _CUSTOM_PH_EXP = /\/\/[\s\S]*i18n[\s\S]*\([\s\S]*ph[\s\S]*=[\s\S]*("|')([\s\S]*?)\1[\s\S]*\)/g;
15824function _extractPlaceholderName(input) {
15825 return input.split(_CUSTOM_PH_EXP)[2];
15826}
15827
15828/**
15829 * @license
15830 * Copyright Google Inc. All Rights Reserved.
15831 *
15832 * Use of this source code is governed by an MIT-style license that can be
15833 * found in the LICENSE file at https://angular.io/license
15834 */
15835function setI18nRefs(html, i18n) {
15836 html.i18n = i18n;
15837}
15838/**
15839 * This visitor walks over HTML parse tree and converts information stored in
15840 * i18n-related attributes ("i18n" and "i18n-*") into i18n meta object that is
15841 * stored with other element's and attribute's information.
15842 */
15843var I18nMetaVisitor = /** @class */ (function () {
15844 function I18nMetaVisitor(interpolationConfig, keepI18nAttrs) {
15845 if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
15846 if (keepI18nAttrs === void 0) { keepI18nAttrs = false; }
15847 this.interpolationConfig = interpolationConfig;
15848 this.keepI18nAttrs = keepI18nAttrs;
15849 // i18n message generation factory
15850 this._createI18nMessage = createI18nMessageFactory(interpolationConfig);
15851 }
15852 I18nMetaVisitor.prototype._generateI18nMessage = function (nodes, meta, visitNodeFn) {
15853 if (meta === void 0) { meta = ''; }
15854 var parsed = typeof meta === 'string' ? parseI18nMeta(meta) : metaFromI18nMessage(meta);
15855 var message = this._createI18nMessage(nodes, parsed.meaning || '', parsed.description || '', parsed.id || '', visitNodeFn);
15856 if (!message.id) {
15857 // generate (or restore) message id if not specified in template
15858 message.id = typeof meta !== 'string' && meta.id || decimalDigest(message);
15859 }
15860 return message;
15861 };
15862 I18nMetaVisitor.prototype.visitElement = function (element, context) {
15863 var e_1, _a, e_2, _b;
15864 if (hasI18nAttrs(element)) {
15865 var attrs = [];
15866 var attrsMeta = {};
15867 try {
15868 for (var _c = __values(element.attrs), _d = _c.next(); !_d.done; _d = _c.next()) {
15869 var attr = _d.value;
15870 if (attr.name === I18N_ATTR) {
15871 // root 'i18n' node attribute
15872 var i18n_1 = element.i18n || attr.value;
15873 var message = this._generateI18nMessage(element.children, i18n_1, setI18nRefs);
15874 // do not assign empty i18n meta
15875 if (message.nodes.length) {
15876 element.i18n = message;
15877 }
15878 }
15879 else if (attr.name.startsWith(I18N_ATTR_PREFIX)) {
15880 // 'i18n-*' attributes
15881 var key = attr.name.slice(I18N_ATTR_PREFIX.length);
15882 attrsMeta[key] = attr.value;
15883 }
15884 else {
15885 // non-i18n attributes
15886 attrs.push(attr);
15887 }
15888 }
15889 }
15890 catch (e_1_1) { e_1 = { error: e_1_1 }; }
15891 finally {
15892 try {
15893 if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
15894 }
15895 finally { if (e_1) throw e_1.error; }
15896 }
15897 // set i18n meta for attributes
15898 if (Object.keys(attrsMeta).length) {
15899 try {
15900 for (var attrs_1 = __values(attrs), attrs_1_1 = attrs_1.next(); !attrs_1_1.done; attrs_1_1 = attrs_1.next()) {
15901 var attr = attrs_1_1.value;
15902 var meta = attrsMeta[attr.name];
15903 // do not create translation for empty attributes
15904 if (meta !== undefined && attr.value) {
15905 attr.i18n = this._generateI18nMessage([attr], attr.i18n || meta);
15906 }
15907 }
15908 }
15909 catch (e_2_1) { e_2 = { error: e_2_1 }; }
15910 finally {
15911 try {
15912 if (attrs_1_1 && !attrs_1_1.done && (_b = attrs_1.return)) _b.call(attrs_1);
15913 }
15914 finally { if (e_2) throw e_2.error; }
15915 }
15916 }
15917 if (!this.keepI18nAttrs) {
15918 // update element's attributes,
15919 // keeping only non-i18n related ones
15920 element.attrs = attrs;
15921 }
15922 }
15923 visitAll$1(this, element.children);
15924 return element;
15925 };
15926 I18nMetaVisitor.prototype.visitExpansion = function (expansion, context) {
15927 var message;
15928 var meta = expansion.i18n;
15929 if (meta instanceof IcuPlaceholder) {
15930 // set ICU placeholder name (e.g. "ICU_1"),
15931 // generated while processing root element contents,
15932 // so we can reference it when we output translation
15933 var name_1 = meta.name;
15934 message = this._generateI18nMessage([expansion], meta);
15935 var icu = icuFromI18nMessage(message);
15936 icu.name = name_1;
15937 }
15938 else {
15939 // when ICU is a root level translation
15940 message = this._generateI18nMessage([expansion], meta);
15941 }
15942 expansion.i18n = message;
15943 return expansion;
15944 };
15945 I18nMetaVisitor.prototype.visitText = function (text, context) { return text; };
15946 I18nMetaVisitor.prototype.visitAttribute = function (attribute, context) { return attribute; };
15947 I18nMetaVisitor.prototype.visitComment = function (comment, context) { return comment; };
15948 I18nMetaVisitor.prototype.visitExpansionCase = function (expansionCase, context) { return expansionCase; };
15949 return I18nMetaVisitor;
15950}());
15951function processI18nMeta(htmlAstWithErrors, interpolationConfig) {
15952 if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
15953 return new ParseTreeResult(visitAll$1(new I18nMetaVisitor(interpolationConfig, /* keepI18nAttrs */ false), htmlAstWithErrors.rootNodes), htmlAstWithErrors.errors);
15954}
15955
15956/**
15957 * @license
15958 * Copyright Google Inc. All Rights Reserved.
15959 *
15960 * Use of this source code is governed by an MIT-style license that can be
15961 * found in the LICENSE file at https://angular.io/license
15962 */
15963/**
15964 * This visitor walks over i18n tree and generates its string representation, including ICUs and
15965 * placeholders in `{$placeholder}` (for plain messages) or `{PLACEHOLDER}` (inside ICUs) format.
15966 */
15967var SerializerVisitor = /** @class */ (function () {
15968 function SerializerVisitor() {
15969 /**
15970 * Keeps track of ICU nesting level, allowing to detect that we are processing elements of an ICU.
15971 *
15972 * This is needed due to the fact that placeholders in ICUs and in other messages are represented
15973 * differently in Closure:
15974 * - {$placeholder} in non-ICU case
15975 * - {PLACEHOLDER} inside ICU
15976 */
15977 this.icuNestingLevel = 0;
15978 }
15979 SerializerVisitor.prototype.formatPh = function (value) {
15980 var isInsideIcu = this.icuNestingLevel > 0;
15981 var formatted = formatI18nPlaceholderName(value, /* useCamelCase */ !isInsideIcu);
15982 return isInsideIcu ? "{" + formatted + "}" : "{$" + formatted + "}";
15983 };
15984 SerializerVisitor.prototype.visitText = function (text, context) { return text.value; };
15985 SerializerVisitor.prototype.visitContainer = function (container, context) {
15986 var _this = this;
15987 return container.children.map(function (child) { return child.visit(_this); }).join('');
15988 };
15989 SerializerVisitor.prototype.visitIcu = function (icu, context) {
15990 var _this = this;
15991 this.icuNestingLevel++;
15992 var strCases = Object.keys(icu.cases).map(function (k) { return k + " {" + icu.cases[k].visit(_this) + "}"; });
15993 var result = "{" + icu.expressionPlaceholder + ", " + icu.type + ", " + strCases.join(' ') + "}";
15994 this.icuNestingLevel--;
15995 return result;
15996 };
15997 SerializerVisitor.prototype.visitTagPlaceholder = function (ph, context) {
15998 var _this = this;
15999 return ph.isVoid ?
16000 this.formatPh(ph.startName) :
16001 "" + this.formatPh(ph.startName) + ph.children.map(function (child) { return child.visit(_this); }).join('') + this.formatPh(ph.closeName);
16002 };
16003 SerializerVisitor.prototype.visitPlaceholder = function (ph, context) { return this.formatPh(ph.name); };
16004 SerializerVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
16005 return this.formatPh(ph.name);
16006 };
16007 return SerializerVisitor;
16008}());
16009var serializerVisitor$1 = new SerializerVisitor();
16010function getSerializedI18nContent(message) {
16011 return message.nodes.map(function (node) { return node.visit(serializerVisitor$1, null); }).join('');
16012}
16013
16014/**
16015 * @license
16016 * Copyright Google Inc. All Rights Reserved.
16017 *
16018 * Use of this source code is governed by an MIT-style license that can be
16019 * found in the LICENSE file at https://angular.io/license
16020 */
16021// Selector attribute name of `<ng-content>`
16022var NG_CONTENT_SELECT_ATTR$1 = 'select';
16023// Attribute name of `ngProjectAs`.
16024var NG_PROJECT_AS_ATTR_NAME = 'ngProjectAs';
16025// List of supported global targets for event listeners
16026var GLOBAL_TARGET_RESOLVERS = new Map([['window', Identifiers$1.resolveWindow], ['document', Identifiers$1.resolveDocument], ['body', Identifiers$1.resolveBody]]);
16027var LEADING_TRIVIA_CHARS = [' ', '\n', '\r', '\t'];
16028// if (rf & flags) { .. }
16029function renderFlagCheckIfStmt(flags, statements) {
16030 return ifStmt(variable(RENDER_FLAGS).bitwiseAnd(literal(flags), null, false), statements);
16031}
16032function prepareEventListenerParameters(eventAst, handlerName, scope) {
16033 if (handlerName === void 0) { handlerName = null; }
16034 if (scope === void 0) { scope = null; }
16035 var type = eventAst.type, name = eventAst.name, target = eventAst.target, phase = eventAst.phase, handler = eventAst.handler;
16036 if (target && !GLOBAL_TARGET_RESOLVERS.has(target)) {
16037 throw new Error("Unexpected global target '" + target + "' defined for '" + name + "' event.\n Supported list of global targets: " + Array.from(GLOBAL_TARGET_RESOLVERS.keys()) + ".");
16038 }
16039 var implicitReceiverExpr = (scope === null || scope.bindingLevel === 0) ?
16040 variable(CONTEXT_NAME) :
16041 scope.getOrCreateSharedContextVar(0);
16042 var bindingExpr = convertActionBinding(scope, implicitReceiverExpr, handler, 'b', function () { return error('Unexpected interpolation'); }, eventAst.handlerSpan);
16043 var statements = [];
16044 if (scope) {
16045 statements.push.apply(statements, __spread(scope.restoreViewStatement()));
16046 statements.push.apply(statements, __spread(scope.variableDeclarations()));
16047 }
16048 statements.push.apply(statements, __spread(bindingExpr.render3Stmts));
16049 var eventName = type === 1 /* Animation */ ? prepareSyntheticListenerName(name, phase) : name;
16050 var fnName = handlerName && sanitizeIdentifier(handlerName);
16051 var fnArgs = [new FnParam('$event', DYNAMIC_TYPE)];
16052 var handlerFn = fn(fnArgs, statements, INFERRED_TYPE, null, fnName);
16053 var params = [literal(eventName), handlerFn];
16054 if (target) {
16055 params.push(literal(false), // `useCapture` flag, defaults to `false`
16056 importExpr(GLOBAL_TARGET_RESOLVERS.get(target)));
16057 }
16058 return params;
16059}
16060var TemplateDefinitionBuilder = /** @class */ (function () {
16061 function TemplateDefinitionBuilder(constantPool, parentBindingScope, level, contextName, i18nContext, templateIndex, templateName, directiveMatcher, directives, pipeTypeByName, pipes, _namespace, relativeContextFilePath, i18nUseExternalIds) {
16062 var _this = this;
16063 if (level === void 0) { level = 0; }
16064 this.constantPool = constantPool;
16065 this.level = level;
16066 this.contextName = contextName;
16067 this.i18nContext = i18nContext;
16068 this.templateIndex = templateIndex;
16069 this.templateName = templateName;
16070 this.directiveMatcher = directiveMatcher;
16071 this.directives = directives;
16072 this.pipeTypeByName = pipeTypeByName;
16073 this.pipes = pipes;
16074 this._namespace = _namespace;
16075 this.relativeContextFilePath = relativeContextFilePath;
16076 this.i18nUseExternalIds = i18nUseExternalIds;
16077 this._dataIndex = 0;
16078 this._bindingContext = 0;
16079 this._prefixCode = [];
16080 /**
16081 * List of callbacks to generate creation mode instructions. We store them here as we process
16082 * the template so bindings in listeners are resolved only once all nodes have been visited.
16083 * This ensures all local refs and context variables are available for matching.
16084 */
16085 this._creationCodeFns = [];
16086 /**
16087 * List of callbacks to generate update mode instructions. We store them here as we process
16088 * the template so bindings are resolved only once all nodes have been visited. This ensures
16089 * all local refs and context variables are available for matching.
16090 */
16091 this._updateCodeFns = [];
16092 /**
16093 * Memorizes the last node index for which a select instruction has been generated.
16094 * We're initializing this to -1 to ensure the `select(0)` instruction is generated before any
16095 * relevant update instructions.
16096 */
16097 this._lastNodeIndexWithFlush = -1;
16098 /** Temporary variable declarations generated from visiting pipes, literals, etc. */
16099 this._tempVariables = [];
16100 /**
16101 * List of callbacks to build nested templates. Nested templates must not be visited until
16102 * after the parent template has finished visiting all of its nodes. This ensures that all
16103 * local ref bindings in nested templates are able to find local ref values if the refs
16104 * are defined after the template declaration.
16105 */
16106 this._nestedTemplateFns = [];
16107 this._unsupported = unsupported;
16108 // i18n context local to this template
16109 this.i18n = null;
16110 // Number of slots to reserve for pureFunctions
16111 this._pureFunctionSlots = 0;
16112 // Number of binding slots
16113 this._bindingSlots = 0;
16114 // Projection slots found in the template. Projection slots can distribute projected
16115 // nodes based on a selector, or can just use the wildcard selector to match
16116 // all nodes which aren't matching any selector.
16117 this._ngContentReservedSlots = [];
16118 // Number of non-default selectors found in all parent templates of this template. We need to
16119 // track it to properly adjust projection slot index in the `projection` instruction.
16120 this._ngContentSelectorsOffset = 0;
16121 // Expression that should be used as implicit receiver when converting template
16122 // expressions to output AST.
16123 this._implicitReceiverExpr = null;
16124 // These should be handled in the template or element directly.
16125 this.visitReference = invalid$1;
16126 this.visitVariable = invalid$1;
16127 this.visitTextAttribute = invalid$1;
16128 this.visitBoundAttribute = invalid$1;
16129 this.visitBoundEvent = invalid$1;
16130 this._bindingScope = parentBindingScope.nestedScope(level);
16131 // Turn the relative context file path into an identifier by replacing non-alphanumeric
16132 // characters with underscores.
16133 this.fileBasedI18nSuffix = relativeContextFilePath.replace(/[^A-Za-z0-9]/g, '_') + '_';
16134 this._valueConverter = new ValueConverter(constantPool, function () { return _this.allocateDataSlot(); }, function (numSlots) { return _this.allocatePureFunctionSlots(numSlots); }, function (name, localName, slot, value) {
16135 var pipeType = pipeTypeByName.get(name);
16136 if (pipeType) {
16137 _this.pipes.add(pipeType);
16138 }
16139 _this._bindingScope.set(_this.level, localName, value);
16140 _this.creationInstruction(null, Identifiers$1.pipe, [literal(slot), literal(name)]);
16141 });
16142 }
16143 TemplateDefinitionBuilder.prototype.registerContextVariables = function (variable$1) {
16144 var scopedName = this._bindingScope.freshReferenceName();
16145 var retrievalLevel = this.level;
16146 var lhs = variable(variable$1.name + scopedName);
16147 this._bindingScope.set(retrievalLevel, variable$1.name, lhs, 1 /* CONTEXT */, function (scope, relativeLevel) {
16148 var rhs;
16149 if (scope.bindingLevel === retrievalLevel) {
16150 // e.g. ctx
16151 rhs = variable(CONTEXT_NAME);
16152 }
16153 else {
16154 var sharedCtxVar = scope.getSharedContextName(retrievalLevel);
16155 // e.g. ctx_r0 OR x(2);
16156 rhs = sharedCtxVar ? sharedCtxVar : generateNextContextExpr(relativeLevel);
16157 }
16158 // e.g. const $item$ = x(2).$implicit;
16159 return [lhs.set(rhs.prop(variable$1.value || IMPLICIT_REFERENCE)).toConstDecl()];
16160 });
16161 };
16162 TemplateDefinitionBuilder.prototype.buildTemplateFunction = function (nodes, variables, ngContentSelectorsOffset, i18n) {
16163 var _this = this;
16164 if (ngContentSelectorsOffset === void 0) { ngContentSelectorsOffset = 0; }
16165 this._ngContentSelectorsOffset = ngContentSelectorsOffset;
16166 if (this._namespace !== Identifiers$1.namespaceHTML) {
16167 this.creationInstruction(null, this._namespace);
16168 }
16169 // Create variable bindings
16170 variables.forEach(function (v) { return _this.registerContextVariables(v); });
16171 // Initiate i18n context in case:
16172 // - this template has parent i18n context
16173 // - or the template has i18n meta associated with it,
16174 // but it's not initiated by the Element (e.g. <ng-template i18n>)
16175 var initI18nContext = this.i18nContext || (isI18nRootNode(i18n) && !isSingleI18nIcu(i18n) &&
16176 !(isSingleElementTemplate(nodes) && nodes[0].i18n === i18n));
16177 var selfClosingI18nInstruction = hasTextChildrenOnly(nodes);
16178 if (initI18nContext) {
16179 this.i18nStart(null, i18n, selfClosingI18nInstruction);
16180 }
16181 // This is the initial pass through the nodes of this template. In this pass, we
16182 // queue all creation mode and update mode instructions for generation in the second
16183 // pass. It's necessary to separate the passes to ensure local refs are defined before
16184 // resolving bindings. We also count bindings in this pass as we walk bound expressions.
16185 visitAll(this, nodes);
16186 // Add total binding count to pure function count so pure function instructions are
16187 // generated with the correct slot offset when update instructions are processed.
16188 this._pureFunctionSlots += this._bindingSlots;
16189 // Pipes are walked in the first pass (to enqueue `pipe()` creation instructions and
16190 // `pipeBind` update instructions), so we have to update the slot offsets manually
16191 // to account for bindings.
16192 this._valueConverter.updatePipeSlotOffsets(this._bindingSlots);
16193 // Nested templates must be processed before creation instructions so template()
16194 // instructions can be generated with the correct internal const count.
16195 this._nestedTemplateFns.forEach(function (buildTemplateFn) { return buildTemplateFn(); });
16196 // Output the `projectionDef` instruction when some `<ng-content>` tags are present.
16197 // The `projectionDef` instruction is only emitted for the component template and
16198 // is skipped for nested templates (<ng-template> tags).
16199 if (this.level === 0 && this._ngContentReservedSlots.length) {
16200 var parameters = [];
16201 // By default the `projectionDef` instructions creates one slot for the wildcard
16202 // selector if no parameters are passed. Therefore we only want to allocate a new
16203 // array for the projection slots if the default projection slot is not sufficient.
16204 if (this._ngContentReservedSlots.length > 1 || this._ngContentReservedSlots[0] !== '*') {
16205 var r3ReservedSlots = this._ngContentReservedSlots.map(function (s) { return s !== '*' ? parseSelectorToR3Selector(s) : s; });
16206 parameters.push(this.constantPool.getConstLiteral(asLiteral(r3ReservedSlots), true));
16207 }
16208 // Since we accumulate ngContent selectors while processing template elements,
16209 // we *prepend* `projectionDef` to creation instructions block, to put it before
16210 // any `projection` instructions
16211 this.creationInstruction(null, Identifiers$1.projectionDef, parameters, /* prepend */ true);
16212 }
16213 if (initI18nContext) {
16214 this.i18nEnd(null, selfClosingI18nInstruction);
16215 }
16216 // Generate all the creation mode instructions (e.g. resolve bindings in listeners)
16217 var creationStatements = this._creationCodeFns.map(function (fn) { return fn(); });
16218 // Generate all the update mode instructions (e.g. resolve property or text bindings)
16219 var updateStatements = this._updateCodeFns.map(function (fn) { return fn(); });
16220 // Variable declaration must occur after binding resolution so we can generate context
16221 // instructions that build on each other.
16222 // e.g. const b = nextContext().$implicit(); const b = nextContext();
16223 var creationVariables = this._bindingScope.viewSnapshotStatements();
16224 var updateVariables = this._bindingScope.variableDeclarations().concat(this._tempVariables);
16225 var creationBlock = creationStatements.length > 0 ?
16226 [renderFlagCheckIfStmt(1 /* Create */, creationVariables.concat(creationStatements))] :
16227 [];
16228 var updateBlock = updateStatements.length > 0 ?
16229 [renderFlagCheckIfStmt(2 /* Update */, updateVariables.concat(updateStatements))] :
16230 [];
16231 return fn(
16232 // i.e. (rf: RenderFlags, ctx: any)
16233 [new FnParam(RENDER_FLAGS, NUMBER_TYPE), new FnParam(CONTEXT_NAME, null)], __spread(this._prefixCode, creationBlock, updateBlock), INFERRED_TYPE, null, this.templateName);
16234 };
16235 // LocalResolver
16236 TemplateDefinitionBuilder.prototype.getLocal = function (name) { return this._bindingScope.get(name); };
16237 // LocalResolver
16238 TemplateDefinitionBuilder.prototype.notifyImplicitReceiverUse = function () { this._bindingScope.notifyImplicitReceiverUse(); };
16239 TemplateDefinitionBuilder.prototype.i18nTranslate = function (message, params, ref, transformFn) {
16240 var _a;
16241 if (params === void 0) { params = {}; }
16242 var _ref = ref || variable(this.constantPool.uniqueName(TRANSLATION_PREFIX));
16243 // Closure Compiler requires const names to start with `MSG_` but disallows any other const to
16244 // start with `MSG_`. We define a variable starting with `MSG_` just for the `goog.getMsg` call
16245 var closureVar = this.i18nGenerateClosureVar(message.id);
16246 var formattedParams = this.i18nFormatPlaceholderNames(params, /* useCamelCase */ true);
16247 var meta = metaFromI18nMessage(message);
16248 var content = getSerializedI18nContent(message);
16249 var statements = getTranslationDeclStmts(_ref, closureVar, content, meta, formattedParams, transformFn);
16250 (_a = this.constantPool.statements).push.apply(_a, __spread(statements));
16251 return _ref;
16252 };
16253 TemplateDefinitionBuilder.prototype.i18nFormatPlaceholderNames = function (params, useCamelCase) {
16254 if (params === void 0) { params = {}; }
16255 var _params = {};
16256 if (params && Object.keys(params).length) {
16257 Object.keys(params).forEach(function (key) { return _params[formatI18nPlaceholderName(key, useCamelCase)] = params[key]; });
16258 }
16259 return _params;
16260 };
16261 TemplateDefinitionBuilder.prototype.i18nAppendBindings = function (expressions) {
16262 var _this = this;
16263 if (expressions.length > 0) {
16264 expressions.forEach(function (expression) { return _this.i18n.appendBinding(expression); });
16265 }
16266 };
16267 TemplateDefinitionBuilder.prototype.i18nBindProps = function (props) {
16268 var _this = this;
16269 var bound = {};
16270 Object.keys(props).forEach(function (key) {
16271 var prop = props[key];
16272 if (prop instanceof Text) {
16273 bound[key] = literal(prop.value);
16274 }
16275 else {
16276 var value = prop.value.visit(_this._valueConverter);
16277 _this.allocateBindingSlots(value);
16278 if (value instanceof Interpolation) {
16279 var strings = value.strings, expressions = value.expressions;
16280 var _a = _this.i18n, id = _a.id, bindings = _a.bindings;
16281 var label = assembleI18nBoundString(strings, bindings.size, id);
16282 _this.i18nAppendBindings(expressions);
16283 bound[key] = literal(label);
16284 }
16285 }
16286 });
16287 return bound;
16288 };
16289 TemplateDefinitionBuilder.prototype.i18nGenerateClosureVar = function (messageId) {
16290 var name;
16291 var suffix = this.fileBasedI18nSuffix.toUpperCase();
16292 if (this.i18nUseExternalIds) {
16293 var prefix = getTranslationConstPrefix("EXTERNAL_");
16294 var uniqueSuffix = this.constantPool.uniqueName(suffix);
16295 name = "" + prefix + sanitizeIdentifier(messageId) + "$$" + uniqueSuffix;
16296 }
16297 else {
16298 var prefix = getTranslationConstPrefix(suffix);
16299 name = this.constantPool.uniqueName(prefix);
16300 }
16301 return variable(name);
16302 };
16303 TemplateDefinitionBuilder.prototype.i18nUpdateRef = function (context) {
16304 var icus = context.icus, meta = context.meta, isRoot = context.isRoot, isResolved = context.isResolved, isEmitted = context.isEmitted;
16305 if (isRoot && isResolved && !isEmitted && !isSingleI18nIcu(meta)) {
16306 context.isEmitted = true;
16307 var placeholders = context.getSerializedPlaceholders();
16308 var icuMapping_1 = {};
16309 var params_1 = placeholders.size ? placeholdersToParams(placeholders) : {};
16310 if (icus.size) {
16311 icus.forEach(function (refs, key) {
16312 if (refs.length === 1) {
16313 // if we have one ICU defined for a given
16314 // placeholder - just output its reference
16315 params_1[key] = refs[0];
16316 }
16317 else {
16318 // ... otherwise we need to activate post-processing
16319 // to replace ICU placeholders with proper values
16320 var placeholder = wrapI18nPlaceholder("" + I18N_ICU_MAPPING_PREFIX + key);
16321 params_1[key] = literal(placeholder);
16322 icuMapping_1[key] = literalArr(refs);
16323 }
16324 });
16325 }
16326 // translation requires post processing in 2 cases:
16327 // - if we have placeholders with multiple values (ex. `START_DIV`: [�#1�, �#2�, ...])
16328 // - if we have multiple ICUs that refer to the same placeholder name
16329 var needsPostprocessing = Array.from(placeholders.values()).some(function (value) { return value.length > 1; }) ||
16330 Object.keys(icuMapping_1).length;
16331 var transformFn = void 0;
16332 if (needsPostprocessing) {
16333 transformFn = function (raw) {
16334 var args = [raw];
16335 if (Object.keys(icuMapping_1).length) {
16336 args.push(mapLiteral(icuMapping_1, true));
16337 }
16338 return instruction(null, Identifiers$1.i18nPostprocess, args);
16339 };
16340 }
16341 this.i18nTranslate(meta, params_1, context.ref, transformFn);
16342 }
16343 };
16344 TemplateDefinitionBuilder.prototype.i18nStart = function (span, meta, selfClosing) {
16345 if (span === void 0) { span = null; }
16346 var index = this.allocateDataSlot();
16347 if (this.i18nContext) {
16348 this.i18n = this.i18nContext.forkChildContext(index, this.templateIndex, meta);
16349 }
16350 else {
16351 var ref_1 = variable(this.constantPool.uniqueName(TRANSLATION_PREFIX));
16352 this.i18n = new I18nContext(index, ref_1, 0, this.templateIndex, meta);
16353 }
16354 // generate i18nStart instruction
16355 var _a = this.i18n, id = _a.id, ref = _a.ref;
16356 var params = [literal(index), ref];
16357 if (id > 0) {
16358 // do not push 3rd argument (sub-block id)
16359 // into i18nStart call for top level i18n context
16360 params.push(literal(id));
16361 }
16362 this.creationInstruction(span, selfClosing ? Identifiers$1.i18n : Identifiers$1.i18nStart, params);
16363 };
16364 TemplateDefinitionBuilder.prototype.i18nEnd = function (span, selfClosing) {
16365 var _this = this;
16366 if (span === void 0) { span = null; }
16367 if (!this.i18n) {
16368 throw new Error('i18nEnd is executed with no i18n context present');
16369 }
16370 if (this.i18nContext) {
16371 this.i18nContext.reconcileChildContext(this.i18n);
16372 this.i18nUpdateRef(this.i18nContext);
16373 }
16374 else {
16375 this.i18nUpdateRef(this.i18n);
16376 }
16377 // setup accumulated bindings
16378 var _a = this.i18n, index = _a.index, bindings = _a.bindings;
16379 if (bindings.size) {
16380 var chainBindings_1 = [];
16381 bindings.forEach(function (binding) {
16382 chainBindings_1.push({ sourceSpan: span, value: function () { return _this.convertPropertyBinding(binding); } });
16383 });
16384 this.updateInstructionChain(index, Identifiers$1.i18nExp, chainBindings_1);
16385 this.updateInstruction(index, span, Identifiers$1.i18nApply, [literal(index)]);
16386 }
16387 if (!selfClosing) {
16388 this.creationInstruction(span, Identifiers$1.i18nEnd);
16389 }
16390 this.i18n = null; // reset local i18n context
16391 };
16392 TemplateDefinitionBuilder.prototype.visitContent = function (ngContent) {
16393 var slot = this.allocateDataSlot();
16394 var projectionSlotIdx = this._ngContentSelectorsOffset + this._ngContentReservedSlots.length;
16395 var parameters = [literal(slot)];
16396 var attributes = [];
16397 this._ngContentReservedSlots.push(ngContent.selector);
16398 ngContent.attributes.forEach(function (attribute) {
16399 var name = attribute.name, value = attribute.value;
16400 if (name === NG_PROJECT_AS_ATTR_NAME) {
16401 attributes.push.apply(attributes, __spread(getNgProjectAsLiteral(attribute)));
16402 }
16403 else if (name.toLowerCase() !== NG_CONTENT_SELECT_ATTR$1) {
16404 attributes.push(literal(name), literal(value));
16405 }
16406 });
16407 if (attributes.length > 0) {
16408 parameters.push(literal(projectionSlotIdx), literalArr(attributes));
16409 }
16410 else if (projectionSlotIdx !== 0) {
16411 parameters.push(literal(projectionSlotIdx));
16412 }
16413 this.creationInstruction(ngContent.sourceSpan, Identifiers$1.projection, parameters);
16414 if (this.i18n) {
16415 this.i18n.appendProjection(ngContent.i18n, slot);
16416 }
16417 };
16418 TemplateDefinitionBuilder.prototype.getNamespaceInstruction = function (namespaceKey) {
16419 switch (namespaceKey) {
16420 case 'math':
16421 return Identifiers$1.namespaceMathML;
16422 case 'svg':
16423 return Identifiers$1.namespaceSVG;
16424 default:
16425 return Identifiers$1.namespaceHTML;
16426 }
16427 };
16428 TemplateDefinitionBuilder.prototype.addNamespaceInstruction = function (nsInstruction, element) {
16429 this._namespace = nsInstruction;
16430 this.creationInstruction(element.sourceSpan, nsInstruction);
16431 };
16432 TemplateDefinitionBuilder.prototype.visitElement = function (element) {
16433 var e_1, _a;
16434 var _this = this;
16435 var elementIndex = this.allocateDataSlot();
16436 var stylingBuilder = new StylingBuilder(literal(elementIndex), null);
16437 var isNonBindableMode = false;
16438 var isI18nRootElement = isI18nRootNode(element.i18n) && !isSingleI18nIcu(element.i18n);
16439 if (isI18nRootElement && this.i18n) {
16440 throw new Error("Could not mark an element as translatable inside of a translatable section");
16441 }
16442 var i18nAttrs = [];
16443 var outputAttrs = [];
16444 var _b = __read(splitNsName(element.name), 2), namespaceKey = _b[0], elementName = _b[1];
16445 var isNgContainer$1 = isNgContainer(element.name);
16446 try {
16447 // Handle styling, i18n, ngNonBindable attributes
16448 for (var _c = __values(element.attributes), _d = _c.next(); !_d.done; _d = _c.next()) {
16449 var attr = _d.value;
16450 var name_1 = attr.name, value = attr.value;
16451 if (name_1 === NON_BINDABLE_ATTR) {
16452 isNonBindableMode = true;
16453 }
16454 else if (name_1 === 'style') {
16455 stylingBuilder.registerStyleAttr(value);
16456 }
16457 else if (name_1 === 'class') {
16458 stylingBuilder.registerClassAttr(value);
16459 }
16460 else {
16461 if (attr.i18n) {
16462 // Place attributes into a separate array for i18n processing, but also keep such
16463 // attributes in the main list to make them available for directive matching at runtime.
16464 // TODO(FW-1248): prevent attributes duplication in `i18nAttributes` and `elementStart`
16465 // arguments
16466 i18nAttrs.push(attr);
16467 }
16468 else {
16469 outputAttrs.push(attr);
16470 }
16471 }
16472 }
16473 }
16474 catch (e_1_1) { e_1 = { error: e_1_1 }; }
16475 finally {
16476 try {
16477 if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
16478 }
16479 finally { if (e_1) throw e_1.error; }
16480 }
16481 // Match directives on non i18n attributes
16482 this.matchDirectives(element.name, element);
16483 // Regular element or ng-container creation mode
16484 var parameters = [literal(elementIndex)];
16485 if (!isNgContainer$1) {
16486 parameters.push(literal(elementName));
16487 }
16488 // Add the attributes
16489 var attributes = [];
16490 var allOtherInputs = [];
16491 element.inputs.forEach(function (input) {
16492 var stylingInputWasSet = stylingBuilder.registerBoundInput(input);
16493 if (!stylingInputWasSet) {
16494 if (input.type === 0 /* Property */ && input.i18n) {
16495 // Place attributes into a separate array for i18n processing, but also keep such
16496 // attributes in the main list to make them available for directive matching at runtime.
16497 // TODO(FW-1248): prevent attributes duplication in `i18nAttributes` and `elementStart`
16498 // arguments
16499 i18nAttrs.push(input);
16500 }
16501 else {
16502 allOtherInputs.push(input);
16503 }
16504 }
16505 });
16506 outputAttrs.forEach(function (attr) {
16507 if (attr.name === NG_PROJECT_AS_ATTR_NAME) {
16508 attributes.push.apply(attributes, __spread(getNgProjectAsLiteral(attr)));
16509 }
16510 else {
16511 attributes.push.apply(attributes, __spread(getAttributeNameLiterals(attr.name), [literal(attr.value)]));
16512 }
16513 });
16514 // add attributes for directive and projection matching purposes
16515 attributes.push.apply(attributes, __spread(this.prepareNonRenderAttrs(allOtherInputs, element.outputs, stylingBuilder, [], i18nAttrs)));
16516 parameters.push(this.toAttrsParam(attributes));
16517 // local refs (ex.: <div #foo #bar="baz">)
16518 parameters.push(this.prepareRefsParameter(element.references));
16519 var wasInNamespace = this._namespace;
16520 var currentNamespace = this.getNamespaceInstruction(namespaceKey);
16521 // If the namespace is changing now, include an instruction to change it
16522 // during element creation.
16523 if (currentNamespace !== wasInNamespace) {
16524 this.addNamespaceInstruction(currentNamespace, element);
16525 }
16526 if (this.i18n) {
16527 this.i18n.appendElement(element.i18n, elementIndex);
16528 }
16529 // Note that we do not append text node instructions and ICUs inside i18n section,
16530 // so we exclude them while calculating whether current element has children
16531 var hasChildren = (!isI18nRootElement && this.i18n) ? !hasTextChildrenOnly(element.children) :
16532 element.children.length > 0;
16533 var createSelfClosingInstruction = !stylingBuilder.hasBindings &&
16534 element.outputs.length === 0 && i18nAttrs.length === 0 && !hasChildren;
16535 var createSelfClosingI18nInstruction = !createSelfClosingInstruction &&
16536 !stylingBuilder.hasBindings && hasTextChildrenOnly(element.children);
16537 if (createSelfClosingInstruction) {
16538 this.creationInstruction(element.sourceSpan, isNgContainer$1 ? Identifiers$1.elementContainer : Identifiers$1.element, trimTrailingNulls(parameters));
16539 }
16540 else {
16541 this.creationInstruction(element.sourceSpan, isNgContainer$1 ? Identifiers$1.elementContainerStart : Identifiers$1.elementStart, trimTrailingNulls(parameters));
16542 if (isNonBindableMode) {
16543 this.creationInstruction(element.sourceSpan, Identifiers$1.disableBindings);
16544 }
16545 // process i18n element attributes
16546 if (i18nAttrs.length) {
16547 var hasBindings_1 = false;
16548 var i18nAttrArgs_1 = [];
16549 var bindings_1 = [];
16550 i18nAttrs.forEach(function (attr) {
16551 var message = attr.i18n;
16552 if (attr instanceof TextAttribute) {
16553 i18nAttrArgs_1.push(literal(attr.name), _this.i18nTranslate(message));
16554 }
16555 else {
16556 var converted = attr.value.visit(_this._valueConverter);
16557 _this.allocateBindingSlots(converted);
16558 if (converted instanceof Interpolation) {
16559 var placeholders = assembleBoundTextPlaceholders(message);
16560 var params = placeholdersToParams(placeholders);
16561 i18nAttrArgs_1.push(literal(attr.name), _this.i18nTranslate(message, params));
16562 converted.expressions.forEach(function (expression) {
16563 hasBindings_1 = true;
16564 bindings_1.push({
16565 sourceSpan: element.sourceSpan,
16566 value: function () { return _this.convertExpressionBinding(expression); }
16567 });
16568 });
16569 }
16570 }
16571 });
16572 if (bindings_1.length) {
16573 this.updateInstructionChain(elementIndex, Identifiers$1.i18nExp, bindings_1);
16574 }
16575 if (i18nAttrArgs_1.length) {
16576 var index = literal(this.allocateDataSlot());
16577 var args = this.constantPool.getConstLiteral(literalArr(i18nAttrArgs_1), true);
16578 this.creationInstruction(element.sourceSpan, Identifiers$1.i18nAttributes, [index, args]);
16579 if (hasBindings_1) {
16580 this.updateInstruction(elementIndex, element.sourceSpan, Identifiers$1.i18nApply, [index]);
16581 }
16582 }
16583 }
16584 // The style bindings code is placed into two distinct blocks within the template function AOT
16585 // code: creation and update. The creation code contains the `styling` instructions
16586 // which will apply the collected binding values to the element. `styling` is
16587 // designed to run inside of `elementStart` and `elementEnd`. The update instructions
16588 // (things like `styleProp`, `classProp`, etc..) are applied later on in this
16589 // file
16590 this.processStylingInstruction(elementIndex, stylingBuilder.buildStylingInstruction(element.sourceSpan, this.constantPool), true);
16591 // Generate Listeners (outputs)
16592 element.outputs.forEach(function (outputAst) {
16593 _this.creationInstruction(outputAst.sourceSpan, Identifiers$1.listener, _this.prepareListenerParameter(element.name, outputAst, elementIndex));
16594 });
16595 // Note: it's important to keep i18n/i18nStart instructions after i18nAttributes and
16596 // listeners, to make sure i18nAttributes instruction targets current element at runtime.
16597 if (isI18nRootElement) {
16598 this.i18nStart(element.sourceSpan, element.i18n, createSelfClosingI18nInstruction);
16599 }
16600 }
16601 // the code here will collect all update-level styling instructions and add them to the
16602 // update block of the template function AOT code. Instructions like `styleProp`,
16603 // `styleMap`, `classMap`, `classProp` and `stylingApply`
16604 // are all generated and assigned in the code below.
16605 var stylingInstructions = stylingBuilder.buildUpdateLevelInstructions(this._valueConverter);
16606 var limit = stylingInstructions.length - 1;
16607 for (var i = 0; i <= limit; i++) {
16608 var instruction_1 = stylingInstructions[i];
16609 this._bindingSlots += instruction_1.allocateBindingSlots;
16610 this.processStylingInstruction(elementIndex, instruction_1, false);
16611 }
16612 // the reason why `undefined` is used is because the renderer understands this as a
16613 // special value to symbolize that there is no RHS to this binding
16614 // TODO (matsko): revisit this once FW-959 is approached
16615 var emptyValueBindInstruction = literal(undefined);
16616 var propertyBindings = [];
16617 var attributeBindings = [];
16618 // Generate element input bindings
16619 allOtherInputs.forEach(function (input) {
16620 var inputType = input.type;
16621 if (inputType === 4 /* Animation */) {
16622 var value_1 = input.value.visit(_this._valueConverter);
16623 // animation bindings can be presented in the following formats:
16624 // 1. [@binding]="fooExp"
16625 // 2. [@binding]="{value:fooExp, params:{...}}"
16626 // 3. [@binding]
16627 // 4. @binding
16628 // All formats will be valid for when a synthetic binding is created.
16629 // The reasoning for this is because the renderer should get each
16630 // synthetic binding value in the order of the array that they are
16631 // defined in...
16632 var hasValue_1 = value_1 instanceof LiteralPrimitive ? !!value_1.value : true;
16633 _this.allocateBindingSlots(value_1);
16634 propertyBindings.push({
16635 name: prepareSyntheticPropertyName(input.name),
16636 sourceSpan: input.sourceSpan,
16637 value: function () { return hasValue_1 ? _this.convertPropertyBinding(value_1) : emptyValueBindInstruction; }
16638 });
16639 }
16640 else {
16641 // we must skip attributes with associated i18n context, since these attributes are handled
16642 // separately and corresponding `i18nExp` and `i18nApply` instructions will be generated
16643 if (input.i18n)
16644 return;
16645 var value_2 = input.value.visit(_this._valueConverter);
16646 if (value_2 !== undefined) {
16647 var params_2 = [];
16648 var _a = __read(splitNsName(input.name), 2), attrNamespace = _a[0], attrName_1 = _a[1];
16649 var isAttributeBinding = inputType === 1 /* Attribute */;
16650 var sanitizationRef = resolveSanitizationFn(input.securityContext, isAttributeBinding);
16651 if (sanitizationRef)
16652 params_2.push(sanitizationRef);
16653 if (attrNamespace) {
16654 var namespaceLiteral = literal(attrNamespace);
16655 if (sanitizationRef) {
16656 params_2.push(namespaceLiteral);
16657 }
16658 else {
16659 // If there wasn't a sanitization ref, we need to add
16660 // an extra param so that we can pass in the namespace.
16661 params_2.push(literal(null), namespaceLiteral);
16662 }
16663 }
16664 _this.allocateBindingSlots(value_2);
16665 if (inputType === 0 /* Property */) {
16666 if (value_2 instanceof Interpolation) {
16667 // prop="{{value}}" and friends
16668 _this.interpolatedUpdateInstruction(getPropertyInterpolationExpression(value_2), elementIndex, attrName_1, input, value_2, params_2);
16669 }
16670 else {
16671 // [prop]="value"
16672 // Collect all the properties so that we can chain into a single function at the end.
16673 propertyBindings.push({
16674 name: attrName_1,
16675 sourceSpan: input.sourceSpan,
16676 value: function () { return _this.convertPropertyBinding(value_2); }, params: params_2
16677 });
16678 }
16679 }
16680 else if (inputType === 1 /* Attribute */) {
16681 if (value_2 instanceof Interpolation && getInterpolationArgsLength(value_2) > 1) {
16682 // attr.name="text{{value}}" and friends
16683 _this.interpolatedUpdateInstruction(getAttributeInterpolationExpression(value_2), elementIndex, attrName_1, input, value_2, params_2);
16684 }
16685 else {
16686 var boundValue_1 = value_2 instanceof Interpolation ? value_2.expressions[0] : value_2;
16687 // [attr.name]="value" or attr.name="{{value}}"
16688 // Collect the attribute bindings so that they can be chained at the end.
16689 attributeBindings.push({
16690 name: attrName_1,
16691 sourceSpan: input.sourceSpan,
16692 value: function () { return _this.convertPropertyBinding(boundValue_1); }, params: params_2
16693 });
16694 }
16695 }
16696 else {
16697 // class prop
16698 _this.updateInstruction(elementIndex, input.sourceSpan, Identifiers$1.classProp, function () {
16699 return __spread([
16700 literal(elementIndex), literal(attrName_1), _this.convertPropertyBinding(value_2)
16701 ], params_2);
16702 });
16703 }
16704 }
16705 }
16706 });
16707 if (propertyBindings.length > 0) {
16708 this.updateInstructionChain(elementIndex, Identifiers$1.property, propertyBindings);
16709 }
16710 if (attributeBindings.length > 0) {
16711 this.updateInstructionChain(elementIndex, Identifiers$1.attribute, attributeBindings);
16712 }
16713 // Traverse element child nodes
16714 visitAll(this, element.children);
16715 if (!isI18nRootElement && this.i18n) {
16716 this.i18n.appendElement(element.i18n, elementIndex, true);
16717 }
16718 if (!createSelfClosingInstruction) {
16719 // Finish element construction mode.
16720 var span = element.endSourceSpan || element.sourceSpan;
16721 if (isI18nRootElement) {
16722 this.i18nEnd(span, createSelfClosingI18nInstruction);
16723 }
16724 if (isNonBindableMode) {
16725 this.creationInstruction(span, Identifiers$1.enableBindings);
16726 }
16727 this.creationInstruction(span, isNgContainer$1 ? Identifiers$1.elementContainerEnd : Identifiers$1.elementEnd);
16728 }
16729 };
16730 /**
16731 * Adds an update instruction for an interpolated property or attribute, such as
16732 * `prop="{{value}}"` or `attr.title="{{value}}"`
16733 */
16734 TemplateDefinitionBuilder.prototype.interpolatedUpdateInstruction = function (instruction, elementIndex, attrName, input, value, params) {
16735 var _this = this;
16736 this.updateInstruction(elementIndex, input.sourceSpan, instruction, function () { return __spread([literal(attrName)], _this.getUpdateInstructionArguments(value), params); });
16737 };
16738 TemplateDefinitionBuilder.prototype.visitTemplate = function (template) {
16739 var _this = this;
16740 var NG_TEMPLATE_TAG_NAME = 'ng-template';
16741 var templateIndex = this.allocateDataSlot();
16742 if (this.i18n) {
16743 this.i18n.appendTemplate(template.i18n, templateIndex);
16744 }
16745 var tagName = sanitizeIdentifier(template.tagName || '');
16746 var contextName = "" + this.contextName + (tagName ? '_' + tagName : '') + "_" + templateIndex;
16747 var templateName = contextName + "_Template";
16748 var parameters = [
16749 literal(templateIndex),
16750 variable(templateName),
16751 // We don't care about the tag's namespace here, because we infer
16752 // it based on the parent nodes inside the template instruction.
16753 literal(template.tagName ? splitNsName(template.tagName)[1] : template.tagName),
16754 ];
16755 // find directives matching on a given <ng-template> node
16756 this.matchDirectives(NG_TEMPLATE_TAG_NAME, template);
16757 // prepare attributes parameter (including attributes used for directive matching)
16758 var attrsExprs = [];
16759 template.attributes.forEach(function (a) { attrsExprs.push(asLiteral(a.name), asLiteral(a.value)); });
16760 attrsExprs.push.apply(attrsExprs, __spread(this.prepareNonRenderAttrs(template.inputs, template.outputs, undefined, template.templateAttrs)));
16761 parameters.push(this.toAttrsParam(attrsExprs));
16762 // local refs (ex.: <ng-template #foo>)
16763 if (template.references && template.references.length) {
16764 parameters.push(this.prepareRefsParameter(template.references));
16765 parameters.push(importExpr(Identifiers$1.templateRefExtractor));
16766 }
16767 // Create the template function
16768 var templateVisitor = new TemplateDefinitionBuilder(this.constantPool, this._bindingScope, this.level + 1, contextName, this.i18n, templateIndex, templateName, this.directiveMatcher, this.directives, this.pipeTypeByName, this.pipes, this._namespace, this.fileBasedI18nSuffix, this.i18nUseExternalIds);
16769 // Nested templates must not be visited until after their parent templates have completed
16770 // processing, so they are queued here until after the initial pass. Otherwise, we wouldn't
16771 // be able to support bindings in nested templates to local refs that occur after the
16772 // template definition. e.g. <div *ngIf="showing">{{ foo }}</div> <div #foo></div>
16773 this._nestedTemplateFns.push(function () {
16774 var _a;
16775 var templateFunctionExpr = templateVisitor.buildTemplateFunction(template.children, template.variables, _this._ngContentReservedSlots.length + _this._ngContentSelectorsOffset, template.i18n);
16776 _this.constantPool.statements.push(templateFunctionExpr.toDeclStmt(templateName, null));
16777 if (templateVisitor._ngContentReservedSlots.length) {
16778 (_a = _this._ngContentReservedSlots).push.apply(_a, __spread(templateVisitor._ngContentReservedSlots));
16779 }
16780 });
16781 // e.g. template(1, MyComp_Template_1)
16782 this.creationInstruction(template.sourceSpan, Identifiers$1.templateCreate, function () {
16783 parameters.splice(2, 0, literal(templateVisitor.getConstCount()), literal(templateVisitor.getVarCount()));
16784 return trimTrailingNulls(parameters);
16785 });
16786 // handle property bindings e.g. ɵɵproperty('ngForOf', ctx.items), et al;
16787 this.templatePropertyBindings(templateIndex, template.templateAttrs);
16788 // Only add normal input/output binding instructions on explicit ng-template elements.
16789 if (template.tagName === NG_TEMPLATE_TAG_NAME) {
16790 // Add the input bindings
16791 this.templatePropertyBindings(templateIndex, template.inputs);
16792 // Generate listeners for directive output
16793 template.outputs.forEach(function (outputAst) {
16794 _this.creationInstruction(outputAst.sourceSpan, Identifiers$1.listener, _this.prepareListenerParameter('ng_template', outputAst, templateIndex));
16795 });
16796 }
16797 };
16798 TemplateDefinitionBuilder.prototype.visitBoundText = function (text) {
16799 var _this = this;
16800 if (this.i18n) {
16801 var value_3 = text.value.visit(this._valueConverter);
16802 this.allocateBindingSlots(value_3);
16803 if (value_3 instanceof Interpolation) {
16804 this.i18n.appendBoundText(text.i18n);
16805 this.i18nAppendBindings(value_3.expressions);
16806 }
16807 return;
16808 }
16809 var nodeIndex = this.allocateDataSlot();
16810 this.creationInstruction(text.sourceSpan, Identifiers$1.text, [literal(nodeIndex)]);
16811 var value = text.value.visit(this._valueConverter);
16812 this.allocateBindingSlots(value);
16813 if (value instanceof Interpolation) {
16814 this.updateInstruction(nodeIndex, text.sourceSpan, getTextInterpolationExpression(value), function () { return _this.getUpdateInstructionArguments(value); });
16815 }
16816 else {
16817 this.updateInstruction(nodeIndex, text.sourceSpan, Identifiers$1.textBinding, function () { return [_this.convertPropertyBinding(value)]; });
16818 }
16819 };
16820 TemplateDefinitionBuilder.prototype.visitText = function (text) {
16821 // when a text element is located within a translatable
16822 // block, we exclude this text element from instructions set,
16823 // since it will be captured in i18n content and processed at runtime
16824 if (!this.i18n) {
16825 this.creationInstruction(text.sourceSpan, Identifiers$1.text, [literal(this.allocateDataSlot()), literal(text.value)]);
16826 }
16827 };
16828 TemplateDefinitionBuilder.prototype.visitIcu = function (icu) {
16829 var _this = this;
16830 var initWasInvoked = false;
16831 // if an ICU was created outside of i18n block, we still treat
16832 // it as a translatable entity and invoke i18nStart and i18nEnd
16833 // to generate i18n context and the necessary instructions
16834 if (!this.i18n) {
16835 initWasInvoked = true;
16836 this.i18nStart(null, icu.i18n, true);
16837 }
16838 var i18n = this.i18n;
16839 var vars = this.i18nBindProps(icu.vars);
16840 var placeholders = this.i18nBindProps(icu.placeholders);
16841 // output ICU directly and keep ICU reference in context
16842 var message = icu.i18n;
16843 // we always need post-processing function for ICUs, to make sure that:
16844 // - all placeholders in a form of {PLACEHOLDER} are replaced with actual values (note:
16845 // `goog.getMsg` does not process ICUs and uses the `{PLACEHOLDER}` format for placeholders
16846 // inside ICUs)
16847 // - all ICU vars (such as `VAR_SELECT` or `VAR_PLURAL`) are replaced with correct values
16848 var transformFn = function (raw) {
16849 var params = __assign({}, vars, placeholders);
16850 var formatted = _this.i18nFormatPlaceholderNames(params, /* useCamelCase */ false);
16851 return instruction(null, Identifiers$1.i18nPostprocess, [raw, mapLiteral(formatted, true)]);
16852 };
16853 // in case the whole i18n message is a single ICU - we do not need to
16854 // create a separate top-level translation, we can use the root ref instead
16855 // and make this ICU a top-level translation
16856 // note: ICU placeholders are replaced with actual values in `i18nPostprocess` function
16857 // separately, so we do not pass placeholders into `i18nTranslate` function.
16858 if (isSingleI18nIcu(i18n.meta)) {
16859 this.i18nTranslate(message, /* placeholders */ {}, i18n.ref, transformFn);
16860 }
16861 else {
16862 // output ICU directly and keep ICU reference in context
16863 var ref = this.i18nTranslate(message, /* placeholders */ {}, /* ref */ undefined, transformFn);
16864 i18n.appendIcu(icuFromI18nMessage(message).name, ref);
16865 }
16866 if (initWasInvoked) {
16867 this.i18nEnd(null, true);
16868 }
16869 return null;
16870 };
16871 TemplateDefinitionBuilder.prototype.allocateDataSlot = function () { return this._dataIndex++; };
16872 TemplateDefinitionBuilder.prototype.getConstCount = function () { return this._dataIndex; };
16873 TemplateDefinitionBuilder.prototype.getVarCount = function () { return this._pureFunctionSlots; };
16874 TemplateDefinitionBuilder.prototype.getNgContentSelectors = function () {
16875 return this._ngContentReservedSlots.length ?
16876 this.constantPool.getConstLiteral(asLiteral(this._ngContentReservedSlots), true) :
16877 null;
16878 };
16879 TemplateDefinitionBuilder.prototype.bindingContext = function () { return "" + this._bindingContext++; };
16880 TemplateDefinitionBuilder.prototype.templatePropertyBindings = function (templateIndex, attrs) {
16881 var _this = this;
16882 var propertyBindings = [];
16883 attrs.forEach(function (input) {
16884 if (input instanceof BoundAttribute) {
16885 var value_4 = input.value.visit(_this._valueConverter);
16886 if (value_4 !== undefined) {
16887 _this.allocateBindingSlots(value_4);
16888 propertyBindings.push({
16889 name: input.name,
16890 sourceSpan: input.sourceSpan,
16891 value: function () { return _this.convertPropertyBinding(value_4); }
16892 });
16893 }
16894 }
16895 });
16896 if (propertyBindings.length > 0) {
16897 this.updateInstructionChain(templateIndex, Identifiers$1.property, propertyBindings);
16898 }
16899 };
16900 // Bindings must only be resolved after all local refs have been visited, so all
16901 // instructions are queued in callbacks that execute once the initial pass has completed.
16902 // Otherwise, we wouldn't be able to support local refs that are defined after their
16903 // bindings. e.g. {{ foo }} <div #foo></div>
16904 TemplateDefinitionBuilder.prototype.instructionFn = function (fns, span, reference, paramsOrFn, prepend) {
16905 if (prepend === void 0) { prepend = false; }
16906 fns[prepend ? 'unshift' : 'push'](function () {
16907 var params = Array.isArray(paramsOrFn) ? paramsOrFn : paramsOrFn();
16908 return instruction(span, reference, params).toStmt();
16909 });
16910 };
16911 TemplateDefinitionBuilder.prototype.processStylingInstruction = function (elementIndex, instruction, createMode) {
16912 var _this = this;
16913 if (instruction) {
16914 if (createMode) {
16915 this.creationInstruction(instruction.sourceSpan, instruction.reference, function () {
16916 return instruction.params(function (value) { return _this.convertPropertyBinding(value); });
16917 });
16918 }
16919 else {
16920 this.updateInstruction(elementIndex, instruction.sourceSpan, instruction.reference, function () {
16921 return instruction
16922 .params(function (value) {
16923 return (instruction.supportsInterpolation && value instanceof Interpolation) ?
16924 _this.getUpdateInstructionArguments(value) :
16925 _this.convertPropertyBinding(value);
16926 });
16927 });
16928 }
16929 }
16930 };
16931 TemplateDefinitionBuilder.prototype.creationInstruction = function (span, reference, paramsOrFn, prepend) {
16932 this.instructionFn(this._creationCodeFns, span, reference, paramsOrFn || [], prepend);
16933 };
16934 TemplateDefinitionBuilder.prototype.updateInstruction = function (nodeIndex, span, reference, paramsOrFn) {
16935 this.addSelectInstructionIfNecessary(nodeIndex, span);
16936 this.instructionFn(this._updateCodeFns, span, reference, paramsOrFn || []);
16937 };
16938 TemplateDefinitionBuilder.prototype.updateInstructionChain = function (nodeIndex, reference, bindings) {
16939 var span = bindings.length ? bindings[0].sourceSpan : null;
16940 this.addSelectInstructionIfNecessary(nodeIndex, span);
16941 this._updateCodeFns.push(function () {
16942 var calls = bindings.map(function (property) {
16943 var fnParams = __spread([property.value()], (property.params || []));
16944 if (property.name) {
16945 fnParams.unshift(literal(property.name));
16946 }
16947 return fnParams;
16948 });
16949 return chainedInstruction(reference, calls, span).toStmt();
16950 });
16951 };
16952 TemplateDefinitionBuilder.prototype.addSelectInstructionIfNecessary = function (nodeIndex, span) {
16953 if (this._lastNodeIndexWithFlush < nodeIndex) {
16954 if (nodeIndex > 0) {
16955 this.instructionFn(this._updateCodeFns, span, Identifiers$1.select, [literal(nodeIndex)]);
16956 }
16957 this._lastNodeIndexWithFlush = nodeIndex;
16958 }
16959 };
16960 TemplateDefinitionBuilder.prototype.allocatePureFunctionSlots = function (numSlots) {
16961 var originalSlots = this._pureFunctionSlots;
16962 this._pureFunctionSlots += numSlots;
16963 return originalSlots;
16964 };
16965 TemplateDefinitionBuilder.prototype.allocateBindingSlots = function (value) {
16966 this._bindingSlots += value instanceof Interpolation ? value.expressions.length : 1;
16967 };
16968 /**
16969 * Gets an expression that refers to the implicit receiver. The implicit
16970 * receiver is always the root level context.
16971 */
16972 TemplateDefinitionBuilder.prototype.getImplicitReceiverExpr = function () {
16973 if (this._implicitReceiverExpr) {
16974 return this._implicitReceiverExpr;
16975 }
16976 return this._implicitReceiverExpr = this.level === 0 ?
16977 variable(CONTEXT_NAME) :
16978 this._bindingScope.getOrCreateSharedContextVar(0);
16979 };
16980 TemplateDefinitionBuilder.prototype.convertExpressionBinding = function (value) {
16981 var convertedPropertyBinding = convertPropertyBinding(this, this.getImplicitReceiverExpr(), value, this.bindingContext(), BindingForm.TrySimple);
16982 return convertedPropertyBinding.currValExpr;
16983 };
16984 TemplateDefinitionBuilder.prototype.convertPropertyBinding = function (value) {
16985 var _a;
16986 var convertedPropertyBinding = convertPropertyBinding(this, this.getImplicitReceiverExpr(), value, this.bindingContext(), BindingForm.TrySimple, function () { return error('Unexpected interpolation'); });
16987 var valExpr = convertedPropertyBinding.currValExpr;
16988 (_a = this._tempVariables).push.apply(_a, __spread(convertedPropertyBinding.stmts));
16989 return valExpr;
16990 };
16991 /**
16992 * Gets a list of argument expressions to pass to an update instruction expression. Also updates
16993 * the temp variables state with temp variables that were identified as needing to be created
16994 * while visiting the arguments.
16995 * @param value The original expression we will be resolving an arguments list from.
16996 */
16997 TemplateDefinitionBuilder.prototype.getUpdateInstructionArguments = function (value) {
16998 var _a;
16999 var _b = convertUpdateArguments(this, this.getImplicitReceiverExpr(), value, this.bindingContext()), args = _b.args, stmts = _b.stmts;
17000 (_a = this._tempVariables).push.apply(_a, __spread(stmts));
17001 return args;
17002 };
17003 TemplateDefinitionBuilder.prototype.matchDirectives = function (tagName, elOrTpl) {
17004 var _this = this;
17005 if (this.directiveMatcher) {
17006 var selector = createCssSelector(tagName, getAttrsForDirectiveMatching(elOrTpl));
17007 this.directiveMatcher.match(selector, function (cssSelector, staticType) { _this.directives.add(staticType); });
17008 }
17009 };
17010 /**
17011 * Prepares all attribute expression values for the `TAttributes` array.
17012 *
17013 * The purpose of this function is to properly construct an attributes array that
17014 * is passed into the `elementStart` (or just `element`) functions. Because there
17015 * are many different types of attributes, the array needs to be constructed in a
17016 * special way so that `elementStart` can properly evaluate them.
17017 *
17018 * The format looks like this:
17019 *
17020 * ```
17021 * attrs = [prop, value, prop2, value2,
17022 * CLASSES, class1, class2,
17023 * STYLES, style1, value1, style2, value2,
17024 * BINDINGS, name1, name2, name3,
17025 * TEMPLATE, name4, name5, name6,
17026 * I18N, name7, name8, ...]
17027 * ```
17028 *
17029 * Note that this function will fully ignore all synthetic (@foo) attribute values
17030 * because those values are intended to always be generated as property instructions.
17031 */
17032 TemplateDefinitionBuilder.prototype.prepareNonRenderAttrs = function (inputs, outputs, styles, templateAttrs, i18nAttrs) {
17033 if (templateAttrs === void 0) { templateAttrs = []; }
17034 if (i18nAttrs === void 0) { i18nAttrs = []; }
17035 var alreadySeen = new Set();
17036 var attrExprs = [];
17037 function addAttrExpr(key, value) {
17038 if (typeof key === 'string') {
17039 if (!alreadySeen.has(key)) {
17040 attrExprs.push.apply(attrExprs, __spread(getAttributeNameLiterals(key)));
17041 value !== undefined && attrExprs.push(value);
17042 alreadySeen.add(key);
17043 }
17044 }
17045 else {
17046 attrExprs.push(literal(key));
17047 }
17048 }
17049 // it's important that this occurs before BINDINGS and TEMPLATE because once `elementStart`
17050 // comes across the BINDINGS or TEMPLATE markers then it will continue reading each value as
17051 // as single property value cell by cell.
17052 if (styles) {
17053 styles.populateInitialStylingAttrs(attrExprs);
17054 }
17055 if (inputs.length || outputs.length) {
17056 var attrsLengthBeforeInputs = attrExprs.length;
17057 for (var i = 0; i < inputs.length; i++) {
17058 var input = inputs[i];
17059 // We don't want the animation and attribute bindings in the
17060 // attributes array since they aren't used for directive matching.
17061 if (input.type !== 4 /* Animation */ && input.type !== 1 /* Attribute */) {
17062 addAttrExpr(input.name);
17063 }
17064 }
17065 for (var i = 0; i < outputs.length; i++) {
17066 var output = outputs[i];
17067 if (output.type !== 1 /* Animation */) {
17068 addAttrExpr(output.name);
17069 }
17070 }
17071 // this is a cheap way of adding the marker only after all the input/output
17072 // values have been filtered (by not including the animation ones) and added
17073 // to the expressions. The marker is important because it tells the runtime
17074 // code that this is where attributes without values start...
17075 if (attrExprs.length !== attrsLengthBeforeInputs) {
17076 attrExprs.splice(attrsLengthBeforeInputs, 0, literal(3 /* Bindings */));
17077 }
17078 }
17079 if (templateAttrs.length) {
17080 attrExprs.push(literal(4 /* Template */));
17081 templateAttrs.forEach(function (attr) { return addAttrExpr(attr.name); });
17082 }
17083 if (i18nAttrs.length) {
17084 attrExprs.push(literal(6 /* I18n */));
17085 i18nAttrs.forEach(function (attr) { return addAttrExpr(attr.name); });
17086 }
17087 return attrExprs;
17088 };
17089 TemplateDefinitionBuilder.prototype.toAttrsParam = function (attrsExprs) {
17090 return attrsExprs.length > 0 ?
17091 this.constantPool.getConstLiteral(literalArr(attrsExprs), true) :
17092 TYPED_NULL_EXPR;
17093 };
17094 TemplateDefinitionBuilder.prototype.prepareRefsParameter = function (references) {
17095 var _this = this;
17096 if (!references || references.length === 0) {
17097 return TYPED_NULL_EXPR;
17098 }
17099 var refsParam = flatten(references.map(function (reference) {
17100 var slot = _this.allocateDataSlot();
17101 // Generate the update temporary.
17102 var variableName = _this._bindingScope.freshReferenceName();
17103 var retrievalLevel = _this.level;
17104 var lhs = variable(variableName);
17105 _this._bindingScope.set(retrievalLevel, reference.name, lhs, 0 /* DEFAULT */, function (scope, relativeLevel) {
17106 // e.g. nextContext(2);
17107 var nextContextStmt = relativeLevel > 0 ? [generateNextContextExpr(relativeLevel).toStmt()] : [];
17108 // e.g. const $foo$ = reference(1);
17109 var refExpr = lhs.set(importExpr(Identifiers$1.reference).callFn([literal(slot)]));
17110 return nextContextStmt.concat(refExpr.toConstDecl());
17111 }, true);
17112 return [reference.name, reference.value];
17113 }));
17114 return this.constantPool.getConstLiteral(asLiteral(refsParam), true);
17115 };
17116 TemplateDefinitionBuilder.prototype.prepareListenerParameter = function (tagName, outputAst, index) {
17117 var _this = this;
17118 return function () {
17119 var eventName = outputAst.name;
17120 var bindingFnName = outputAst.type === 1 /* Animation */ ?
17121 // synthetic @listener.foo values are treated the exact same as are standard listeners
17122 prepareSyntheticListenerFunctionName(eventName, outputAst.phase) :
17123 sanitizeIdentifier(eventName);
17124 var handlerName = _this.templateName + "_" + tagName + "_" + bindingFnName + "_" + index + "_listener";
17125 var scope = _this._bindingScope.nestedScope(_this._bindingScope.bindingLevel);
17126 return prepareEventListenerParameters(outputAst, handlerName, scope);
17127 };
17128 };
17129 return TemplateDefinitionBuilder;
17130}());
17131var ValueConverter = /** @class */ (function (_super) {
17132 __extends(ValueConverter, _super);
17133 function ValueConverter(constantPool, allocateSlot, allocatePureFunctionSlots, definePipe) {
17134 var _this = _super.call(this) || this;
17135 _this.constantPool = constantPool;
17136 _this.allocateSlot = allocateSlot;
17137 _this.allocatePureFunctionSlots = allocatePureFunctionSlots;
17138 _this.definePipe = definePipe;
17139 _this._pipeBindExprs = [];
17140 return _this;
17141 }
17142 // AstMemoryEfficientTransformer
17143 ValueConverter.prototype.visitPipe = function (pipe, context) {
17144 // Allocate a slot to create the pipe
17145 var slot = this.allocateSlot();
17146 var slotPseudoLocal = "PIPE:" + slot;
17147 // Allocate one slot for the result plus one slot per pipe argument
17148 var pureFunctionSlot = this.allocatePureFunctionSlots(2 + pipe.args.length);
17149 var target = new PropertyRead(pipe.span, new ImplicitReceiver(pipe.span), slotPseudoLocal);
17150 var _a = pipeBindingCallInfo(pipe.args), identifier = _a.identifier, isVarLength = _a.isVarLength;
17151 this.definePipe(pipe.name, slotPseudoLocal, slot, importExpr(identifier));
17152 var args = __spread([pipe.exp], pipe.args);
17153 var convertedArgs = isVarLength ? this.visitAll([new LiteralArray(pipe.span, args)]) : this.visitAll(args);
17154 var pipeBindExpr = new FunctionCall(pipe.span, target, __spread([
17155 new LiteralPrimitive(pipe.span, slot),
17156 new LiteralPrimitive(pipe.span, pureFunctionSlot)
17157 ], convertedArgs));
17158 this._pipeBindExprs.push(pipeBindExpr);
17159 return pipeBindExpr;
17160 };
17161 ValueConverter.prototype.updatePipeSlotOffsets = function (bindingSlots) {
17162 this._pipeBindExprs.forEach(function (pipe) {
17163 // update the slot offset arg (index 1) to account for binding slots
17164 var slotOffset = pipe.args[1];
17165 slotOffset.value += bindingSlots;
17166 });
17167 };
17168 ValueConverter.prototype.visitLiteralArray = function (array, context) {
17169 var _this = this;
17170 return new BuiltinFunctionCall(array.span, this.visitAll(array.expressions), function (values) {
17171 // If the literal has calculated (non-literal) elements transform it into
17172 // calls to literal factories that compose the literal and will cache intermediate
17173 // values. Otherwise, just return an literal array that contains the values.
17174 var literal = literalArr(values);
17175 return values.every(function (a) { return a.isConstant(); }) ?
17176 _this.constantPool.getConstLiteral(literal, true) :
17177 getLiteralFactory(_this.constantPool, literal, _this.allocatePureFunctionSlots);
17178 });
17179 };
17180 ValueConverter.prototype.visitLiteralMap = function (map, context) {
17181 var _this = this;
17182 return new BuiltinFunctionCall(map.span, this.visitAll(map.values), function (values) {
17183 // If the literal has calculated (non-literal) elements transform it into
17184 // calls to literal factories that compose the literal and will cache intermediate
17185 // values. Otherwise, just return an literal array that contains the values.
17186 var literal = literalMap(values.map(function (value, index) { return ({ key: map.keys[index].key, value: value, quoted: map.keys[index].quoted }); }));
17187 return values.every(function (a) { return a.isConstant(); }) ?
17188 _this.constantPool.getConstLiteral(literal, true) :
17189 getLiteralFactory(_this.constantPool, literal, _this.allocatePureFunctionSlots);
17190 });
17191 };
17192 return ValueConverter;
17193}(AstMemoryEfficientTransformer));
17194// Pipes always have at least one parameter, the value they operate on
17195var pipeBindingIdentifiers = [Identifiers$1.pipeBind1, Identifiers$1.pipeBind2, Identifiers$1.pipeBind3, Identifiers$1.pipeBind4];
17196function pipeBindingCallInfo(args) {
17197 var identifier = pipeBindingIdentifiers[args.length];
17198 return {
17199 identifier: identifier || Identifiers$1.pipeBindV,
17200 isVarLength: !identifier,
17201 };
17202}
17203var pureFunctionIdentifiers = [
17204 Identifiers$1.pureFunction0, Identifiers$1.pureFunction1, Identifiers$1.pureFunction2, Identifiers$1.pureFunction3, Identifiers$1.pureFunction4,
17205 Identifiers$1.pureFunction5, Identifiers$1.pureFunction6, Identifiers$1.pureFunction7, Identifiers$1.pureFunction8
17206];
17207function pureFunctionCallInfo(args) {
17208 var identifier = pureFunctionIdentifiers[args.length];
17209 return {
17210 identifier: identifier || Identifiers$1.pureFunctionV,
17211 isVarLength: !identifier,
17212 };
17213}
17214function instruction(span, reference, params) {
17215 return importExpr(reference, null, span).callFn(params, span);
17216}
17217// e.g. x(2);
17218function generateNextContextExpr(relativeLevelDiff) {
17219 return importExpr(Identifiers$1.nextContext)
17220 .callFn(relativeLevelDiff > 1 ? [literal(relativeLevelDiff)] : []);
17221}
17222function getLiteralFactory(constantPool, literal$1, allocateSlots) {
17223 var _a = constantPool.getLiteralFactory(literal$1), literalFactory = _a.literalFactory, literalFactoryArguments = _a.literalFactoryArguments;
17224 // Allocate 1 slot for the result plus 1 per argument
17225 var startSlot = allocateSlots(1 + literalFactoryArguments.length);
17226 literalFactoryArguments.length > 0 || error("Expected arguments to a literal factory function");
17227 var _b = pureFunctionCallInfo(literalFactoryArguments), identifier = _b.identifier, isVarLength = _b.isVarLength;
17228 // Literal factories are pure functions that only need to be re-invoked when the parameters
17229 // change.
17230 var args = [
17231 literal(startSlot),
17232 literalFactory,
17233 ];
17234 if (isVarLength) {
17235 args.push(literalArr(literalFactoryArguments));
17236 }
17237 else {
17238 args.push.apply(args, __spread(literalFactoryArguments));
17239 }
17240 return importExpr(identifier).callFn(args);
17241}
17242/**
17243 * Gets an array of literals that can be added to an expression
17244 * to represent the name and namespace of an attribute. E.g.
17245 * `:xlink:href` turns into `[AttributeMarker.NamespaceURI, 'xlink', 'href']`.
17246 *
17247 * @param name Name of the attribute, including the namespace.
17248 */
17249function getAttributeNameLiterals(name) {
17250 var _a = __read(splitNsName(name), 2), attributeNamespace = _a[0], attributeName = _a[1];
17251 var nameLiteral = literal(attributeName);
17252 if (attributeNamespace) {
17253 return [
17254 literal(0 /* NamespaceURI */), literal(attributeNamespace), nameLiteral
17255 ];
17256 }
17257 return [nameLiteral];
17258}
17259/** The prefix used to get a shared context in BindingScope's map. */
17260var SHARED_CONTEXT_KEY = '$$shared_ctx$$';
17261var BindingScope = /** @class */ (function () {
17262 function BindingScope(bindingLevel, parent) {
17263 if (bindingLevel === void 0) { bindingLevel = 0; }
17264 if (parent === void 0) { parent = null; }
17265 this.bindingLevel = bindingLevel;
17266 this.parent = parent;
17267 /** Keeps a map from local variables to their BindingData. */
17268 this.map = new Map();
17269 this.referenceNameIndex = 0;
17270 this.restoreViewVariable = null;
17271 }
17272 Object.defineProperty(BindingScope, "ROOT_SCOPE", {
17273 get: function () {
17274 if (!BindingScope._ROOT_SCOPE) {
17275 BindingScope._ROOT_SCOPE = new BindingScope().set(0, '$event', variable('$event'));
17276 }
17277 return BindingScope._ROOT_SCOPE;
17278 },
17279 enumerable: true,
17280 configurable: true
17281 });
17282 BindingScope.prototype.get = function (name) {
17283 var current = this;
17284 while (current) {
17285 var value = current.map.get(name);
17286 if (value != null) {
17287 if (current !== this) {
17288 // make a local copy and reset the `declare` state
17289 value = {
17290 retrievalLevel: value.retrievalLevel,
17291 lhs: value.lhs,
17292 declareLocalCallback: value.declareLocalCallback,
17293 declare: false,
17294 priority: value.priority,
17295 localRef: value.localRef
17296 };
17297 // Cache the value locally.
17298 this.map.set(name, value);
17299 // Possibly generate a shared context var
17300 this.maybeGenerateSharedContextVar(value);
17301 this.maybeRestoreView(value.retrievalLevel, value.localRef);
17302 }
17303 if (value.declareLocalCallback && !value.declare) {
17304 value.declare = true;
17305 }
17306 return value.lhs;
17307 }
17308 current = current.parent;
17309 }
17310 // If we get to this point, we are looking for a property on the top level component
17311 // - If level === 0, we are on the top and don't need to re-declare `ctx`.
17312 // - If level > 0, we are in an embedded view. We need to retrieve the name of the
17313 // local var we used to store the component context, e.g. const $comp$ = x();
17314 return this.bindingLevel === 0 ? null : this.getComponentProperty(name);
17315 };
17316 /**
17317 * Create a local variable for later reference.
17318 *
17319 * @param retrievalLevel The level from which this value can be retrieved
17320 * @param name Name of the variable.
17321 * @param lhs AST representing the left hand side of the `let lhs = rhs;`.
17322 * @param priority The sorting priority of this var
17323 * @param declareLocalCallback The callback to invoke when declaring this local var
17324 * @param localRef Whether or not this is a local ref
17325 */
17326 BindingScope.prototype.set = function (retrievalLevel, name, lhs, priority, declareLocalCallback, localRef) {
17327 if (priority === void 0) { priority = 0 /* DEFAULT */; }
17328 if (this.map.has(name)) {
17329 if (localRef) {
17330 // Do not throw an error if it's a local ref and do not update existing value,
17331 // so the first defined ref is always returned.
17332 return this;
17333 }
17334 error("The name " + name + " is already defined in scope to be " + this.map.get(name));
17335 }
17336 this.map.set(name, {
17337 retrievalLevel: retrievalLevel,
17338 lhs: lhs,
17339 declare: false,
17340 declareLocalCallback: declareLocalCallback,
17341 priority: priority,
17342 localRef: localRef || false
17343 });
17344 return this;
17345 };
17346 // Implemented as part of LocalResolver.
17347 BindingScope.prototype.getLocal = function (name) { return this.get(name); };
17348 // Implemented as part of LocalResolver.
17349 BindingScope.prototype.notifyImplicitReceiverUse = function () {
17350 if (this.bindingLevel !== 0) {
17351 // Since the implicit receiver is accessed in an embedded view, we need to
17352 // ensure that we declare a shared context variable for the current template
17353 // in the update variables.
17354 this.map.get(SHARED_CONTEXT_KEY + 0).declare = true;
17355 }
17356 };
17357 BindingScope.prototype.nestedScope = function (level) {
17358 var newScope = new BindingScope(level, this);
17359 if (level > 0)
17360 newScope.generateSharedContextVar(0);
17361 return newScope;
17362 };
17363 /**
17364 * Gets or creates a shared context variable and returns its expression. Note that
17365 * this does not mean that the shared variable will be declared. Variables in the
17366 * binding scope will be only declared if they are used.
17367 */
17368 BindingScope.prototype.getOrCreateSharedContextVar = function (retrievalLevel) {
17369 var bindingKey = SHARED_CONTEXT_KEY + retrievalLevel;
17370 if (!this.map.has(bindingKey)) {
17371 this.generateSharedContextVar(retrievalLevel);
17372 }
17373 // Shared context variables are always generated as "ReadVarExpr".
17374 return this.map.get(bindingKey).lhs;
17375 };
17376 BindingScope.prototype.getSharedContextName = function (retrievalLevel) {
17377 var sharedCtxObj = this.map.get(SHARED_CONTEXT_KEY + retrievalLevel);
17378 // Shared context variables are always generated as "ReadVarExpr".
17379 return sharedCtxObj && sharedCtxObj.declare ? sharedCtxObj.lhs : null;
17380 };
17381 BindingScope.prototype.maybeGenerateSharedContextVar = function (value) {
17382 if (value.priority === 1 /* CONTEXT */ &&
17383 value.retrievalLevel < this.bindingLevel) {
17384 var sharedCtxObj = this.map.get(SHARED_CONTEXT_KEY + value.retrievalLevel);
17385 if (sharedCtxObj) {
17386 sharedCtxObj.declare = true;
17387 }
17388 else {
17389 this.generateSharedContextVar(value.retrievalLevel);
17390 }
17391 }
17392 };
17393 BindingScope.prototype.generateSharedContextVar = function (retrievalLevel) {
17394 var lhs = variable(CONTEXT_NAME + this.freshReferenceName());
17395 this.map.set(SHARED_CONTEXT_KEY + retrievalLevel, {
17396 retrievalLevel: retrievalLevel,
17397 lhs: lhs,
17398 declareLocalCallback: function (scope, relativeLevel) {
17399 // const ctx_r0 = nextContext(2);
17400 return [lhs.set(generateNextContextExpr(relativeLevel)).toConstDecl()];
17401 },
17402 declare: false,
17403 priority: 2 /* SHARED_CONTEXT */,
17404 localRef: false
17405 });
17406 };
17407 BindingScope.prototype.getComponentProperty = function (name) {
17408 var componentValue = this.map.get(SHARED_CONTEXT_KEY + 0);
17409 componentValue.declare = true;
17410 this.maybeRestoreView(0, false);
17411 return componentValue.lhs.prop(name);
17412 };
17413 BindingScope.prototype.maybeRestoreView = function (retrievalLevel, localRefLookup) {
17414 // We want to restore the current view in listener fns if:
17415 // 1 - we are accessing a value in a parent view, which requires walking the view tree rather
17416 // than using the ctx arg. In this case, the retrieval and binding level will be different.
17417 // 2 - we are looking up a local ref, which requires restoring the view where the local
17418 // ref is stored
17419 if (this.isListenerScope() && (retrievalLevel < this.bindingLevel || localRefLookup)) {
17420 if (!this.parent.restoreViewVariable) {
17421 // parent saves variable to generate a shared `const $s$ = getCurrentView();` instruction
17422 this.parent.restoreViewVariable = variable(this.parent.freshReferenceName());
17423 }
17424 this.restoreViewVariable = this.parent.restoreViewVariable;
17425 }
17426 };
17427 BindingScope.prototype.restoreViewStatement = function () {
17428 // restoreView($state$);
17429 return this.restoreViewVariable ?
17430 [instruction(null, Identifiers$1.restoreView, [this.restoreViewVariable]).toStmt()] :
17431 [];
17432 };
17433 BindingScope.prototype.viewSnapshotStatements = function () {
17434 // const $state$ = getCurrentView();
17435 var getCurrentViewInstruction = instruction(null, Identifiers$1.getCurrentView, []);
17436 return this.restoreViewVariable ?
17437 [this.restoreViewVariable.set(getCurrentViewInstruction).toConstDecl()] :
17438 [];
17439 };
17440 BindingScope.prototype.isListenerScope = function () { return this.parent && this.parent.bindingLevel === this.bindingLevel; };
17441 BindingScope.prototype.variableDeclarations = function () {
17442 var _this = this;
17443 var currentContextLevel = 0;
17444 return Array.from(this.map.values())
17445 .filter(function (value) { return value.declare; })
17446 .sort(function (a, b) { return b.retrievalLevel - a.retrievalLevel || b.priority - a.priority; })
17447 .reduce(function (stmts, value) {
17448 var levelDiff = _this.bindingLevel - value.retrievalLevel;
17449 var currStmts = value.declareLocalCallback(_this, levelDiff - currentContextLevel);
17450 currentContextLevel = levelDiff;
17451 return stmts.concat(currStmts);
17452 }, []);
17453 };
17454 BindingScope.prototype.freshReferenceName = function () {
17455 var current = this;
17456 // Find the top scope as it maintains the global reference count
17457 while (current.parent)
17458 current = current.parent;
17459 var ref = "" + REFERENCE_PREFIX + current.referenceNameIndex++;
17460 return ref;
17461 };
17462 return BindingScope;
17463}());
17464/**
17465 * Creates a `CssSelector` given a tag name and a map of attributes
17466 */
17467function createCssSelector(tag, attributes) {
17468 var cssSelector = new CssSelector();
17469 cssSelector.setElement(tag);
17470 Object.getOwnPropertyNames(attributes).forEach(function (name) {
17471 var value = attributes[name];
17472 cssSelector.addAttribute(name, value);
17473 if (name.toLowerCase() === 'class') {
17474 var classes = value.trim().split(/\s+/);
17475 classes.forEach(function (className) { return cssSelector.addClassName(className); });
17476 }
17477 });
17478 return cssSelector;
17479}
17480/**
17481 * Creates an array of expressions out of an `ngProjectAs` attributes
17482 * which can be added to the instruction parameters.
17483 */
17484function getNgProjectAsLiteral(attribute) {
17485 // Parse the attribute value into a CssSelectorList. Note that we only take the
17486 // first selector, because we don't support multiple selectors in ngProjectAs.
17487 var parsedR3Selector = parseSelectorToR3Selector(attribute.value)[0];
17488 return [literal(5 /* ProjectAs */), asLiteral(parsedR3Selector)];
17489}
17490/**
17491 * Gets the instruction to generate for an interpolated property
17492 * @param interpolation An Interpolation AST
17493 */
17494function getPropertyInterpolationExpression(interpolation) {
17495 switch (getInterpolationArgsLength(interpolation)) {
17496 case 1:
17497 return Identifiers$1.propertyInterpolate;
17498 case 3:
17499 return Identifiers$1.propertyInterpolate1;
17500 case 5:
17501 return Identifiers$1.propertyInterpolate2;
17502 case 7:
17503 return Identifiers$1.propertyInterpolate3;
17504 case 9:
17505 return Identifiers$1.propertyInterpolate4;
17506 case 11:
17507 return Identifiers$1.propertyInterpolate5;
17508 case 13:
17509 return Identifiers$1.propertyInterpolate6;
17510 case 15:
17511 return Identifiers$1.propertyInterpolate7;
17512 case 17:
17513 return Identifiers$1.propertyInterpolate8;
17514 default:
17515 return Identifiers$1.propertyInterpolateV;
17516 }
17517}
17518/**
17519 * Gets the instruction to generate for an interpolated attribute
17520 * @param interpolation An Interpolation AST
17521 */
17522function getAttributeInterpolationExpression(interpolation) {
17523 switch (getInterpolationArgsLength(interpolation)) {
17524 case 3:
17525 return Identifiers$1.attributeInterpolate1;
17526 case 5:
17527 return Identifiers$1.attributeInterpolate2;
17528 case 7:
17529 return Identifiers$1.attributeInterpolate3;
17530 case 9:
17531 return Identifiers$1.attributeInterpolate4;
17532 case 11:
17533 return Identifiers$1.attributeInterpolate5;
17534 case 13:
17535 return Identifiers$1.attributeInterpolate6;
17536 case 15:
17537 return Identifiers$1.attributeInterpolate7;
17538 case 17:
17539 return Identifiers$1.attributeInterpolate8;
17540 default:
17541 return Identifiers$1.attributeInterpolateV;
17542 }
17543}
17544/**
17545 * Gets the instruction to generate for interpolated text.
17546 * @param interpolation An Interpolation AST
17547 */
17548function getTextInterpolationExpression(interpolation) {
17549 switch (getInterpolationArgsLength(interpolation)) {
17550 case 1:
17551 return Identifiers$1.textInterpolate;
17552 case 3:
17553 return Identifiers$1.textInterpolate1;
17554 case 5:
17555 return Identifiers$1.textInterpolate2;
17556 case 7:
17557 return Identifiers$1.textInterpolate3;
17558 case 9:
17559 return Identifiers$1.textInterpolate4;
17560 case 11:
17561 return Identifiers$1.textInterpolate5;
17562 case 13:
17563 return Identifiers$1.textInterpolate6;
17564 case 15:
17565 return Identifiers$1.textInterpolate7;
17566 case 17:
17567 return Identifiers$1.textInterpolate8;
17568 default:
17569 return Identifiers$1.textInterpolateV;
17570 }
17571}
17572/**
17573 * Parse a template into render3 `Node`s and additional metadata, with no other dependencies.
17574 *
17575 * @param template text of the template to parse
17576 * @param templateUrl URL to use for source mapping of the parsed template
17577 * @param options options to modify how the template is parsed
17578 */
17579function parseTemplate(template, templateUrl, options) {
17580 if (options === void 0) { options = {}; }
17581 var interpolationConfig = options.interpolationConfig, preserveWhitespaces = options.preserveWhitespaces;
17582 var bindingParser = makeBindingParser(interpolationConfig);
17583 var htmlParser = new HtmlParser();
17584 var parseResult = htmlParser.parse(template, templateUrl, __assign({ leadingTriviaChars: LEADING_TRIVIA_CHARS }, options, { tokenizeExpansionForms: true }));
17585 if (parseResult.errors && parseResult.errors.length > 0) {
17586 return { errors: parseResult.errors, nodes: [], styleUrls: [], styles: [] };
17587 }
17588 var rootNodes = parseResult.rootNodes;
17589 // process i18n meta information (scan attributes, generate ids)
17590 // before we run whitespace removal process, because existing i18n
17591 // extraction process (ng xi18n) relies on a raw content to generate
17592 // message ids
17593 rootNodes =
17594 visitAll$1(new I18nMetaVisitor(interpolationConfig, !preserveWhitespaces), rootNodes);
17595 if (!preserveWhitespaces) {
17596 rootNodes = visitAll$1(new WhitespaceVisitor(), rootNodes);
17597 // run i18n meta visitor again in case we remove whitespaces, because
17598 // that might affect generated i18n message content. During this pass
17599 // i18n IDs generated at the first pass will be preserved, so we can mimic
17600 // existing extraction process (ng xi18n)
17601 rootNodes = visitAll$1(new I18nMetaVisitor(interpolationConfig, /* keepI18nAttrs */ false), rootNodes);
17602 }
17603 var _a = htmlAstToRender3Ast(rootNodes, bindingParser), nodes = _a.nodes, errors = _a.errors, styleUrls = _a.styleUrls, styles = _a.styles;
17604 if (errors && errors.length > 0) {
17605 return { errors: errors, nodes: [], styleUrls: [], styles: [] };
17606 }
17607 return { nodes: nodes, styleUrls: styleUrls, styles: styles };
17608}
17609/**
17610 * Construct a `BindingParser` with a default configuration.
17611 */
17612function makeBindingParser(interpolationConfig) {
17613 if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
17614 return new BindingParser(new Parser$1(new Lexer()), interpolationConfig, new DomElementSchemaRegistry(), null, []);
17615}
17616function resolveSanitizationFn(context, isAttribute) {
17617 switch (context) {
17618 case SecurityContext.HTML:
17619 return importExpr(Identifiers$1.sanitizeHtml);
17620 case SecurityContext.SCRIPT:
17621 return importExpr(Identifiers$1.sanitizeScript);
17622 case SecurityContext.STYLE:
17623 // the compiler does not fill in an instruction for [style.prop?] binding
17624 // values because the style algorithm knows internally what props are subject
17625 // to sanitization (only [attr.style] values are explicitly sanitized)
17626 return isAttribute ? importExpr(Identifiers$1.sanitizeStyle) : null;
17627 case SecurityContext.URL:
17628 return importExpr(Identifiers$1.sanitizeUrl);
17629 case SecurityContext.RESOURCE_URL:
17630 return importExpr(Identifiers$1.sanitizeResourceUrl);
17631 default:
17632 return null;
17633 }
17634}
17635function isSingleElementTemplate(children) {
17636 return children.length === 1 && children[0] instanceof Element;
17637}
17638function isTextNode(node) {
17639 return node instanceof Text || node instanceof BoundText || node instanceof Icu;
17640}
17641function hasTextChildrenOnly(children) {
17642 return children.every(isTextNode);
17643}
17644
17645/**
17646 * @license
17647 * Copyright Google Inc. All Rights Reserved.
17648 *
17649 * Use of this source code is governed by an MIT-style license that can be
17650 * found in the LICENSE file at https://angular.io/license
17651 */
17652var EMPTY_ARRAY = [];
17653// This regex matches any binding names that contain the "attr." prefix, e.g. "attr.required"
17654// If there is a match, the first matching group will contain the attribute name to bind.
17655var ATTR_REGEX = /attr\.([^\]]+)/;
17656function getStylingPrefix(name) {
17657 return name.substring(0, 5); // style or class
17658}
17659function baseDirectiveFields(meta, constantPool, bindingParser) {
17660 var definitionMap = new DefinitionMap();
17661 // e.g. `type: MyDirective`
17662 definitionMap.set('type', meta.type);
17663 // e.g. `selectors: [['', 'someDir', '']]`
17664 definitionMap.set('selectors', createDirectiveSelector(meta.selector));
17665 // e.g. `factory: () => new MyApp(directiveInject(ElementRef))`
17666 var result = compileFactoryFunction({
17667 name: meta.name,
17668 type: meta.type,
17669 deps: meta.deps,
17670 injectFn: Identifiers$1.directiveInject,
17671 });
17672 definitionMap.set('factory', result.factory);
17673 if (meta.queries.length > 0) {
17674 // e.g. `contentQueries: (rf, ctx, dirIndex) => { ... }
17675 definitionMap.set('contentQueries', createContentQueriesFunction(meta.queries, constantPool, meta.name));
17676 }
17677 if (meta.viewQueries.length) {
17678 definitionMap.set('viewQuery', createViewQueriesFunction(meta.viewQueries, constantPool, meta.name));
17679 }
17680 // e.g. `hostBindings: (rf, ctx, elIndex) => { ... }
17681 definitionMap.set('hostBindings', createHostBindingsFunction(meta.host, meta.typeSourceSpan, bindingParser, constantPool, meta.selector || '', meta.name));
17682 // e.g 'inputs: {a: 'a'}`
17683 definitionMap.set('inputs', conditionallyCreateMapObjectLiteral(meta.inputs, true));
17684 // e.g 'outputs: {a: 'a'}`
17685 definitionMap.set('outputs', conditionallyCreateMapObjectLiteral(meta.outputs));
17686 if (meta.exportAs !== null) {
17687 definitionMap.set('exportAs', literalArr(meta.exportAs.map(function (e) { return literal(e); })));
17688 }
17689 return { definitionMap: definitionMap, statements: result.statements };
17690}
17691/**
17692 * Add features to the definition map.
17693 */
17694function addFeatures(definitionMap, meta) {
17695 // e.g. `features: [NgOnChangesFeature()]`
17696 var features = [];
17697 var providers = meta.providers;
17698 var viewProviders = meta.viewProviders;
17699 if (providers || viewProviders) {
17700 var args = [providers || new LiteralArrayExpr([])];
17701 if (viewProviders) {
17702 args.push(viewProviders);
17703 }
17704 features.push(importExpr(Identifiers$1.ProvidersFeature).callFn(args));
17705 }
17706 if (meta.usesInheritance) {
17707 features.push(importExpr(Identifiers$1.InheritDefinitionFeature));
17708 }
17709 if (meta.lifecycle.usesOnChanges) {
17710 features.push(importExpr(Identifiers$1.NgOnChangesFeature).callFn(EMPTY_ARRAY));
17711 }
17712 if (features.length) {
17713 definitionMap.set('features', literalArr(features));
17714 }
17715}
17716/**
17717 * Compile a directive for the render3 runtime as defined by the `R3DirectiveMetadata`.
17718 */
17719function compileDirectiveFromMetadata(meta, constantPool, bindingParser) {
17720 var _a = baseDirectiveFields(meta, constantPool, bindingParser), definitionMap = _a.definitionMap, statements = _a.statements;
17721 addFeatures(definitionMap, meta);
17722 var expression = importExpr(Identifiers$1.defineDirective).callFn([definitionMap.toLiteralMap()]);
17723 if (!meta.selector) {
17724 throw new Error("Directive " + meta.name + " has no selector, please add it!");
17725 }
17726 var type = createTypeForDef(meta, Identifiers$1.DirectiveDefWithMeta);
17727 return { expression: expression, type: type, statements: statements };
17728}
17729/**
17730 * Compile a base definition for the render3 runtime as defined by {@link R3BaseRefMetadata}
17731 * @param meta the metadata used for compilation.
17732 */
17733function compileBaseDefFromMetadata(meta, constantPool, bindingParser) {
17734 var definitionMap = new DefinitionMap();
17735 if (meta.inputs) {
17736 var inputs_1 = meta.inputs;
17737 var inputsMap = Object.keys(inputs_1).map(function (key) {
17738 var v = inputs_1[key];
17739 var value = Array.isArray(v) ? literalArr(v.map(function (vx) { return literal(vx); })) : literal(v);
17740 return { key: key, value: value, quoted: false };
17741 });
17742 definitionMap.set('inputs', literalMap(inputsMap));
17743 }
17744 if (meta.outputs) {
17745 var outputs_1 = meta.outputs;
17746 var outputsMap = Object.keys(outputs_1).map(function (key) {
17747 var value = literal(outputs_1[key]);
17748 return { key: key, value: value, quoted: false };
17749 });
17750 definitionMap.set('outputs', literalMap(outputsMap));
17751 }
17752 if (meta.viewQueries && meta.viewQueries.length > 0) {
17753 definitionMap.set('viewQuery', createViewQueriesFunction(meta.viewQueries, constantPool));
17754 }
17755 if (meta.queries && meta.queries.length > 0) {
17756 definitionMap.set('contentQueries', createContentQueriesFunction(meta.queries, constantPool));
17757 }
17758 if (meta.host) {
17759 definitionMap.set('hostBindings', createHostBindingsFunction(meta.host, meta.typeSourceSpan, bindingParser, constantPool, meta.name));
17760 }
17761 var expression = importExpr(Identifiers$1.defineBase).callFn([definitionMap.toLiteralMap()]);
17762 var type = new ExpressionType(importExpr(Identifiers$1.BaseDef), /* modifiers */ null, [expressionType(meta.type)]);
17763 return { expression: expression, type: type };
17764}
17765/**
17766 * Compile a component for the render3 runtime as defined by the `R3ComponentMetadata`.
17767 */
17768function compileComponentFromMetadata(meta, constantPool, bindingParser) {
17769 var e_1, _a;
17770 var _b = baseDirectiveFields(meta, constantPool, bindingParser), definitionMap = _b.definitionMap, statements = _b.statements;
17771 addFeatures(definitionMap, meta);
17772 var selector = meta.selector && CssSelector.parse(meta.selector);
17773 var firstSelector = selector && selector[0];
17774 // e.g. `attr: ["class", ".my.app"]`
17775 // This is optional an only included if the first selector of a component specifies attributes.
17776 if (firstSelector) {
17777 var selectorAttributes = firstSelector.getAttrs();
17778 if (selectorAttributes.length) {
17779 definitionMap.set('attrs', constantPool.getConstLiteral(literalArr(selectorAttributes.map(function (value) { return value != null ? literal(value) : literal(undefined); })),
17780 /* forceShared */ true));
17781 }
17782 }
17783 // Generate the CSS matcher that recognize directive
17784 var directiveMatcher = null;
17785 if (meta.directives.length > 0) {
17786 var matcher = new SelectorMatcher();
17787 try {
17788 for (var _c = __values(meta.directives), _d = _c.next(); !_d.done; _d = _c.next()) {
17789 var _e = _d.value, selector_1 = _e.selector, expression_1 = _e.expression;
17790 matcher.addSelectables(CssSelector.parse(selector_1), expression_1);
17791 }
17792 }
17793 catch (e_1_1) { e_1 = { error: e_1_1 }; }
17794 finally {
17795 try {
17796 if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
17797 }
17798 finally { if (e_1) throw e_1.error; }
17799 }
17800 directiveMatcher = matcher;
17801 }
17802 // e.g. `template: function MyComponent_Template(_ctx, _cm) {...}`
17803 var templateTypeName = meta.name;
17804 var templateName = templateTypeName ? templateTypeName + "_Template" : null;
17805 var directivesUsed = new Set();
17806 var pipesUsed = new Set();
17807 var changeDetection = meta.changeDetection;
17808 var template = meta.template;
17809 var templateBuilder = new TemplateDefinitionBuilder(constantPool, BindingScope.ROOT_SCOPE, 0, templateTypeName, null, null, templateName, directiveMatcher, directivesUsed, meta.pipes, pipesUsed, Identifiers$1.namespaceHTML, meta.relativeContextFilePath, meta.i18nUseExternalIds);
17810 var templateFunctionExpression = templateBuilder.buildTemplateFunction(template.nodes, []);
17811 // We need to provide this so that dynamically generated components know what
17812 // projected content blocks to pass through to the component when it is instantiated.
17813 var ngContentSelectors = templateBuilder.getNgContentSelectors();
17814 if (ngContentSelectors) {
17815 definitionMap.set('ngContentSelectors', ngContentSelectors);
17816 }
17817 // e.g. `consts: 2`
17818 definitionMap.set('consts', literal(templateBuilder.getConstCount()));
17819 // e.g. `vars: 2`
17820 definitionMap.set('vars', literal(templateBuilder.getVarCount()));
17821 definitionMap.set('template', templateFunctionExpression);
17822 // e.g. `directives: [MyDirective]`
17823 if (directivesUsed.size) {
17824 var directivesExpr = literalArr(Array.from(directivesUsed));
17825 if (meta.wrapDirectivesAndPipesInClosure) {
17826 directivesExpr = fn([], [new ReturnStatement(directivesExpr)]);
17827 }
17828 definitionMap.set('directives', directivesExpr);
17829 }
17830 // e.g. `pipes: [MyPipe]`
17831 if (pipesUsed.size) {
17832 var pipesExpr = literalArr(Array.from(pipesUsed));
17833 if (meta.wrapDirectivesAndPipesInClosure) {
17834 pipesExpr = fn([], [new ReturnStatement(pipesExpr)]);
17835 }
17836 definitionMap.set('pipes', pipesExpr);
17837 }
17838 if (meta.encapsulation === null) {
17839 meta.encapsulation = ViewEncapsulation.Emulated;
17840 }
17841 // e.g. `styles: [str1, str2]`
17842 if (meta.styles && meta.styles.length) {
17843 var styleValues = meta.encapsulation == ViewEncapsulation.Emulated ?
17844 compileStyles(meta.styles, CONTENT_ATTR, HOST_ATTR) :
17845 meta.styles;
17846 var strings = styleValues.map(function (str) { return literal(str); });
17847 definitionMap.set('styles', literalArr(strings));
17848 }
17849 else if (meta.encapsulation === ViewEncapsulation.Emulated) {
17850 // If there is no style, don't generate css selectors on elements
17851 meta.encapsulation = ViewEncapsulation.None;
17852 }
17853 // Only set view encapsulation if it's not the default value
17854 if (meta.encapsulation !== ViewEncapsulation.Emulated) {
17855 definitionMap.set('encapsulation', literal(meta.encapsulation));
17856 }
17857 // e.g. `animation: [trigger('123', [])]`
17858 if (meta.animations !== null) {
17859 definitionMap.set('data', literalMap([{ key: 'animation', value: meta.animations, quoted: false }]));
17860 }
17861 // Only set the change detection flag if it's defined and it's not the default.
17862 if (changeDetection != null && changeDetection !== ChangeDetectionStrategy.Default) {
17863 definitionMap.set('changeDetection', literal(changeDetection));
17864 }
17865 // On the type side, remove newlines from the selector as it will need to fit into a TypeScript
17866 // string literal, which must be on one line.
17867 var selectorForType = (meta.selector || '').replace(/\n/g, '');
17868 var expression = importExpr(Identifiers$1.defineComponent).callFn([definitionMap.toLiteralMap()]);
17869 var type = createTypeForDef(meta, Identifiers$1.ComponentDefWithMeta);
17870 return { expression: expression, type: type, statements: statements };
17871}
17872/**
17873 * A wrapper around `compileDirective` which depends on render2 global analysis data as its input
17874 * instead of the `R3DirectiveMetadata`.
17875 *
17876 * `R3DirectiveMetadata` is computed from `CompileDirectiveMetadata` and other statically reflected
17877 * information.
17878 */
17879function compileDirectiveFromRender2(outputCtx, directive, reflector, bindingParser) {
17880 var name = identifierName(directive.type);
17881 name || error("Cannot resolver the name of " + directive.type);
17882 var definitionField = outputCtx.constantPool.propertyNameOf(1 /* Directive */);
17883 var meta = directiveMetadataFromGlobalMetadata(directive, outputCtx, reflector);
17884 var res = compileDirectiveFromMetadata(meta, outputCtx.constantPool, bindingParser);
17885 // Create the partial class to be merged with the actual class.
17886 outputCtx.statements.push(new ClassStmt(name, null, [new ClassField(definitionField, INFERRED_TYPE, [StmtModifier.Static], res.expression)], [], new ClassMethod(null, [], []), []));
17887}
17888/**
17889 * A wrapper around `compileComponent` which depends on render2 global analysis data as its input
17890 * instead of the `R3DirectiveMetadata`.
17891 *
17892 * `R3ComponentMetadata` is computed from `CompileDirectiveMetadata` and other statically reflected
17893 * information.
17894 */
17895function compileComponentFromRender2(outputCtx, component, render3Ast, reflector, bindingParser, directiveTypeBySel, pipeTypeByName) {
17896 var name = identifierName(component.type);
17897 name || error("Cannot resolver the name of " + component.type);
17898 var definitionField = outputCtx.constantPool.propertyNameOf(2 /* Component */);
17899 var summary = component.toSummary();
17900 // Compute the R3ComponentMetadata from the CompileDirectiveMetadata
17901 var meta = __assign({}, directiveMetadataFromGlobalMetadata(component, outputCtx, reflector), { selector: component.selector, template: { nodes: render3Ast.nodes }, directives: [], pipes: typeMapToExpressionMap(pipeTypeByName, outputCtx), viewQueries: queriesFromGlobalMetadata(component.viewQueries, outputCtx), wrapDirectivesAndPipesInClosure: false, styles: (summary.template && summary.template.styles) || EMPTY_ARRAY, encapsulation: (summary.template && summary.template.encapsulation) || ViewEncapsulation.Emulated, interpolation: DEFAULT_INTERPOLATION_CONFIG, animations: null, viewProviders: component.viewProviders.length > 0 ? new WrappedNodeExpr(component.viewProviders) : null, relativeContextFilePath: '', i18nUseExternalIds: true });
17902 var res = compileComponentFromMetadata(meta, outputCtx.constantPool, bindingParser);
17903 // Create the partial class to be merged with the actual class.
17904 outputCtx.statements.push(new ClassStmt(name, null, [new ClassField(definitionField, INFERRED_TYPE, [StmtModifier.Static], res.expression)], [], new ClassMethod(null, [], []), []));
17905}
17906/**
17907 * Compute `R3DirectiveMetadata` given `CompileDirectiveMetadata` and a `CompileReflector`.
17908 */
17909function directiveMetadataFromGlobalMetadata(directive, outputCtx, reflector) {
17910 // The global-analysis based Ivy mode in ngc is no longer utilized/supported.
17911 throw new Error('unsupported');
17912}
17913/**
17914 * Convert `CompileQueryMetadata` into `R3QueryMetadata`.
17915 */
17916function queriesFromGlobalMetadata(queries, outputCtx) {
17917 return queries.map(function (query) {
17918 var read = null;
17919 if (query.read && query.read.identifier) {
17920 read = outputCtx.importExpr(query.read.identifier.reference);
17921 }
17922 return {
17923 propertyName: query.propertyName,
17924 first: query.first,
17925 predicate: selectorsFromGlobalMetadata(query.selectors, outputCtx),
17926 descendants: query.descendants, read: read,
17927 static: !!query.static
17928 };
17929 });
17930}
17931/**
17932 * Convert `CompileTokenMetadata` for query selectors into either an expression for a predicate
17933 * type, or a list of string predicates.
17934 */
17935function selectorsFromGlobalMetadata(selectors, outputCtx) {
17936 if (selectors.length > 1 || (selectors.length == 1 && selectors[0].value)) {
17937 var selectorStrings = selectors.map(function (value) { return value.value; });
17938 selectorStrings.some(function (value) { return !value; }) &&
17939 error('Found a type among the string selectors expected');
17940 return outputCtx.constantPool.getConstLiteral(literalArr(selectorStrings.map(function (value) { return literal(value); })));
17941 }
17942 if (selectors.length == 1) {
17943 var first = selectors[0];
17944 if (first.identifier) {
17945 return outputCtx.importExpr(first.identifier.reference);
17946 }
17947 }
17948 error('Unexpected query form');
17949 return NULL_EXPR;
17950}
17951function prepareQueryParams(query, constantPool) {
17952 var parameters = [getQueryPredicate(query, constantPool), literal(query.descendants)];
17953 if (query.read) {
17954 parameters.push(query.read);
17955 }
17956 return parameters;
17957}
17958// Turn a directive selector into an R3-compatible selector for directive def
17959function createDirectiveSelector(selector) {
17960 return asLiteral(parseSelectorToR3Selector(selector));
17961}
17962function convertAttributesToExpressions(attributes) {
17963 var e_2, _a;
17964 var values = [];
17965 try {
17966 for (var _b = __values(Object.getOwnPropertyNames(attributes)), _c = _b.next(); !_c.done; _c = _b.next()) {
17967 var key = _c.value;
17968 var value = attributes[key];
17969 values.push(literal(key), value);
17970 }
17971 }
17972 catch (e_2_1) { e_2 = { error: e_2_1 }; }
17973 finally {
17974 try {
17975 if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
17976 }
17977 finally { if (e_2) throw e_2.error; }
17978 }
17979 return values;
17980}
17981// Define and update any content queries
17982function createContentQueriesFunction(queries, constantPool, name) {
17983 var e_3, _a;
17984 var createStatements = [];
17985 var updateStatements = [];
17986 var tempAllocator = temporaryAllocator(updateStatements, TEMPORARY_NAME);
17987 try {
17988 for (var queries_1 = __values(queries), queries_1_1 = queries_1.next(); !queries_1_1.done; queries_1_1 = queries_1.next()) {
17989 var query = queries_1_1.value;
17990 var queryInstruction = query.static ? Identifiers$1.staticContentQuery : Identifiers$1.contentQuery;
17991 // creation, e.g. r3.contentQuery(dirIndex, somePredicate, true, null);
17992 createStatements.push(importExpr(queryInstruction)
17993 .callFn(__spread([variable('dirIndex')], prepareQueryParams(query, constantPool)))
17994 .toStmt());
17995 // update, e.g. (r3.queryRefresh(tmp = r3.loadContentQuery()) && (ctx.someDir = tmp));
17996 var temporary = tempAllocator();
17997 var getQueryList = importExpr(Identifiers$1.loadContentQuery).callFn([]);
17998 var refresh = importExpr(Identifiers$1.queryRefresh).callFn([temporary.set(getQueryList)]);
17999 var updateDirective = variable(CONTEXT_NAME)
18000 .prop(query.propertyName)
18001 .set(query.first ? temporary.prop('first') : temporary);
18002 updateStatements.push(refresh.and(updateDirective).toStmt());
18003 }
18004 }
18005 catch (e_3_1) { e_3 = { error: e_3_1 }; }
18006 finally {
18007 try {
18008 if (queries_1_1 && !queries_1_1.done && (_a = queries_1.return)) _a.call(queries_1);
18009 }
18010 finally { if (e_3) throw e_3.error; }
18011 }
18012 var contentQueriesFnName = name ? name + "_ContentQueries" : null;
18013 return fn([
18014 new FnParam(RENDER_FLAGS, NUMBER_TYPE), new FnParam(CONTEXT_NAME, null),
18015 new FnParam('dirIndex', null)
18016 ], [
18017 renderFlagCheckIfStmt(1 /* Create */, createStatements),
18018 renderFlagCheckIfStmt(2 /* Update */, updateStatements)
18019 ], INFERRED_TYPE, null, contentQueriesFnName);
18020}
18021function stringAsType(str) {
18022 return expressionType(literal(str));
18023}
18024function stringMapAsType(map) {
18025 var mapValues = Object.keys(map).map(function (key) {
18026 var value = Array.isArray(map[key]) ? map[key][0] : map[key];
18027 return {
18028 key: key,
18029 value: literal(value),
18030 quoted: true,
18031 };
18032 });
18033 return expressionType(literalMap(mapValues));
18034}
18035function stringArrayAsType(arr) {
18036 return arr.length > 0 ? expressionType(literalArr(arr.map(function (value) { return literal(value); }))) :
18037 NONE_TYPE;
18038}
18039function createTypeForDef(meta, typeBase) {
18040 // On the type side, remove newlines from the selector as it will need to fit into a TypeScript
18041 // string literal, which must be on one line.
18042 var selectorForType = (meta.selector || '').replace(/\n/g, '');
18043 return expressionType(importExpr(typeBase, [
18044 typeWithParameters(meta.type, meta.typeArgumentCount),
18045 stringAsType(selectorForType),
18046 meta.exportAs !== null ? stringArrayAsType(meta.exportAs) : NONE_TYPE,
18047 stringMapAsType(meta.inputs),
18048 stringMapAsType(meta.outputs),
18049 stringArrayAsType(meta.queries.map(function (q) { return q.propertyName; })),
18050 ]));
18051}
18052// Define and update any view queries
18053function createViewQueriesFunction(viewQueries, constantPool, name) {
18054 var createStatements = [];
18055 var updateStatements = [];
18056 var tempAllocator = temporaryAllocator(updateStatements, TEMPORARY_NAME);
18057 viewQueries.forEach(function (query) {
18058 var queryInstruction = query.static ? Identifiers$1.staticViewQuery : Identifiers$1.viewQuery;
18059 // creation, e.g. r3.viewQuery(somePredicate, true);
18060 var queryDefinition = importExpr(queryInstruction).callFn(prepareQueryParams(query, constantPool));
18061 createStatements.push(queryDefinition.toStmt());
18062 // update, e.g. (r3.queryRefresh(tmp = r3.loadViewQuery()) && (ctx.someDir = tmp));
18063 var temporary = tempAllocator();
18064 var getQueryList = importExpr(Identifiers$1.loadViewQuery).callFn([]);
18065 var refresh = importExpr(Identifiers$1.queryRefresh).callFn([temporary.set(getQueryList)]);
18066 var updateDirective = variable(CONTEXT_NAME)
18067 .prop(query.propertyName)
18068 .set(query.first ? temporary.prop('first') : temporary);
18069 updateStatements.push(refresh.and(updateDirective).toStmt());
18070 });
18071 var viewQueryFnName = name ? name + "_Query" : null;
18072 return fn([new FnParam(RENDER_FLAGS, NUMBER_TYPE), new FnParam(CONTEXT_NAME, null)], [
18073 renderFlagCheckIfStmt(1 /* Create */, createStatements),
18074 renderFlagCheckIfStmt(2 /* Update */, updateStatements)
18075 ], INFERRED_TYPE, null, viewQueryFnName);
18076}
18077// Return a host binding function or null if one is not necessary.
18078function createHostBindingsFunction(hostBindingsMetadata, typeSourceSpan, bindingParser, constantPool, selector, name) {
18079 // Initialize hostVarsCount to number of bound host properties (interpolations illegal)
18080 var hostVarsCount = Object.keys(hostBindingsMetadata.properties).length;
18081 var elVarExp = variable('elIndex');
18082 var bindingContext = variable(CONTEXT_NAME);
18083 var styleBuilder = new StylingBuilder(elVarExp, bindingContext);
18084 var _a = hostBindingsMetadata.specialAttributes, styleAttr = _a.styleAttr, classAttr = _a.classAttr;
18085 if (styleAttr !== undefined) {
18086 styleBuilder.registerStyleAttr(styleAttr);
18087 }
18088 if (classAttr !== undefined) {
18089 styleBuilder.registerClassAttr(classAttr);
18090 }
18091 var createStatements = [];
18092 var updateStatements = [];
18093 var totalHostVarsCount = hostVarsCount;
18094 var hostBindingSourceSpan = typeSourceSpan;
18095 var directiveSummary = metadataAsSummary(hostBindingsMetadata);
18096 var valueConverter;
18097 var getValueConverter = function () {
18098 if (!valueConverter) {
18099 var hostVarsCountFn = function (numSlots) {
18100 var originalVarsCount = totalHostVarsCount;
18101 totalHostVarsCount += numSlots;
18102 return originalVarsCount;
18103 };
18104 valueConverter = new ValueConverter(constantPool, function () { return error('Unexpected node'); }, // new nodes are illegal here
18105 hostVarsCountFn, function () { return error('Unexpected pipe'); }); // pipes are illegal here
18106 }
18107 return valueConverter;
18108 };
18109 // Calculate host event bindings
18110 var eventBindings = bindingParser.createDirectiveHostEventAsts(directiveSummary, hostBindingSourceSpan);
18111 if (eventBindings && eventBindings.length) {
18112 var listeners = createHostListeners(eventBindings, name);
18113 createStatements.push.apply(createStatements, __spread(listeners));
18114 }
18115 // Calculate the host property bindings
18116 var bindings = bindingParser.createBoundHostProperties(directiveSummary, hostBindingSourceSpan);
18117 var propertyBindings = [];
18118 var attributeBindings = [];
18119 var syntheticHostBindings = [];
18120 bindings && bindings.forEach(function (binding) {
18121 var name = binding.name;
18122 var stylingInputWasSet = styleBuilder.registerInputBasedOnName(name, binding.expression, binding.sourceSpan);
18123 if (!stylingInputWasSet) {
18124 // resolve literal arrays and literal objects
18125 var value = binding.expression.visit(getValueConverter());
18126 var bindingExpr = bindingFn(bindingContext, value);
18127 var _a = getBindingNameAndInstruction(binding), bindingName = _a.bindingName, instruction = _a.instruction, isAttribute = _a.isAttribute;
18128 var securityContexts = bindingParser.calcPossibleSecurityContexts(selector, bindingName, isAttribute)
18129 .filter(function (context) { return context !== SecurityContext.NONE; });
18130 var sanitizerFn = null;
18131 if (securityContexts.length) {
18132 if (securityContexts.length === 2 &&
18133 securityContexts.indexOf(SecurityContext.URL) > -1 &&
18134 securityContexts.indexOf(SecurityContext.RESOURCE_URL) > -1) {
18135 // Special case for some URL attributes (such as "src" and "href") that may be a part
18136 // of different security contexts. In this case we use special santitization function and
18137 // select the actual sanitizer at runtime based on a tag name that is provided while
18138 // invoking sanitization function.
18139 sanitizerFn = importExpr(Identifiers$1.sanitizeUrlOrResourceUrl);
18140 }
18141 else {
18142 sanitizerFn = resolveSanitizationFn(securityContexts[0], isAttribute);
18143 }
18144 }
18145 var instructionParams = [literal(bindingName), bindingExpr.currValExpr];
18146 if (sanitizerFn) {
18147 instructionParams.push(sanitizerFn);
18148 }
18149 updateStatements.push.apply(updateStatements, __spread(bindingExpr.stmts));
18150 if (instruction === Identifiers$1.hostProperty) {
18151 propertyBindings.push(instructionParams);
18152 }
18153 else if (instruction === Identifiers$1.attribute) {
18154 attributeBindings.push(instructionParams);
18155 }
18156 else if (instruction === Identifiers$1.updateSyntheticHostBinding) {
18157 syntheticHostBindings.push(instructionParams);
18158 }
18159 else {
18160 updateStatements.push(importExpr(instruction).callFn(instructionParams).toStmt());
18161 }
18162 }
18163 });
18164 if (propertyBindings.length > 0) {
18165 updateStatements.push(chainedInstruction(Identifiers$1.hostProperty, propertyBindings).toStmt());
18166 }
18167 if (attributeBindings.length > 0) {
18168 updateStatements.push(chainedInstruction(Identifiers$1.attribute, attributeBindings).toStmt());
18169 }
18170 if (syntheticHostBindings.length > 0) {
18171 updateStatements.push(chainedInstruction(Identifiers$1.updateSyntheticHostBinding, syntheticHostBindings).toStmt());
18172 }
18173 // since we're dealing with directives/components and both have hostBinding
18174 // functions, we need to generate a special hostAttrs instruction that deals
18175 // with both the assignment of styling as well as static attributes to the host
18176 // element. The instruction below will instruct all initial styling (styling
18177 // that is inside of a host binding within a directive/component) to be attached
18178 // to the host element alongside any of the provided host attributes that were
18179 // collected earlier.
18180 var hostAttrs = convertAttributesToExpressions(hostBindingsMetadata.attributes);
18181 var hostInstruction = styleBuilder.buildHostAttrsInstruction(null, hostAttrs, constantPool);
18182 if (hostInstruction) {
18183 createStatements.push(createStylingStmt(hostInstruction, bindingContext, bindingFn));
18184 }
18185 if (styleBuilder.hasBindings) {
18186 // singular style/class bindings (things like `[style.prop]` and `[class.name]`)
18187 // MUST be registered on a given element within the component/directive
18188 // templateFn/hostBindingsFn functions. The instruction below will figure out
18189 // what all the bindings are and then generate the statements required to register
18190 // those bindings to the element via `styling`.
18191 var stylingInstruction = styleBuilder.buildStylingInstruction(null, constantPool);
18192 if (stylingInstruction) {
18193 createStatements.push(createStylingStmt(stylingInstruction, bindingContext, bindingFn));
18194 }
18195 // finally each binding that was registered in the statement above will need to be added to
18196 // the update block of a component/directive templateFn/hostBindingsFn so that the bindings
18197 // are evaluated and updated for the element.
18198 styleBuilder.buildUpdateLevelInstructions(getValueConverter()).forEach(function (instruction) {
18199 // we subtract a value of `1` here because the binding slot was already
18200 // allocated at the top of this method when all the input bindings were
18201 // counted.
18202 totalHostVarsCount += Math.max(instruction.allocateBindingSlots - 1, 0);
18203 updateStatements.push(createStylingStmt(instruction, bindingContext, bindingFn));
18204 });
18205 }
18206 if (totalHostVarsCount) {
18207 createStatements.unshift(importExpr(Identifiers$1.allocHostVars).callFn([literal(totalHostVarsCount)]).toStmt());
18208 }
18209 if (createStatements.length > 0 || updateStatements.length > 0) {
18210 var hostBindingsFnName = name ? name + "_HostBindings" : null;
18211 var statements = [];
18212 if (createStatements.length > 0) {
18213 statements.push(renderFlagCheckIfStmt(1 /* Create */, createStatements));
18214 }
18215 if (updateStatements.length > 0) {
18216 statements.push(renderFlagCheckIfStmt(2 /* Update */, updateStatements));
18217 }
18218 return fn([
18219 new FnParam(RENDER_FLAGS, NUMBER_TYPE), new FnParam(CONTEXT_NAME, null),
18220 new FnParam(elVarExp.name, NUMBER_TYPE)
18221 ], statements, INFERRED_TYPE, null, hostBindingsFnName);
18222 }
18223 return null;
18224}
18225function bindingFn(implicit, value) {
18226 return convertPropertyBinding(null, implicit, value, 'b', BindingForm.TrySimple, function () { return error('Unexpected interpolation'); });
18227}
18228function createStylingStmt(instruction, bindingContext, bindingFn) {
18229 var params = instruction.params(function (value) { return bindingFn(bindingContext, value).currValExpr; });
18230 return importExpr(instruction.reference, null, instruction.sourceSpan)
18231 .callFn(params, instruction.sourceSpan)
18232 .toStmt();
18233}
18234function getBindingNameAndInstruction(binding) {
18235 var bindingName = binding.name;
18236 var instruction;
18237 // Check to see if this is an attr binding or a property binding
18238 var attrMatches = bindingName.match(ATTR_REGEX);
18239 if (attrMatches) {
18240 bindingName = attrMatches[1];
18241 instruction = Identifiers$1.attribute;
18242 }
18243 else {
18244 if (binding.isAnimation) {
18245 bindingName = prepareSyntheticPropertyName(bindingName);
18246 // host bindings that have a synthetic property (e.g. @foo) should always be rendered
18247 // in the context of the component and not the parent. Therefore there is a special
18248 // compatibility instruction available for this purpose.
18249 instruction = Identifiers$1.updateSyntheticHostBinding;
18250 }
18251 else {
18252 instruction = Identifiers$1.hostProperty;
18253 }
18254 }
18255 return { bindingName: bindingName, instruction: instruction, isAttribute: !!attrMatches };
18256}
18257function createHostListeners(eventBindings, name) {
18258 return eventBindings.map(function (binding) {
18259 var bindingName = binding.name && sanitizeIdentifier(binding.name);
18260 var bindingFnName = binding.type === 1 /* Animation */ ?
18261 prepareSyntheticListenerFunctionName(bindingName, binding.targetOrPhase) :
18262 bindingName;
18263 var handlerName = name && bindingName ? name + "_" + bindingFnName + "_HostBindingHandler" : null;
18264 var params = prepareEventListenerParameters(BoundEvent.fromParsedEvent(binding), handlerName);
18265 var instruction = binding.type == 1 /* Animation */ ? Identifiers$1.componentHostSyntheticListener : Identifiers$1.listener;
18266 return importExpr(instruction).callFn(params).toStmt();
18267 });
18268}
18269function metadataAsSummary(meta) {
18270 // clang-format off
18271 return {
18272 // This is used by the BindingParser, which only deals with listeners and properties. There's no
18273 // need to pass attributes to it.
18274 hostAttributes: {},
18275 hostListeners: meta.listeners,
18276 hostProperties: meta.properties,
18277 };
18278 // clang-format on
18279}
18280function typeMapToExpressionMap(map, outputCtx) {
18281 // Convert each map entry into another entry where the value is an expression importing the type.
18282 var entries = Array.from(map).map(function (_a) {
18283 var _b = __read(_a, 2), key = _b[0], type = _b[1];
18284 return [key, outputCtx.importExpr(type)];
18285 });
18286 return new Map(entries);
18287}
18288var HOST_REG_EXP$1 = /^(?:\[([^\]]+)\])|(?:\(([^\)]+)\))$/;
18289function parseHostBindings(host) {
18290 var e_4, _a;
18291 var attributes = {};
18292 var listeners = {};
18293 var properties = {};
18294 var specialAttributes = {};
18295 try {
18296 for (var _b = __values(Object.keys(host)), _c = _b.next(); !_c.done; _c = _b.next()) {
18297 var key = _c.value;
18298 var value = host[key];
18299 var matches = key.match(HOST_REG_EXP$1);
18300 if (matches === null) {
18301 switch (key) {
18302 case 'class':
18303 if (typeof value !== 'string') {
18304 // TODO(alxhub): make this a diagnostic.
18305 throw new Error("Class binding must be string");
18306 }
18307 specialAttributes.classAttr = value;
18308 break;
18309 case 'style':
18310 if (typeof value !== 'string') {
18311 // TODO(alxhub): make this a diagnostic.
18312 throw new Error("Style binding must be string");
18313 }
18314 specialAttributes.styleAttr = value;
18315 break;
18316 default:
18317 if (typeof value === 'string') {
18318 attributes[key] = literal(value);
18319 }
18320 else {
18321 attributes[key] = value;
18322 }
18323 }
18324 }
18325 else if (matches[1 /* Binding */] != null) {
18326 if (typeof value !== 'string') {
18327 // TODO(alxhub): make this a diagnostic.
18328 throw new Error("Property binding must be string");
18329 }
18330 // synthetic properties (the ones that have a `@` as a prefix)
18331 // are still treated the same as regular properties. Therefore
18332 // there is no point in storing them in a separate map.
18333 properties[matches[1 /* Binding */]] = value;
18334 }
18335 else if (matches[2 /* Event */] != null) {
18336 if (typeof value !== 'string') {
18337 // TODO(alxhub): make this a diagnostic.
18338 throw new Error("Event binding must be string");
18339 }
18340 listeners[matches[2 /* Event */]] = value;
18341 }
18342 }
18343 }
18344 catch (e_4_1) { e_4 = { error: e_4_1 }; }
18345 finally {
18346 try {
18347 if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
18348 }
18349 finally { if (e_4) throw e_4.error; }
18350 }
18351 return { attributes: attributes, listeners: listeners, properties: properties, specialAttributes: specialAttributes };
18352}
18353/**
18354 * Verifies host bindings and returns the list of errors (if any). Empty array indicates that a
18355 * given set of host bindings has no errors.
18356 *
18357 * @param bindings set of host bindings to verify.
18358 * @param sourceSpan source span where host bindings were defined.
18359 * @returns array of errors associated with a given set of host bindings.
18360 */
18361function verifyHostBindings(bindings, sourceSpan) {
18362 var summary = metadataAsSummary(bindings);
18363 // TODO: abstract out host bindings verification logic and use it instead of
18364 // creating events and properties ASTs to detect errors (FW-996)
18365 var bindingParser = makeBindingParser();
18366 bindingParser.createDirectiveHostEventAsts(summary, sourceSpan);
18367 bindingParser.createBoundHostProperties(summary, sourceSpan);
18368 return bindingParser.errors;
18369}
18370function compileStyles(styles, selector, hostSelector) {
18371 var shadowCss = new ShadowCss();
18372 return styles.map(function (style) { return shadowCss.shimCssText(style, selector, hostSelector); });
18373}
18374
18375/**
18376 * @license
18377 * Copyright Google Inc. All Rights Reserved.
18378 *
18379 * Use of this source code is governed by an MIT-style license that can be
18380 * found in the LICENSE file at https://angular.io/license
18381 */
18382/**
18383 * An interface for retrieving documents by URL that the compiler uses
18384 * to load templates.
18385 */
18386var ResourceLoader = /** @class */ (function () {
18387 function ResourceLoader() {
18388 }
18389 ResourceLoader.prototype.get = function (url) { return ''; };
18390 return ResourceLoader;
18391}());
18392
18393/**
18394 * @license
18395 * Copyright Google Inc. All Rights Reserved.
18396 *
18397 * Use of this source code is governed by an MIT-style license that can be
18398 * found in the LICENSE file at https://angular.io/license
18399 */
18400var CompilerFacadeImpl = /** @class */ (function () {
18401 function CompilerFacadeImpl(jitEvaluator) {
18402 if (jitEvaluator === void 0) { jitEvaluator = new JitEvaluator(); }
18403 this.jitEvaluator = jitEvaluator;
18404 this.R3ResolvedDependencyType = R3ResolvedDependencyType;
18405 this.ResourceLoader = ResourceLoader;
18406 this.elementSchemaRegistry = new DomElementSchemaRegistry();
18407 }
18408 CompilerFacadeImpl.prototype.compilePipe = function (angularCoreEnv, sourceMapUrl, facade) {
18409 var res = compilePipeFromMetadata({
18410 name: facade.name,
18411 type: new WrappedNodeExpr(facade.type),
18412 typeArgumentCount: facade.typeArgumentCount,
18413 deps: convertR3DependencyMetadataArray(facade.deps),
18414 pipeName: facade.pipeName,
18415 pure: facade.pure,
18416 });
18417 return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, res.statements);
18418 };
18419 CompilerFacadeImpl.prototype.compileInjectable = function (angularCoreEnv, sourceMapUrl, facade) {
18420 var _a = compileInjectable({
18421 name: facade.name,
18422 type: new WrappedNodeExpr(facade.type),
18423 typeArgumentCount: facade.typeArgumentCount,
18424 providedIn: computeProvidedIn(facade.providedIn),
18425 useClass: wrapExpression(facade, USE_CLASS),
18426 useFactory: wrapExpression(facade, USE_FACTORY),
18427 useValue: wrapExpression(facade, USE_VALUE),
18428 useExisting: wrapExpression(facade, USE_EXISTING),
18429 ctorDeps: convertR3DependencyMetadataArray(facade.ctorDeps),
18430 userDeps: convertR3DependencyMetadataArray(facade.userDeps) || undefined,
18431 }), expression = _a.expression, statements = _a.statements;
18432 return this.jitExpression(expression, angularCoreEnv, sourceMapUrl, statements);
18433 };
18434 CompilerFacadeImpl.prototype.compileInjector = function (angularCoreEnv, sourceMapUrl, facade) {
18435 var meta = {
18436 name: facade.name,
18437 type: new WrappedNodeExpr(facade.type),
18438 deps: convertR3DependencyMetadataArray(facade.deps),
18439 providers: new WrappedNodeExpr(facade.providers),
18440 imports: facade.imports.map(function (i) { return new WrappedNodeExpr(i); }),
18441 };
18442 var res = compileInjector(meta);
18443 return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, res.statements);
18444 };
18445 CompilerFacadeImpl.prototype.compileNgModule = function (angularCoreEnv, sourceMapUrl, facade) {
18446 var meta = {
18447 type: new WrappedNodeExpr(facade.type),
18448 bootstrap: facade.bootstrap.map(wrapReference),
18449 declarations: facade.declarations.map(wrapReference),
18450 imports: facade.imports.map(wrapReference),
18451 exports: facade.exports.map(wrapReference),
18452 emitInline: true,
18453 containsForwardDecls: false,
18454 schemas: facade.schemas ? facade.schemas.map(wrapReference) : null,
18455 id: facade.id ? new WrappedNodeExpr(facade.id) : null,
18456 };
18457 var res = compileNgModule(meta);
18458 return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, []);
18459 };
18460 CompilerFacadeImpl.prototype.compileDirective = function (angularCoreEnv, sourceMapUrl, facade) {
18461 var constantPool = new ConstantPool();
18462 var bindingParser = makeBindingParser();
18463 var meta = convertDirectiveFacadeToMetadata(facade);
18464 var res = compileDirectiveFromMetadata(meta, constantPool, bindingParser);
18465 var preStatements = __spread(constantPool.statements, res.statements);
18466 return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, preStatements);
18467 };
18468 CompilerFacadeImpl.prototype.compileComponent = function (angularCoreEnv, sourceMapUrl, facade) {
18469 // The ConstantPool is a requirement of the JIT'er.
18470 var constantPool = new ConstantPool();
18471 var interpolationConfig = facade.interpolation ?
18472 InterpolationConfig.fromArray(facade.interpolation) :
18473 DEFAULT_INTERPOLATION_CONFIG;
18474 // Parse the template and check for errors.
18475 var template = parseTemplate(facade.template, sourceMapUrl, { preserveWhitespaces: facade.preserveWhitespaces, interpolationConfig: interpolationConfig });
18476 if (template.errors !== undefined) {
18477 var errors = template.errors.map(function (err) { return err.toString(); }).join(', ');
18478 throw new Error("Errors during JIT compilation of template for " + facade.name + ": " + errors);
18479 }
18480 // Compile the component metadata, including template, into an expression.
18481 // TODO(alxhub): implement inputs, outputs, queries, etc.
18482 var res = compileComponentFromMetadata(__assign({}, facade, convertDirectiveFacadeToMetadata(facade), { selector: facade.selector || this.elementSchemaRegistry.getDefaultComponentElementName(), template: template, wrapDirectivesAndPipesInClosure: false, styles: facade.styles || [], encapsulation: facade.encapsulation, interpolation: interpolationConfig, changeDetection: facade.changeDetection, animations: facade.animations != null ? new WrappedNodeExpr(facade.animations) : null, viewProviders: facade.viewProviders != null ? new WrappedNodeExpr(facade.viewProviders) :
18483 null, relativeContextFilePath: '', i18nUseExternalIds: true }), constantPool, makeBindingParser(interpolationConfig));
18484 var preStatements = __spread(constantPool.statements, res.statements);
18485 return this.jitExpression(res.expression, angularCoreEnv, "ng:///" + facade.name + ".js", preStatements);
18486 };
18487 CompilerFacadeImpl.prototype.compileBase = function (angularCoreEnv, sourceMapUrl, facade) {
18488 var constantPool = new ConstantPool();
18489 var typeSourceSpan = this.createParseSourceSpan('Base', facade.name, "ng:///" + facade.name + ".js");
18490 var meta = __assign({}, facade, { typeSourceSpan: typeSourceSpan, viewQueries: facade.viewQueries ? facade.viewQueries.map(convertToR3QueryMetadata) :
18491 facade.viewQueries, queries: facade.queries ? facade.queries.map(convertToR3QueryMetadata) : facade.queries, host: extractHostBindings(facade.propMetadata, typeSourceSpan) });
18492 var res = compileBaseDefFromMetadata(meta, constantPool, makeBindingParser());
18493 return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, constantPool.statements);
18494 };
18495 CompilerFacadeImpl.prototype.createParseSourceSpan = function (kind, typeName, sourceUrl) {
18496 return r3JitTypeSourceSpan(kind, typeName, sourceUrl);
18497 };
18498 /**
18499 * JIT compiles an expression and returns the result of executing that expression.
18500 *
18501 * @param def the definition which will be compiled and executed to get the value to patch
18502 * @param context an object map of @angular/core symbol names to symbols which will be available
18503 * in the context of the compiled expression
18504 * @param sourceUrl a URL to use for the source map of the compiled expression
18505 * @param preStatements a collection of statements that should be evaluated before the expression.
18506 */
18507 CompilerFacadeImpl.prototype.jitExpression = function (def, context, sourceUrl, preStatements) {
18508 // The ConstantPool may contain Statements which declare variables used in the final expression.
18509 // Therefore, its statements need to precede the actual JIT operation. The final statement is a
18510 // declaration of $def which is set to the expression being compiled.
18511 var statements = __spread(preStatements, [
18512 new DeclareVarStmt('$def', def, undefined, [StmtModifier.Exported]),
18513 ]);
18514 var res = this.jitEvaluator.evaluateStatements(sourceUrl, statements, new R3JitReflector(context), /* enableSourceMaps */ true);
18515 return res['$def'];
18516 };
18517 return CompilerFacadeImpl;
18518}());
18519var USE_CLASS = Object.keys({ useClass: null })[0];
18520var USE_FACTORY = Object.keys({ useFactory: null })[0];
18521var USE_VALUE = Object.keys({ useValue: null })[0];
18522var USE_EXISTING = Object.keys({ useExisting: null })[0];
18523var wrapReference = function (value) {
18524 var wrapped = new WrappedNodeExpr(value);
18525 return { value: wrapped, type: wrapped };
18526};
18527function convertToR3QueryMetadata(facade) {
18528 return __assign({}, facade, { predicate: Array.isArray(facade.predicate) ? facade.predicate :
18529 new WrappedNodeExpr(facade.predicate), read: facade.read ? new WrappedNodeExpr(facade.read) : null, static: facade.static });
18530}
18531function convertDirectiveFacadeToMetadata(facade) {
18532 var inputsFromMetadata = parseInputOutputs(facade.inputs || []);
18533 var outputsFromMetadata = parseInputOutputs(facade.outputs || []);
18534 var propMetadata = facade.propMetadata;
18535 var inputsFromType = {};
18536 var outputsFromType = {};
18537 var _loop_1 = function (field) {
18538 if (propMetadata.hasOwnProperty(field)) {
18539 propMetadata[field].forEach(function (ann) {
18540 if (isInput(ann)) {
18541 inputsFromType[field] =
18542 ann.bindingPropertyName ? [ann.bindingPropertyName, field] : field;
18543 }
18544 else if (isOutput(ann)) {
18545 outputsFromType[field] = ann.bindingPropertyName || field;
18546 }
18547 });
18548 }
18549 };
18550 for (var field in propMetadata) {
18551 _loop_1(field);
18552 }
18553 return __assign({}, facade, { typeSourceSpan: facade.typeSourceSpan, type: new WrappedNodeExpr(facade.type), deps: convertR3DependencyMetadataArray(facade.deps), host: extractHostBindings(facade.propMetadata, facade.typeSourceSpan, facade.host), inputs: __assign({}, inputsFromMetadata, inputsFromType), outputs: __assign({}, outputsFromMetadata, outputsFromType), queries: facade.queries.map(convertToR3QueryMetadata), providers: facade.providers != null ? new WrappedNodeExpr(facade.providers) : null, viewQueries: facade.viewQueries.map(convertToR3QueryMetadata) });
18554}
18555function wrapExpression(obj, property) {
18556 if (obj.hasOwnProperty(property)) {
18557 return new WrappedNodeExpr(obj[property]);
18558 }
18559 else {
18560 return undefined;
18561 }
18562}
18563function computeProvidedIn(providedIn) {
18564 if (providedIn == null || typeof providedIn === 'string') {
18565 return new LiteralExpr(providedIn);
18566 }
18567 else {
18568 return new WrappedNodeExpr(providedIn);
18569 }
18570}
18571function convertR3DependencyMetadata(facade) {
18572 var tokenExpr;
18573 if (facade.token === null) {
18574 tokenExpr = new LiteralExpr(null);
18575 }
18576 else if (facade.resolved === R3ResolvedDependencyType.Attribute) {
18577 tokenExpr = new LiteralExpr(facade.token);
18578 }
18579 else {
18580 tokenExpr = new WrappedNodeExpr(facade.token);
18581 }
18582 return {
18583 token: tokenExpr,
18584 resolved: facade.resolved,
18585 host: facade.host,
18586 optional: facade.optional,
18587 self: facade.self,
18588 skipSelf: facade.skipSelf
18589 };
18590}
18591function convertR3DependencyMetadataArray(facades) {
18592 return facades == null ? null : facades.map(convertR3DependencyMetadata);
18593}
18594function extractHostBindings(propMetadata, sourceSpan, host) {
18595 // First parse the declarations from the metadata.
18596 var bindings = parseHostBindings(host || {});
18597 // After that check host bindings for errors
18598 var errors = verifyHostBindings(bindings, sourceSpan);
18599 if (errors.length) {
18600 throw new Error(errors.map(function (error) { return error.msg; }).join('\n'));
18601 }
18602 var _loop_2 = function (field) {
18603 if (propMetadata.hasOwnProperty(field)) {
18604 propMetadata[field].forEach(function (ann) {
18605 if (isHostBinding(ann)) {
18606 bindings.properties[ann.hostPropertyName || field] = field;
18607 }
18608 else if (isHostListener(ann)) {
18609 bindings.listeners[ann.eventName || field] = field + "(" + (ann.args || []).join(',') + ")";
18610 }
18611 });
18612 }
18613 };
18614 // Next, loop over the properties of the object, looking for @HostBinding and @HostListener.
18615 for (var field in propMetadata) {
18616 _loop_2(field);
18617 }
18618 return bindings;
18619}
18620function isHostBinding(value) {
18621 return value.ngMetadataName === 'HostBinding';
18622}
18623function isHostListener(value) {
18624 return value.ngMetadataName === 'HostListener';
18625}
18626function isInput(value) {
18627 return value.ngMetadataName === 'Input';
18628}
18629function isOutput(value) {
18630 return value.ngMetadataName === 'Output';
18631}
18632function parseInputOutputs(values) {
18633 return values.reduce(function (map, value) {
18634 var _a = __read(value.split(',').map(function (piece) { return piece.trim(); }), 2), field = _a[0], property = _a[1];
18635 map[field] = property || field;
18636 return map;
18637 }, {});
18638}
18639function publishFacade(global) {
18640 var ng = global.ng || (global.ng = {});
18641 ng.ɵcompilerFacade = new CompilerFacadeImpl();
18642}
18643
18644/**
18645 * @license
18646 * Copyright Google Inc. All Rights Reserved.
18647 *
18648 * Use of this source code is governed by an MIT-style license that can be
18649 * found in the LICENSE file at https://angular.io/license
18650 */
18651var VERSION$1 = new Version('8.2.14');
18652
18653/**
18654 * @license
18655 * Copyright Google Inc. All Rights Reserved.
18656 *
18657 * Use of this source code is governed by an MIT-style license that can be
18658 * found in the LICENSE file at https://angular.io/license
18659 */
18660var CompilerConfig = /** @class */ (function () {
18661 function CompilerConfig(_a) {
18662 var _b = _a === void 0 ? {} : _a, _c = _b.defaultEncapsulation, defaultEncapsulation = _c === void 0 ? ViewEncapsulation.Emulated : _c, _d = _b.useJit, useJit = _d === void 0 ? true : _d, _e = _b.jitDevMode, jitDevMode = _e === void 0 ? false : _e, _f = _b.missingTranslation, missingTranslation = _f === void 0 ? null : _f, preserveWhitespaces = _b.preserveWhitespaces, strictInjectionParameters = _b.strictInjectionParameters;
18663 this.defaultEncapsulation = defaultEncapsulation;
18664 this.useJit = !!useJit;
18665 this.jitDevMode = !!jitDevMode;
18666 this.missingTranslation = missingTranslation;
18667 this.preserveWhitespaces = preserveWhitespacesDefault(noUndefined(preserveWhitespaces));
18668 this.strictInjectionParameters = strictInjectionParameters === true;
18669 }
18670 return CompilerConfig;
18671}());
18672function preserveWhitespacesDefault(preserveWhitespacesOption, defaultSetting) {
18673 if (defaultSetting === void 0) { defaultSetting = false; }
18674 return preserveWhitespacesOption === null ? defaultSetting : preserveWhitespacesOption;
18675}
18676
18677/**
18678 * @license
18679 * Copyright Google Inc. All Rights Reserved.
18680 *
18681 * Use of this source code is governed by an MIT-style license that can be
18682 * found in the LICENSE file at https://angular.io/license
18683 */
18684var DirectiveNormalizer = /** @class */ (function () {
18685 function DirectiveNormalizer(_resourceLoader, _urlResolver, _htmlParser, _config) {
18686 this._resourceLoader = _resourceLoader;
18687 this._urlResolver = _urlResolver;
18688 this._htmlParser = _htmlParser;
18689 this._config = _config;
18690 this._resourceLoaderCache = new Map();
18691 }
18692 DirectiveNormalizer.prototype.clearCache = function () { this._resourceLoaderCache.clear(); };
18693 DirectiveNormalizer.prototype.clearCacheFor = function (normalizedDirective) {
18694 var _this = this;
18695 if (!normalizedDirective.isComponent) {
18696 return;
18697 }
18698 var template = normalizedDirective.template;
18699 this._resourceLoaderCache.delete(template.templateUrl);
18700 template.externalStylesheets.forEach(function (stylesheet) { _this._resourceLoaderCache.delete(stylesheet.moduleUrl); });
18701 };
18702 DirectiveNormalizer.prototype._fetch = function (url) {
18703 var result = this._resourceLoaderCache.get(url);
18704 if (!result) {
18705 result = this._resourceLoader.get(url);
18706 this._resourceLoaderCache.set(url, result);
18707 }
18708 return result;
18709 };
18710 DirectiveNormalizer.prototype.normalizeTemplate = function (prenormData) {
18711 var _this = this;
18712 if (isDefined(prenormData.template)) {
18713 if (isDefined(prenormData.templateUrl)) {
18714 throw syntaxError("'" + stringify(prenormData.componentType) + "' component cannot define both template and templateUrl");
18715 }
18716 if (typeof prenormData.template !== 'string') {
18717 throw syntaxError("The template specified for component " + stringify(prenormData.componentType) + " is not a string");
18718 }
18719 }
18720 else if (isDefined(prenormData.templateUrl)) {
18721 if (typeof prenormData.templateUrl !== 'string') {
18722 throw syntaxError("The templateUrl specified for component " + stringify(prenormData.componentType) + " is not a string");
18723 }
18724 }
18725 else {
18726 throw syntaxError("No template specified for component " + stringify(prenormData.componentType));
18727 }
18728 if (isDefined(prenormData.preserveWhitespaces) &&
18729 typeof prenormData.preserveWhitespaces !== 'boolean') {
18730 throw syntaxError("The preserveWhitespaces option for component " + stringify(prenormData.componentType) + " must be a boolean");
18731 }
18732 return SyncAsync.then(this._preParseTemplate(prenormData), function (preparsedTemplate) { return _this._normalizeTemplateMetadata(prenormData, preparsedTemplate); });
18733 };
18734 DirectiveNormalizer.prototype._preParseTemplate = function (prenomData) {
18735 var _this = this;
18736 var template;
18737 var templateUrl;
18738 if (prenomData.template != null) {
18739 template = prenomData.template;
18740 templateUrl = prenomData.moduleUrl;
18741 }
18742 else {
18743 templateUrl = this._urlResolver.resolve(prenomData.moduleUrl, prenomData.templateUrl);
18744 template = this._fetch(templateUrl);
18745 }
18746 return SyncAsync.then(template, function (template) { return _this._preparseLoadedTemplate(prenomData, template, templateUrl); });
18747 };
18748 DirectiveNormalizer.prototype._preparseLoadedTemplate = function (prenormData, template, templateAbsUrl) {
18749 var isInline = !!prenormData.template;
18750 var interpolationConfig = InterpolationConfig.fromArray(prenormData.interpolation);
18751 var templateUrl = templateSourceUrl({ reference: prenormData.ngModuleType }, { type: { reference: prenormData.componentType } }, { isInline: isInline, templateUrl: templateAbsUrl });
18752 var rootNodesAndErrors = this._htmlParser.parse(template, templateUrl, { tokenizeExpansionForms: true, interpolationConfig: interpolationConfig });
18753 if (rootNodesAndErrors.errors.length > 0) {
18754 var errorString = rootNodesAndErrors.errors.join('\n');
18755 throw syntaxError("Template parse errors:\n" + errorString);
18756 }
18757 var templateMetadataStyles = this._normalizeStylesheet(new CompileStylesheetMetadata({ styles: prenormData.styles, moduleUrl: prenormData.moduleUrl }));
18758 var visitor = new TemplatePreparseVisitor();
18759 visitAll$1(visitor, rootNodesAndErrors.rootNodes);
18760 var templateStyles = this._normalizeStylesheet(new CompileStylesheetMetadata({ styles: visitor.styles, styleUrls: visitor.styleUrls, moduleUrl: templateAbsUrl }));
18761 var styles = templateMetadataStyles.styles.concat(templateStyles.styles);
18762 var inlineStyleUrls = templateMetadataStyles.styleUrls.concat(templateStyles.styleUrls);
18763 var styleUrls = this
18764 ._normalizeStylesheet(new CompileStylesheetMetadata({ styleUrls: prenormData.styleUrls, moduleUrl: prenormData.moduleUrl }))
18765 .styleUrls;
18766 return {
18767 template: template,
18768 templateUrl: templateAbsUrl, isInline: isInline,
18769 htmlAst: rootNodesAndErrors, styles: styles, inlineStyleUrls: inlineStyleUrls, styleUrls: styleUrls,
18770 ngContentSelectors: visitor.ngContentSelectors,
18771 };
18772 };
18773 DirectiveNormalizer.prototype._normalizeTemplateMetadata = function (prenormData, preparsedTemplate) {
18774 var _this = this;
18775 return SyncAsync.then(this._loadMissingExternalStylesheets(preparsedTemplate.styleUrls.concat(preparsedTemplate.inlineStyleUrls)), function (externalStylesheets) { return _this._normalizeLoadedTemplateMetadata(prenormData, preparsedTemplate, externalStylesheets); });
18776 };
18777 DirectiveNormalizer.prototype._normalizeLoadedTemplateMetadata = function (prenormData, preparsedTemplate, stylesheets) {
18778 // Algorithm:
18779 // - produce exactly 1 entry per original styleUrl in
18780 // CompileTemplateMetadata.externalStylesheets with all styles inlined
18781 // - inline all styles that are referenced by the template into CompileTemplateMetadata.styles.
18782 // Reason: be able to determine how many stylesheets there are even without loading
18783 // the template nor the stylesheets, so we can create a stub for TypeScript always synchronously
18784 // (as resource loading may be async)
18785 var _this = this;
18786 var styles = __spread(preparsedTemplate.styles);
18787 this._inlineStyles(preparsedTemplate.inlineStyleUrls, stylesheets, styles);
18788 var styleUrls = preparsedTemplate.styleUrls;
18789 var externalStylesheets = styleUrls.map(function (styleUrl) {
18790 var stylesheet = stylesheets.get(styleUrl);
18791 var styles = __spread(stylesheet.styles);
18792 _this._inlineStyles(stylesheet.styleUrls, stylesheets, styles);
18793 return new CompileStylesheetMetadata({ moduleUrl: styleUrl, styles: styles });
18794 });
18795 var encapsulation = prenormData.encapsulation;
18796 if (encapsulation == null) {
18797 encapsulation = this._config.defaultEncapsulation;
18798 }
18799 if (encapsulation === ViewEncapsulation.Emulated && styles.length === 0 &&
18800 styleUrls.length === 0) {
18801 encapsulation = ViewEncapsulation.None;
18802 }
18803 return new CompileTemplateMetadata({
18804 encapsulation: encapsulation,
18805 template: preparsedTemplate.template,
18806 templateUrl: preparsedTemplate.templateUrl,
18807 htmlAst: preparsedTemplate.htmlAst, styles: styles, styleUrls: styleUrls,
18808 ngContentSelectors: preparsedTemplate.ngContentSelectors,
18809 animations: prenormData.animations,
18810 interpolation: prenormData.interpolation,
18811 isInline: preparsedTemplate.isInline, externalStylesheets: externalStylesheets,
18812 preserveWhitespaces: preserveWhitespacesDefault(prenormData.preserveWhitespaces, this._config.preserveWhitespaces),
18813 });
18814 };
18815 DirectiveNormalizer.prototype._inlineStyles = function (styleUrls, stylesheets, targetStyles) {
18816 var _this = this;
18817 styleUrls.forEach(function (styleUrl) {
18818 var stylesheet = stylesheets.get(styleUrl);
18819 stylesheet.styles.forEach(function (style) { return targetStyles.push(style); });
18820 _this._inlineStyles(stylesheet.styleUrls, stylesheets, targetStyles);
18821 });
18822 };
18823 DirectiveNormalizer.prototype._loadMissingExternalStylesheets = function (styleUrls, loadedStylesheets) {
18824 var _this = this;
18825 if (loadedStylesheets === void 0) { loadedStylesheets = new Map(); }
18826 return SyncAsync.then(SyncAsync.all(styleUrls.filter(function (styleUrl) { return !loadedStylesheets.has(styleUrl); })
18827 .map(function (styleUrl) { return SyncAsync.then(_this._fetch(styleUrl), function (loadedStyle) {
18828 var stylesheet = _this._normalizeStylesheet(new CompileStylesheetMetadata({ styles: [loadedStyle], moduleUrl: styleUrl }));
18829 loadedStylesheets.set(styleUrl, stylesheet);
18830 return _this._loadMissingExternalStylesheets(stylesheet.styleUrls, loadedStylesheets);
18831 }); })), function (_) { return loadedStylesheets; });
18832 };
18833 DirectiveNormalizer.prototype._normalizeStylesheet = function (stylesheet) {
18834 var _this = this;
18835 var moduleUrl = stylesheet.moduleUrl;
18836 var allStyleUrls = stylesheet.styleUrls.filter(isStyleUrlResolvable)
18837 .map(function (url) { return _this._urlResolver.resolve(moduleUrl, url); });
18838 var allStyles = stylesheet.styles.map(function (style) {
18839 var styleWithImports = extractStyleUrls(_this._urlResolver, moduleUrl, style);
18840 allStyleUrls.push.apply(allStyleUrls, __spread(styleWithImports.styleUrls));
18841 return styleWithImports.style;
18842 });
18843 return new CompileStylesheetMetadata({ styles: allStyles, styleUrls: allStyleUrls, moduleUrl: moduleUrl });
18844 };
18845 return DirectiveNormalizer;
18846}());
18847var TemplatePreparseVisitor = /** @class */ (function () {
18848 function TemplatePreparseVisitor() {
18849 this.ngContentSelectors = [];
18850 this.styles = [];
18851 this.styleUrls = [];
18852 this.ngNonBindableStackCount = 0;
18853 }
18854 TemplatePreparseVisitor.prototype.visitElement = function (ast, context) {
18855 var preparsedElement = preparseElement(ast);
18856 switch (preparsedElement.type) {
18857 case PreparsedElementType.NG_CONTENT:
18858 if (this.ngNonBindableStackCount === 0) {
18859 this.ngContentSelectors.push(preparsedElement.selectAttr);
18860 }
18861 break;
18862 case PreparsedElementType.STYLE:
18863 var textContent_1 = '';
18864 ast.children.forEach(function (child) {
18865 if (child instanceof Text$3) {
18866 textContent_1 += child.value;
18867 }
18868 });
18869 this.styles.push(textContent_1);
18870 break;
18871 case PreparsedElementType.STYLESHEET:
18872 this.styleUrls.push(preparsedElement.hrefAttr);
18873 break;
18874 default:
18875 break;
18876 }
18877 if (preparsedElement.nonBindable) {
18878 this.ngNonBindableStackCount++;
18879 }
18880 visitAll$1(this, ast.children);
18881 if (preparsedElement.nonBindable) {
18882 this.ngNonBindableStackCount--;
18883 }
18884 return null;
18885 };
18886 TemplatePreparseVisitor.prototype.visitExpansion = function (ast, context) { visitAll$1(this, ast.cases); };
18887 TemplatePreparseVisitor.prototype.visitExpansionCase = function (ast, context) {
18888 visitAll$1(this, ast.expression);
18889 };
18890 TemplatePreparseVisitor.prototype.visitComment = function (ast, context) { return null; };
18891 TemplatePreparseVisitor.prototype.visitAttribute = function (ast, context) { return null; };
18892 TemplatePreparseVisitor.prototype.visitText = function (ast, context) { return null; };
18893 return TemplatePreparseVisitor;
18894}());
18895
18896/**
18897 * @license
18898 * Copyright Google Inc. All Rights Reserved.
18899 *
18900 * Use of this source code is governed by an MIT-style license that can be
18901 * found in the LICENSE file at https://angular.io/license
18902 */
18903var QUERY_METADATA_IDENTIFIERS = [
18904 createViewChild,
18905 createViewChildren,
18906 createContentChild,
18907 createContentChildren,
18908];
18909/*
18910 * Resolve a `Type` for {@link Directive}.
18911 *
18912 * This interface can be overridden by the application developer to create custom behavior.
18913 *
18914 * See {@link Compiler}
18915 */
18916var DirectiveResolver = /** @class */ (function () {
18917 function DirectiveResolver(_reflector) {
18918 this._reflector = _reflector;
18919 }
18920 DirectiveResolver.prototype.isDirective = function (type) {
18921 var typeMetadata = this._reflector.annotations(resolveForwardRef(type));
18922 return typeMetadata && typeMetadata.some(isDirectiveMetadata);
18923 };
18924 DirectiveResolver.prototype.resolve = function (type, throwIfNotFound) {
18925 if (throwIfNotFound === void 0) { throwIfNotFound = true; }
18926 var typeMetadata = this._reflector.annotations(resolveForwardRef(type));
18927 if (typeMetadata) {
18928 var metadata = findLast(typeMetadata, isDirectiveMetadata);
18929 if (metadata) {
18930 var propertyMetadata = this._reflector.propMetadata(type);
18931 var guards = this._reflector.guards(type);
18932 return this._mergeWithPropertyMetadata(metadata, propertyMetadata, guards, type);
18933 }
18934 }
18935 if (throwIfNotFound) {
18936 throw new Error("No Directive annotation found on " + stringify(type));
18937 }
18938 return null;
18939 };
18940 DirectiveResolver.prototype._mergeWithPropertyMetadata = function (dm, propertyMetadata, guards, directiveType) {
18941 var inputs = [];
18942 var outputs = [];
18943 var host = {};
18944 var queries = {};
18945 Object.keys(propertyMetadata).forEach(function (propName) {
18946 var input = findLast(propertyMetadata[propName], function (a) { return createInput.isTypeOf(a); });
18947 if (input) {
18948 if (input.bindingPropertyName) {
18949 inputs.push(propName + ": " + input.bindingPropertyName);
18950 }
18951 else {
18952 inputs.push(propName);
18953 }
18954 }
18955 var output = findLast(propertyMetadata[propName], function (a) { return createOutput.isTypeOf(a); });
18956 if (output) {
18957 if (output.bindingPropertyName) {
18958 outputs.push(propName + ": " + output.bindingPropertyName);
18959 }
18960 else {
18961 outputs.push(propName);
18962 }
18963 }
18964 var hostBindings = propertyMetadata[propName].filter(function (a) { return createHostBinding.isTypeOf(a); });
18965 hostBindings.forEach(function (hostBinding) {
18966 if (hostBinding.hostPropertyName) {
18967 var startWith = hostBinding.hostPropertyName[0];
18968 if (startWith === '(') {
18969 throw new Error("@HostBinding can not bind to events. Use @HostListener instead.");
18970 }
18971 else if (startWith === '[') {
18972 throw new Error("@HostBinding parameter should be a property name, 'class.<name>', or 'attr.<name>'.");
18973 }
18974 host["[" + hostBinding.hostPropertyName + "]"] = propName;
18975 }
18976 else {
18977 host["[" + propName + "]"] = propName;
18978 }
18979 });
18980 var hostListeners = propertyMetadata[propName].filter(function (a) { return createHostListener.isTypeOf(a); });
18981 hostListeners.forEach(function (hostListener) {
18982 var args = hostListener.args || [];
18983 host["(" + hostListener.eventName + ")"] = propName + "(" + args.join(',') + ")";
18984 });
18985 var query = findLast(propertyMetadata[propName], function (a) { return QUERY_METADATA_IDENTIFIERS.some(function (i) { return i.isTypeOf(a); }); });
18986 if (query) {
18987 queries[propName] = query;
18988 }
18989 });
18990 return this._merge(dm, inputs, outputs, host, queries, guards, directiveType);
18991 };
18992 DirectiveResolver.prototype._extractPublicName = function (def) { return splitAtColon(def, [null, def])[1].trim(); };
18993 DirectiveResolver.prototype._dedupeBindings = function (bindings) {
18994 var names = new Set();
18995 var publicNames = new Set();
18996 var reversedResult = [];
18997 // go last to first to allow later entries to overwrite previous entries
18998 for (var i = bindings.length - 1; i >= 0; i--) {
18999 var binding = bindings[i];
19000 var name_1 = this._extractPublicName(binding);
19001 publicNames.add(name_1);
19002 if (!names.has(name_1)) {
19003 names.add(name_1);
19004 reversedResult.push(binding);
19005 }
19006 }
19007 return reversedResult.reverse();
19008 };
19009 DirectiveResolver.prototype._merge = function (directive, inputs, outputs, host, queries, guards, directiveType) {
19010 var mergedInputs = this._dedupeBindings(directive.inputs ? directive.inputs.concat(inputs) : inputs);
19011 var mergedOutputs = this._dedupeBindings(directive.outputs ? directive.outputs.concat(outputs) : outputs);
19012 var mergedHost = directive.host ? __assign({}, directive.host, host) : host;
19013 var mergedQueries = directive.queries ? __assign({}, directive.queries, queries) : queries;
19014 if (createComponent.isTypeOf(directive)) {
19015 var comp = directive;
19016 return createComponent({
19017 selector: comp.selector,
19018 inputs: mergedInputs,
19019 outputs: mergedOutputs,
19020 host: mergedHost,
19021 exportAs: comp.exportAs,
19022 moduleId: comp.moduleId,
19023 queries: mergedQueries,
19024 changeDetection: comp.changeDetection,
19025 providers: comp.providers,
19026 viewProviders: comp.viewProviders,
19027 entryComponents: comp.entryComponents,
19028 template: comp.template,
19029 templateUrl: comp.templateUrl,
19030 styles: comp.styles,
19031 styleUrls: comp.styleUrls,
19032 encapsulation: comp.encapsulation,
19033 animations: comp.animations,
19034 interpolation: comp.interpolation,
19035 preserveWhitespaces: directive.preserveWhitespaces,
19036 });
19037 }
19038 else {
19039 return createDirective({
19040 selector: directive.selector,
19041 inputs: mergedInputs,
19042 outputs: mergedOutputs,
19043 host: mergedHost,
19044 exportAs: directive.exportAs,
19045 queries: mergedQueries,
19046 providers: directive.providers, guards: guards
19047 });
19048 }
19049 };
19050 return DirectiveResolver;
19051}());
19052function isDirectiveMetadata(type) {
19053 return createDirective.isTypeOf(type) || createComponent.isTypeOf(type);
19054}
19055function findLast(arr, condition) {
19056 for (var i = arr.length - 1; i >= 0; i--) {
19057 if (condition(arr[i])) {
19058 return arr[i];
19059 }
19060 }
19061 return null;
19062}
19063
19064/**
19065 * @license
19066 * Copyright Google Inc. All Rights Reserved.
19067 *
19068 * Use of this source code is governed by an MIT-style license that can be
19069 * found in the LICENSE file at https://angular.io/license
19070 */
19071/**
19072 * An i18n error.
19073 */
19074var I18nError = /** @class */ (function (_super) {
19075 __extends(I18nError, _super);
19076 function I18nError(span, msg) {
19077 return _super.call(this, span, msg) || this;
19078 }
19079 return I18nError;
19080}(ParseError));
19081
19082/**
19083 * @license
19084 * Copyright Google Inc. All Rights Reserved.
19085 *
19086 * Use of this source code is governed by an MIT-style license that can be
19087 * found in the LICENSE file at https://angular.io/license
19088 */
19089var _I18N_ATTR = 'i18n';
19090var _I18N_ATTR_PREFIX = 'i18n-';
19091var _I18N_COMMENT_PREFIX_REGEXP = /^i18n:?/;
19092var MEANING_SEPARATOR = '|';
19093var ID_SEPARATOR = '@@';
19094var i18nCommentsWarned = false;
19095/**
19096 * Extract translatable messages from an html AST
19097 */
19098function extractMessages(nodes, interpolationConfig, implicitTags, implicitAttrs) {
19099 var visitor = new _Visitor$2(implicitTags, implicitAttrs);
19100 return visitor.extract(nodes, interpolationConfig);
19101}
19102function mergeTranslations(nodes, translations, interpolationConfig, implicitTags, implicitAttrs) {
19103 var visitor = new _Visitor$2(implicitTags, implicitAttrs);
19104 return visitor.merge(nodes, translations, interpolationConfig);
19105}
19106var ExtractionResult = /** @class */ (function () {
19107 function ExtractionResult(messages, errors) {
19108 this.messages = messages;
19109 this.errors = errors;
19110 }
19111 return ExtractionResult;
19112}());
19113var _VisitorMode;
19114(function (_VisitorMode) {
19115 _VisitorMode[_VisitorMode["Extract"] = 0] = "Extract";
19116 _VisitorMode[_VisitorMode["Merge"] = 1] = "Merge";
19117})(_VisitorMode || (_VisitorMode = {}));
19118/**
19119 * This Visitor is used:
19120 * 1. to extract all the translatable strings from an html AST (see `extract()`),
19121 * 2. to replace the translatable strings with the actual translations (see `merge()`)
19122 *
19123 * @internal
19124 */
19125var _Visitor$2 = /** @class */ (function () {
19126 function _Visitor(_implicitTags, _implicitAttrs) {
19127 this._implicitTags = _implicitTags;
19128 this._implicitAttrs = _implicitAttrs;
19129 }
19130 /**
19131 * Extracts the messages from the tree
19132 */
19133 _Visitor.prototype.extract = function (nodes, interpolationConfig) {
19134 var _this = this;
19135 this._init(_VisitorMode.Extract, interpolationConfig);
19136 nodes.forEach(function (node) { return node.visit(_this, null); });
19137 if (this._inI18nBlock) {
19138 this._reportError(nodes[nodes.length - 1], 'Unclosed block');
19139 }
19140 return new ExtractionResult(this._messages, this._errors);
19141 };
19142 /**
19143 * Returns a tree where all translatable nodes are translated
19144 */
19145 _Visitor.prototype.merge = function (nodes, translations, interpolationConfig) {
19146 this._init(_VisitorMode.Merge, interpolationConfig);
19147 this._translations = translations;
19148 // Construct a single fake root element
19149 var wrapper = new Element$1('wrapper', [], nodes, undefined, undefined, undefined);
19150 var translatedNode = wrapper.visit(this, null);
19151 if (this._inI18nBlock) {
19152 this._reportError(nodes[nodes.length - 1], 'Unclosed block');
19153 }
19154 return new ParseTreeResult(translatedNode.children, this._errors);
19155 };
19156 _Visitor.prototype.visitExpansionCase = function (icuCase, context) {
19157 // Parse cases for translatable html attributes
19158 var expression = visitAll$1(this, icuCase.expression, context);
19159 if (this._mode === _VisitorMode.Merge) {
19160 return new ExpansionCase(icuCase.value, expression, icuCase.sourceSpan, icuCase.valueSourceSpan, icuCase.expSourceSpan);
19161 }
19162 };
19163 _Visitor.prototype.visitExpansion = function (icu, context) {
19164 this._mayBeAddBlockChildren(icu);
19165 var wasInIcu = this._inIcu;
19166 if (!this._inIcu) {
19167 // nested ICU messages should not be extracted but top-level translated as a whole
19168 if (this._isInTranslatableSection) {
19169 this._addMessage([icu]);
19170 }
19171 this._inIcu = true;
19172 }
19173 var cases = visitAll$1(this, icu.cases, context);
19174 if (this._mode === _VisitorMode.Merge) {
19175 icu = new Expansion(icu.switchValue, icu.type, cases, icu.sourceSpan, icu.switchValueSourceSpan);
19176 }
19177 this._inIcu = wasInIcu;
19178 return icu;
19179 };
19180 _Visitor.prototype.visitComment = function (comment, context) {
19181 var isOpening = _isOpeningComment(comment);
19182 if (isOpening && this._isInTranslatableSection) {
19183 this._reportError(comment, 'Could not start a block inside a translatable section');
19184 return;
19185 }
19186 var isClosing = _isClosingComment(comment);
19187 if (isClosing && !this._inI18nBlock) {
19188 this._reportError(comment, 'Trying to close an unopened block');
19189 return;
19190 }
19191 if (!this._inI18nNode && !this._inIcu) {
19192 if (!this._inI18nBlock) {
19193 if (isOpening) {
19194 // deprecated from v5 you should use <ng-container i18n> instead of i18n comments
19195 if (!i18nCommentsWarned && console && console.warn) {
19196 i18nCommentsWarned = true;
19197 var details = comment.sourceSpan.details ? ", " + comment.sourceSpan.details : '';
19198 // TODO(ocombe): use a log service once there is a public one available
19199 console.warn("I18n comments are deprecated, use an <ng-container> element instead (" + comment.sourceSpan.start + details + ")");
19200 }
19201 this._inI18nBlock = true;
19202 this._blockStartDepth = this._depth;
19203 this._blockChildren = [];
19204 this._blockMeaningAndDesc =
19205 comment.value.replace(_I18N_COMMENT_PREFIX_REGEXP, '').trim();
19206 this._openTranslatableSection(comment);
19207 }
19208 }
19209 else {
19210 if (isClosing) {
19211 if (this._depth == this._blockStartDepth) {
19212 this._closeTranslatableSection(comment, this._blockChildren);
19213 this._inI18nBlock = false;
19214 var message = this._addMessage(this._blockChildren, this._blockMeaningAndDesc);
19215 // merge attributes in sections
19216 var nodes = this._translateMessage(comment, message);
19217 return visitAll$1(this, nodes);
19218 }
19219 else {
19220 this._reportError(comment, 'I18N blocks should not cross element boundaries');
19221 return;
19222 }
19223 }
19224 }
19225 }
19226 };
19227 _Visitor.prototype.visitText = function (text, context) {
19228 if (this._isInTranslatableSection) {
19229 this._mayBeAddBlockChildren(text);
19230 }
19231 return text;
19232 };
19233 _Visitor.prototype.visitElement = function (el, context) {
19234 var _this = this;
19235 this._mayBeAddBlockChildren(el);
19236 this._depth++;
19237 var wasInI18nNode = this._inI18nNode;
19238 var wasInImplicitNode = this._inImplicitNode;
19239 var childNodes = [];
19240 var translatedChildNodes = undefined;
19241 // Extract:
19242 // - top level nodes with the (implicit) "i18n" attribute if not already in a section
19243 // - ICU messages
19244 var i18nAttr = _getI18nAttr(el);
19245 var i18nMeta = i18nAttr ? i18nAttr.value : '';
19246 var isImplicit = this._implicitTags.some(function (tag) { return el.name === tag; }) && !this._inIcu &&
19247 !this._isInTranslatableSection;
19248 var isTopLevelImplicit = !wasInImplicitNode && isImplicit;
19249 this._inImplicitNode = wasInImplicitNode || isImplicit;
19250 if (!this._isInTranslatableSection && !this._inIcu) {
19251 if (i18nAttr || isTopLevelImplicit) {
19252 this._inI18nNode = true;
19253 var message = this._addMessage(el.children, i18nMeta);
19254 translatedChildNodes = this._translateMessage(el, message);
19255 }
19256 if (this._mode == _VisitorMode.Extract) {
19257 var isTranslatable = i18nAttr || isTopLevelImplicit;
19258 if (isTranslatable)
19259 this._openTranslatableSection(el);
19260 visitAll$1(this, el.children);
19261 if (isTranslatable)
19262 this._closeTranslatableSection(el, el.children);
19263 }
19264 }
19265 else {
19266 if (i18nAttr || isTopLevelImplicit) {
19267 this._reportError(el, 'Could not mark an element as translatable inside a translatable section');
19268 }
19269 if (this._mode == _VisitorMode.Extract) {
19270 // Descend into child nodes for extraction
19271 visitAll$1(this, el.children);
19272 }
19273 }
19274 if (this._mode === _VisitorMode.Merge) {
19275 var visitNodes = translatedChildNodes || el.children;
19276 visitNodes.forEach(function (child) {
19277 var visited = child.visit(_this, context);
19278 if (visited && !_this._isInTranslatableSection) {
19279 // Do not add the children from translatable sections (= i18n blocks here)
19280 // They will be added later in this loop when the block closes (i.e. on `<!-- /i18n -->`)
19281 childNodes = childNodes.concat(visited);
19282 }
19283 });
19284 }
19285 this._visitAttributesOf(el);
19286 this._depth--;
19287 this._inI18nNode = wasInI18nNode;
19288 this._inImplicitNode = wasInImplicitNode;
19289 if (this._mode === _VisitorMode.Merge) {
19290 var translatedAttrs = this._translateAttributes(el);
19291 return new Element$1(el.name, translatedAttrs, childNodes, el.sourceSpan, el.startSourceSpan, el.endSourceSpan);
19292 }
19293 return null;
19294 };
19295 _Visitor.prototype.visitAttribute = function (attribute, context) {
19296 throw new Error('unreachable code');
19297 };
19298 _Visitor.prototype._init = function (mode, interpolationConfig) {
19299 this._mode = mode;
19300 this._inI18nBlock = false;
19301 this._inI18nNode = false;
19302 this._depth = 0;
19303 this._inIcu = false;
19304 this._msgCountAtSectionStart = undefined;
19305 this._errors = [];
19306 this._messages = [];
19307 this._inImplicitNode = false;
19308 this._createI18nMessage = createI18nMessageFactory(interpolationConfig);
19309 };
19310 // looks for translatable attributes
19311 _Visitor.prototype._visitAttributesOf = function (el) {
19312 var _this = this;
19313 var explicitAttrNameToValue = {};
19314 var implicitAttrNames = this._implicitAttrs[el.name] || [];
19315 el.attrs.filter(function (attr) { return attr.name.startsWith(_I18N_ATTR_PREFIX); })
19316 .forEach(function (attr) { return explicitAttrNameToValue[attr.name.slice(_I18N_ATTR_PREFIX.length)] =
19317 attr.value; });
19318 el.attrs.forEach(function (attr) {
19319 if (attr.name in explicitAttrNameToValue) {
19320 _this._addMessage([attr], explicitAttrNameToValue[attr.name]);
19321 }
19322 else if (implicitAttrNames.some(function (name) { return attr.name === name; })) {
19323 _this._addMessage([attr]);
19324 }
19325 });
19326 };
19327 // add a translatable message
19328 _Visitor.prototype._addMessage = function (ast, msgMeta) {
19329 if (ast.length == 0 ||
19330 ast.length == 1 && ast[0] instanceof Attribute && !ast[0].value) {
19331 // Do not create empty messages
19332 return null;
19333 }
19334 var _a = _parseMessageMeta(msgMeta), meaning = _a.meaning, description = _a.description, id = _a.id;
19335 var message = this._createI18nMessage(ast, meaning, description, id);
19336 this._messages.push(message);
19337 return message;
19338 };
19339 // Translates the given message given the `TranslationBundle`
19340 // This is used for translating elements / blocks - see `_translateAttributes` for attributes
19341 // no-op when called in extraction mode (returns [])
19342 _Visitor.prototype._translateMessage = function (el, message) {
19343 if (message && this._mode === _VisitorMode.Merge) {
19344 var nodes = this._translations.get(message);
19345 if (nodes) {
19346 return nodes;
19347 }
19348 this._reportError(el, "Translation unavailable for message id=\"" + this._translations.digest(message) + "\"");
19349 }
19350 return [];
19351 };
19352 // translate the attributes of an element and remove i18n specific attributes
19353 _Visitor.prototype._translateAttributes = function (el) {
19354 var _this = this;
19355 var attributes = el.attrs;
19356 var i18nParsedMessageMeta = {};
19357 attributes.forEach(function (attr) {
19358 if (attr.name.startsWith(_I18N_ATTR_PREFIX)) {
19359 i18nParsedMessageMeta[attr.name.slice(_I18N_ATTR_PREFIX.length)] =
19360 _parseMessageMeta(attr.value);
19361 }
19362 });
19363 var translatedAttributes = [];
19364 attributes.forEach(function (attr) {
19365 if (attr.name === _I18N_ATTR || attr.name.startsWith(_I18N_ATTR_PREFIX)) {
19366 // strip i18n specific attributes
19367 return;
19368 }
19369 if (attr.value && attr.value != '' && i18nParsedMessageMeta.hasOwnProperty(attr.name)) {
19370 var _a = i18nParsedMessageMeta[attr.name], meaning = _a.meaning, description = _a.description, id = _a.id;
19371 var message = _this._createI18nMessage([attr], meaning, description, id);
19372 var nodes = _this._translations.get(message);
19373 if (nodes) {
19374 if (nodes.length == 0) {
19375 translatedAttributes.push(new Attribute(attr.name, '', attr.sourceSpan));
19376 }
19377 else if (nodes[0] instanceof Text$3) {
19378 var value = nodes[0].value;
19379 translatedAttributes.push(new Attribute(attr.name, value, attr.sourceSpan));
19380 }
19381 else {
19382 _this._reportError(el, "Unexpected translation for attribute \"" + attr.name + "\" (id=\"" + (id || _this._translations.digest(message)) + "\")");
19383 }
19384 }
19385 else {
19386 _this._reportError(el, "Translation unavailable for attribute \"" + attr.name + "\" (id=\"" + (id || _this._translations.digest(message)) + "\")");
19387 }
19388 }
19389 else {
19390 translatedAttributes.push(attr);
19391 }
19392 });
19393 return translatedAttributes;
19394 };
19395 /**
19396 * Add the node as a child of the block when:
19397 * - we are in a block,
19398 * - we are not inside a ICU message (those are handled separately),
19399 * - the node is a "direct child" of the block
19400 */
19401 _Visitor.prototype._mayBeAddBlockChildren = function (node) {
19402 if (this._inI18nBlock && !this._inIcu && this._depth == this._blockStartDepth) {
19403 this._blockChildren.push(node);
19404 }
19405 };
19406 /**
19407 * Marks the start of a section, see `_closeTranslatableSection`
19408 */
19409 _Visitor.prototype._openTranslatableSection = function (node) {
19410 if (this._isInTranslatableSection) {
19411 this._reportError(node, 'Unexpected section start');
19412 }
19413 else {
19414 this._msgCountAtSectionStart = this._messages.length;
19415 }
19416 };
19417 Object.defineProperty(_Visitor.prototype, "_isInTranslatableSection", {
19418 /**
19419 * A translatable section could be:
19420 * - the content of translatable element,
19421 * - nodes between `<!-- i18n -->` and `<!-- /i18n -->` comments
19422 */
19423 get: function () {
19424 return this._msgCountAtSectionStart !== void 0;
19425 },
19426 enumerable: true,
19427 configurable: true
19428 });
19429 /**
19430 * Terminates a section.
19431 *
19432 * If a section has only one significant children (comments not significant) then we should not
19433 * keep the message from this children:
19434 *
19435 * `<p i18n="meaning|description">{ICU message}</p>` would produce two messages:
19436 * - one for the <p> content with meaning and description,
19437 * - another one for the ICU message.
19438 *
19439 * In this case the last message is discarded as it contains less information (the AST is
19440 * otherwise identical).
19441 *
19442 * Note that we should still keep messages extracted from attributes inside the section (ie in the
19443 * ICU message here)
19444 */
19445 _Visitor.prototype._closeTranslatableSection = function (node, directChildren) {
19446 if (!this._isInTranslatableSection) {
19447 this._reportError(node, 'Unexpected section end');
19448 return;
19449 }
19450 var startIndex = this._msgCountAtSectionStart;
19451 var significantChildren = directChildren.reduce(function (count, node) { return count + (node instanceof Comment ? 0 : 1); }, 0);
19452 if (significantChildren == 1) {
19453 for (var i = this._messages.length - 1; i >= startIndex; i--) {
19454 var ast = this._messages[i].nodes;
19455 if (!(ast.length == 1 && ast[0] instanceof Text$1)) {
19456 this._messages.splice(i, 1);
19457 break;
19458 }
19459 }
19460 }
19461 this._msgCountAtSectionStart = undefined;
19462 };
19463 _Visitor.prototype._reportError = function (node, msg) {
19464 this._errors.push(new I18nError(node.sourceSpan, msg));
19465 };
19466 return _Visitor;
19467}());
19468function _isOpeningComment(n) {
19469 return !!(n instanceof Comment && n.value && n.value.startsWith('i18n'));
19470}
19471function _isClosingComment(n) {
19472 return !!(n instanceof Comment && n.value && n.value === '/i18n');
19473}
19474function _getI18nAttr(p) {
19475 return p.attrs.find(function (attr) { return attr.name === _I18N_ATTR; }) || null;
19476}
19477function _parseMessageMeta(i18n) {
19478 if (!i18n)
19479 return { meaning: '', description: '', id: '' };
19480 var idIndex = i18n.indexOf(ID_SEPARATOR);
19481 var descIndex = i18n.indexOf(MEANING_SEPARATOR);
19482 var _a = __read((idIndex > -1) ? [i18n.slice(0, idIndex), i18n.slice(idIndex + 2)] : [i18n, ''], 2), meaningAndDesc = _a[0], id = _a[1];
19483 var _b = __read((descIndex > -1) ?
19484 [meaningAndDesc.slice(0, descIndex), meaningAndDesc.slice(descIndex + 1)] :
19485 ['', meaningAndDesc], 2), meaning = _b[0], description = _b[1];
19486 return { meaning: meaning, description: description, id: id };
19487}
19488
19489/**
19490 * @license
19491 * Copyright Google Inc. All Rights Reserved.
19492 *
19493 * Use of this source code is governed by an MIT-style license that can be
19494 * found in the LICENSE file at https://angular.io/license
19495 */
19496var XmlTagDefinition = /** @class */ (function () {
19497 function XmlTagDefinition() {
19498 this.closedByParent = false;
19499 this.contentType = TagContentType.PARSABLE_DATA;
19500 this.isVoid = false;
19501 this.ignoreFirstLf = false;
19502 this.canSelfClose = true;
19503 }
19504 XmlTagDefinition.prototype.requireExtraParent = function (currentParent) { return false; };
19505 XmlTagDefinition.prototype.isClosedByChild = function (name) { return false; };
19506 return XmlTagDefinition;
19507}());
19508var _TAG_DEFINITION = new XmlTagDefinition();
19509function getXmlTagDefinition(tagName) {
19510 return _TAG_DEFINITION;
19511}
19512
19513/**
19514 * @license
19515 * Copyright Google Inc. All Rights Reserved.
19516 *
19517 * Use of this source code is governed by an MIT-style license that can be
19518 * found in the LICENSE file at https://angular.io/license
19519 */
19520var XmlParser = /** @class */ (function (_super) {
19521 __extends(XmlParser, _super);
19522 function XmlParser() {
19523 return _super.call(this, getXmlTagDefinition) || this;
19524 }
19525 XmlParser.prototype.parse = function (source, url, options) {
19526 return _super.prototype.parse.call(this, source, url, options);
19527 };
19528 return XmlParser;
19529}(Parser));
19530
19531/**
19532 * @license
19533 * Copyright Google Inc. All Rights Reserved.
19534 *
19535 * Use of this source code is governed by an MIT-style license that can be
19536 * found in the LICENSE file at https://angular.io/license
19537 */
19538var _VERSION = '1.2';
19539var _XMLNS = 'urn:oasis:names:tc:xliff:document:1.2';
19540// TODO(vicb): make this a param (s/_/-/)
19541var _DEFAULT_SOURCE_LANG = 'en';
19542var _PLACEHOLDER_TAG$1 = 'x';
19543var _MARKER_TAG = 'mrk';
19544var _FILE_TAG = 'file';
19545var _SOURCE_TAG$1 = 'source';
19546var _SEGMENT_SOURCE_TAG = 'seg-source';
19547var _ALT_TRANS_TAG = 'alt-trans';
19548var _TARGET_TAG = 'target';
19549var _UNIT_TAG = 'trans-unit';
19550var _CONTEXT_GROUP_TAG = 'context-group';
19551var _CONTEXT_TAG = 'context';
19552// http://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html
19553// http://docs.oasis-open.org/xliff/v1.2/xliff-profile-html/xliff-profile-html-1.2.html
19554var Xliff = /** @class */ (function (_super) {
19555 __extends(Xliff, _super);
19556 function Xliff() {
19557 return _super !== null && _super.apply(this, arguments) || this;
19558 }
19559 Xliff.prototype.write = function (messages, locale) {
19560 var visitor = new _WriteVisitor();
19561 var transUnits = [];
19562 messages.forEach(function (message) {
19563 var _a;
19564 var contextTags = [];
19565 message.sources.forEach(function (source) {
19566 var contextGroupTag = new Tag(_CONTEXT_GROUP_TAG, { purpose: 'location' });
19567 contextGroupTag.children.push(new CR(10), new Tag(_CONTEXT_TAG, { 'context-type': 'sourcefile' }, [new Text$2(source.filePath)]), new CR(10), new Tag(_CONTEXT_TAG, { 'context-type': 'linenumber' }, [new Text$2("" + source.startLine)]), new CR(8));
19568 contextTags.push(new CR(8), contextGroupTag);
19569 });
19570 var transUnit = new Tag(_UNIT_TAG, { id: message.id, datatype: 'html' });
19571 (_a = transUnit.children).push.apply(_a, __spread([new CR(8), new Tag(_SOURCE_TAG$1, {}, visitor.serialize(message.nodes))], contextTags));
19572 if (message.description) {
19573 transUnit.children.push(new CR(8), new Tag('note', { priority: '1', from: 'description' }, [new Text$2(message.description)]));
19574 }
19575 if (message.meaning) {
19576 transUnit.children.push(new CR(8), new Tag('note', { priority: '1', from: 'meaning' }, [new Text$2(message.meaning)]));
19577 }
19578 transUnit.children.push(new CR(6));
19579 transUnits.push(new CR(6), transUnit);
19580 });
19581 var body = new Tag('body', {}, __spread(transUnits, [new CR(4)]));
19582 var file = new Tag('file', {
19583 'source-language': locale || _DEFAULT_SOURCE_LANG,
19584 datatype: 'plaintext',
19585 original: 'ng2.template',
19586 }, [new CR(4), body, new CR(2)]);
19587 var xliff = new Tag('xliff', { version: _VERSION, xmlns: _XMLNS }, [new CR(2), file, new CR()]);
19588 return serialize([
19589 new Declaration({ version: '1.0', encoding: 'UTF-8' }), new CR(), xliff, new CR()
19590 ]);
19591 };
19592 Xliff.prototype.load = function (content, url) {
19593 // xliff to xml nodes
19594 var xliffParser = new XliffParser();
19595 var _a = xliffParser.parse(content, url), locale = _a.locale, msgIdToHtml = _a.msgIdToHtml, errors = _a.errors;
19596 // xml nodes to i18n nodes
19597 var i18nNodesByMsgId = {};
19598 var converter = new XmlToI18n();
19599 Object.keys(msgIdToHtml).forEach(function (msgId) {
19600 var _a = converter.convert(msgIdToHtml[msgId], url), i18nNodes = _a.i18nNodes, e = _a.errors;
19601 errors.push.apply(errors, __spread(e));
19602 i18nNodesByMsgId[msgId] = i18nNodes;
19603 });
19604 if (errors.length) {
19605 throw new Error("xliff parse errors:\n" + errors.join('\n'));
19606 }
19607 return { locale: locale, i18nNodesByMsgId: i18nNodesByMsgId };
19608 };
19609 Xliff.prototype.digest = function (message) { return digest(message); };
19610 return Xliff;
19611}(Serializer));
19612var _WriteVisitor = /** @class */ (function () {
19613 function _WriteVisitor() {
19614 }
19615 _WriteVisitor.prototype.visitText = function (text, context) { return [new Text$2(text.value)]; };
19616 _WriteVisitor.prototype.visitContainer = function (container, context) {
19617 var _this = this;
19618 var nodes = [];
19619 container.children.forEach(function (node) { return nodes.push.apply(nodes, __spread(node.visit(_this))); });
19620 return nodes;
19621 };
19622 _WriteVisitor.prototype.visitIcu = function (icu, context) {
19623 var _this = this;
19624 var nodes = [new Text$2("{" + icu.expressionPlaceholder + ", " + icu.type + ", ")];
19625 Object.keys(icu.cases).forEach(function (c) {
19626 nodes.push.apply(nodes, __spread([new Text$2(c + " {")], icu.cases[c].visit(_this), [new Text$2("} ")]));
19627 });
19628 nodes.push(new Text$2("}"));
19629 return nodes;
19630 };
19631 _WriteVisitor.prototype.visitTagPlaceholder = function (ph, context) {
19632 var ctype = getCtypeForTag(ph.tag);
19633 if (ph.isVoid) {
19634 // void tags have no children nor closing tags
19635 return [new Tag(_PLACEHOLDER_TAG$1, { id: ph.startName, ctype: ctype, 'equiv-text': "<" + ph.tag + "/>" })];
19636 }
19637 var startTagPh = new Tag(_PLACEHOLDER_TAG$1, { id: ph.startName, ctype: ctype, 'equiv-text': "<" + ph.tag + ">" });
19638 var closeTagPh = new Tag(_PLACEHOLDER_TAG$1, { id: ph.closeName, ctype: ctype, 'equiv-text': "</" + ph.tag + ">" });
19639 return __spread([startTagPh], this.serialize(ph.children), [closeTagPh]);
19640 };
19641 _WriteVisitor.prototype.visitPlaceholder = function (ph, context) {
19642 return [new Tag(_PLACEHOLDER_TAG$1, { id: ph.name, 'equiv-text': "{{" + ph.value + "}}" })];
19643 };
19644 _WriteVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
19645 var equivText = "{" + ph.value.expression + ", " + ph.value.type + ", " + Object.keys(ph.value.cases).map(function (value) { return value + ' {...}'; }).join(' ') + "}";
19646 return [new Tag(_PLACEHOLDER_TAG$1, { id: ph.name, 'equiv-text': equivText })];
19647 };
19648 _WriteVisitor.prototype.serialize = function (nodes) {
19649 var _this = this;
19650 return [].concat.apply([], __spread(nodes.map(function (node) { return node.visit(_this); })));
19651 };
19652 return _WriteVisitor;
19653}());
19654// TODO(vicb): add error management (structure)
19655// Extract messages as xml nodes from the xliff file
19656var XliffParser = /** @class */ (function () {
19657 function XliffParser() {
19658 this._locale = null;
19659 }
19660 XliffParser.prototype.parse = function (xliff, url) {
19661 this._unitMlString = null;
19662 this._msgIdToHtml = {};
19663 var xml = new XmlParser().parse(xliff, url);
19664 this._errors = xml.errors;
19665 visitAll$1(this, xml.rootNodes, null);
19666 return {
19667 msgIdToHtml: this._msgIdToHtml,
19668 errors: this._errors,
19669 locale: this._locale,
19670 };
19671 };
19672 XliffParser.prototype.visitElement = function (element, context) {
19673 switch (element.name) {
19674 case _UNIT_TAG:
19675 this._unitMlString = null;
19676 var idAttr = element.attrs.find(function (attr) { return attr.name === 'id'; });
19677 if (!idAttr) {
19678 this._addError(element, "<" + _UNIT_TAG + "> misses the \"id\" attribute");
19679 }
19680 else {
19681 var id = idAttr.value;
19682 if (this._msgIdToHtml.hasOwnProperty(id)) {
19683 this._addError(element, "Duplicated translations for msg " + id);
19684 }
19685 else {
19686 visitAll$1(this, element.children, null);
19687 if (typeof this._unitMlString === 'string') {
19688 this._msgIdToHtml[id] = this._unitMlString;
19689 }
19690 else {
19691 this._addError(element, "Message " + id + " misses a translation");
19692 }
19693 }
19694 }
19695 break;
19696 // ignore those tags
19697 case _SOURCE_TAG$1:
19698 case _SEGMENT_SOURCE_TAG:
19699 case _ALT_TRANS_TAG:
19700 break;
19701 case _TARGET_TAG:
19702 var innerTextStart = element.startSourceSpan.end.offset;
19703 var innerTextEnd = element.endSourceSpan.start.offset;
19704 var content = element.startSourceSpan.start.file.content;
19705 var innerText = content.slice(innerTextStart, innerTextEnd);
19706 this._unitMlString = innerText;
19707 break;
19708 case _FILE_TAG:
19709 var localeAttr = element.attrs.find(function (attr) { return attr.name === 'target-language'; });
19710 if (localeAttr) {
19711 this._locale = localeAttr.value;
19712 }
19713 visitAll$1(this, element.children, null);
19714 break;
19715 default:
19716 // TODO(vicb): assert file structure, xliff version
19717 // For now only recurse on unhandled nodes
19718 visitAll$1(this, element.children, null);
19719 }
19720 };
19721 XliffParser.prototype.visitAttribute = function (attribute, context) { };
19722 XliffParser.prototype.visitText = function (text, context) { };
19723 XliffParser.prototype.visitComment = function (comment, context) { };
19724 XliffParser.prototype.visitExpansion = function (expansion, context) { };
19725 XliffParser.prototype.visitExpansionCase = function (expansionCase, context) { };
19726 XliffParser.prototype._addError = function (node, message) {
19727 this._errors.push(new I18nError(node.sourceSpan, message));
19728 };
19729 return XliffParser;
19730}());
19731// Convert ml nodes (xliff syntax) to i18n nodes
19732var XmlToI18n = /** @class */ (function () {
19733 function XmlToI18n() {
19734 }
19735 XmlToI18n.prototype.convert = function (message, url) {
19736 var xmlIcu = new XmlParser().parse(message, url, { tokenizeExpansionForms: true });
19737 this._errors = xmlIcu.errors;
19738 var i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ?
19739 [] : [].concat.apply([], __spread(visitAll$1(this, xmlIcu.rootNodes)));
19740 return {
19741 i18nNodes: i18nNodes,
19742 errors: this._errors,
19743 };
19744 };
19745 XmlToI18n.prototype.visitText = function (text, context) { return new Text$1(text.value, text.sourceSpan); };
19746 XmlToI18n.prototype.visitElement = function (el, context) {
19747 if (el.name === _PLACEHOLDER_TAG$1) {
19748 var nameAttr = el.attrs.find(function (attr) { return attr.name === 'id'; });
19749 if (nameAttr) {
19750 return new Placeholder('', nameAttr.value, el.sourceSpan);
19751 }
19752 this._addError(el, "<" + _PLACEHOLDER_TAG$1 + "> misses the \"id\" attribute");
19753 return null;
19754 }
19755 if (el.name === _MARKER_TAG) {
19756 return [].concat.apply([], __spread(visitAll$1(this, el.children)));
19757 }
19758 this._addError(el, "Unexpected tag");
19759 return null;
19760 };
19761 XmlToI18n.prototype.visitExpansion = function (icu, context) {
19762 var caseMap = {};
19763 visitAll$1(this, icu.cases).forEach(function (c) {
19764 caseMap[c.value] = new Container(c.nodes, icu.sourceSpan);
19765 });
19766 return new Icu$1(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
19767 };
19768 XmlToI18n.prototype.visitExpansionCase = function (icuCase, context) {
19769 return {
19770 value: icuCase.value,
19771 nodes: visitAll$1(this, icuCase.expression),
19772 };
19773 };
19774 XmlToI18n.prototype.visitComment = function (comment, context) { };
19775 XmlToI18n.prototype.visitAttribute = function (attribute, context) { };
19776 XmlToI18n.prototype._addError = function (node, message) {
19777 this._errors.push(new I18nError(node.sourceSpan, message));
19778 };
19779 return XmlToI18n;
19780}());
19781function getCtypeForTag(tag) {
19782 switch (tag.toLowerCase()) {
19783 case 'br':
19784 return 'lb';
19785 case 'img':
19786 return 'image';
19787 default:
19788 return "x-" + tag;
19789 }
19790}
19791
19792/**
19793 * @license
19794 * Copyright Google Inc. All Rights Reserved.
19795 *
19796 * Use of this source code is governed by an MIT-style license that can be
19797 * found in the LICENSE file at https://angular.io/license
19798 */
19799var _VERSION$1 = '2.0';
19800var _XMLNS$1 = 'urn:oasis:names:tc:xliff:document:2.0';
19801// TODO(vicb): make this a param (s/_/-/)
19802var _DEFAULT_SOURCE_LANG$1 = 'en';
19803var _PLACEHOLDER_TAG$2 = 'ph';
19804var _PLACEHOLDER_SPANNING_TAG = 'pc';
19805var _MARKER_TAG$1 = 'mrk';
19806var _XLIFF_TAG = 'xliff';
19807var _SOURCE_TAG$2 = 'source';
19808var _TARGET_TAG$1 = 'target';
19809var _UNIT_TAG$1 = 'unit';
19810// http://docs.oasis-open.org/xliff/xliff-core/v2.0/os/xliff-core-v2.0-os.html
19811var Xliff2 = /** @class */ (function (_super) {
19812 __extends(Xliff2, _super);
19813 function Xliff2() {
19814 return _super !== null && _super.apply(this, arguments) || this;
19815 }
19816 Xliff2.prototype.write = function (messages, locale) {
19817 var visitor = new _WriteVisitor$1();
19818 var units = [];
19819 messages.forEach(function (message) {
19820 var unit = new Tag(_UNIT_TAG$1, { id: message.id });
19821 var notes = new Tag('notes');
19822 if (message.description || message.meaning) {
19823 if (message.description) {
19824 notes.children.push(new CR(8), new Tag('note', { category: 'description' }, [new Text$2(message.description)]));
19825 }
19826 if (message.meaning) {
19827 notes.children.push(new CR(8), new Tag('note', { category: 'meaning' }, [new Text$2(message.meaning)]));
19828 }
19829 }
19830 message.sources.forEach(function (source) {
19831 notes.children.push(new CR(8), new Tag('note', { category: 'location' }, [
19832 new Text$2(source.filePath + ":" + source.startLine + (source.endLine !== source.startLine ? ',' + source.endLine : ''))
19833 ]));
19834 });
19835 notes.children.push(new CR(6));
19836 unit.children.push(new CR(6), notes);
19837 var segment = new Tag('segment');
19838 segment.children.push(new CR(8), new Tag(_SOURCE_TAG$2, {}, visitor.serialize(message.nodes)), new CR(6));
19839 unit.children.push(new CR(6), segment, new CR(4));
19840 units.push(new CR(4), unit);
19841 });
19842 var file = new Tag('file', { 'original': 'ng.template', id: 'ngi18n' }, __spread(units, [new CR(2)]));
19843 var xliff = new Tag(_XLIFF_TAG, { version: _VERSION$1, xmlns: _XMLNS$1, srcLang: locale || _DEFAULT_SOURCE_LANG$1 }, [new CR(2), file, new CR()]);
19844 return serialize([
19845 new Declaration({ version: '1.0', encoding: 'UTF-8' }), new CR(), xliff, new CR()
19846 ]);
19847 };
19848 Xliff2.prototype.load = function (content, url) {
19849 // xliff to xml nodes
19850 var xliff2Parser = new Xliff2Parser();
19851 var _a = xliff2Parser.parse(content, url), locale = _a.locale, msgIdToHtml = _a.msgIdToHtml, errors = _a.errors;
19852 // xml nodes to i18n nodes
19853 var i18nNodesByMsgId = {};
19854 var converter = new XmlToI18n$1();
19855 Object.keys(msgIdToHtml).forEach(function (msgId) {
19856 var _a = converter.convert(msgIdToHtml[msgId], url), i18nNodes = _a.i18nNodes, e = _a.errors;
19857 errors.push.apply(errors, __spread(e));
19858 i18nNodesByMsgId[msgId] = i18nNodes;
19859 });
19860 if (errors.length) {
19861 throw new Error("xliff2 parse errors:\n" + errors.join('\n'));
19862 }
19863 return { locale: locale, i18nNodesByMsgId: i18nNodesByMsgId };
19864 };
19865 Xliff2.prototype.digest = function (message) { return decimalDigest(message); };
19866 return Xliff2;
19867}(Serializer));
19868var _WriteVisitor$1 = /** @class */ (function () {
19869 function _WriteVisitor() {
19870 }
19871 _WriteVisitor.prototype.visitText = function (text, context) { return [new Text$2(text.value)]; };
19872 _WriteVisitor.prototype.visitContainer = function (container, context) {
19873 var _this = this;
19874 var nodes = [];
19875 container.children.forEach(function (node) { return nodes.push.apply(nodes, __spread(node.visit(_this))); });
19876 return nodes;
19877 };
19878 _WriteVisitor.prototype.visitIcu = function (icu, context) {
19879 var _this = this;
19880 var nodes = [new Text$2("{" + icu.expressionPlaceholder + ", " + icu.type + ", ")];
19881 Object.keys(icu.cases).forEach(function (c) {
19882 nodes.push.apply(nodes, __spread([new Text$2(c + " {")], icu.cases[c].visit(_this), [new Text$2("} ")]));
19883 });
19884 nodes.push(new Text$2("}"));
19885 return nodes;
19886 };
19887 _WriteVisitor.prototype.visitTagPlaceholder = function (ph, context) {
19888 var _this = this;
19889 var type = getTypeForTag(ph.tag);
19890 if (ph.isVoid) {
19891 var tagPh = new Tag(_PLACEHOLDER_TAG$2, {
19892 id: (this._nextPlaceholderId++).toString(),
19893 equiv: ph.startName,
19894 type: type,
19895 disp: "<" + ph.tag + "/>",
19896 });
19897 return [tagPh];
19898 }
19899 var tagPc = new Tag(_PLACEHOLDER_SPANNING_TAG, {
19900 id: (this._nextPlaceholderId++).toString(),
19901 equivStart: ph.startName,
19902 equivEnd: ph.closeName,
19903 type: type,
19904 dispStart: "<" + ph.tag + ">",
19905 dispEnd: "</" + ph.tag + ">",
19906 });
19907 var nodes = [].concat.apply([], __spread(ph.children.map(function (node) { return node.visit(_this); })));
19908 if (nodes.length) {
19909 nodes.forEach(function (node) { return tagPc.children.push(node); });
19910 }
19911 else {
19912 tagPc.children.push(new Text$2(''));
19913 }
19914 return [tagPc];
19915 };
19916 _WriteVisitor.prototype.visitPlaceholder = function (ph, context) {
19917 var idStr = (this._nextPlaceholderId++).toString();
19918 return [new Tag(_PLACEHOLDER_TAG$2, {
19919 id: idStr,
19920 equiv: ph.name,
19921 disp: "{{" + ph.value + "}}",
19922 })];
19923 };
19924 _WriteVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
19925 var cases = Object.keys(ph.value.cases).map(function (value) { return value + ' {...}'; }).join(' ');
19926 var idStr = (this._nextPlaceholderId++).toString();
19927 return [new Tag(_PLACEHOLDER_TAG$2, { id: idStr, equiv: ph.name, disp: "{" + ph.value.expression + ", " + ph.value.type + ", " + cases + "}" })];
19928 };
19929 _WriteVisitor.prototype.serialize = function (nodes) {
19930 var _this = this;
19931 this._nextPlaceholderId = 0;
19932 return [].concat.apply([], __spread(nodes.map(function (node) { return node.visit(_this); })));
19933 };
19934 return _WriteVisitor;
19935}());
19936// Extract messages as xml nodes from the xliff file
19937var Xliff2Parser = /** @class */ (function () {
19938 function Xliff2Parser() {
19939 this._locale = null;
19940 }
19941 Xliff2Parser.prototype.parse = function (xliff, url) {
19942 this._unitMlString = null;
19943 this._msgIdToHtml = {};
19944 var xml = new XmlParser().parse(xliff, url);
19945 this._errors = xml.errors;
19946 visitAll$1(this, xml.rootNodes, null);
19947 return {
19948 msgIdToHtml: this._msgIdToHtml,
19949 errors: this._errors,
19950 locale: this._locale,
19951 };
19952 };
19953 Xliff2Parser.prototype.visitElement = function (element, context) {
19954 switch (element.name) {
19955 case _UNIT_TAG$1:
19956 this._unitMlString = null;
19957 var idAttr = element.attrs.find(function (attr) { return attr.name === 'id'; });
19958 if (!idAttr) {
19959 this._addError(element, "<" + _UNIT_TAG$1 + "> misses the \"id\" attribute");
19960 }
19961 else {
19962 var id = idAttr.value;
19963 if (this._msgIdToHtml.hasOwnProperty(id)) {
19964 this._addError(element, "Duplicated translations for msg " + id);
19965 }
19966 else {
19967 visitAll$1(this, element.children, null);
19968 if (typeof this._unitMlString === 'string') {
19969 this._msgIdToHtml[id] = this._unitMlString;
19970 }
19971 else {
19972 this._addError(element, "Message " + id + " misses a translation");
19973 }
19974 }
19975 }
19976 break;
19977 case _SOURCE_TAG$2:
19978 // ignore source message
19979 break;
19980 case _TARGET_TAG$1:
19981 var innerTextStart = element.startSourceSpan.end.offset;
19982 var innerTextEnd = element.endSourceSpan.start.offset;
19983 var content = element.startSourceSpan.start.file.content;
19984 var innerText = content.slice(innerTextStart, innerTextEnd);
19985 this._unitMlString = innerText;
19986 break;
19987 case _XLIFF_TAG:
19988 var localeAttr = element.attrs.find(function (attr) { return attr.name === 'trgLang'; });
19989 if (localeAttr) {
19990 this._locale = localeAttr.value;
19991 }
19992 var versionAttr = element.attrs.find(function (attr) { return attr.name === 'version'; });
19993 if (versionAttr) {
19994 var version = versionAttr.value;
19995 if (version !== '2.0') {
19996 this._addError(element, "The XLIFF file version " + version + " is not compatible with XLIFF 2.0 serializer");
19997 }
19998 else {
19999 visitAll$1(this, element.children, null);
20000 }
20001 }
20002 break;
20003 default:
20004 visitAll$1(this, element.children, null);
20005 }
20006 };
20007 Xliff2Parser.prototype.visitAttribute = function (attribute, context) { };
20008 Xliff2Parser.prototype.visitText = function (text, context) { };
20009 Xliff2Parser.prototype.visitComment = function (comment, context) { };
20010 Xliff2Parser.prototype.visitExpansion = function (expansion, context) { };
20011 Xliff2Parser.prototype.visitExpansionCase = function (expansionCase, context) { };
20012 Xliff2Parser.prototype._addError = function (node, message) {
20013 this._errors.push(new I18nError(node.sourceSpan, message));
20014 };
20015 return Xliff2Parser;
20016}());
20017// Convert ml nodes (xliff syntax) to i18n nodes
20018var XmlToI18n$1 = /** @class */ (function () {
20019 function XmlToI18n() {
20020 }
20021 XmlToI18n.prototype.convert = function (message, url) {
20022 var xmlIcu = new XmlParser().parse(message, url, { tokenizeExpansionForms: true });
20023 this._errors = xmlIcu.errors;
20024 var i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ?
20025 [] : [].concat.apply([], __spread(visitAll$1(this, xmlIcu.rootNodes)));
20026 return {
20027 i18nNodes: i18nNodes,
20028 errors: this._errors,
20029 };
20030 };
20031 XmlToI18n.prototype.visitText = function (text, context) { return new Text$1(text.value, text.sourceSpan); };
20032 XmlToI18n.prototype.visitElement = function (el, context) {
20033 var _this = this;
20034 switch (el.name) {
20035 case _PLACEHOLDER_TAG$2:
20036 var nameAttr = el.attrs.find(function (attr) { return attr.name === 'equiv'; });
20037 if (nameAttr) {
20038 return [new Placeholder('', nameAttr.value, el.sourceSpan)];
20039 }
20040 this._addError(el, "<" + _PLACEHOLDER_TAG$2 + "> misses the \"equiv\" attribute");
20041 break;
20042 case _PLACEHOLDER_SPANNING_TAG:
20043 var startAttr = el.attrs.find(function (attr) { return attr.name === 'equivStart'; });
20044 var endAttr = el.attrs.find(function (attr) { return attr.name === 'equivEnd'; });
20045 if (!startAttr) {
20046 this._addError(el, "<" + _PLACEHOLDER_TAG$2 + "> misses the \"equivStart\" attribute");
20047 }
20048 else if (!endAttr) {
20049 this._addError(el, "<" + _PLACEHOLDER_TAG$2 + "> misses the \"equivEnd\" attribute");
20050 }
20051 else {
20052 var startId = startAttr.value;
20053 var endId = endAttr.value;
20054 var nodes = [];
20055 return nodes.concat.apply(nodes, __spread([new Placeholder('', startId, el.sourceSpan)], el.children.map(function (node) { return node.visit(_this, null); }), [new Placeholder('', endId, el.sourceSpan)]));
20056 }
20057 break;
20058 case _MARKER_TAG$1:
20059 return [].concat.apply([], __spread(visitAll$1(this, el.children)));
20060 default:
20061 this._addError(el, "Unexpected tag");
20062 }
20063 return null;
20064 };
20065 XmlToI18n.prototype.visitExpansion = function (icu, context) {
20066 var caseMap = {};
20067 visitAll$1(this, icu.cases).forEach(function (c) {
20068 caseMap[c.value] = new Container(c.nodes, icu.sourceSpan);
20069 });
20070 return new Icu$1(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
20071 };
20072 XmlToI18n.prototype.visitExpansionCase = function (icuCase, context) {
20073 return {
20074 value: icuCase.value,
20075 nodes: [].concat.apply([], __spread(visitAll$1(this, icuCase.expression))),
20076 };
20077 };
20078 XmlToI18n.prototype.visitComment = function (comment, context) { };
20079 XmlToI18n.prototype.visitAttribute = function (attribute, context) { };
20080 XmlToI18n.prototype._addError = function (node, message) {
20081 this._errors.push(new I18nError(node.sourceSpan, message));
20082 };
20083 return XmlToI18n;
20084}());
20085function getTypeForTag(tag) {
20086 switch (tag.toLowerCase()) {
20087 case 'br':
20088 case 'b':
20089 case 'i':
20090 case 'u':
20091 return 'fmt';
20092 case 'img':
20093 return 'image';
20094 case 'a':
20095 return 'link';
20096 default:
20097 return 'other';
20098 }
20099}
20100
20101/**
20102 * @license
20103 * Copyright Google Inc. All Rights Reserved.
20104 *
20105 * Use of this source code is governed by an MIT-style license that can be
20106 * found in the LICENSE file at https://angular.io/license
20107 */
20108var _TRANSLATIONS_TAG = 'translationbundle';
20109var _TRANSLATION_TAG = 'translation';
20110var _PLACEHOLDER_TAG$3 = 'ph';
20111var Xtb = /** @class */ (function (_super) {
20112 __extends(Xtb, _super);
20113 function Xtb() {
20114 return _super !== null && _super.apply(this, arguments) || this;
20115 }
20116 Xtb.prototype.write = function (messages, locale) { throw new Error('Unsupported'); };
20117 Xtb.prototype.load = function (content, url) {
20118 // xtb to xml nodes
20119 var xtbParser = new XtbParser();
20120 var _a = xtbParser.parse(content, url), locale = _a.locale, msgIdToHtml = _a.msgIdToHtml, errors = _a.errors;
20121 // xml nodes to i18n nodes
20122 var i18nNodesByMsgId = {};
20123 var converter = new XmlToI18n$2();
20124 // Because we should be able to load xtb files that rely on features not supported by angular,
20125 // we need to delay the conversion of html to i18n nodes so that non angular messages are not
20126 // converted
20127 Object.keys(msgIdToHtml).forEach(function (msgId) {
20128 var valueFn = function () {
20129 var _a = converter.convert(msgIdToHtml[msgId], url), i18nNodes = _a.i18nNodes, errors = _a.errors;
20130 if (errors.length) {
20131 throw new Error("xtb parse errors:\n" + errors.join('\n'));
20132 }
20133 return i18nNodes;
20134 };
20135 createLazyProperty(i18nNodesByMsgId, msgId, valueFn);
20136 });
20137 if (errors.length) {
20138 throw new Error("xtb parse errors:\n" + errors.join('\n'));
20139 }
20140 return { locale: locale, i18nNodesByMsgId: i18nNodesByMsgId };
20141 };
20142 Xtb.prototype.digest = function (message) { return digest$1(message); };
20143 Xtb.prototype.createNameMapper = function (message) {
20144 return new SimplePlaceholderMapper(message, toPublicName);
20145 };
20146 return Xtb;
20147}(Serializer));
20148function createLazyProperty(messages, id, valueFn) {
20149 Object.defineProperty(messages, id, {
20150 configurable: true,
20151 enumerable: true,
20152 get: function () {
20153 var value = valueFn();
20154 Object.defineProperty(messages, id, { enumerable: true, value: value });
20155 return value;
20156 },
20157 set: function (_) { throw new Error('Could not overwrite an XTB translation'); },
20158 });
20159}
20160// Extract messages as xml nodes from the xtb file
20161var XtbParser = /** @class */ (function () {
20162 function XtbParser() {
20163 this._locale = null;
20164 }
20165 XtbParser.prototype.parse = function (xtb, url) {
20166 this._bundleDepth = 0;
20167 this._msgIdToHtml = {};
20168 // We can not parse the ICU messages at this point as some messages might not originate
20169 // from Angular that could not be lex'd.
20170 var xml = new XmlParser().parse(xtb, url);
20171 this._errors = xml.errors;
20172 visitAll$1(this, xml.rootNodes);
20173 return {
20174 msgIdToHtml: this._msgIdToHtml,
20175 errors: this._errors,
20176 locale: this._locale,
20177 };
20178 };
20179 XtbParser.prototype.visitElement = function (element, context) {
20180 switch (element.name) {
20181 case _TRANSLATIONS_TAG:
20182 this._bundleDepth++;
20183 if (this._bundleDepth > 1) {
20184 this._addError(element, "<" + _TRANSLATIONS_TAG + "> elements can not be nested");
20185 }
20186 var langAttr = element.attrs.find(function (attr) { return attr.name === 'lang'; });
20187 if (langAttr) {
20188 this._locale = langAttr.value;
20189 }
20190 visitAll$1(this, element.children, null);
20191 this._bundleDepth--;
20192 break;
20193 case _TRANSLATION_TAG:
20194 var idAttr = element.attrs.find(function (attr) { return attr.name === 'id'; });
20195 if (!idAttr) {
20196 this._addError(element, "<" + _TRANSLATION_TAG + "> misses the \"id\" attribute");
20197 }
20198 else {
20199 var id = idAttr.value;
20200 if (this._msgIdToHtml.hasOwnProperty(id)) {
20201 this._addError(element, "Duplicated translations for msg " + id);
20202 }
20203 else {
20204 var innerTextStart = element.startSourceSpan.end.offset;
20205 var innerTextEnd = element.endSourceSpan.start.offset;
20206 var content = element.startSourceSpan.start.file.content;
20207 var innerText = content.slice(innerTextStart, innerTextEnd);
20208 this._msgIdToHtml[id] = innerText;
20209 }
20210 }
20211 break;
20212 default:
20213 this._addError(element, 'Unexpected tag');
20214 }
20215 };
20216 XtbParser.prototype.visitAttribute = function (attribute, context) { };
20217 XtbParser.prototype.visitText = function (text, context) { };
20218 XtbParser.prototype.visitComment = function (comment, context) { };
20219 XtbParser.prototype.visitExpansion = function (expansion, context) { };
20220 XtbParser.prototype.visitExpansionCase = function (expansionCase, context) { };
20221 XtbParser.prototype._addError = function (node, message) {
20222 this._errors.push(new I18nError(node.sourceSpan, message));
20223 };
20224 return XtbParser;
20225}());
20226// Convert ml nodes (xtb syntax) to i18n nodes
20227var XmlToI18n$2 = /** @class */ (function () {
20228 function XmlToI18n() {
20229 }
20230 XmlToI18n.prototype.convert = function (message, url) {
20231 var xmlIcu = new XmlParser().parse(message, url, { tokenizeExpansionForms: true });
20232 this._errors = xmlIcu.errors;
20233 var i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ?
20234 [] :
20235 visitAll$1(this, xmlIcu.rootNodes);
20236 return {
20237 i18nNodes: i18nNodes,
20238 errors: this._errors,
20239 };
20240 };
20241 XmlToI18n.prototype.visitText = function (text, context) { return new Text$1(text.value, text.sourceSpan); };
20242 XmlToI18n.prototype.visitExpansion = function (icu, context) {
20243 var caseMap = {};
20244 visitAll$1(this, icu.cases).forEach(function (c) {
20245 caseMap[c.value] = new Container(c.nodes, icu.sourceSpan);
20246 });
20247 return new Icu$1(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
20248 };
20249 XmlToI18n.prototype.visitExpansionCase = function (icuCase, context) {
20250 return {
20251 value: icuCase.value,
20252 nodes: visitAll$1(this, icuCase.expression),
20253 };
20254 };
20255 XmlToI18n.prototype.visitElement = function (el, context) {
20256 if (el.name === _PLACEHOLDER_TAG$3) {
20257 var nameAttr = el.attrs.find(function (attr) { return attr.name === 'name'; });
20258 if (nameAttr) {
20259 return new Placeholder('', nameAttr.value, el.sourceSpan);
20260 }
20261 this._addError(el, "<" + _PLACEHOLDER_TAG$3 + "> misses the \"name\" attribute");
20262 }
20263 else {
20264 this._addError(el, "Unexpected tag");
20265 }
20266 return null;
20267 };
20268 XmlToI18n.prototype.visitComment = function (comment, context) { };
20269 XmlToI18n.prototype.visitAttribute = function (attribute, context) { };
20270 XmlToI18n.prototype._addError = function (node, message) {
20271 this._errors.push(new I18nError(node.sourceSpan, message));
20272 };
20273 return XmlToI18n;
20274}());
20275
20276/**
20277 * @license
20278 * Copyright Google Inc. All Rights Reserved.
20279 *
20280 * Use of this source code is governed by an MIT-style license that can be
20281 * found in the LICENSE file at https://angular.io/license
20282 */
20283/**
20284 * A container for translated messages
20285 */
20286var TranslationBundle = /** @class */ (function () {
20287 function TranslationBundle(_i18nNodesByMsgId, locale, digest, mapperFactory, missingTranslationStrategy, console) {
20288 if (_i18nNodesByMsgId === void 0) { _i18nNodesByMsgId = {}; }
20289 if (missingTranslationStrategy === void 0) { missingTranslationStrategy = MissingTranslationStrategy.Warning; }
20290 this._i18nNodesByMsgId = _i18nNodesByMsgId;
20291 this.digest = digest;
20292 this.mapperFactory = mapperFactory;
20293 this._i18nToHtml = new I18nToHtmlVisitor(_i18nNodesByMsgId, locale, digest, mapperFactory, missingTranslationStrategy, console);
20294 }
20295 // Creates a `TranslationBundle` by parsing the given `content` with the `serializer`.
20296 TranslationBundle.load = function (content, url, serializer, missingTranslationStrategy, console) {
20297 var _a = serializer.load(content, url), locale = _a.locale, i18nNodesByMsgId = _a.i18nNodesByMsgId;
20298 var digestFn = function (m) { return serializer.digest(m); };
20299 var mapperFactory = function (m) { return serializer.createNameMapper(m); };
20300 return new TranslationBundle(i18nNodesByMsgId, locale, digestFn, mapperFactory, missingTranslationStrategy, console);
20301 };
20302 // Returns the translation as HTML nodes from the given source message.
20303 TranslationBundle.prototype.get = function (srcMsg) {
20304 var html = this._i18nToHtml.convert(srcMsg);
20305 if (html.errors.length) {
20306 throw new Error(html.errors.join('\n'));
20307 }
20308 return html.nodes;
20309 };
20310 TranslationBundle.prototype.has = function (srcMsg) { return this.digest(srcMsg) in this._i18nNodesByMsgId; };
20311 return TranslationBundle;
20312}());
20313var I18nToHtmlVisitor = /** @class */ (function () {
20314 function I18nToHtmlVisitor(_i18nNodesByMsgId, _locale, _digest, _mapperFactory, _missingTranslationStrategy, _console) {
20315 if (_i18nNodesByMsgId === void 0) { _i18nNodesByMsgId = {}; }
20316 this._i18nNodesByMsgId = _i18nNodesByMsgId;
20317 this._locale = _locale;
20318 this._digest = _digest;
20319 this._mapperFactory = _mapperFactory;
20320 this._missingTranslationStrategy = _missingTranslationStrategy;
20321 this._console = _console;
20322 this._contextStack = [];
20323 this._errors = [];
20324 }
20325 I18nToHtmlVisitor.prototype.convert = function (srcMsg) {
20326 this._contextStack.length = 0;
20327 this._errors.length = 0;
20328 // i18n to text
20329 var text = this._convertToText(srcMsg);
20330 // text to html
20331 var url = srcMsg.nodes[0].sourceSpan.start.file.url;
20332 var html = new HtmlParser().parse(text, url, { tokenizeExpansionForms: true });
20333 return {
20334 nodes: html.rootNodes,
20335 errors: __spread(this._errors, html.errors),
20336 };
20337 };
20338 I18nToHtmlVisitor.prototype.visitText = function (text, context) {
20339 // `convert()` uses an `HtmlParser` to return `html.Node`s
20340 // we should then make sure that any special characters are escaped
20341 return escapeXml(text.value);
20342 };
20343 I18nToHtmlVisitor.prototype.visitContainer = function (container, context) {
20344 var _this = this;
20345 return container.children.map(function (n) { return n.visit(_this); }).join('');
20346 };
20347 I18nToHtmlVisitor.prototype.visitIcu = function (icu, context) {
20348 var _this = this;
20349 var cases = Object.keys(icu.cases).map(function (k) { return k + " {" + icu.cases[k].visit(_this) + "}"; });
20350 // TODO(vicb): Once all format switch to using expression placeholders
20351 // we should throw when the placeholder is not in the source message
20352 var exp = this._srcMsg.placeholders.hasOwnProperty(icu.expression) ?
20353 this._srcMsg.placeholders[icu.expression] :
20354 icu.expression;
20355 return "{" + exp + ", " + icu.type + ", " + cases.join(' ') + "}";
20356 };
20357 I18nToHtmlVisitor.prototype.visitPlaceholder = function (ph, context) {
20358 var phName = this._mapper(ph.name);
20359 if (this._srcMsg.placeholders.hasOwnProperty(phName)) {
20360 return this._srcMsg.placeholders[phName];
20361 }
20362 if (this._srcMsg.placeholderToMessage.hasOwnProperty(phName)) {
20363 return this._convertToText(this._srcMsg.placeholderToMessage[phName]);
20364 }
20365 this._addError(ph, "Unknown placeholder \"" + ph.name + "\"");
20366 return '';
20367 };
20368 // Loaded message contains only placeholders (vs tag and icu placeholders).
20369 // However when a translation can not be found, we need to serialize the source message
20370 // which can contain tag placeholders
20371 I18nToHtmlVisitor.prototype.visitTagPlaceholder = function (ph, context) {
20372 var _this = this;
20373 var tag = "" + ph.tag;
20374 var attrs = Object.keys(ph.attrs).map(function (name) { return name + "=\"" + ph.attrs[name] + "\""; }).join(' ');
20375 if (ph.isVoid) {
20376 return "<" + tag + " " + attrs + "/>";
20377 }
20378 var children = ph.children.map(function (c) { return c.visit(_this); }).join('');
20379 return "<" + tag + " " + attrs + ">" + children + "</" + tag + ">";
20380 };
20381 // Loaded message contains only placeholders (vs tag and icu placeholders).
20382 // However when a translation can not be found, we need to serialize the source message
20383 // which can contain tag placeholders
20384 I18nToHtmlVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
20385 // An ICU placeholder references the source message to be serialized
20386 return this._convertToText(this._srcMsg.placeholderToMessage[ph.name]);
20387 };
20388 /**
20389 * Convert a source message to a translated text string:
20390 * - text nodes are replaced with their translation,
20391 * - placeholders are replaced with their content,
20392 * - ICU nodes are converted to ICU expressions.
20393 */
20394 I18nToHtmlVisitor.prototype._convertToText = function (srcMsg) {
20395 var _this = this;
20396 var id = this._digest(srcMsg);
20397 var mapper = this._mapperFactory ? this._mapperFactory(srcMsg) : null;
20398 var nodes;
20399 this._contextStack.push({ msg: this._srcMsg, mapper: this._mapper });
20400 this._srcMsg = srcMsg;
20401 if (this._i18nNodesByMsgId.hasOwnProperty(id)) {
20402 // When there is a translation use its nodes as the source
20403 // And create a mapper to convert serialized placeholder names to internal names
20404 nodes = this._i18nNodesByMsgId[id];
20405 this._mapper = function (name) { return mapper ? mapper.toInternalName(name) : name; };
20406 }
20407 else {
20408 // When no translation has been found
20409 // - report an error / a warning / nothing,
20410 // - use the nodes from the original message
20411 // - placeholders are already internal and need no mapper
20412 if (this._missingTranslationStrategy === MissingTranslationStrategy.Error) {
20413 var ctx = this._locale ? " for locale \"" + this._locale + "\"" : '';
20414 this._addError(srcMsg.nodes[0], "Missing translation for message \"" + id + "\"" + ctx);
20415 }
20416 else if (this._console &&
20417 this._missingTranslationStrategy === MissingTranslationStrategy.Warning) {
20418 var ctx = this._locale ? " for locale \"" + this._locale + "\"" : '';
20419 this._console.warn("Missing translation for message \"" + id + "\"" + ctx);
20420 }
20421 nodes = srcMsg.nodes;
20422 this._mapper = function (name) { return name; };
20423 }
20424 var text = nodes.map(function (node) { return node.visit(_this); }).join('');
20425 var context = this._contextStack.pop();
20426 this._srcMsg = context.msg;
20427 this._mapper = context.mapper;
20428 return text;
20429 };
20430 I18nToHtmlVisitor.prototype._addError = function (el, msg) {
20431 this._errors.push(new I18nError(el.sourceSpan, msg));
20432 };
20433 return I18nToHtmlVisitor;
20434}());
20435
20436/**
20437 * @license
20438 * Copyright Google Inc. All Rights Reserved.
20439 *
20440 * Use of this source code is governed by an MIT-style license that can be
20441 * found in the LICENSE file at https://angular.io/license
20442 */
20443var I18NHtmlParser = /** @class */ (function () {
20444 function I18NHtmlParser(_htmlParser, translations, translationsFormat, missingTranslation, console) {
20445 if (missingTranslation === void 0) { missingTranslation = MissingTranslationStrategy.Warning; }
20446 this._htmlParser = _htmlParser;
20447 if (translations) {
20448 var serializer = createSerializer(translationsFormat);
20449 this._translationBundle =
20450 TranslationBundle.load(translations, 'i18n', serializer, missingTranslation, console);
20451 }
20452 else {
20453 this._translationBundle =
20454 new TranslationBundle({}, null, digest, undefined, missingTranslation, console);
20455 }
20456 }
20457 I18NHtmlParser.prototype.parse = function (source, url, options) {
20458 if (options === void 0) { options = {}; }
20459 var interpolationConfig = options.interpolationConfig || DEFAULT_INTERPOLATION_CONFIG;
20460 var parseResult = this._htmlParser.parse(source, url, __assign({ interpolationConfig: interpolationConfig }, options));
20461 if (parseResult.errors.length) {
20462 return new ParseTreeResult(parseResult.rootNodes, parseResult.errors);
20463 }
20464 return mergeTranslations(parseResult.rootNodes, this._translationBundle, interpolationConfig, [], {});
20465 };
20466 return I18NHtmlParser;
20467}());
20468function createSerializer(format) {
20469 format = (format || 'xlf').toLowerCase();
20470 switch (format) {
20471 case 'xmb':
20472 return new Xmb();
20473 case 'xtb':
20474 return new Xtb();
20475 case 'xliff2':
20476 case 'xlf2':
20477 return new Xliff2();
20478 case 'xliff':
20479 case 'xlf':
20480 default:
20481 return new Xliff();
20482 }
20483}
20484
20485/**
20486 * @license
20487 * Copyright Google Inc. All Rights Reserved.
20488 *
20489 * Use of this source code is governed by an MIT-style license that can be
20490 * found in the LICENSE file at https://angular.io/license
20491 */
20492var QUOTED_KEYS = '$quoted$';
20493function convertValueToOutputAst(ctx, value, type) {
20494 if (type === void 0) { type = null; }
20495 return visitValue(value, new _ValueOutputAstTransformer(ctx), type);
20496}
20497var _ValueOutputAstTransformer = /** @class */ (function () {
20498 function _ValueOutputAstTransformer(ctx) {
20499 this.ctx = ctx;
20500 }
20501 _ValueOutputAstTransformer.prototype.visitArray = function (arr, type) {
20502 var _this = this;
20503 return literalArr(arr.map(function (value) { return visitValue(value, _this, null); }), type);
20504 };
20505 _ValueOutputAstTransformer.prototype.visitStringMap = function (map, type) {
20506 var _this = this;
20507 var entries = [];
20508 var quotedSet = new Set(map && map[QUOTED_KEYS]);
20509 Object.keys(map).forEach(function (key) {
20510 entries.push(new LiteralMapEntry(key, visitValue(map[key], _this, null), quotedSet.has(key)));
20511 });
20512 return new LiteralMapExpr(entries, type);
20513 };
20514 _ValueOutputAstTransformer.prototype.visitPrimitive = function (value, type) { return literal(value, type); };
20515 _ValueOutputAstTransformer.prototype.visitOther = function (value, type) {
20516 if (value instanceof Expression) {
20517 return value;
20518 }
20519 else {
20520 return this.ctx.importExpr(value);
20521 }
20522 };
20523 return _ValueOutputAstTransformer;
20524}());
20525
20526/**
20527 * @license
20528 * Copyright Google Inc. All Rights Reserved.
20529 *
20530 * Use of this source code is governed by an MIT-style license that can be
20531 * found in the LICENSE file at https://angular.io/license
20532 */
20533function mapEntry$1(key, value) {
20534 return { key: key, value: value, quoted: false };
20535}
20536var InjectableCompiler = /** @class */ (function () {
20537 function InjectableCompiler(reflector, alwaysGenerateDef) {
20538 this.reflector = reflector;
20539 this.alwaysGenerateDef = alwaysGenerateDef;
20540 this.tokenInjector = reflector.resolveExternalReference(Identifiers.Injector);
20541 }
20542 InjectableCompiler.prototype.depsArray = function (deps, ctx) {
20543 var _this = this;
20544 return deps.map(function (dep) {
20545 var token = dep;
20546 var args = [token];
20547 var flags = 0 /* Default */;
20548 if (Array.isArray(dep)) {
20549 for (var i = 0; i < dep.length; i++) {
20550 var v = dep[i];
20551 if (v) {
20552 if (v.ngMetadataName === 'Optional') {
20553 flags |= 8 /* Optional */;
20554 }
20555 else if (v.ngMetadataName === 'SkipSelf') {
20556 flags |= 4 /* SkipSelf */;
20557 }
20558 else if (v.ngMetadataName === 'Self') {
20559 flags |= 2 /* Self */;
20560 }
20561 else if (v.ngMetadataName === 'Inject') {
20562 token = v.token;
20563 }
20564 else {
20565 token = v;
20566 }
20567 }
20568 }
20569 }
20570 var tokenExpr;
20571 if (typeof token === 'string') {
20572 tokenExpr = literal(token);
20573 }
20574 else if (token === _this.tokenInjector) {
20575 tokenExpr = importExpr(Identifiers.INJECTOR);
20576 }
20577 else {
20578 tokenExpr = ctx.importExpr(token);
20579 }
20580 if (flags !== 0 /* Default */) {
20581 args = [tokenExpr, literal(flags)];
20582 }
20583 else {
20584 args = [tokenExpr];
20585 }
20586 return importExpr(Identifiers.inject).callFn(args);
20587 });
20588 };
20589 InjectableCompiler.prototype.factoryFor = function (injectable, ctx) {
20590 var retValue;
20591 if (injectable.useExisting) {
20592 retValue = importExpr(Identifiers.inject).callFn([ctx.importExpr(injectable.useExisting)]);
20593 }
20594 else if (injectable.useFactory) {
20595 var deps = injectable.deps || [];
20596 if (deps.length > 0) {
20597 retValue = ctx.importExpr(injectable.useFactory).callFn(this.depsArray(deps, ctx));
20598 }
20599 else {
20600 return ctx.importExpr(injectable.useFactory);
20601 }
20602 }
20603 else if (injectable.useValue) {
20604 retValue = convertValueToOutputAst(ctx, injectable.useValue);
20605 }
20606 else {
20607 var clazz = injectable.useClass || injectable.symbol;
20608 var depArgs = this.depsArray(this.reflector.parameters(clazz), ctx);
20609 retValue = new InstantiateExpr(ctx.importExpr(clazz), depArgs);
20610 }
20611 return fn([], [new ReturnStatement(retValue)], undefined, undefined, injectable.symbol.name + '_Factory');
20612 };
20613 InjectableCompiler.prototype.injectableDef = function (injectable, ctx) {
20614 var providedIn = NULL_EXPR;
20615 if (injectable.providedIn !== undefined) {
20616 if (injectable.providedIn === null) {
20617 providedIn = NULL_EXPR;
20618 }
20619 else if (typeof injectable.providedIn === 'string') {
20620 providedIn = literal(injectable.providedIn);
20621 }
20622 else {
20623 providedIn = ctx.importExpr(injectable.providedIn);
20624 }
20625 }
20626 var def = [
20627 mapEntry$1('factory', this.factoryFor(injectable, ctx)),
20628 mapEntry$1('token', ctx.importExpr(injectable.type.reference)),
20629 mapEntry$1('providedIn', providedIn),
20630 ];
20631 return importExpr(Identifiers.ɵɵdefineInjectable).callFn([literalMap(def)]);
20632 };
20633 InjectableCompiler.prototype.compile = function (injectable, ctx) {
20634 if (this.alwaysGenerateDef || injectable.providedIn !== undefined) {
20635 var className = identifierName(injectable.type);
20636 var clazz = new ClassStmt(className, null, [
20637 new ClassField('ngInjectableDef', INFERRED_TYPE, [StmtModifier.Static], this.injectableDef(injectable, ctx)),
20638 ], [], new ClassMethod(null, [], []), []);
20639 ctx.statements.push(clazz);
20640 }
20641 };
20642 return InjectableCompiler;
20643}());
20644
20645/**
20646 * @license
20647 * Copyright Google Inc. All Rights Reserved.
20648 *
20649 * Use of this source code is governed by an MIT-style license that can be
20650 * found in the LICENSE file at https://angular.io/license
20651 */
20652var STRIP_SRC_FILE_SUFFIXES = /(\.ts|\.d\.ts|\.js|\.jsx|\.tsx)$/;
20653var GENERATED_FILE = /\.ngfactory\.|\.ngsummary\./;
20654var JIT_SUMMARY_FILE = /\.ngsummary\./;
20655var JIT_SUMMARY_NAME = /NgSummary$/;
20656function ngfactoryFilePath(filePath, forceSourceFile) {
20657 if (forceSourceFile === void 0) { forceSourceFile = false; }
20658 var urlWithSuffix = splitTypescriptSuffix(filePath, forceSourceFile);
20659 return urlWithSuffix[0] + ".ngfactory" + normalizeGenFileSuffix(urlWithSuffix[1]);
20660}
20661function stripGeneratedFileSuffix(filePath) {
20662 return filePath.replace(GENERATED_FILE, '.');
20663}
20664function isGeneratedFile(filePath) {
20665 return GENERATED_FILE.test(filePath);
20666}
20667function splitTypescriptSuffix(path, forceSourceFile) {
20668 if (forceSourceFile === void 0) { forceSourceFile = false; }
20669 if (path.endsWith('.d.ts')) {
20670 return [path.slice(0, -5), forceSourceFile ? '.ts' : '.d.ts'];
20671 }
20672 var lastDot = path.lastIndexOf('.');
20673 if (lastDot !== -1) {
20674 return [path.substring(0, lastDot), path.substring(lastDot)];
20675 }
20676 return [path, ''];
20677}
20678function normalizeGenFileSuffix(srcFileSuffix) {
20679 return srcFileSuffix === '.tsx' ? '.ts' : srcFileSuffix;
20680}
20681function summaryFileName(fileName) {
20682 var fileNameWithoutSuffix = fileName.replace(STRIP_SRC_FILE_SUFFIXES, '');
20683 return fileNameWithoutSuffix + ".ngsummary.json";
20684}
20685function summaryForJitFileName(fileName, forceSourceFile) {
20686 if (forceSourceFile === void 0) { forceSourceFile = false; }
20687 var urlWithSuffix = splitTypescriptSuffix(stripGeneratedFileSuffix(fileName), forceSourceFile);
20688 return urlWithSuffix[0] + ".ngsummary" + urlWithSuffix[1];
20689}
20690function stripSummaryForJitFileSuffix(filePath) {
20691 return filePath.replace(JIT_SUMMARY_FILE, '.');
20692}
20693function summaryForJitName(symbolName) {
20694 return symbolName + "NgSummary";
20695}
20696function stripSummaryForJitNameSuffix(symbolName) {
20697 return symbolName.replace(JIT_SUMMARY_NAME, '');
20698}
20699var LOWERED_SYMBOL = /\u0275\d+/;
20700function isLoweredSymbol(name) {
20701 return LOWERED_SYMBOL.test(name);
20702}
20703function createLoweredSymbol(id) {
20704 return "\u0275" + id;
20705}
20706
20707/**
20708 * @license
20709 * Copyright Google Inc. All Rights Reserved.
20710 *
20711 * Use of this source code is governed by an MIT-style license that can be
20712 * found in the LICENSE file at https://angular.io/license
20713 */
20714var LifecycleHooks;
20715(function (LifecycleHooks) {
20716 LifecycleHooks[LifecycleHooks["OnInit"] = 0] = "OnInit";
20717 LifecycleHooks[LifecycleHooks["OnDestroy"] = 1] = "OnDestroy";
20718 LifecycleHooks[LifecycleHooks["DoCheck"] = 2] = "DoCheck";
20719 LifecycleHooks[LifecycleHooks["OnChanges"] = 3] = "OnChanges";
20720 LifecycleHooks[LifecycleHooks["AfterContentInit"] = 4] = "AfterContentInit";
20721 LifecycleHooks[LifecycleHooks["AfterContentChecked"] = 5] = "AfterContentChecked";
20722 LifecycleHooks[LifecycleHooks["AfterViewInit"] = 6] = "AfterViewInit";
20723 LifecycleHooks[LifecycleHooks["AfterViewChecked"] = 7] = "AfterViewChecked";
20724})(LifecycleHooks || (LifecycleHooks = {}));
20725var LIFECYCLE_HOOKS_VALUES = [
20726 LifecycleHooks.OnInit, LifecycleHooks.OnDestroy, LifecycleHooks.DoCheck, LifecycleHooks.OnChanges,
20727 LifecycleHooks.AfterContentInit, LifecycleHooks.AfterContentChecked, LifecycleHooks.AfterViewInit,
20728 LifecycleHooks.AfterViewChecked
20729];
20730function hasLifecycleHook(reflector, hook, token) {
20731 return reflector.hasLifecycleHook(token, getHookName(hook));
20732}
20733function getAllLifecycleHooks(reflector, token) {
20734 return LIFECYCLE_HOOKS_VALUES.filter(function (hook) { return hasLifecycleHook(reflector, hook, token); });
20735}
20736function getHookName(hook) {
20737 switch (hook) {
20738 case LifecycleHooks.OnInit:
20739 return 'ngOnInit';
20740 case LifecycleHooks.OnDestroy:
20741 return 'ngOnDestroy';
20742 case LifecycleHooks.DoCheck:
20743 return 'ngDoCheck';
20744 case LifecycleHooks.OnChanges:
20745 return 'ngOnChanges';
20746 case LifecycleHooks.AfterContentInit:
20747 return 'ngAfterContentInit';
20748 case LifecycleHooks.AfterContentChecked:
20749 return 'ngAfterContentChecked';
20750 case LifecycleHooks.AfterViewInit:
20751 return 'ngAfterViewInit';
20752 case LifecycleHooks.AfterViewChecked:
20753 return 'ngAfterViewChecked';
20754 default:
20755 // This default case is not needed by TypeScript compiler, as the switch is exhaustive.
20756 // However Closure Compiler does not understand that and reports an error in typed mode.
20757 // The `throw new Error` below works around the problem, and the unexpected: never variable
20758 // makes sure tsc still checks this code is unreachable.
20759 var unexpected = hook;
20760 throw new Error("unexpected " + unexpected);
20761 }
20762}
20763
20764/**
20765 * @license
20766 * Copyright Google Inc. All Rights Reserved.
20767 *
20768 * Use of this source code is governed by an MIT-style license that can be
20769 * found in the LICENSE file at https://angular.io/license
20770 */
20771var ERROR_COMPONENT_TYPE = 'ngComponentType';
20772// Design notes:
20773// - don't lazily create metadata:
20774// For some metadata, we need to do async work sometimes,
20775// so the user has to kick off this loading.
20776// But we want to report errors even when the async work is
20777// not required to check that the user would have been able
20778// to wait correctly.
20779var CompileMetadataResolver = /** @class */ (function () {
20780 function CompileMetadataResolver(_config, _htmlParser, _ngModuleResolver, _directiveResolver, _pipeResolver, _summaryResolver, _schemaRegistry, _directiveNormalizer, _console, _staticSymbolCache, _reflector, _errorCollector) {
20781 this._config = _config;
20782 this._htmlParser = _htmlParser;
20783 this._ngModuleResolver = _ngModuleResolver;
20784 this._directiveResolver = _directiveResolver;
20785 this._pipeResolver = _pipeResolver;
20786 this._summaryResolver = _summaryResolver;
20787 this._schemaRegistry = _schemaRegistry;
20788 this._directiveNormalizer = _directiveNormalizer;
20789 this._console = _console;
20790 this._staticSymbolCache = _staticSymbolCache;
20791 this._reflector = _reflector;
20792 this._errorCollector = _errorCollector;
20793 this._nonNormalizedDirectiveCache = new Map();
20794 this._directiveCache = new Map();
20795 this._summaryCache = new Map();
20796 this._pipeCache = new Map();
20797 this._ngModuleCache = new Map();
20798 this._ngModuleOfTypes = new Map();
20799 this._shallowModuleCache = new Map();
20800 }
20801 CompileMetadataResolver.prototype.getReflector = function () { return this._reflector; };
20802 CompileMetadataResolver.prototype.clearCacheFor = function (type) {
20803 var dirMeta = this._directiveCache.get(type);
20804 this._directiveCache.delete(type);
20805 this._nonNormalizedDirectiveCache.delete(type);
20806 this._summaryCache.delete(type);
20807 this._pipeCache.delete(type);
20808 this._ngModuleOfTypes.delete(type);
20809 // Clear all of the NgModule as they contain transitive information!
20810 this._ngModuleCache.clear();
20811 if (dirMeta) {
20812 this._directiveNormalizer.clearCacheFor(dirMeta);
20813 }
20814 };
20815 CompileMetadataResolver.prototype.clearCache = function () {
20816 this._directiveCache.clear();
20817 this._nonNormalizedDirectiveCache.clear();
20818 this._summaryCache.clear();
20819 this._pipeCache.clear();
20820 this._ngModuleCache.clear();
20821 this._ngModuleOfTypes.clear();
20822 this._directiveNormalizer.clearCache();
20823 };
20824 CompileMetadataResolver.prototype._createProxyClass = function (baseType, name) {
20825 var delegate = null;
20826 var proxyClass = function () {
20827 if (!delegate) {
20828 throw new Error("Illegal state: Class " + name + " for type " + stringify(baseType) + " is not compiled yet!");
20829 }
20830 return delegate.apply(this, arguments);
20831 };
20832 proxyClass.setDelegate = function (d) {
20833 delegate = d;
20834 proxyClass.prototype = d.prototype;
20835 };
20836 // Make stringify work correctly
20837 proxyClass.overriddenName = name;
20838 return proxyClass;
20839 };
20840 CompileMetadataResolver.prototype.getGeneratedClass = function (dirType, name) {
20841 if (dirType instanceof StaticSymbol) {
20842 return this._staticSymbolCache.get(ngfactoryFilePath(dirType.filePath), name);
20843 }
20844 else {
20845 return this._createProxyClass(dirType, name);
20846 }
20847 };
20848 CompileMetadataResolver.prototype.getComponentViewClass = function (dirType) {
20849 return this.getGeneratedClass(dirType, viewClassName(dirType, 0));
20850 };
20851 CompileMetadataResolver.prototype.getHostComponentViewClass = function (dirType) {
20852 return this.getGeneratedClass(dirType, hostViewClassName(dirType));
20853 };
20854 CompileMetadataResolver.prototype.getHostComponentType = function (dirType) {
20855 var name = identifierName({ reference: dirType }) + "_Host";
20856 if (dirType instanceof StaticSymbol) {
20857 return this._staticSymbolCache.get(dirType.filePath, name);
20858 }
20859 return this._createProxyClass(dirType, name);
20860 };
20861 CompileMetadataResolver.prototype.getRendererType = function (dirType) {
20862 if (dirType instanceof StaticSymbol) {
20863 return this._staticSymbolCache.get(ngfactoryFilePath(dirType.filePath), rendererTypeName(dirType));
20864 }
20865 else {
20866 // returning an object as proxy,
20867 // that we fill later during runtime compilation.
20868 return {};
20869 }
20870 };
20871 CompileMetadataResolver.prototype.getComponentFactory = function (selector, dirType, inputs, outputs) {
20872 if (dirType instanceof StaticSymbol) {
20873 return this._staticSymbolCache.get(ngfactoryFilePath(dirType.filePath), componentFactoryName(dirType));
20874 }
20875 else {
20876 var hostView = this.getHostComponentViewClass(dirType);
20877 // Note: ngContentSelectors will be filled later once the template is
20878 // loaded.
20879 var createComponentFactory = this._reflector.resolveExternalReference(Identifiers.createComponentFactory);
20880 return createComponentFactory(selector, dirType, hostView, inputs, outputs, []);
20881 }
20882 };
20883 CompileMetadataResolver.prototype.initComponentFactory = function (factory, ngContentSelectors) {
20884 var _a;
20885 if (!(factory instanceof StaticSymbol)) {
20886 (_a = factory.ngContentSelectors).push.apply(_a, __spread(ngContentSelectors));
20887 }
20888 };
20889 CompileMetadataResolver.prototype._loadSummary = function (type, kind) {
20890 var typeSummary = this._summaryCache.get(type);
20891 if (!typeSummary) {
20892 var summary = this._summaryResolver.resolveSummary(type);
20893 typeSummary = summary ? summary.type : null;
20894 this._summaryCache.set(type, typeSummary || null);
20895 }
20896 return typeSummary && typeSummary.summaryKind === kind ? typeSummary : null;
20897 };
20898 CompileMetadataResolver.prototype.getHostComponentMetadata = function (compMeta, hostViewType) {
20899 var hostType = this.getHostComponentType(compMeta.type.reference);
20900 if (!hostViewType) {
20901 hostViewType = this.getHostComponentViewClass(hostType);
20902 }
20903 // Note: ! is ok here as this method should only be called with normalized directive
20904 // metadata, which always fills in the selector.
20905 var template = CssSelector.parse(compMeta.selector)[0].getMatchingElementTemplate();
20906 var templateUrl = '';
20907 var htmlAst = this._htmlParser.parse(template, templateUrl);
20908 return CompileDirectiveMetadata.create({
20909 isHost: true,
20910 type: { reference: hostType, diDeps: [], lifecycleHooks: [] },
20911 template: new CompileTemplateMetadata({
20912 encapsulation: ViewEncapsulation.None,
20913 template: template,
20914 templateUrl: templateUrl,
20915 htmlAst: htmlAst,
20916 styles: [],
20917 styleUrls: [],
20918 ngContentSelectors: [],
20919 animations: [],
20920 isInline: true,
20921 externalStylesheets: [],
20922 interpolation: null,
20923 preserveWhitespaces: false,
20924 }),
20925 exportAs: null,
20926 changeDetection: ChangeDetectionStrategy.Default,
20927 inputs: [],
20928 outputs: [],
20929 host: {},
20930 isComponent: true,
20931 selector: '*',
20932 providers: [],
20933 viewProviders: [],
20934 queries: [],
20935 guards: {},
20936 viewQueries: [],
20937 componentViewType: hostViewType,
20938 rendererType: { id: '__Host__', encapsulation: ViewEncapsulation.None, styles: [], data: {} },
20939 entryComponents: [],
20940 componentFactory: null
20941 });
20942 };
20943 CompileMetadataResolver.prototype.loadDirectiveMetadata = function (ngModuleType, directiveType, isSync) {
20944 var _this = this;
20945 if (this._directiveCache.has(directiveType)) {
20946 return null;
20947 }
20948 directiveType = resolveForwardRef(directiveType);
20949 var _a = this.getNonNormalizedDirectiveMetadata(directiveType), annotation = _a.annotation, metadata = _a.metadata;
20950 var createDirectiveMetadata = function (templateMetadata) {
20951 var normalizedDirMeta = new CompileDirectiveMetadata({
20952 isHost: false,
20953 type: metadata.type,
20954 isComponent: metadata.isComponent,
20955 selector: metadata.selector,
20956 exportAs: metadata.exportAs,
20957 changeDetection: metadata.changeDetection,
20958 inputs: metadata.inputs,
20959 outputs: metadata.outputs,
20960 hostListeners: metadata.hostListeners,
20961 hostProperties: metadata.hostProperties,
20962 hostAttributes: metadata.hostAttributes,
20963 providers: metadata.providers,
20964 viewProviders: metadata.viewProviders,
20965 queries: metadata.queries,
20966 guards: metadata.guards,
20967 viewQueries: metadata.viewQueries,
20968 entryComponents: metadata.entryComponents,
20969 componentViewType: metadata.componentViewType,
20970 rendererType: metadata.rendererType,
20971 componentFactory: metadata.componentFactory,
20972 template: templateMetadata
20973 });
20974 if (templateMetadata) {
20975 _this.initComponentFactory(metadata.componentFactory, templateMetadata.ngContentSelectors);
20976 }
20977 _this._directiveCache.set(directiveType, normalizedDirMeta);
20978 _this._summaryCache.set(directiveType, normalizedDirMeta.toSummary());
20979 return null;
20980 };
20981 if (metadata.isComponent) {
20982 var template = metadata.template;
20983 var templateMeta = this._directiveNormalizer.normalizeTemplate({
20984 ngModuleType: ngModuleType,
20985 componentType: directiveType,
20986 moduleUrl: this._reflector.componentModuleUrl(directiveType, annotation),
20987 encapsulation: template.encapsulation,
20988 template: template.template,
20989 templateUrl: template.templateUrl,
20990 styles: template.styles,
20991 styleUrls: template.styleUrls,
20992 animations: template.animations,
20993 interpolation: template.interpolation,
20994 preserveWhitespaces: template.preserveWhitespaces
20995 });
20996 if (isPromise(templateMeta) && isSync) {
20997 this._reportError(componentStillLoadingError(directiveType), directiveType);
20998 return null;
20999 }
21000 return SyncAsync.then(templateMeta, createDirectiveMetadata);
21001 }
21002 else {
21003 // directive
21004 createDirectiveMetadata(null);
21005 return null;
21006 }
21007 };
21008 CompileMetadataResolver.prototype.getNonNormalizedDirectiveMetadata = function (directiveType) {
21009 var _this = this;
21010 directiveType = resolveForwardRef(directiveType);
21011 if (!directiveType) {
21012 return null;
21013 }
21014 var cacheEntry = this._nonNormalizedDirectiveCache.get(directiveType);
21015 if (cacheEntry) {
21016 return cacheEntry;
21017 }
21018 var dirMeta = this._directiveResolver.resolve(directiveType, false);
21019 if (!dirMeta) {
21020 return null;
21021 }
21022 var nonNormalizedTemplateMetadata = undefined;
21023 if (createComponent.isTypeOf(dirMeta)) {
21024 // component
21025 var compMeta = dirMeta;
21026 assertArrayOfStrings('styles', compMeta.styles);
21027 assertArrayOfStrings('styleUrls', compMeta.styleUrls);
21028 assertInterpolationSymbols('interpolation', compMeta.interpolation);
21029 var animations = compMeta.animations;
21030 nonNormalizedTemplateMetadata = new CompileTemplateMetadata({
21031 encapsulation: noUndefined(compMeta.encapsulation),
21032 template: noUndefined(compMeta.template),
21033 templateUrl: noUndefined(compMeta.templateUrl),
21034 htmlAst: null,
21035 styles: compMeta.styles || [],
21036 styleUrls: compMeta.styleUrls || [],
21037 animations: animations || [],
21038 interpolation: noUndefined(compMeta.interpolation),
21039 isInline: !!compMeta.template,
21040 externalStylesheets: [],
21041 ngContentSelectors: [],
21042 preserveWhitespaces: noUndefined(dirMeta.preserveWhitespaces),
21043 });
21044 }
21045 var changeDetectionStrategy = null;
21046 var viewProviders = [];
21047 var entryComponentMetadata = [];
21048 var selector = dirMeta.selector;
21049 if (createComponent.isTypeOf(dirMeta)) {
21050 // Component
21051 var compMeta = dirMeta;
21052 changeDetectionStrategy = compMeta.changeDetection;
21053 if (compMeta.viewProviders) {
21054 viewProviders = this._getProvidersMetadata(compMeta.viewProviders, entryComponentMetadata, "viewProviders for \"" + stringifyType(directiveType) + "\"", [], directiveType);
21055 }
21056 if (compMeta.entryComponents) {
21057 entryComponentMetadata = flattenAndDedupeArray(compMeta.entryComponents)
21058 .map(function (type) { return _this._getEntryComponentMetadata(type); })
21059 .concat(entryComponentMetadata);
21060 }
21061 if (!selector) {
21062 selector = this._schemaRegistry.getDefaultComponentElementName();
21063 }
21064 }
21065 else {
21066 // Directive
21067 if (!selector) {
21068 this._reportError(syntaxError("Directive " + stringifyType(directiveType) + " has no selector, please add it!"), directiveType);
21069 selector = 'error';
21070 }
21071 }
21072 var providers = [];
21073 if (dirMeta.providers != null) {
21074 providers = this._getProvidersMetadata(dirMeta.providers, entryComponentMetadata, "providers for \"" + stringifyType(directiveType) + "\"", [], directiveType);
21075 }
21076 var queries = [];
21077 var viewQueries = [];
21078 if (dirMeta.queries != null) {
21079 queries = this._getQueriesMetadata(dirMeta.queries, false, directiveType);
21080 viewQueries = this._getQueriesMetadata(dirMeta.queries, true, directiveType);
21081 }
21082 var metadata = CompileDirectiveMetadata.create({
21083 isHost: false,
21084 selector: selector,
21085 exportAs: noUndefined(dirMeta.exportAs),
21086 isComponent: !!nonNormalizedTemplateMetadata,
21087 type: this._getTypeMetadata(directiveType),
21088 template: nonNormalizedTemplateMetadata,
21089 changeDetection: changeDetectionStrategy,
21090 inputs: dirMeta.inputs || [],
21091 outputs: dirMeta.outputs || [],
21092 host: dirMeta.host || {},
21093 providers: providers || [],
21094 viewProviders: viewProviders || [],
21095 queries: queries || [],
21096 guards: dirMeta.guards || {},
21097 viewQueries: viewQueries || [],
21098 entryComponents: entryComponentMetadata,
21099 componentViewType: nonNormalizedTemplateMetadata ? this.getComponentViewClass(directiveType) :
21100 null,
21101 rendererType: nonNormalizedTemplateMetadata ? this.getRendererType(directiveType) : null,
21102 componentFactory: null
21103 });
21104 if (nonNormalizedTemplateMetadata) {
21105 metadata.componentFactory =
21106 this.getComponentFactory(selector, directiveType, metadata.inputs, metadata.outputs);
21107 }
21108 cacheEntry = { metadata: metadata, annotation: dirMeta };
21109 this._nonNormalizedDirectiveCache.set(directiveType, cacheEntry);
21110 return cacheEntry;
21111 };
21112 /**
21113 * Gets the metadata for the given directive.
21114 * This assumes `loadNgModuleDirectiveAndPipeMetadata` has been called first.
21115 */
21116 CompileMetadataResolver.prototype.getDirectiveMetadata = function (directiveType) {
21117 var dirMeta = this._directiveCache.get(directiveType);
21118 if (!dirMeta) {
21119 this._reportError(syntaxError("Illegal state: getDirectiveMetadata can only be called after loadNgModuleDirectiveAndPipeMetadata for a module that declares it. Directive " + stringifyType(directiveType) + "."), directiveType);
21120 }
21121 return dirMeta;
21122 };
21123 CompileMetadataResolver.prototype.getDirectiveSummary = function (dirType) {
21124 var dirSummary = this._loadSummary(dirType, CompileSummaryKind.Directive);
21125 if (!dirSummary) {
21126 this._reportError(syntaxError("Illegal state: Could not load the summary for directive " + stringifyType(dirType) + "."), dirType);
21127 }
21128 return dirSummary;
21129 };
21130 CompileMetadataResolver.prototype.isDirective = function (type) {
21131 return !!this._loadSummary(type, CompileSummaryKind.Directive) ||
21132 this._directiveResolver.isDirective(type);
21133 };
21134 CompileMetadataResolver.prototype.isPipe = function (type) {
21135 return !!this._loadSummary(type, CompileSummaryKind.Pipe) ||
21136 this._pipeResolver.isPipe(type);
21137 };
21138 CompileMetadataResolver.prototype.isNgModule = function (type) {
21139 return !!this._loadSummary(type, CompileSummaryKind.NgModule) ||
21140 this._ngModuleResolver.isNgModule(type);
21141 };
21142 CompileMetadataResolver.prototype.getNgModuleSummary = function (moduleType, alreadyCollecting) {
21143 if (alreadyCollecting === void 0) { alreadyCollecting = null; }
21144 var moduleSummary = this._loadSummary(moduleType, CompileSummaryKind.NgModule);
21145 if (!moduleSummary) {
21146 var moduleMeta = this.getNgModuleMetadata(moduleType, false, alreadyCollecting);
21147 moduleSummary = moduleMeta ? moduleMeta.toSummary() : null;
21148 if (moduleSummary) {
21149 this._summaryCache.set(moduleType, moduleSummary);
21150 }
21151 }
21152 return moduleSummary;
21153 };
21154 /**
21155 * Loads the declared directives and pipes of an NgModule.
21156 */
21157 CompileMetadataResolver.prototype.loadNgModuleDirectiveAndPipeMetadata = function (moduleType, isSync, throwIfNotFound) {
21158 var _this = this;
21159 if (throwIfNotFound === void 0) { throwIfNotFound = true; }
21160 var ngModule = this.getNgModuleMetadata(moduleType, throwIfNotFound);
21161 var loading = [];
21162 if (ngModule) {
21163 ngModule.declaredDirectives.forEach(function (id) {
21164 var promise = _this.loadDirectiveMetadata(moduleType, id.reference, isSync);
21165 if (promise) {
21166 loading.push(promise);
21167 }
21168 });
21169 ngModule.declaredPipes.forEach(function (id) { return _this._loadPipeMetadata(id.reference); });
21170 }
21171 return Promise.all(loading);
21172 };
21173 CompileMetadataResolver.prototype.getShallowModuleMetadata = function (moduleType) {
21174 var compileMeta = this._shallowModuleCache.get(moduleType);
21175 if (compileMeta) {
21176 return compileMeta;
21177 }
21178 var ngModuleMeta = findLast(this._reflector.shallowAnnotations(moduleType), createNgModule.isTypeOf);
21179 compileMeta = {
21180 type: this._getTypeMetadata(moduleType),
21181 rawExports: ngModuleMeta.exports,
21182 rawImports: ngModuleMeta.imports,
21183 rawProviders: ngModuleMeta.providers,
21184 };
21185 this._shallowModuleCache.set(moduleType, compileMeta);
21186 return compileMeta;
21187 };
21188 CompileMetadataResolver.prototype.getNgModuleMetadata = function (moduleType, throwIfNotFound, alreadyCollecting) {
21189 var _this = this;
21190 if (throwIfNotFound === void 0) { throwIfNotFound = true; }
21191 if (alreadyCollecting === void 0) { alreadyCollecting = null; }
21192 moduleType = resolveForwardRef(moduleType);
21193 var compileMeta = this._ngModuleCache.get(moduleType);
21194 if (compileMeta) {
21195 return compileMeta;
21196 }
21197 var meta = this._ngModuleResolver.resolve(moduleType, throwIfNotFound);
21198 if (!meta) {
21199 return null;
21200 }
21201 var declaredDirectives = [];
21202 var exportedNonModuleIdentifiers = [];
21203 var declaredPipes = [];
21204 var importedModules = [];
21205 var exportedModules = [];
21206 var providers = [];
21207 var entryComponents = [];
21208 var bootstrapComponents = [];
21209 var schemas = [];
21210 if (meta.imports) {
21211 flattenAndDedupeArray(meta.imports).forEach(function (importedType) {
21212 var importedModuleType = undefined;
21213 if (isValidType(importedType)) {
21214 importedModuleType = importedType;
21215 }
21216 else if (importedType && importedType.ngModule) {
21217 var moduleWithProviders = importedType;
21218 importedModuleType = moduleWithProviders.ngModule;
21219 if (moduleWithProviders.providers) {
21220 providers.push.apply(providers, __spread(_this._getProvidersMetadata(moduleWithProviders.providers, entryComponents, "provider for the NgModule '" + stringifyType(importedModuleType) + "'", [], importedType)));
21221 }
21222 }
21223 if (importedModuleType) {
21224 if (_this._checkSelfImport(moduleType, importedModuleType))
21225 return;
21226 if (!alreadyCollecting)
21227 alreadyCollecting = new Set();
21228 if (alreadyCollecting.has(importedModuleType)) {
21229 _this._reportError(syntaxError(_this._getTypeDescriptor(importedModuleType) + " '" + stringifyType(importedType) + "' is imported recursively by the module '" + stringifyType(moduleType) + "'."), moduleType);
21230 return;
21231 }
21232 alreadyCollecting.add(importedModuleType);
21233 var importedModuleSummary = _this.getNgModuleSummary(importedModuleType, alreadyCollecting);
21234 alreadyCollecting.delete(importedModuleType);
21235 if (!importedModuleSummary) {
21236 _this._reportError(syntaxError("Unexpected " + _this._getTypeDescriptor(importedType) + " '" + stringifyType(importedType) + "' imported by the module '" + stringifyType(moduleType) + "'. Please add a @NgModule annotation."), moduleType);
21237 return;
21238 }
21239 importedModules.push(importedModuleSummary);
21240 }
21241 else {
21242 _this._reportError(syntaxError("Unexpected value '" + stringifyType(importedType) + "' imported by the module '" + stringifyType(moduleType) + "'"), moduleType);
21243 return;
21244 }
21245 });
21246 }
21247 if (meta.exports) {
21248 flattenAndDedupeArray(meta.exports).forEach(function (exportedType) {
21249 if (!isValidType(exportedType)) {
21250 _this._reportError(syntaxError("Unexpected value '" + stringifyType(exportedType) + "' exported by the module '" + stringifyType(moduleType) + "'"), moduleType);
21251 return;
21252 }
21253 if (!alreadyCollecting)
21254 alreadyCollecting = new Set();
21255 if (alreadyCollecting.has(exportedType)) {
21256 _this._reportError(syntaxError(_this._getTypeDescriptor(exportedType) + " '" + stringify(exportedType) + "' is exported recursively by the module '" + stringifyType(moduleType) + "'"), moduleType);
21257 return;
21258 }
21259 alreadyCollecting.add(exportedType);
21260 var exportedModuleSummary = _this.getNgModuleSummary(exportedType, alreadyCollecting);
21261 alreadyCollecting.delete(exportedType);
21262 if (exportedModuleSummary) {
21263 exportedModules.push(exportedModuleSummary);
21264 }
21265 else {
21266 exportedNonModuleIdentifiers.push(_this._getIdentifierMetadata(exportedType));
21267 }
21268 });
21269 }
21270 // Note: This will be modified later, so we rely on
21271 // getting a new instance every time!
21272 var transitiveModule = this._getTransitiveNgModuleMetadata(importedModules, exportedModules);
21273 if (meta.declarations) {
21274 flattenAndDedupeArray(meta.declarations).forEach(function (declaredType) {
21275 if (!isValidType(declaredType)) {
21276 _this._reportError(syntaxError("Unexpected value '" + stringifyType(declaredType) + "' declared by the module '" + stringifyType(moduleType) + "'"), moduleType);
21277 return;
21278 }
21279 var declaredIdentifier = _this._getIdentifierMetadata(declaredType);
21280 if (_this.isDirective(declaredType)) {
21281 transitiveModule.addDirective(declaredIdentifier);
21282 declaredDirectives.push(declaredIdentifier);
21283 _this._addTypeToModule(declaredType, moduleType);
21284 }
21285 else if (_this.isPipe(declaredType)) {
21286 transitiveModule.addPipe(declaredIdentifier);
21287 transitiveModule.pipes.push(declaredIdentifier);
21288 declaredPipes.push(declaredIdentifier);
21289 _this._addTypeToModule(declaredType, moduleType);
21290 }
21291 else {
21292 _this._reportError(syntaxError("Unexpected " + _this._getTypeDescriptor(declaredType) + " '" + stringifyType(declaredType) + "' declared by the module '" + stringifyType(moduleType) + "'. Please add a @Pipe/@Directive/@Component annotation."), moduleType);
21293 return;
21294 }
21295 });
21296 }
21297 var exportedDirectives = [];
21298 var exportedPipes = [];
21299 exportedNonModuleIdentifiers.forEach(function (exportedId) {
21300 if (transitiveModule.directivesSet.has(exportedId.reference)) {
21301 exportedDirectives.push(exportedId);
21302 transitiveModule.addExportedDirective(exportedId);
21303 }
21304 else if (transitiveModule.pipesSet.has(exportedId.reference)) {
21305 exportedPipes.push(exportedId);
21306 transitiveModule.addExportedPipe(exportedId);
21307 }
21308 else {
21309 _this._reportError(syntaxError("Can't export " + _this._getTypeDescriptor(exportedId.reference) + " " + stringifyType(exportedId.reference) + " from " + stringifyType(moduleType) + " as it was neither declared nor imported!"), moduleType);
21310 return;
21311 }
21312 });
21313 // The providers of the module have to go last
21314 // so that they overwrite any other provider we already added.
21315 if (meta.providers) {
21316 providers.push.apply(providers, __spread(this._getProvidersMetadata(meta.providers, entryComponents, "provider for the NgModule '" + stringifyType(moduleType) + "'", [], moduleType)));
21317 }
21318 if (meta.entryComponents) {
21319 entryComponents.push.apply(entryComponents, __spread(flattenAndDedupeArray(meta.entryComponents)
21320 .map(function (type) { return _this._getEntryComponentMetadata(type); })));
21321 }
21322 if (meta.bootstrap) {
21323 flattenAndDedupeArray(meta.bootstrap).forEach(function (type) {
21324 if (!isValidType(type)) {
21325 _this._reportError(syntaxError("Unexpected value '" + stringifyType(type) + "' used in the bootstrap property of module '" + stringifyType(moduleType) + "'"), moduleType);
21326 return;
21327 }
21328 bootstrapComponents.push(_this._getIdentifierMetadata(type));
21329 });
21330 }
21331 entryComponents.push.apply(entryComponents, __spread(bootstrapComponents.map(function (type) { return _this._getEntryComponentMetadata(type.reference); })));
21332 if (meta.schemas) {
21333 schemas.push.apply(schemas, __spread(flattenAndDedupeArray(meta.schemas)));
21334 }
21335 compileMeta = new CompileNgModuleMetadata({
21336 type: this._getTypeMetadata(moduleType),
21337 providers: providers,
21338 entryComponents: entryComponents,
21339 bootstrapComponents: bootstrapComponents,
21340 schemas: schemas,
21341 declaredDirectives: declaredDirectives,
21342 exportedDirectives: exportedDirectives,
21343 declaredPipes: declaredPipes,
21344 exportedPipes: exportedPipes,
21345 importedModules: importedModules,
21346 exportedModules: exportedModules,
21347 transitiveModule: transitiveModule,
21348 id: meta.id || null,
21349 });
21350 entryComponents.forEach(function (id) { return transitiveModule.addEntryComponent(id); });
21351 providers.forEach(function (provider) { return transitiveModule.addProvider(provider, compileMeta.type); });
21352 transitiveModule.addModule(compileMeta.type);
21353 this._ngModuleCache.set(moduleType, compileMeta);
21354 return compileMeta;
21355 };
21356 CompileMetadataResolver.prototype._checkSelfImport = function (moduleType, importedModuleType) {
21357 if (moduleType === importedModuleType) {
21358 this._reportError(syntaxError("'" + stringifyType(moduleType) + "' module can't import itself"), moduleType);
21359 return true;
21360 }
21361 return false;
21362 };
21363 CompileMetadataResolver.prototype._getTypeDescriptor = function (type) {
21364 if (isValidType(type)) {
21365 if (this.isDirective(type)) {
21366 return 'directive';
21367 }
21368 if (this.isPipe(type)) {
21369 return 'pipe';
21370 }
21371 if (this.isNgModule(type)) {
21372 return 'module';
21373 }
21374 }
21375 if (type.provide) {
21376 return 'provider';
21377 }
21378 return 'value';
21379 };
21380 CompileMetadataResolver.prototype._addTypeToModule = function (type, moduleType) {
21381 var oldModule = this._ngModuleOfTypes.get(type);
21382 if (oldModule && oldModule !== moduleType) {
21383 this._reportError(syntaxError("Type " + stringifyType(type) + " is part of the declarations of 2 modules: " + stringifyType(oldModule) + " and " + stringifyType(moduleType) + "! " +
21384 ("Please consider moving " + stringifyType(type) + " to a higher module that imports " + stringifyType(oldModule) + " and " + stringifyType(moduleType) + ". ") +
21385 ("You can also create a new NgModule that exports and includes " + stringifyType(type) + " then import that NgModule in " + stringifyType(oldModule) + " and " + stringifyType(moduleType) + ".")), moduleType);
21386 return;
21387 }
21388 this._ngModuleOfTypes.set(type, moduleType);
21389 };
21390 CompileMetadataResolver.prototype._getTransitiveNgModuleMetadata = function (importedModules, exportedModules) {
21391 // collect `providers` / `entryComponents` from all imported and all exported modules
21392 var result = new TransitiveCompileNgModuleMetadata();
21393 var modulesByToken = new Map();
21394 importedModules.concat(exportedModules).forEach(function (modSummary) {
21395 modSummary.modules.forEach(function (mod) { return result.addModule(mod); });
21396 modSummary.entryComponents.forEach(function (comp) { return result.addEntryComponent(comp); });
21397 var addedTokens = new Set();
21398 modSummary.providers.forEach(function (entry) {
21399 var tokenRef = tokenReference(entry.provider.token);
21400 var prevModules = modulesByToken.get(tokenRef);
21401 if (!prevModules) {
21402 prevModules = new Set();
21403 modulesByToken.set(tokenRef, prevModules);
21404 }
21405 var moduleRef = entry.module.reference;
21406 // Note: the providers of one module may still contain multiple providers
21407 // per token (e.g. for multi providers), and we need to preserve these.
21408 if (addedTokens.has(tokenRef) || !prevModules.has(moduleRef)) {
21409 prevModules.add(moduleRef);
21410 addedTokens.add(tokenRef);
21411 result.addProvider(entry.provider, entry.module);
21412 }
21413 });
21414 });
21415 exportedModules.forEach(function (modSummary) {
21416 modSummary.exportedDirectives.forEach(function (id) { return result.addExportedDirective(id); });
21417 modSummary.exportedPipes.forEach(function (id) { return result.addExportedPipe(id); });
21418 });
21419 importedModules.forEach(function (modSummary) {
21420 modSummary.exportedDirectives.forEach(function (id) { return result.addDirective(id); });
21421 modSummary.exportedPipes.forEach(function (id) { return result.addPipe(id); });
21422 });
21423 return result;
21424 };
21425 CompileMetadataResolver.prototype._getIdentifierMetadata = function (type) {
21426 type = resolveForwardRef(type);
21427 return { reference: type };
21428 };
21429 CompileMetadataResolver.prototype.isInjectable = function (type) {
21430 var annotations = this._reflector.tryAnnotations(type);
21431 return annotations.some(function (ann) { return createInjectable.isTypeOf(ann); });
21432 };
21433 CompileMetadataResolver.prototype.getInjectableSummary = function (type) {
21434 return {
21435 summaryKind: CompileSummaryKind.Injectable,
21436 type: this._getTypeMetadata(type, null, false)
21437 };
21438 };
21439 CompileMetadataResolver.prototype.getInjectableMetadata = function (type, dependencies, throwOnUnknownDeps) {
21440 if (dependencies === void 0) { dependencies = null; }
21441 if (throwOnUnknownDeps === void 0) { throwOnUnknownDeps = true; }
21442 var typeSummary = this._loadSummary(type, CompileSummaryKind.Injectable);
21443 var typeMetadata = typeSummary ?
21444 typeSummary.type :
21445 this._getTypeMetadata(type, dependencies, throwOnUnknownDeps);
21446 var annotations = this._reflector.annotations(type).filter(function (ann) { return createInjectable.isTypeOf(ann); });
21447 if (annotations.length === 0) {
21448 return null;
21449 }
21450 var meta = annotations[annotations.length - 1];
21451 return {
21452 symbol: type,
21453 type: typeMetadata,
21454 providedIn: meta.providedIn,
21455 useValue: meta.useValue,
21456 useClass: meta.useClass,
21457 useExisting: meta.useExisting,
21458 useFactory: meta.useFactory,
21459 deps: meta.deps,
21460 };
21461 };
21462 CompileMetadataResolver.prototype._getTypeMetadata = function (type, dependencies, throwOnUnknownDeps) {
21463 if (dependencies === void 0) { dependencies = null; }
21464 if (throwOnUnknownDeps === void 0) { throwOnUnknownDeps = true; }
21465 var identifier = this._getIdentifierMetadata(type);
21466 return {
21467 reference: identifier.reference,
21468 diDeps: this._getDependenciesMetadata(identifier.reference, dependencies, throwOnUnknownDeps),
21469 lifecycleHooks: getAllLifecycleHooks(this._reflector, identifier.reference),
21470 };
21471 };
21472 CompileMetadataResolver.prototype._getFactoryMetadata = function (factory, dependencies) {
21473 if (dependencies === void 0) { dependencies = null; }
21474 factory = resolveForwardRef(factory);
21475 return { reference: factory, diDeps: this._getDependenciesMetadata(factory, dependencies) };
21476 };
21477 /**
21478 * Gets the metadata for the given pipe.
21479 * This assumes `loadNgModuleDirectiveAndPipeMetadata` has been called first.
21480 */
21481 CompileMetadataResolver.prototype.getPipeMetadata = function (pipeType) {
21482 var pipeMeta = this._pipeCache.get(pipeType);
21483 if (!pipeMeta) {
21484 this._reportError(syntaxError("Illegal state: getPipeMetadata can only be called after loadNgModuleDirectiveAndPipeMetadata for a module that declares it. Pipe " + stringifyType(pipeType) + "."), pipeType);
21485 }
21486 return pipeMeta || null;
21487 };
21488 CompileMetadataResolver.prototype.getPipeSummary = function (pipeType) {
21489 var pipeSummary = this._loadSummary(pipeType, CompileSummaryKind.Pipe);
21490 if (!pipeSummary) {
21491 this._reportError(syntaxError("Illegal state: Could not load the summary for pipe " + stringifyType(pipeType) + "."), pipeType);
21492 }
21493 return pipeSummary;
21494 };
21495 CompileMetadataResolver.prototype.getOrLoadPipeMetadata = function (pipeType) {
21496 var pipeMeta = this._pipeCache.get(pipeType);
21497 if (!pipeMeta) {
21498 pipeMeta = this._loadPipeMetadata(pipeType);
21499 }
21500 return pipeMeta;
21501 };
21502 CompileMetadataResolver.prototype._loadPipeMetadata = function (pipeType) {
21503 pipeType = resolveForwardRef(pipeType);
21504 var pipeAnnotation = this._pipeResolver.resolve(pipeType);
21505 var pipeMeta = new CompilePipeMetadata({
21506 type: this._getTypeMetadata(pipeType),
21507 name: pipeAnnotation.name,
21508 pure: !!pipeAnnotation.pure
21509 });
21510 this._pipeCache.set(pipeType, pipeMeta);
21511 this._summaryCache.set(pipeType, pipeMeta.toSummary());
21512 return pipeMeta;
21513 };
21514 CompileMetadataResolver.prototype._getDependenciesMetadata = function (typeOrFunc, dependencies, throwOnUnknownDeps) {
21515 var _this = this;
21516 if (throwOnUnknownDeps === void 0) { throwOnUnknownDeps = true; }
21517 var hasUnknownDeps = false;
21518 var params = dependencies || this._reflector.parameters(typeOrFunc) || [];
21519 var dependenciesMetadata = params.map(function (param) {
21520 var isAttribute = false;
21521 var isHost = false;
21522 var isSelf = false;
21523 var isSkipSelf = false;
21524 var isOptional = false;
21525 var token = null;
21526 if (Array.isArray(param)) {
21527 param.forEach(function (paramEntry) {
21528 if (createHost.isTypeOf(paramEntry)) {
21529 isHost = true;
21530 }
21531 else if (createSelf.isTypeOf(paramEntry)) {
21532 isSelf = true;
21533 }
21534 else if (createSkipSelf.isTypeOf(paramEntry)) {
21535 isSkipSelf = true;
21536 }
21537 else if (createOptional.isTypeOf(paramEntry)) {
21538 isOptional = true;
21539 }
21540 else if (createAttribute.isTypeOf(paramEntry)) {
21541 isAttribute = true;
21542 token = paramEntry.attributeName;
21543 }
21544 else if (createInject.isTypeOf(paramEntry)) {
21545 token = paramEntry.token;
21546 }
21547 else if (createInjectionToken.isTypeOf(paramEntry) ||
21548 paramEntry instanceof StaticSymbol) {
21549 token = paramEntry;
21550 }
21551 else if (isValidType(paramEntry) && token == null) {
21552 token = paramEntry;
21553 }
21554 });
21555 }
21556 else {
21557 token = param;
21558 }
21559 if (token == null) {
21560 hasUnknownDeps = true;
21561 return {};
21562 }
21563 return {
21564 isAttribute: isAttribute,
21565 isHost: isHost,
21566 isSelf: isSelf,
21567 isSkipSelf: isSkipSelf,
21568 isOptional: isOptional,
21569 token: _this._getTokenMetadata(token)
21570 };
21571 });
21572 if (hasUnknownDeps) {
21573 var depsTokens = dependenciesMetadata.map(function (dep) { return dep.token ? stringifyType(dep.token) : '?'; }).join(', ');
21574 var message = "Can't resolve all parameters for " + stringifyType(typeOrFunc) + ": (" + depsTokens + ").";
21575 if (throwOnUnknownDeps || this._config.strictInjectionParameters) {
21576 this._reportError(syntaxError(message), typeOrFunc);
21577 }
21578 else {
21579 this._console.warn("Warning: " + message + " This will become an error in Angular v6.x");
21580 }
21581 }
21582 return dependenciesMetadata;
21583 };
21584 CompileMetadataResolver.prototype._getTokenMetadata = function (token) {
21585 token = resolveForwardRef(token);
21586 var compileToken;
21587 if (typeof token === 'string') {
21588 compileToken = { value: token };
21589 }
21590 else {
21591 compileToken = { identifier: { reference: token } };
21592 }
21593 return compileToken;
21594 };
21595 CompileMetadataResolver.prototype._getProvidersMetadata = function (providers, targetEntryComponents, debugInfo, compileProviders, type) {
21596 var _this = this;
21597 if (compileProviders === void 0) { compileProviders = []; }
21598 providers.forEach(function (provider, providerIdx) {
21599 if (Array.isArray(provider)) {
21600 _this._getProvidersMetadata(provider, targetEntryComponents, debugInfo, compileProviders);
21601 }
21602 else {
21603 provider = resolveForwardRef(provider);
21604 var providerMeta = undefined;
21605 if (provider && typeof provider === 'object' && provider.hasOwnProperty('provide')) {
21606 _this._validateProvider(provider);
21607 providerMeta = new ProviderMeta(provider.provide, provider);
21608 }
21609 else if (isValidType(provider)) {
21610 providerMeta = new ProviderMeta(provider, { useClass: provider });
21611 }
21612 else if (provider === void 0) {
21613 _this._reportError(syntaxError("Encountered undefined provider! Usually this means you have a circular dependencies. This might be caused by using 'barrel' index.ts files."));
21614 return;
21615 }
21616 else {
21617 var providersInfo = providers.reduce(function (soFar, seenProvider, seenProviderIdx) {
21618 if (seenProviderIdx < providerIdx) {
21619 soFar.push("" + stringifyType(seenProvider));
21620 }
21621 else if (seenProviderIdx == providerIdx) {
21622 soFar.push("?" + stringifyType(seenProvider) + "?");
21623 }
21624 else if (seenProviderIdx == providerIdx + 1) {
21625 soFar.push('...');
21626 }
21627 return soFar;
21628 }, [])
21629 .join(', ');
21630 _this._reportError(syntaxError("Invalid " + (debugInfo ? debugInfo : 'provider') + " - only instances of Provider and Type are allowed, got: [" + providersInfo + "]"), type);
21631 return;
21632 }
21633 if (providerMeta.token ===
21634 _this._reflector.resolveExternalReference(Identifiers.ANALYZE_FOR_ENTRY_COMPONENTS)) {
21635 targetEntryComponents.push.apply(targetEntryComponents, __spread(_this._getEntryComponentsFromProvider(providerMeta, type)));
21636 }
21637 else {
21638 compileProviders.push(_this.getProviderMetadata(providerMeta));
21639 }
21640 }
21641 });
21642 return compileProviders;
21643 };
21644 CompileMetadataResolver.prototype._validateProvider = function (provider) {
21645 if (provider.hasOwnProperty('useClass') && provider.useClass == null) {
21646 this._reportError(syntaxError("Invalid provider for " + stringifyType(provider.provide) + ". useClass cannot be " + provider.useClass + ".\n Usually it happens when:\n 1. There's a circular dependency (might be caused by using index.ts (barrel) files).\n 2. Class was used before it was declared. Use forwardRef in this case."));
21647 }
21648 };
21649 CompileMetadataResolver.prototype._getEntryComponentsFromProvider = function (provider, type) {
21650 var _this = this;
21651 var components = [];
21652 var collectedIdentifiers = [];
21653 if (provider.useFactory || provider.useExisting || provider.useClass) {
21654 this._reportError(syntaxError("The ANALYZE_FOR_ENTRY_COMPONENTS token only supports useValue!"), type);
21655 return [];
21656 }
21657 if (!provider.multi) {
21658 this._reportError(syntaxError("The ANALYZE_FOR_ENTRY_COMPONENTS token only supports 'multi = true'!"), type);
21659 return [];
21660 }
21661 extractIdentifiers(provider.useValue, collectedIdentifiers);
21662 collectedIdentifiers.forEach(function (identifier) {
21663 var entry = _this._getEntryComponentMetadata(identifier.reference, false);
21664 if (entry) {
21665 components.push(entry);
21666 }
21667 });
21668 return components;
21669 };
21670 CompileMetadataResolver.prototype._getEntryComponentMetadata = function (dirType, throwIfNotFound) {
21671 if (throwIfNotFound === void 0) { throwIfNotFound = true; }
21672 var dirMeta = this.getNonNormalizedDirectiveMetadata(dirType);
21673 if (dirMeta && dirMeta.metadata.isComponent) {
21674 return { componentType: dirType, componentFactory: dirMeta.metadata.componentFactory };
21675 }
21676 var dirSummary = this._loadSummary(dirType, CompileSummaryKind.Directive);
21677 if (dirSummary && dirSummary.isComponent) {
21678 return { componentType: dirType, componentFactory: dirSummary.componentFactory };
21679 }
21680 if (throwIfNotFound) {
21681 throw syntaxError(dirType.name + " cannot be used as an entry component.");
21682 }
21683 return null;
21684 };
21685 CompileMetadataResolver.prototype._getInjectableTypeMetadata = function (type, dependencies) {
21686 if (dependencies === void 0) { dependencies = null; }
21687 var typeSummary = this._loadSummary(type, CompileSummaryKind.Injectable);
21688 if (typeSummary) {
21689 return typeSummary.type;
21690 }
21691 return this._getTypeMetadata(type, dependencies);
21692 };
21693 CompileMetadataResolver.prototype.getProviderMetadata = function (provider) {
21694 var compileDeps = undefined;
21695 var compileTypeMetadata = null;
21696 var compileFactoryMetadata = null;
21697 var token = this._getTokenMetadata(provider.token);
21698 if (provider.useClass) {
21699 compileTypeMetadata =
21700 this._getInjectableTypeMetadata(provider.useClass, provider.dependencies);
21701 compileDeps = compileTypeMetadata.diDeps;
21702 if (provider.token === provider.useClass) {
21703 // use the compileTypeMetadata as it contains information about lifecycleHooks...
21704 token = { identifier: compileTypeMetadata };
21705 }
21706 }
21707 else if (provider.useFactory) {
21708 compileFactoryMetadata = this._getFactoryMetadata(provider.useFactory, provider.dependencies);
21709 compileDeps = compileFactoryMetadata.diDeps;
21710 }
21711 return {
21712 token: token,
21713 useClass: compileTypeMetadata,
21714 useValue: provider.useValue,
21715 useFactory: compileFactoryMetadata,
21716 useExisting: provider.useExisting ? this._getTokenMetadata(provider.useExisting) : undefined,
21717 deps: compileDeps,
21718 multi: provider.multi
21719 };
21720 };
21721 CompileMetadataResolver.prototype._getQueriesMetadata = function (queries, isViewQuery, directiveType) {
21722 var _this = this;
21723 var res = [];
21724 Object.keys(queries).forEach(function (propertyName) {
21725 var query = queries[propertyName];
21726 if (query.isViewQuery === isViewQuery) {
21727 res.push(_this._getQueryMetadata(query, propertyName, directiveType));
21728 }
21729 });
21730 return res;
21731 };
21732 CompileMetadataResolver.prototype._queryVarBindings = function (selector) { return selector.split(/\s*,\s*/); };
21733 CompileMetadataResolver.prototype._getQueryMetadata = function (q, propertyName, typeOrFunc) {
21734 var _this = this;
21735 var selectors;
21736 if (typeof q.selector === 'string') {
21737 selectors =
21738 this._queryVarBindings(q.selector).map(function (varName) { return _this._getTokenMetadata(varName); });
21739 }
21740 else {
21741 if (!q.selector) {
21742 this._reportError(syntaxError("Can't construct a query for the property \"" + propertyName + "\" of \"" + stringifyType(typeOrFunc) + "\" since the query selector wasn't defined."), typeOrFunc);
21743 selectors = [];
21744 }
21745 else {
21746 selectors = [this._getTokenMetadata(q.selector)];
21747 }
21748 }
21749 return {
21750 selectors: selectors,
21751 first: q.first,
21752 descendants: q.descendants, propertyName: propertyName,
21753 read: q.read ? this._getTokenMetadata(q.read) : null,
21754 static: q.static
21755 };
21756 };
21757 CompileMetadataResolver.prototype._reportError = function (error, type, otherType) {
21758 if (this._errorCollector) {
21759 this._errorCollector(error, type);
21760 if (otherType) {
21761 this._errorCollector(error, otherType);
21762 }
21763 }
21764 else {
21765 throw error;
21766 }
21767 };
21768 return CompileMetadataResolver;
21769}());
21770function flattenArray(tree, out) {
21771 if (out === void 0) { out = []; }
21772 if (tree) {
21773 for (var i = 0; i < tree.length; i++) {
21774 var item = resolveForwardRef(tree[i]);
21775 if (Array.isArray(item)) {
21776 flattenArray(item, out);
21777 }
21778 else {
21779 out.push(item);
21780 }
21781 }
21782 }
21783 return out;
21784}
21785function dedupeArray(array) {
21786 if (array) {
21787 return Array.from(new Set(array));
21788 }
21789 return [];
21790}
21791function flattenAndDedupeArray(tree) {
21792 return dedupeArray(flattenArray(tree));
21793}
21794function isValidType(value) {
21795 return (value instanceof StaticSymbol) || (value instanceof Type);
21796}
21797function extractIdentifiers(value, targetIdentifiers) {
21798 visitValue(value, new _CompileValueConverter(), targetIdentifiers);
21799}
21800var _CompileValueConverter = /** @class */ (function (_super) {
21801 __extends(_CompileValueConverter, _super);
21802 function _CompileValueConverter() {
21803 return _super !== null && _super.apply(this, arguments) || this;
21804 }
21805 _CompileValueConverter.prototype.visitOther = function (value, targetIdentifiers) {
21806 targetIdentifiers.push({ reference: value });
21807 };
21808 return _CompileValueConverter;
21809}(ValueTransformer));
21810function stringifyType(type) {
21811 if (type instanceof StaticSymbol) {
21812 return type.name + " in " + type.filePath;
21813 }
21814 else {
21815 return stringify(type);
21816 }
21817}
21818/**
21819 * Indicates that a component is still being loaded in a synchronous compile.
21820 */
21821function componentStillLoadingError(compType) {
21822 var error = Error("Can't compile synchronously as " + stringify(compType) + " is still being loaded!");
21823 error[ERROR_COMPONENT_TYPE] = compType;
21824 return error;
21825}
21826
21827/**
21828 * @license
21829 * Copyright Google Inc. All Rights Reserved.
21830 *
21831 * Use of this source code is governed by an MIT-style license that can be
21832 * found in the LICENSE file at https://angular.io/license
21833 */
21834function providerDef(ctx, providerAst) {
21835 var flags = 0 /* None */;
21836 if (!providerAst.eager) {
21837 flags |= 4096 /* LazyProvider */;
21838 }
21839 if (providerAst.providerType === ProviderAstType.PrivateService) {
21840 flags |= 8192 /* PrivateProvider */;
21841 }
21842 if (providerAst.isModule) {
21843 flags |= 1073741824 /* TypeModuleProvider */;
21844 }
21845 providerAst.lifecycleHooks.forEach(function (lifecycleHook) {
21846 // for regular providers, we only support ngOnDestroy
21847 if (lifecycleHook === LifecycleHooks.OnDestroy ||
21848 providerAst.providerType === ProviderAstType.Directive ||
21849 providerAst.providerType === ProviderAstType.Component) {
21850 flags |= lifecycleHookToNodeFlag(lifecycleHook);
21851 }
21852 });
21853 var _a = providerAst.multiProvider ?
21854 multiProviderDef(ctx, flags, providerAst.providers) :
21855 singleProviderDef(ctx, flags, providerAst.providerType, providerAst.providers[0]), providerExpr = _a.providerExpr, providerFlags = _a.flags, depsExpr = _a.depsExpr;
21856 return {
21857 providerExpr: providerExpr,
21858 flags: providerFlags, depsExpr: depsExpr,
21859 tokenExpr: tokenExpr(ctx, providerAst.token),
21860 };
21861}
21862function multiProviderDef(ctx, flags, providers) {
21863 var allDepDefs = [];
21864 var allParams = [];
21865 var exprs = providers.map(function (provider, providerIndex) {
21866 var expr;
21867 if (provider.useClass) {
21868 var depExprs = convertDeps(providerIndex, provider.deps || provider.useClass.diDeps);
21869 expr = ctx.importExpr(provider.useClass.reference).instantiate(depExprs);
21870 }
21871 else if (provider.useFactory) {
21872 var depExprs = convertDeps(providerIndex, provider.deps || provider.useFactory.diDeps);
21873 expr = ctx.importExpr(provider.useFactory.reference).callFn(depExprs);
21874 }
21875 else if (provider.useExisting) {
21876 var depExprs = convertDeps(providerIndex, [{ token: provider.useExisting }]);
21877 expr = depExprs[0];
21878 }
21879 else {
21880 expr = convertValueToOutputAst(ctx, provider.useValue);
21881 }
21882 return expr;
21883 });
21884 var providerExpr = fn(allParams, [new ReturnStatement(literalArr(exprs))], INFERRED_TYPE);
21885 return {
21886 providerExpr: providerExpr,
21887 flags: flags | 1024 /* TypeFactoryProvider */,
21888 depsExpr: literalArr(allDepDefs)
21889 };
21890 function convertDeps(providerIndex, deps) {
21891 return deps.map(function (dep, depIndex) {
21892 var paramName = "p" + providerIndex + "_" + depIndex;
21893 allParams.push(new FnParam(paramName, DYNAMIC_TYPE));
21894 allDepDefs.push(depDef(ctx, dep));
21895 return variable(paramName);
21896 });
21897 }
21898}
21899function singleProviderDef(ctx, flags, providerType, providerMeta) {
21900 var providerExpr;
21901 var deps;
21902 if (providerType === ProviderAstType.Directive || providerType === ProviderAstType.Component) {
21903 providerExpr = ctx.importExpr(providerMeta.useClass.reference);
21904 flags |= 16384 /* TypeDirective */;
21905 deps = providerMeta.deps || providerMeta.useClass.diDeps;
21906 }
21907 else {
21908 if (providerMeta.useClass) {
21909 providerExpr = ctx.importExpr(providerMeta.useClass.reference);
21910 flags |= 512 /* TypeClassProvider */;
21911 deps = providerMeta.deps || providerMeta.useClass.diDeps;
21912 }
21913 else if (providerMeta.useFactory) {
21914 providerExpr = ctx.importExpr(providerMeta.useFactory.reference);
21915 flags |= 1024 /* TypeFactoryProvider */;
21916 deps = providerMeta.deps || providerMeta.useFactory.diDeps;
21917 }
21918 else if (providerMeta.useExisting) {
21919 providerExpr = NULL_EXPR;
21920 flags |= 2048 /* TypeUseExistingProvider */;
21921 deps = [{ token: providerMeta.useExisting }];
21922 }
21923 else {
21924 providerExpr = convertValueToOutputAst(ctx, providerMeta.useValue);
21925 flags |= 256 /* TypeValueProvider */;
21926 deps = [];
21927 }
21928 }
21929 var depsExpr = literalArr(deps.map(function (dep) { return depDef(ctx, dep); }));
21930 return { providerExpr: providerExpr, flags: flags, depsExpr: depsExpr };
21931}
21932function tokenExpr(ctx, tokenMeta) {
21933 return tokenMeta.identifier ? ctx.importExpr(tokenMeta.identifier.reference) :
21934 literal(tokenMeta.value);
21935}
21936function depDef(ctx, dep) {
21937 // Note: the following fields have already been normalized out by provider_analyzer:
21938 // - isAttribute, isHost
21939 var expr = dep.isValue ? convertValueToOutputAst(ctx, dep.value) : tokenExpr(ctx, dep.token);
21940 var flags = 0 /* None */;
21941 if (dep.isSkipSelf) {
21942 flags |= 1 /* SkipSelf */;
21943 }
21944 if (dep.isOptional) {
21945 flags |= 2 /* Optional */;
21946 }
21947 if (dep.isSelf) {
21948 flags |= 4 /* Self */;
21949 }
21950 if (dep.isValue) {
21951 flags |= 8 /* Value */;
21952 }
21953 return flags === 0 /* None */ ? expr : literalArr([literal(flags), expr]);
21954}
21955function lifecycleHookToNodeFlag(lifecycleHook) {
21956 var nodeFlag = 0 /* None */;
21957 switch (lifecycleHook) {
21958 case LifecycleHooks.AfterContentChecked:
21959 nodeFlag = 2097152 /* AfterContentChecked */;
21960 break;
21961 case LifecycleHooks.AfterContentInit:
21962 nodeFlag = 1048576 /* AfterContentInit */;
21963 break;
21964 case LifecycleHooks.AfterViewChecked:
21965 nodeFlag = 8388608 /* AfterViewChecked */;
21966 break;
21967 case LifecycleHooks.AfterViewInit:
21968 nodeFlag = 4194304 /* AfterViewInit */;
21969 break;
21970 case LifecycleHooks.DoCheck:
21971 nodeFlag = 262144 /* DoCheck */;
21972 break;
21973 case LifecycleHooks.OnChanges:
21974 nodeFlag = 524288 /* OnChanges */;
21975 break;
21976 case LifecycleHooks.OnDestroy:
21977 nodeFlag = 131072 /* OnDestroy */;
21978 break;
21979 case LifecycleHooks.OnInit:
21980 nodeFlag = 65536 /* OnInit */;
21981 break;
21982 }
21983 return nodeFlag;
21984}
21985function componentFactoryResolverProviderDef(reflector, ctx, flags, entryComponents) {
21986 var entryComponentFactories = entryComponents.map(function (entryComponent) { return ctx.importExpr(entryComponent.componentFactory); });
21987 var token = createTokenForExternalReference(reflector, Identifiers.ComponentFactoryResolver);
21988 var classMeta = {
21989 diDeps: [
21990 { isValue: true, value: literalArr(entryComponentFactories) },
21991 { token: token, isSkipSelf: true, isOptional: true },
21992 { token: createTokenForExternalReference(reflector, Identifiers.NgModuleRef) },
21993 ],
21994 lifecycleHooks: [],
21995 reference: reflector.resolveExternalReference(Identifiers.CodegenComponentFactoryResolver)
21996 };
21997 var _a = singleProviderDef(ctx, flags, ProviderAstType.PrivateService, {
21998 token: token,
21999 multi: false,
22000 useClass: classMeta,
22001 }), providerExpr = _a.providerExpr, providerFlags = _a.flags, depsExpr = _a.depsExpr;
22002 return { providerExpr: providerExpr, flags: providerFlags, depsExpr: depsExpr, tokenExpr: tokenExpr(ctx, token) };
22003}
22004
22005/**
22006 * @license
22007 * Copyright Google Inc. All Rights Reserved.
22008 *
22009 * Use of this source code is governed by an MIT-style license that can be
22010 * found in the LICENSE file at https://angular.io/license
22011 */
22012var NgModuleCompileResult = /** @class */ (function () {
22013 function NgModuleCompileResult(ngModuleFactoryVar) {
22014 this.ngModuleFactoryVar = ngModuleFactoryVar;
22015 }
22016 return NgModuleCompileResult;
22017}());
22018var LOG_VAR = variable('_l');
22019var NgModuleCompiler = /** @class */ (function () {
22020 function NgModuleCompiler(reflector) {
22021 this.reflector = reflector;
22022 }
22023 NgModuleCompiler.prototype.compile = function (ctx, ngModuleMeta, extraProviders) {
22024 var sourceSpan = typeSourceSpan('NgModule', ngModuleMeta.type);
22025 var entryComponentFactories = ngModuleMeta.transitiveModule.entryComponents;
22026 var bootstrapComponents = ngModuleMeta.bootstrapComponents;
22027 var providerParser = new NgModuleProviderAnalyzer(this.reflector, ngModuleMeta, extraProviders, sourceSpan);
22028 var providerDefs = [componentFactoryResolverProviderDef(this.reflector, ctx, 0 /* None */, entryComponentFactories)]
22029 .concat(providerParser.parse().map(function (provider) { return providerDef(ctx, provider); }))
22030 .map(function (_a) {
22031 var providerExpr = _a.providerExpr, depsExpr = _a.depsExpr, flags = _a.flags, tokenExpr = _a.tokenExpr;
22032 return importExpr(Identifiers.moduleProviderDef).callFn([
22033 literal(flags), tokenExpr, providerExpr, depsExpr
22034 ]);
22035 });
22036 var ngModuleDef = importExpr(Identifiers.moduleDef).callFn([literalArr(providerDefs)]);
22037 var ngModuleDefFactory = fn([new FnParam(LOG_VAR.name)], [new ReturnStatement(ngModuleDef)], INFERRED_TYPE);
22038 var ngModuleFactoryVar = identifierName(ngModuleMeta.type) + "NgFactory";
22039 this._createNgModuleFactory(ctx, ngModuleMeta.type.reference, importExpr(Identifiers.createModuleFactory).callFn([
22040 ctx.importExpr(ngModuleMeta.type.reference),
22041 literalArr(bootstrapComponents.map(function (id) { return ctx.importExpr(id.reference); })),
22042 ngModuleDefFactory
22043 ]));
22044 if (ngModuleMeta.id) {
22045 var id = typeof ngModuleMeta.id === 'string' ? literal(ngModuleMeta.id) :
22046 ctx.importExpr(ngModuleMeta.id);
22047 var registerFactoryStmt = importExpr(Identifiers.RegisterModuleFactoryFn)
22048 .callFn([id, variable(ngModuleFactoryVar)])
22049 .toStmt();
22050 ctx.statements.push(registerFactoryStmt);
22051 }
22052 return new NgModuleCompileResult(ngModuleFactoryVar);
22053 };
22054 NgModuleCompiler.prototype.createStub = function (ctx, ngModuleReference) {
22055 this._createNgModuleFactory(ctx, ngModuleReference, NULL_EXPR);
22056 };
22057 NgModuleCompiler.prototype._createNgModuleFactory = function (ctx, reference, value) {
22058 var ngModuleFactoryVar = identifierName({ reference: reference }) + "NgFactory";
22059 var ngModuleFactoryStmt = variable(ngModuleFactoryVar)
22060 .set(value)
22061 .toDeclStmt(importType(Identifiers.NgModuleFactory, [expressionType(ctx.importExpr(reference))], [TypeModifier.Const]), [StmtModifier.Final, StmtModifier.Exported]);
22062 ctx.statements.push(ngModuleFactoryStmt);
22063 };
22064 return NgModuleCompiler;
22065}());
22066
22067/**
22068 * @license
22069 * Copyright Google Inc. All Rights Reserved.
22070 *
22071 * Use of this source code is governed by an MIT-style license that can be
22072 * found in the LICENSE file at https://angular.io/license
22073 */
22074/**
22075 * Resolves types to {@link NgModule}.
22076 */
22077var NgModuleResolver = /** @class */ (function () {
22078 function NgModuleResolver(_reflector) {
22079 this._reflector = _reflector;
22080 }
22081 NgModuleResolver.prototype.isNgModule = function (type) { return this._reflector.annotations(type).some(createNgModule.isTypeOf); };
22082 NgModuleResolver.prototype.resolve = function (type, throwIfNotFound) {
22083 if (throwIfNotFound === void 0) { throwIfNotFound = true; }
22084 var ngModuleMeta = findLast(this._reflector.annotations(type), createNgModule.isTypeOf);
22085 if (ngModuleMeta) {
22086 return ngModuleMeta;
22087 }
22088 else {
22089 if (throwIfNotFound) {
22090 throw new Error("No NgModule metadata found for '" + stringify(type) + "'.");
22091 }
22092 return null;
22093 }
22094 };
22095 return NgModuleResolver;
22096}());
22097
22098/**
22099 * @license
22100 * Copyright Google Inc. All Rights Reserved.
22101 *
22102 * Use of this source code is governed by an MIT-style license that can be
22103 * found in the LICENSE file at https://angular.io/license
22104 */
22105var _debugFilePath = '/debug/lib';
22106function debugOutputAstAsTypeScript(ast) {
22107 var converter = new _TsEmitterVisitor();
22108 var ctx = EmitterVisitorContext.createRoot();
22109 var asts = Array.isArray(ast) ? ast : [ast];
22110 asts.forEach(function (ast) {
22111 if (ast instanceof Statement) {
22112 ast.visitStatement(converter, ctx);
22113 }
22114 else if (ast instanceof Expression) {
22115 ast.visitExpression(converter, ctx);
22116 }
22117 else if (ast instanceof Type$1) {
22118 ast.visitType(converter, ctx);
22119 }
22120 else {
22121 throw new Error("Don't know how to print debug info for " + ast);
22122 }
22123 });
22124 return ctx.toSource();
22125}
22126var TypeScriptEmitter = /** @class */ (function () {
22127 function TypeScriptEmitter() {
22128 }
22129 TypeScriptEmitter.prototype.emitStatementsAndContext = function (genFilePath, stmts, preamble, emitSourceMaps, referenceFilter, importFilter) {
22130 if (preamble === void 0) { preamble = ''; }
22131 if (emitSourceMaps === void 0) { emitSourceMaps = true; }
22132 var converter = new _TsEmitterVisitor(referenceFilter, importFilter);
22133 var ctx = EmitterVisitorContext.createRoot();
22134 converter.visitAllStatements(stmts, ctx);
22135 var preambleLines = preamble ? preamble.split('\n') : [];
22136 converter.reexports.forEach(function (reexports, exportedModuleName) {
22137 var reexportsCode = reexports.map(function (reexport) { return reexport.name + " as " + reexport.as; }).join(',');
22138 preambleLines.push("export {" + reexportsCode + "} from '" + exportedModuleName + "';");
22139 });
22140 converter.importsWithPrefixes.forEach(function (prefix, importedModuleName) {
22141 // Note: can't write the real word for import as it screws up system.js auto detection...
22142 preambleLines.push("imp" +
22143 ("ort * as " + prefix + " from '" + importedModuleName + "';"));
22144 });
22145 var sm = emitSourceMaps ?
22146 ctx.toSourceMapGenerator(genFilePath, preambleLines.length).toJsComment() :
22147 '';
22148 var lines = __spread(preambleLines, [ctx.toSource(), sm]);
22149 if (sm) {
22150 // always add a newline at the end, as some tools have bugs without it.
22151 lines.push('');
22152 }
22153 ctx.setPreambleLineCount(preambleLines.length);
22154 return { sourceText: lines.join('\n'), context: ctx };
22155 };
22156 TypeScriptEmitter.prototype.emitStatements = function (genFilePath, stmts, preamble) {
22157 if (preamble === void 0) { preamble = ''; }
22158 return this.emitStatementsAndContext(genFilePath, stmts, preamble).sourceText;
22159 };
22160 return TypeScriptEmitter;
22161}());
22162var _TsEmitterVisitor = /** @class */ (function (_super) {
22163 __extends(_TsEmitterVisitor, _super);
22164 function _TsEmitterVisitor(referenceFilter, importFilter) {
22165 var _this = _super.call(this, false) || this;
22166 _this.referenceFilter = referenceFilter;
22167 _this.importFilter = importFilter;
22168 _this.typeExpression = 0;
22169 _this.importsWithPrefixes = new Map();
22170 _this.reexports = new Map();
22171 return _this;
22172 }
22173 _TsEmitterVisitor.prototype.visitType = function (t, ctx, defaultType) {
22174 if (defaultType === void 0) { defaultType = 'any'; }
22175 if (t) {
22176 this.typeExpression++;
22177 t.visitType(this, ctx);
22178 this.typeExpression--;
22179 }
22180 else {
22181 ctx.print(null, defaultType);
22182 }
22183 };
22184 _TsEmitterVisitor.prototype.visitLiteralExpr = function (ast, ctx) {
22185 var value = ast.value;
22186 if (value == null && ast.type != INFERRED_TYPE) {
22187 ctx.print(ast, "(" + value + " as any)");
22188 return null;
22189 }
22190 return _super.prototype.visitLiteralExpr.call(this, ast, ctx);
22191 };
22192 // Temporary workaround to support strictNullCheck enabled consumers of ngc emit.
22193 // In SNC mode, [] have the type never[], so we cast here to any[].
22194 // TODO: narrow the cast to a more explicit type, or use a pattern that does not
22195 // start with [].concat. see https://github.com/angular/angular/pull/11846
22196 _TsEmitterVisitor.prototype.visitLiteralArrayExpr = function (ast, ctx) {
22197 if (ast.entries.length === 0) {
22198 ctx.print(ast, '(');
22199 }
22200 var result = _super.prototype.visitLiteralArrayExpr.call(this, ast, ctx);
22201 if (ast.entries.length === 0) {
22202 ctx.print(ast, ' as any[])');
22203 }
22204 return result;
22205 };
22206 _TsEmitterVisitor.prototype.visitExternalExpr = function (ast, ctx) {
22207 this._visitIdentifier(ast.value, ast.typeParams, ctx);
22208 return null;
22209 };
22210 _TsEmitterVisitor.prototype.visitAssertNotNullExpr = function (ast, ctx) {
22211 var result = _super.prototype.visitAssertNotNullExpr.call(this, ast, ctx);
22212 ctx.print(ast, '!');
22213 return result;
22214 };
22215 _TsEmitterVisitor.prototype.visitDeclareVarStmt = function (stmt, ctx) {
22216 if (stmt.hasModifier(StmtModifier.Exported) && stmt.value instanceof ExternalExpr &&
22217 !stmt.type) {
22218 // check for a reexport
22219 var _a = stmt.value.value, name_1 = _a.name, moduleName = _a.moduleName;
22220 if (moduleName) {
22221 var reexports = this.reexports.get(moduleName);
22222 if (!reexports) {
22223 reexports = [];
22224 this.reexports.set(moduleName, reexports);
22225 }
22226 reexports.push({ name: name_1, as: stmt.name });
22227 return null;
22228 }
22229 }
22230 if (stmt.hasModifier(StmtModifier.Exported)) {
22231 ctx.print(stmt, "export ");
22232 }
22233 if (stmt.hasModifier(StmtModifier.Final)) {
22234 ctx.print(stmt, "const");
22235 }
22236 else {
22237 ctx.print(stmt, "var");
22238 }
22239 ctx.print(stmt, " " + stmt.name);
22240 this._printColonType(stmt.type, ctx);
22241 if (stmt.value) {
22242 ctx.print(stmt, " = ");
22243 stmt.value.visitExpression(this, ctx);
22244 }
22245 ctx.println(stmt, ";");
22246 return null;
22247 };
22248 _TsEmitterVisitor.prototype.visitWrappedNodeExpr = function (ast, ctx) {
22249 throw new Error('Cannot visit a WrappedNodeExpr when outputting Typescript.');
22250 };
22251 _TsEmitterVisitor.prototype.visitCastExpr = function (ast, ctx) {
22252 ctx.print(ast, "(<");
22253 ast.type.visitType(this, ctx);
22254 ctx.print(ast, ">");
22255 ast.value.visitExpression(this, ctx);
22256 ctx.print(ast, ")");
22257 return null;
22258 };
22259 _TsEmitterVisitor.prototype.visitInstantiateExpr = function (ast, ctx) {
22260 ctx.print(ast, "new ");
22261 this.typeExpression++;
22262 ast.classExpr.visitExpression(this, ctx);
22263 this.typeExpression--;
22264 ctx.print(ast, "(");
22265 this.visitAllExpressions(ast.args, ctx, ',');
22266 ctx.print(ast, ")");
22267 return null;
22268 };
22269 _TsEmitterVisitor.prototype.visitDeclareClassStmt = function (stmt, ctx) {
22270 var _this = this;
22271 ctx.pushClass(stmt);
22272 if (stmt.hasModifier(StmtModifier.Exported)) {
22273 ctx.print(stmt, "export ");
22274 }
22275 ctx.print(stmt, "class " + stmt.name);
22276 if (stmt.parent != null) {
22277 ctx.print(stmt, " extends ");
22278 this.typeExpression++;
22279 stmt.parent.visitExpression(this, ctx);
22280 this.typeExpression--;
22281 }
22282 ctx.println(stmt, " {");
22283 ctx.incIndent();
22284 stmt.fields.forEach(function (field) { return _this._visitClassField(field, ctx); });
22285 if (stmt.constructorMethod != null) {
22286 this._visitClassConstructor(stmt, ctx);
22287 }
22288 stmt.getters.forEach(function (getter) { return _this._visitClassGetter(getter, ctx); });
22289 stmt.methods.forEach(function (method) { return _this._visitClassMethod(method, ctx); });
22290 ctx.decIndent();
22291 ctx.println(stmt, "}");
22292 ctx.popClass();
22293 return null;
22294 };
22295 _TsEmitterVisitor.prototype._visitClassField = function (field, ctx) {
22296 if (field.hasModifier(StmtModifier.Private)) {
22297 // comment out as a workaround for #10967
22298 ctx.print(null, "/*private*/ ");
22299 }
22300 if (field.hasModifier(StmtModifier.Static)) {
22301 ctx.print(null, 'static ');
22302 }
22303 ctx.print(null, field.name);
22304 this._printColonType(field.type, ctx);
22305 if (field.initializer) {
22306 ctx.print(null, ' = ');
22307 field.initializer.visitExpression(this, ctx);
22308 }
22309 ctx.println(null, ";");
22310 };
22311 _TsEmitterVisitor.prototype._visitClassGetter = function (getter, ctx) {
22312 if (getter.hasModifier(StmtModifier.Private)) {
22313 ctx.print(null, "private ");
22314 }
22315 ctx.print(null, "get " + getter.name + "()");
22316 this._printColonType(getter.type, ctx);
22317 ctx.println(null, " {");
22318 ctx.incIndent();
22319 this.visitAllStatements(getter.body, ctx);
22320 ctx.decIndent();
22321 ctx.println(null, "}");
22322 };
22323 _TsEmitterVisitor.prototype._visitClassConstructor = function (stmt, ctx) {
22324 ctx.print(stmt, "constructor(");
22325 this._visitParams(stmt.constructorMethod.params, ctx);
22326 ctx.println(stmt, ") {");
22327 ctx.incIndent();
22328 this.visitAllStatements(stmt.constructorMethod.body, ctx);
22329 ctx.decIndent();
22330 ctx.println(stmt, "}");
22331 };
22332 _TsEmitterVisitor.prototype._visitClassMethod = function (method, ctx) {
22333 if (method.hasModifier(StmtModifier.Private)) {
22334 ctx.print(null, "private ");
22335 }
22336 ctx.print(null, method.name + "(");
22337 this._visitParams(method.params, ctx);
22338 ctx.print(null, ")");
22339 this._printColonType(method.type, ctx, 'void');
22340 ctx.println(null, " {");
22341 ctx.incIndent();
22342 this.visitAllStatements(method.body, ctx);
22343 ctx.decIndent();
22344 ctx.println(null, "}");
22345 };
22346 _TsEmitterVisitor.prototype.visitFunctionExpr = function (ast, ctx) {
22347 if (ast.name) {
22348 ctx.print(ast, 'function ');
22349 ctx.print(ast, ast.name);
22350 }
22351 ctx.print(ast, "(");
22352 this._visitParams(ast.params, ctx);
22353 ctx.print(ast, ")");
22354 this._printColonType(ast.type, ctx, 'void');
22355 if (!ast.name) {
22356 ctx.print(ast, " => ");
22357 }
22358 ctx.println(ast, '{');
22359 ctx.incIndent();
22360 this.visitAllStatements(ast.statements, ctx);
22361 ctx.decIndent();
22362 ctx.print(ast, "}");
22363 return null;
22364 };
22365 _TsEmitterVisitor.prototype.visitDeclareFunctionStmt = function (stmt, ctx) {
22366 if (stmt.hasModifier(StmtModifier.Exported)) {
22367 ctx.print(stmt, "export ");
22368 }
22369 ctx.print(stmt, "function " + stmt.name + "(");
22370 this._visitParams(stmt.params, ctx);
22371 ctx.print(stmt, ")");
22372 this._printColonType(stmt.type, ctx, 'void');
22373 ctx.println(stmt, " {");
22374 ctx.incIndent();
22375 this.visitAllStatements(stmt.statements, ctx);
22376 ctx.decIndent();
22377 ctx.println(stmt, "}");
22378 return null;
22379 };
22380 _TsEmitterVisitor.prototype.visitTryCatchStmt = function (stmt, ctx) {
22381 ctx.println(stmt, "try {");
22382 ctx.incIndent();
22383 this.visitAllStatements(stmt.bodyStmts, ctx);
22384 ctx.decIndent();
22385 ctx.println(stmt, "} catch (" + CATCH_ERROR_VAR$1.name + ") {");
22386 ctx.incIndent();
22387 var catchStmts = [CATCH_STACK_VAR$1.set(CATCH_ERROR_VAR$1.prop('stack', null)).toDeclStmt(null, [
22388 StmtModifier.Final
22389 ])].concat(stmt.catchStmts);
22390 this.visitAllStatements(catchStmts, ctx);
22391 ctx.decIndent();
22392 ctx.println(stmt, "}");
22393 return null;
22394 };
22395 _TsEmitterVisitor.prototype.visitBuiltinType = function (type, ctx) {
22396 var typeStr;
22397 switch (type.name) {
22398 case BuiltinTypeName.Bool:
22399 typeStr = 'boolean';
22400 break;
22401 case BuiltinTypeName.Dynamic:
22402 typeStr = 'any';
22403 break;
22404 case BuiltinTypeName.Function:
22405 typeStr = 'Function';
22406 break;
22407 case BuiltinTypeName.Number:
22408 typeStr = 'number';
22409 break;
22410 case BuiltinTypeName.Int:
22411 typeStr = 'number';
22412 break;
22413 case BuiltinTypeName.String:
22414 typeStr = 'string';
22415 break;
22416 case BuiltinTypeName.None:
22417 typeStr = 'never';
22418 break;
22419 default:
22420 throw new Error("Unsupported builtin type " + type.name);
22421 }
22422 ctx.print(null, typeStr);
22423 return null;
22424 };
22425 _TsEmitterVisitor.prototype.visitExpressionType = function (ast, ctx) {
22426 var _this = this;
22427 ast.value.visitExpression(this, ctx);
22428 if (ast.typeParams !== null) {
22429 ctx.print(null, '<');
22430 this.visitAllObjects(function (type) { return _this.visitType(type, ctx); }, ast.typeParams, ctx, ',');
22431 ctx.print(null, '>');
22432 }
22433 return null;
22434 };
22435 _TsEmitterVisitor.prototype.visitArrayType = function (type, ctx) {
22436 this.visitType(type.of, ctx);
22437 ctx.print(null, "[]");
22438 return null;
22439 };
22440 _TsEmitterVisitor.prototype.visitMapType = function (type, ctx) {
22441 ctx.print(null, "{[key: string]:");
22442 this.visitType(type.valueType, ctx);
22443 ctx.print(null, "}");
22444 return null;
22445 };
22446 _TsEmitterVisitor.prototype.getBuiltinMethodName = function (method) {
22447 var name;
22448 switch (method) {
22449 case BuiltinMethod.ConcatArray:
22450 name = 'concat';
22451 break;
22452 case BuiltinMethod.SubscribeObservable:
22453 name = 'subscribe';
22454 break;
22455 case BuiltinMethod.Bind:
22456 name = 'bind';
22457 break;
22458 default:
22459 throw new Error("Unknown builtin method: " + method);
22460 }
22461 return name;
22462 };
22463 _TsEmitterVisitor.prototype._visitParams = function (params, ctx) {
22464 var _this = this;
22465 this.visitAllObjects(function (param) {
22466 ctx.print(null, param.name);
22467 _this._printColonType(param.type, ctx);
22468 }, params, ctx, ',');
22469 };
22470 _TsEmitterVisitor.prototype._visitIdentifier = function (value, typeParams, ctx) {
22471 var _this = this;
22472 var name = value.name, moduleName = value.moduleName;
22473 if (this.referenceFilter && this.referenceFilter(value)) {
22474 ctx.print(null, '(null as any)');
22475 return;
22476 }
22477 if (moduleName && (!this.importFilter || !this.importFilter(value))) {
22478 var prefix = this.importsWithPrefixes.get(moduleName);
22479 if (prefix == null) {
22480 prefix = "i" + this.importsWithPrefixes.size;
22481 this.importsWithPrefixes.set(moduleName, prefix);
22482 }
22483 ctx.print(null, prefix + ".");
22484 }
22485 ctx.print(null, name);
22486 if (this.typeExpression > 0) {
22487 // If we are in a type expression that refers to a generic type then supply
22488 // the required type parameters. If there were not enough type parameters
22489 // supplied, supply any as the type. Outside a type expression the reference
22490 // should not supply type parameters and be treated as a simple value reference
22491 // to the constructor function itself.
22492 var suppliedParameters = typeParams || [];
22493 if (suppliedParameters.length > 0) {
22494 ctx.print(null, "<");
22495 this.visitAllObjects(function (type) { return type.visitType(_this, ctx); }, typeParams, ctx, ',');
22496 ctx.print(null, ">");
22497 }
22498 }
22499 };
22500 _TsEmitterVisitor.prototype._printColonType = function (type, ctx, defaultType) {
22501 if (type !== INFERRED_TYPE) {
22502 ctx.print(null, ':');
22503 this.visitType(type, ctx, defaultType);
22504 }
22505 };
22506 return _TsEmitterVisitor;
22507}(AbstractEmitterVisitor));
22508
22509/**
22510 * @license
22511 * Copyright Google Inc. All Rights Reserved.
22512 *
22513 * Use of this source code is governed by an MIT-style license that can be
22514 * found in the LICENSE file at https://angular.io/license
22515 */
22516/**
22517 * Resolve a `Type` for {@link Pipe}.
22518 *
22519 * This interface can be overridden by the application developer to create custom behavior.
22520 *
22521 * See {@link Compiler}
22522 */
22523var PipeResolver = /** @class */ (function () {
22524 function PipeResolver(_reflector) {
22525 this._reflector = _reflector;
22526 }
22527 PipeResolver.prototype.isPipe = function (type) {
22528 var typeMetadata = this._reflector.annotations(resolveForwardRef(type));
22529 return typeMetadata && typeMetadata.some(createPipe.isTypeOf);
22530 };
22531 /**
22532 * Return {@link Pipe} for a given `Type`.
22533 */
22534 PipeResolver.prototype.resolve = function (type, throwIfNotFound) {
22535 if (throwIfNotFound === void 0) { throwIfNotFound = true; }
22536 var metas = this._reflector.annotations(resolveForwardRef(type));
22537 if (metas) {
22538 var annotation = findLast(metas, createPipe.isTypeOf);
22539 if (annotation) {
22540 return annotation;
22541 }
22542 }
22543 if (throwIfNotFound) {
22544 throw new Error("No Pipe decorator found on " + stringify(type));
22545 }
22546 return null;
22547 };
22548 return PipeResolver;
22549}());
22550
22551/**
22552 * @license
22553 * Copyright Google Inc. All Rights Reserved.
22554 *
22555 * Use of this source code is governed by an MIT-style license that can be
22556 * found in the LICENSE file at https://angular.io/license
22557 */
22558/**
22559 * Generates code that is used to type check templates.
22560 */
22561var TypeCheckCompiler = /** @class */ (function () {
22562 function TypeCheckCompiler(options, reflector) {
22563 this.options = options;
22564 this.reflector = reflector;
22565 }
22566 /**
22567 * Important notes:
22568 * - This must not produce new `import` statements, but only refer to types outside
22569 * of the file via the variables provided via externalReferenceVars.
22570 * This allows Typescript to reuse the old program's structure as no imports have changed.
22571 * - This must not produce any exports, as this would pollute the .d.ts file
22572 * and also violate the point above.
22573 */
22574 TypeCheckCompiler.prototype.compileComponent = function (componentId, component, template, usedPipes, externalReferenceVars, ctx) {
22575 var _this = this;
22576 var pipes = new Map();
22577 usedPipes.forEach(function (p) { return pipes.set(p.name, p.type.reference); });
22578 var embeddedViewCount = 0;
22579 var viewBuilderFactory = function (parent, guards) {
22580 var embeddedViewIndex = embeddedViewCount++;
22581 return new ViewBuilder(_this.options, _this.reflector, externalReferenceVars, parent, component.type.reference, component.isHost, embeddedViewIndex, pipes, guards, ctx, viewBuilderFactory);
22582 };
22583 var visitor = viewBuilderFactory(null, []);
22584 visitor.visitAll([], template);
22585 return visitor.build(componentId);
22586 };
22587 return TypeCheckCompiler;
22588}());
22589var DYNAMIC_VAR_NAME = '_any';
22590var TypeCheckLocalResolver = /** @class */ (function () {
22591 function TypeCheckLocalResolver() {
22592 }
22593 TypeCheckLocalResolver.prototype.notifyImplicitReceiverUse = function () { };
22594 TypeCheckLocalResolver.prototype.getLocal = function (name) {
22595 if (name === EventHandlerVars.event.name) {
22596 // References to the event should not be type-checked.
22597 // TODO(chuckj): determine a better type for the event.
22598 return variable(DYNAMIC_VAR_NAME);
22599 }
22600 return null;
22601 };
22602 return TypeCheckLocalResolver;
22603}());
22604var defaultResolver = new TypeCheckLocalResolver();
22605var ViewBuilder = /** @class */ (function () {
22606 function ViewBuilder(options, reflector, externalReferenceVars, parent, component, isHostComponent, embeddedViewIndex, pipes, guards, ctx, viewBuilderFactory) {
22607 this.options = options;
22608 this.reflector = reflector;
22609 this.externalReferenceVars = externalReferenceVars;
22610 this.parent = parent;
22611 this.component = component;
22612 this.isHostComponent = isHostComponent;
22613 this.embeddedViewIndex = embeddedViewIndex;
22614 this.pipes = pipes;
22615 this.guards = guards;
22616 this.ctx = ctx;
22617 this.viewBuilderFactory = viewBuilderFactory;
22618 this.refOutputVars = new Map();
22619 this.variables = [];
22620 this.children = [];
22621 this.updates = [];
22622 this.actions = [];
22623 }
22624 ViewBuilder.prototype.getOutputVar = function (type) {
22625 var varName;
22626 if (type === this.component && this.isHostComponent) {
22627 varName = DYNAMIC_VAR_NAME;
22628 }
22629 else if (type instanceof StaticSymbol) {
22630 varName = this.externalReferenceVars.get(type);
22631 }
22632 else {
22633 varName = DYNAMIC_VAR_NAME;
22634 }
22635 if (!varName) {
22636 throw new Error("Illegal State: referring to a type without a variable " + JSON.stringify(type));
22637 }
22638 return varName;
22639 };
22640 ViewBuilder.prototype.getTypeGuardExpressions = function (ast) {
22641 var e_1, _a, e_2, _b;
22642 var result = __spread(this.guards);
22643 try {
22644 for (var _c = __values(ast.directives), _d = _c.next(); !_d.done; _d = _c.next()) {
22645 var directive = _d.value;
22646 try {
22647 for (var _e = (e_2 = void 0, __values(directive.inputs)), _f = _e.next(); !_f.done; _f = _e.next()) {
22648 var input = _f.value;
22649 var guard = directive.directive.guards[input.directiveName];
22650 if (guard) {
22651 var useIf = guard === 'UseIf';
22652 result.push({
22653 guard: guard,
22654 useIf: useIf,
22655 expression: { context: this.component, value: input.value }
22656 });
22657 }
22658 }
22659 }
22660 catch (e_2_1) { e_2 = { error: e_2_1 }; }
22661 finally {
22662 try {
22663 if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
22664 }
22665 finally { if (e_2) throw e_2.error; }
22666 }
22667 }
22668 }
22669 catch (e_1_1) { e_1 = { error: e_1_1 }; }
22670 finally {
22671 try {
22672 if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
22673 }
22674 finally { if (e_1) throw e_1.error; }
22675 }
22676 return result;
22677 };
22678 ViewBuilder.prototype.visitAll = function (variables, astNodes) {
22679 this.variables = variables;
22680 templateVisitAll(this, astNodes);
22681 };
22682 ViewBuilder.prototype.build = function (componentId, targetStatements) {
22683 var e_3, _a;
22684 var _this = this;
22685 if (targetStatements === void 0) { targetStatements = []; }
22686 this.children.forEach(function (child) { return child.build(componentId, targetStatements); });
22687 var viewStmts = [variable(DYNAMIC_VAR_NAME).set(NULL_EXPR).toDeclStmt(DYNAMIC_TYPE)];
22688 var bindingCount = 0;
22689 this.updates.forEach(function (expression) {
22690 var _a = _this.preprocessUpdateExpression(expression), sourceSpan = _a.sourceSpan, context = _a.context, value = _a.value;
22691 var bindingId = "" + bindingCount++;
22692 var nameResolver = context === _this.component ? _this : defaultResolver;
22693 var _b = convertPropertyBinding(nameResolver, variable(_this.getOutputVar(context)), value, bindingId, BindingForm.General), stmts = _b.stmts, currValExpr = _b.currValExpr;
22694 stmts.push(new ExpressionStatement(currValExpr));
22695 viewStmts.push.apply(viewStmts, __spread(stmts.map(function (stmt) { return applySourceSpanToStatementIfNeeded(stmt, sourceSpan); })));
22696 });
22697 this.actions.forEach(function (_a) {
22698 var sourceSpan = _a.sourceSpan, context = _a.context, value = _a.value;
22699 var bindingId = "" + bindingCount++;
22700 var nameResolver = context === _this.component ? _this : defaultResolver;
22701 var stmts = convertActionBinding(nameResolver, variable(_this.getOutputVar(context)), value, bindingId).stmts;
22702 viewStmts.push.apply(viewStmts, __spread(stmts.map(function (stmt) { return applySourceSpanToStatementIfNeeded(stmt, sourceSpan); })));
22703 });
22704 if (this.guards.length) {
22705 var guardExpression = undefined;
22706 try {
22707 for (var _b = __values(this.guards), _c = _b.next(); !_c.done; _c = _b.next()) {
22708 var guard = _c.value;
22709 var _d = this.preprocessUpdateExpression(guard.expression), context = _d.context, value = _d.value;
22710 var bindingId = "" + bindingCount++;
22711 var nameResolver = context === this.component ? this : defaultResolver;
22712 // We only support support simple expressions and ignore others as they
22713 // are unlikely to affect type narrowing.
22714 var _e = convertPropertyBinding(nameResolver, variable(this.getOutputVar(context)), value, bindingId, BindingForm.TrySimple), stmts = _e.stmts, currValExpr = _e.currValExpr;
22715 if (stmts.length == 0) {
22716 var guardClause = guard.useIf ? currValExpr : this.ctx.importExpr(guard.guard).callFn([currValExpr]);
22717 guardExpression = guardExpression ? guardExpression.and(guardClause) : guardClause;
22718 }
22719 }
22720 }
22721 catch (e_3_1) { e_3 = { error: e_3_1 }; }
22722 finally {
22723 try {
22724 if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
22725 }
22726 finally { if (e_3) throw e_3.error; }
22727 }
22728 if (guardExpression) {
22729 viewStmts = [new IfStmt(guardExpression, viewStmts)];
22730 }
22731 }
22732 var viewName = "_View_" + componentId + "_" + this.embeddedViewIndex;
22733 var viewFactory = new DeclareFunctionStmt(viewName, [], viewStmts);
22734 targetStatements.push(viewFactory);
22735 return targetStatements;
22736 };
22737 ViewBuilder.prototype.visitBoundText = function (ast, context) {
22738 var _this = this;
22739 var astWithSource = ast.value;
22740 var inter = astWithSource.ast;
22741 inter.expressions.forEach(function (expr) {
22742 return _this.updates.push({ context: _this.component, value: expr, sourceSpan: ast.sourceSpan });
22743 });
22744 };
22745 ViewBuilder.prototype.visitEmbeddedTemplate = function (ast, context) {
22746 this.visitElementOrTemplate(ast);
22747 // Note: The old view compiler used to use an `any` type
22748 // for the context in any embedded view.
22749 // We keep this behaivor behind a flag for now.
22750 if (this.options.fullTemplateTypeCheck) {
22751 // Find any applicable type guards. For example, NgIf has a type guard on ngIf
22752 // (see NgIf.ngIfTypeGuard) that can be used to indicate that a template is only
22753 // stamped out if ngIf is truthy so any bindings in the template can assume that,
22754 // if a nullable type is used for ngIf, that expression is not null or undefined.
22755 var guards = this.getTypeGuardExpressions(ast);
22756 var childVisitor = this.viewBuilderFactory(this, guards);
22757 this.children.push(childVisitor);
22758 childVisitor.visitAll(ast.variables, ast.children);
22759 }
22760 };
22761 ViewBuilder.prototype.visitElement = function (ast, context) {
22762 var _this = this;
22763 this.visitElementOrTemplate(ast);
22764 var inputDefs = [];
22765 var updateRendererExpressions = [];
22766 var outputDefs = [];
22767 ast.inputs.forEach(function (inputAst) {
22768 _this.updates.push({ context: _this.component, value: inputAst.value, sourceSpan: inputAst.sourceSpan });
22769 });
22770 templateVisitAll(this, ast.children);
22771 };
22772 ViewBuilder.prototype.visitElementOrTemplate = function (ast) {
22773 var _this = this;
22774 ast.directives.forEach(function (dirAst) { _this.visitDirective(dirAst); });
22775 ast.references.forEach(function (ref) {
22776 var outputVarType = null;
22777 // Note: The old view compiler used to use an `any` type
22778 // for directives exposed via `exportAs`.
22779 // We keep this behaivor behind a flag for now.
22780 if (ref.value && ref.value.identifier && _this.options.fullTemplateTypeCheck) {
22781 outputVarType = ref.value.identifier.reference;
22782 }
22783 else {
22784 outputVarType = BuiltinTypeName.Dynamic;
22785 }
22786 _this.refOutputVars.set(ref.name, outputVarType);
22787 });
22788 ast.outputs.forEach(function (outputAst) {
22789 _this.actions.push({ context: _this.component, value: outputAst.handler, sourceSpan: outputAst.sourceSpan });
22790 });
22791 };
22792 ViewBuilder.prototype.visitDirective = function (dirAst) {
22793 var _this = this;
22794 var dirType = dirAst.directive.type.reference;
22795 dirAst.inputs.forEach(function (input) { return _this.updates.push({ context: _this.component, value: input.value, sourceSpan: input.sourceSpan }); });
22796 // Note: The old view compiler used to use an `any` type
22797 // for expressions in host properties / events.
22798 // We keep this behaivor behind a flag for now.
22799 if (this.options.fullTemplateTypeCheck) {
22800 dirAst.hostProperties.forEach(function (inputAst) { return _this.updates.push({ context: dirType, value: inputAst.value, sourceSpan: inputAst.sourceSpan }); });
22801 dirAst.hostEvents.forEach(function (hostEventAst) { return _this.actions.push({
22802 context: dirType,
22803 value: hostEventAst.handler,
22804 sourceSpan: hostEventAst.sourceSpan
22805 }); });
22806 }
22807 };
22808 ViewBuilder.prototype.notifyImplicitReceiverUse = function () { };
22809 ViewBuilder.prototype.getLocal = function (name) {
22810 if (name == EventHandlerVars.event.name) {
22811 return variable(this.getOutputVar(BuiltinTypeName.Dynamic));
22812 }
22813 for (var currBuilder = this; currBuilder; currBuilder = currBuilder.parent) {
22814 var outputVarType = void 0;
22815 // check references
22816 outputVarType = currBuilder.refOutputVars.get(name);
22817 if (outputVarType == null) {
22818 // check variables
22819 var varAst = currBuilder.variables.find(function (varAst) { return varAst.name === name; });
22820 if (varAst) {
22821 outputVarType = BuiltinTypeName.Dynamic;
22822 }
22823 }
22824 if (outputVarType != null) {
22825 return variable(this.getOutputVar(outputVarType));
22826 }
22827 }
22828 return null;
22829 };
22830 ViewBuilder.prototype.pipeOutputVar = function (name) {
22831 var pipe = this.pipes.get(name);
22832 if (!pipe) {
22833 throw new Error("Illegal State: Could not find pipe " + name + " in template of " + this.component);
22834 }
22835 return this.getOutputVar(pipe);
22836 };
22837 ViewBuilder.prototype.preprocessUpdateExpression = function (expression) {
22838 var _this = this;
22839 return {
22840 sourceSpan: expression.sourceSpan,
22841 context: expression.context,
22842 value: convertPropertyBindingBuiltins({
22843 createLiteralArrayConverter: function (argCount) { return function (args) {
22844 var arr = literalArr(args);
22845 // Note: The old view compiler used to use an `any` type
22846 // for arrays.
22847 return _this.options.fullTemplateTypeCheck ? arr : arr.cast(DYNAMIC_TYPE);
22848 }; },
22849 createLiteralMapConverter: function (keys) { return function (values) {
22850 var entries = keys.map(function (k, i) { return ({
22851 key: k.key,
22852 value: values[i],
22853 quoted: k.quoted,
22854 }); });
22855 var map = literalMap(entries);
22856 // Note: The old view compiler used to use an `any` type
22857 // for maps.
22858 return _this.options.fullTemplateTypeCheck ? map : map.cast(DYNAMIC_TYPE);
22859 }; },
22860 createPipeConverter: function (name, argCount) { return function (args) {
22861 // Note: The old view compiler used to use an `any` type
22862 // for pipes.
22863 var pipeExpr = _this.options.fullTemplateTypeCheck ?
22864 variable(_this.pipeOutputVar(name)) :
22865 variable(_this.getOutputVar(BuiltinTypeName.Dynamic));
22866 return pipeExpr.callMethod('transform', args);
22867 }; },
22868 }, expression.value)
22869 };
22870 };
22871 ViewBuilder.prototype.visitNgContent = function (ast, context) { };
22872 ViewBuilder.prototype.visitText = function (ast, context) { };
22873 ViewBuilder.prototype.visitDirectiveProperty = function (ast, context) { };
22874 ViewBuilder.prototype.visitReference = function (ast, context) { };
22875 ViewBuilder.prototype.visitVariable = function (ast, context) { };
22876 ViewBuilder.prototype.visitEvent = function (ast, context) { };
22877 ViewBuilder.prototype.visitElementProperty = function (ast, context) { };
22878 ViewBuilder.prototype.visitAttr = function (ast, context) { };
22879 return ViewBuilder;
22880}());
22881
22882/**
22883 * @license
22884 * Copyright Google Inc. All Rights Reserved.
22885 *
22886 * Use of this source code is governed by an MIT-style license that can be
22887 * found in the LICENSE file at https://angular.io/license
22888 */
22889var CLASS_ATTR$1 = 'class';
22890var STYLE_ATTR = 'style';
22891var IMPLICIT_TEMPLATE_VAR = '\$implicit';
22892var ViewCompileResult = /** @class */ (function () {
22893 function ViewCompileResult(viewClassVar, rendererTypeVar) {
22894 this.viewClassVar = viewClassVar;
22895 this.rendererTypeVar = rendererTypeVar;
22896 }
22897 return ViewCompileResult;
22898}());
22899var ViewCompiler = /** @class */ (function () {
22900 function ViewCompiler(_reflector) {
22901 this._reflector = _reflector;
22902 }
22903 ViewCompiler.prototype.compileComponent = function (outputCtx, component, template, styles, usedPipes) {
22904 var _a;
22905 var _this = this;
22906 var embeddedViewCount = 0;
22907 var staticQueryIds = findStaticQueryIds(template);
22908 var renderComponentVarName = undefined;
22909 if (!component.isHost) {
22910 var template_1 = component.template;
22911 var customRenderData = [];
22912 if (template_1.animations && template_1.animations.length) {
22913 customRenderData.push(new LiteralMapEntry('animation', convertValueToOutputAst(outputCtx, template_1.animations), true));
22914 }
22915 var renderComponentVar = variable(rendererTypeName(component.type.reference));
22916 renderComponentVarName = renderComponentVar.name;
22917 outputCtx.statements.push(renderComponentVar
22918 .set(importExpr(Identifiers.createRendererType2).callFn([new LiteralMapExpr([
22919 new LiteralMapEntry('encapsulation', literal(template_1.encapsulation), false),
22920 new LiteralMapEntry('styles', styles, false),
22921 new LiteralMapEntry('data', new LiteralMapExpr(customRenderData), false)
22922 ])]))
22923 .toDeclStmt(importType(Identifiers.RendererType2), [StmtModifier.Final, StmtModifier.Exported]));
22924 }
22925 var viewBuilderFactory = function (parent) {
22926 var embeddedViewIndex = embeddedViewCount++;
22927 return new ViewBuilder$1(_this._reflector, outputCtx, parent, component, embeddedViewIndex, usedPipes, staticQueryIds, viewBuilderFactory);
22928 };
22929 var visitor = viewBuilderFactory(null);
22930 visitor.visitAll([], template);
22931 (_a = outputCtx.statements).push.apply(_a, __spread(visitor.build()));
22932 return new ViewCompileResult(visitor.viewName, renderComponentVarName);
22933 };
22934 return ViewCompiler;
22935}());
22936var LOG_VAR$1 = variable('_l');
22937var VIEW_VAR = variable('_v');
22938var CHECK_VAR = variable('_ck');
22939var COMP_VAR = variable('_co');
22940var EVENT_NAME_VAR = variable('en');
22941var ALLOW_DEFAULT_VAR = variable("ad");
22942var ViewBuilder$1 = /** @class */ (function () {
22943 function ViewBuilder(reflector, outputCtx, parent, component, embeddedViewIndex, usedPipes, staticQueryIds, viewBuilderFactory) {
22944 this.reflector = reflector;
22945 this.outputCtx = outputCtx;
22946 this.parent = parent;
22947 this.component = component;
22948 this.embeddedViewIndex = embeddedViewIndex;
22949 this.usedPipes = usedPipes;
22950 this.staticQueryIds = staticQueryIds;
22951 this.viewBuilderFactory = viewBuilderFactory;
22952 this.nodes = [];
22953 this.purePipeNodeIndices = Object.create(null);
22954 // Need Object.create so that we don't have builtin values...
22955 this.refNodeIndices = Object.create(null);
22956 this.variables = [];
22957 this.children = [];
22958 // TODO(tbosch): The old view compiler used to use an `any` type
22959 // for the context in any embedded view. We keep this behaivor for now
22960 // to be able to introduce the new view compiler without too many errors.
22961 this.compType = this.embeddedViewIndex > 0 ?
22962 DYNAMIC_TYPE :
22963 expressionType(outputCtx.importExpr(this.component.type.reference));
22964 this.viewName = viewClassName(this.component.type.reference, this.embeddedViewIndex);
22965 }
22966 ViewBuilder.prototype.visitAll = function (variables, astNodes) {
22967 var _this = this;
22968 this.variables = variables;
22969 // create the pipes for the pure pipes immediately, so that we know their indices.
22970 if (!this.parent) {
22971 this.usedPipes.forEach(function (pipe) {
22972 if (pipe.pure) {
22973 _this.purePipeNodeIndices[pipe.name] = _this._createPipe(null, pipe);
22974 }
22975 });
22976 }
22977 if (!this.parent) {
22978 var queryIds_1 = staticViewQueryIds(this.staticQueryIds);
22979 this.component.viewQueries.forEach(function (query, queryIndex) {
22980 // Note: queries start with id 1 so we can use the number in a Bloom filter!
22981 var queryId = queryIndex + 1;
22982 var bindingType = query.first ? 0 /* First */ : 1 /* All */;
22983 var flags = 134217728 /* TypeViewQuery */ | calcStaticDynamicQueryFlags(queryIds_1, queryId, query);
22984 _this.nodes.push(function () { return ({
22985 sourceSpan: null,
22986 nodeFlags: flags,
22987 nodeDef: importExpr(Identifiers.queryDef).callFn([
22988 literal(flags), literal(queryId),
22989 new LiteralMapExpr([new LiteralMapEntry(query.propertyName, literal(bindingType), false)])
22990 ])
22991 }); });
22992 });
22993 }
22994 templateVisitAll(this, astNodes);
22995 if (this.parent && (astNodes.length === 0 || needsAdditionalRootNode(astNodes))) {
22996 // if the view is an embedded view, then we need to add an additional root node in some cases
22997 this.nodes.push(function () { return ({
22998 sourceSpan: null,
22999 nodeFlags: 1 /* TypeElement */,
23000 nodeDef: importExpr(Identifiers.anchorDef).callFn([
23001 literal(0 /* None */), NULL_EXPR, NULL_EXPR, literal(0)
23002 ])
23003 }); });
23004 }
23005 };
23006 ViewBuilder.prototype.build = function (targetStatements) {
23007 if (targetStatements === void 0) { targetStatements = []; }
23008 this.children.forEach(function (child) { return child.build(targetStatements); });
23009 var _a = this._createNodeExpressions(), updateRendererStmts = _a.updateRendererStmts, updateDirectivesStmts = _a.updateDirectivesStmts, nodeDefExprs = _a.nodeDefExprs;
23010 var updateRendererFn = this._createUpdateFn(updateRendererStmts);
23011 var updateDirectivesFn = this._createUpdateFn(updateDirectivesStmts);
23012 var viewFlags = 0 /* None */;
23013 if (!this.parent && this.component.changeDetection === ChangeDetectionStrategy.OnPush) {
23014 viewFlags |= 2 /* OnPush */;
23015 }
23016 var viewFactory = new DeclareFunctionStmt(this.viewName, [new FnParam(LOG_VAR$1.name)], [new ReturnStatement(importExpr(Identifiers.viewDef).callFn([
23017 literal(viewFlags),
23018 literalArr(nodeDefExprs),
23019 updateDirectivesFn,
23020 updateRendererFn,
23021 ]))], importType(Identifiers.ViewDefinition), this.embeddedViewIndex === 0 ? [StmtModifier.Exported] : []);
23022 targetStatements.push(viewFactory);
23023 return targetStatements;
23024 };
23025 ViewBuilder.prototype._createUpdateFn = function (updateStmts) {
23026 var updateFn;
23027 if (updateStmts.length > 0) {
23028 var preStmts = [];
23029 if (!this.component.isHost && findReadVarNames(updateStmts).has(COMP_VAR.name)) {
23030 preStmts.push(COMP_VAR.set(VIEW_VAR.prop('component')).toDeclStmt(this.compType));
23031 }
23032 updateFn = fn([
23033 new FnParam(CHECK_VAR.name, INFERRED_TYPE),
23034 new FnParam(VIEW_VAR.name, INFERRED_TYPE)
23035 ], __spread(preStmts, updateStmts), INFERRED_TYPE);
23036 }
23037 else {
23038 updateFn = NULL_EXPR;
23039 }
23040 return updateFn;
23041 };
23042 ViewBuilder.prototype.visitNgContent = function (ast, context) {
23043 // ngContentDef(ngContentIndex: number, index: number): NodeDef;
23044 this.nodes.push(function () { return ({
23045 sourceSpan: ast.sourceSpan,
23046 nodeFlags: 8 /* TypeNgContent */,
23047 nodeDef: importExpr(Identifiers.ngContentDef).callFn([
23048 literal(ast.ngContentIndex), literal(ast.index)
23049 ])
23050 }); });
23051 };
23052 ViewBuilder.prototype.visitText = function (ast, context) {
23053 // Static text nodes have no check function
23054 var checkIndex = -1;
23055 this.nodes.push(function () { return ({
23056 sourceSpan: ast.sourceSpan,
23057 nodeFlags: 2 /* TypeText */,
23058 nodeDef: importExpr(Identifiers.textDef).callFn([
23059 literal(checkIndex),
23060 literal(ast.ngContentIndex),
23061 literalArr([literal(ast.value)]),
23062 ])
23063 }); });
23064 };
23065 ViewBuilder.prototype.visitBoundText = function (ast, context) {
23066 var _this = this;
23067 var nodeIndex = this.nodes.length;
23068 // reserve the space in the nodeDefs array
23069 this.nodes.push(null);
23070 var astWithSource = ast.value;
23071 var inter = astWithSource.ast;
23072 var updateRendererExpressions = inter.expressions.map(function (expr, bindingIndex) { return _this._preprocessUpdateExpression({ nodeIndex: nodeIndex, bindingIndex: bindingIndex, sourceSpan: ast.sourceSpan, context: COMP_VAR, value: expr }); });
23073 // Check index is the same as the node index during compilation
23074 // They might only differ at runtime
23075 var checkIndex = nodeIndex;
23076 this.nodes[nodeIndex] = function () { return ({
23077 sourceSpan: ast.sourceSpan,
23078 nodeFlags: 2 /* TypeText */,
23079 nodeDef: importExpr(Identifiers.textDef).callFn([
23080 literal(checkIndex),
23081 literal(ast.ngContentIndex),
23082 literalArr(inter.strings.map(function (s) { return literal(s); })),
23083 ]),
23084 updateRenderer: updateRendererExpressions
23085 }); };
23086 };
23087 ViewBuilder.prototype.visitEmbeddedTemplate = function (ast, context) {
23088 var _this = this;
23089 var nodeIndex = this.nodes.length;
23090 // reserve the space in the nodeDefs array
23091 this.nodes.push(null);
23092 var _a = this._visitElementOrTemplate(nodeIndex, ast), flags = _a.flags, queryMatchesExpr = _a.queryMatchesExpr, hostEvents = _a.hostEvents;
23093 var childVisitor = this.viewBuilderFactory(this);
23094 this.children.push(childVisitor);
23095 childVisitor.visitAll(ast.variables, ast.children);
23096 var childCount = this.nodes.length - nodeIndex - 1;
23097 // anchorDef(
23098 // flags: NodeFlags, matchedQueries: [string, QueryValueType][], ngContentIndex: number,
23099 // childCount: number, handleEventFn?: ElementHandleEventFn, templateFactory?:
23100 // ViewDefinitionFactory): NodeDef;
23101 this.nodes[nodeIndex] = function () { return ({
23102 sourceSpan: ast.sourceSpan,
23103 nodeFlags: 1 /* TypeElement */ | flags,
23104 nodeDef: importExpr(Identifiers.anchorDef).callFn([
23105 literal(flags),
23106 queryMatchesExpr,
23107 literal(ast.ngContentIndex),
23108 literal(childCount),
23109 _this._createElementHandleEventFn(nodeIndex, hostEvents),
23110 variable(childVisitor.viewName),
23111 ])
23112 }); };
23113 };
23114 ViewBuilder.prototype.visitElement = function (ast, context) {
23115 var _this = this;
23116 var nodeIndex = this.nodes.length;
23117 // reserve the space in the nodeDefs array so we can add children
23118 this.nodes.push(null);
23119 // Using a null element name creates an anchor.
23120 var elName = isNgContainer(ast.name) ? null : ast.name;
23121 var _a = this._visitElementOrTemplate(nodeIndex, ast), flags = _a.flags, usedEvents = _a.usedEvents, queryMatchesExpr = _a.queryMatchesExpr, dirHostBindings = _a.hostBindings, hostEvents = _a.hostEvents;
23122 var inputDefs = [];
23123 var updateRendererExpressions = [];
23124 var outputDefs = [];
23125 if (elName) {
23126 var hostBindings = ast.inputs
23127 .map(function (inputAst) { return ({
23128 context: COMP_VAR,
23129 inputAst: inputAst,
23130 dirAst: null,
23131 }); })
23132 .concat(dirHostBindings);
23133 if (hostBindings.length) {
23134 updateRendererExpressions =
23135 hostBindings.map(function (hostBinding, bindingIndex) { return _this._preprocessUpdateExpression({
23136 context: hostBinding.context,
23137 nodeIndex: nodeIndex,
23138 bindingIndex: bindingIndex,
23139 sourceSpan: hostBinding.inputAst.sourceSpan,
23140 value: hostBinding.inputAst.value
23141 }); });
23142 inputDefs = hostBindings.map(function (hostBinding) { return elementBindingDef(hostBinding.inputAst, hostBinding.dirAst); });
23143 }
23144 outputDefs = usedEvents.map(function (_a) {
23145 var _b = __read(_a, 2), target = _b[0], eventName = _b[1];
23146 return literalArr([literal(target), literal(eventName)]);
23147 });
23148 }
23149 templateVisitAll(this, ast.children);
23150 var childCount = this.nodes.length - nodeIndex - 1;
23151 var compAst = ast.directives.find(function (dirAst) { return dirAst.directive.isComponent; });
23152 var compRendererType = NULL_EXPR;
23153 var compView = NULL_EXPR;
23154 if (compAst) {
23155 compView = this.outputCtx.importExpr(compAst.directive.componentViewType);
23156 compRendererType = this.outputCtx.importExpr(compAst.directive.rendererType);
23157 }
23158 // Check index is the same as the node index during compilation
23159 // They might only differ at runtime
23160 var checkIndex = nodeIndex;
23161 this.nodes[nodeIndex] = function () { return ({
23162 sourceSpan: ast.sourceSpan,
23163 nodeFlags: 1 /* TypeElement */ | flags,
23164 nodeDef: importExpr(Identifiers.elementDef).callFn([
23165 literal(checkIndex),
23166 literal(flags),
23167 queryMatchesExpr,
23168 literal(ast.ngContentIndex),
23169 literal(childCount),
23170 literal(elName),
23171 elName ? fixedAttrsDef(ast) : NULL_EXPR,
23172 inputDefs.length ? literalArr(inputDefs) : NULL_EXPR,
23173 outputDefs.length ? literalArr(outputDefs) : NULL_EXPR,
23174 _this._createElementHandleEventFn(nodeIndex, hostEvents),
23175 compView,
23176 compRendererType,
23177 ]),
23178 updateRenderer: updateRendererExpressions
23179 }); };
23180 };
23181 ViewBuilder.prototype._visitElementOrTemplate = function (nodeIndex, ast) {
23182 var _this = this;
23183 var flags = 0 /* None */;
23184 if (ast.hasViewContainer) {
23185 flags |= 16777216 /* EmbeddedViews */;
23186 }
23187 var usedEvents = new Map();
23188 ast.outputs.forEach(function (event) {
23189 var _a = elementEventNameAndTarget(event, null), name = _a.name, target = _a.target;
23190 usedEvents.set(elementEventFullName(target, name), [target, name]);
23191 });
23192 ast.directives.forEach(function (dirAst) {
23193 dirAst.hostEvents.forEach(function (event) {
23194 var _a = elementEventNameAndTarget(event, dirAst), name = _a.name, target = _a.target;
23195 usedEvents.set(elementEventFullName(target, name), [target, name]);
23196 });
23197 });
23198 var hostBindings = [];
23199 var hostEvents = [];
23200 this._visitComponentFactoryResolverProvider(ast.directives);
23201 ast.providers.forEach(function (providerAst, providerIndex) {
23202 var dirAst = undefined;
23203 var dirIndex = undefined;
23204 ast.directives.forEach(function (localDirAst, i) {
23205 if (localDirAst.directive.type.reference === tokenReference(providerAst.token)) {
23206 dirAst = localDirAst;
23207 dirIndex = i;
23208 }
23209 });
23210 if (dirAst) {
23211 var _a = _this._visitDirective(providerAst, dirAst, dirIndex, nodeIndex, ast.references, ast.queryMatches, usedEvents, _this.staticQueryIds.get(ast)), dirHostBindings = _a.hostBindings, dirHostEvents = _a.hostEvents;
23212 hostBindings.push.apply(hostBindings, __spread(dirHostBindings));
23213 hostEvents.push.apply(hostEvents, __spread(dirHostEvents));
23214 }
23215 else {
23216 _this._visitProvider(providerAst, ast.queryMatches);
23217 }
23218 });
23219 var queryMatchExprs = [];
23220 ast.queryMatches.forEach(function (match) {
23221 var valueType = undefined;
23222 if (tokenReference(match.value) ===
23223 _this.reflector.resolveExternalReference(Identifiers.ElementRef)) {
23224 valueType = 0 /* ElementRef */;
23225 }
23226 else if (tokenReference(match.value) ===
23227 _this.reflector.resolveExternalReference(Identifiers.ViewContainerRef)) {
23228 valueType = 3 /* ViewContainerRef */;
23229 }
23230 else if (tokenReference(match.value) ===
23231 _this.reflector.resolveExternalReference(Identifiers.TemplateRef)) {
23232 valueType = 2 /* TemplateRef */;
23233 }
23234 if (valueType != null) {
23235 queryMatchExprs.push(literalArr([literal(match.queryId), literal(valueType)]));
23236 }
23237 });
23238 ast.references.forEach(function (ref) {
23239 var valueType = undefined;
23240 if (!ref.value) {
23241 valueType = 1 /* RenderElement */;
23242 }
23243 else if (tokenReference(ref.value) ===
23244 _this.reflector.resolveExternalReference(Identifiers.TemplateRef)) {
23245 valueType = 2 /* TemplateRef */;
23246 }
23247 if (valueType != null) {
23248 _this.refNodeIndices[ref.name] = nodeIndex;
23249 queryMatchExprs.push(literalArr([literal(ref.name), literal(valueType)]));
23250 }
23251 });
23252 ast.outputs.forEach(function (outputAst) {
23253 hostEvents.push({ context: COMP_VAR, eventAst: outputAst, dirAst: null });
23254 });
23255 return {
23256 flags: flags,
23257 usedEvents: Array.from(usedEvents.values()),
23258 queryMatchesExpr: queryMatchExprs.length ? literalArr(queryMatchExprs) : NULL_EXPR,
23259 hostBindings: hostBindings,
23260 hostEvents: hostEvents
23261 };
23262 };
23263 ViewBuilder.prototype._visitDirective = function (providerAst, dirAst, directiveIndex, elementNodeIndex, refs, queryMatches, usedEvents, queryIds) {
23264 var _this = this;
23265 var nodeIndex = this.nodes.length;
23266 // reserve the space in the nodeDefs array so we can add children
23267 this.nodes.push(null);
23268 dirAst.directive.queries.forEach(function (query, queryIndex) {
23269 var queryId = dirAst.contentQueryStartId + queryIndex;
23270 var flags = 67108864 /* TypeContentQuery */ | calcStaticDynamicQueryFlags(queryIds, queryId, query);
23271 var bindingType = query.first ? 0 /* First */ : 1 /* All */;
23272 _this.nodes.push(function () { return ({
23273 sourceSpan: dirAst.sourceSpan,
23274 nodeFlags: flags,
23275 nodeDef: importExpr(Identifiers.queryDef).callFn([
23276 literal(flags), literal(queryId),
23277 new LiteralMapExpr([new LiteralMapEntry(query.propertyName, literal(bindingType), false)])
23278 ]),
23279 }); });
23280 });
23281 // Note: the operation below might also create new nodeDefs,
23282 // but we don't want them to be a child of a directive,
23283 // as they might be a provider/pipe on their own.
23284 // I.e. we only allow queries as children of directives nodes.
23285 var childCount = this.nodes.length - nodeIndex - 1;
23286 var _a = this._visitProviderOrDirective(providerAst, queryMatches), flags = _a.flags, queryMatchExprs = _a.queryMatchExprs, providerExpr = _a.providerExpr, depsExpr = _a.depsExpr;
23287 refs.forEach(function (ref) {
23288 if (ref.value && tokenReference(ref.value) === tokenReference(providerAst.token)) {
23289 _this.refNodeIndices[ref.name] = nodeIndex;
23290 queryMatchExprs.push(literalArr([literal(ref.name), literal(4 /* Provider */)]));
23291 }
23292 });
23293 if (dirAst.directive.isComponent) {
23294 flags |= 32768 /* Component */;
23295 }
23296 var inputDefs = dirAst.inputs.map(function (inputAst, inputIndex) {
23297 var mapValue = literalArr([literal(inputIndex), literal(inputAst.directiveName)]);
23298 // Note: it's important to not quote the key so that we can capture renames by minifiers!
23299 return new LiteralMapEntry(inputAst.directiveName, mapValue, false);
23300 });
23301 var outputDefs = [];
23302 var dirMeta = dirAst.directive;
23303 Object.keys(dirMeta.outputs).forEach(function (propName) {
23304 var eventName = dirMeta.outputs[propName];
23305 if (usedEvents.has(eventName)) {
23306 // Note: it's important to not quote the key so that we can capture renames by minifiers!
23307 outputDefs.push(new LiteralMapEntry(propName, literal(eventName), false));
23308 }
23309 });
23310 var updateDirectiveExpressions = [];
23311 if (dirAst.inputs.length || (flags & (262144 /* DoCheck */ | 65536 /* OnInit */)) > 0) {
23312 updateDirectiveExpressions =
23313 dirAst.inputs.map(function (input, bindingIndex) { return _this._preprocessUpdateExpression({
23314 nodeIndex: nodeIndex,
23315 bindingIndex: bindingIndex,
23316 sourceSpan: input.sourceSpan,
23317 context: COMP_VAR,
23318 value: input.value
23319 }); });
23320 }
23321 var dirContextExpr = importExpr(Identifiers.nodeValue).callFn([VIEW_VAR, literal(nodeIndex)]);
23322 var hostBindings = dirAst.hostProperties.map(function (inputAst) { return ({
23323 context: dirContextExpr,
23324 dirAst: dirAst,
23325 inputAst: inputAst,
23326 }); });
23327 var hostEvents = dirAst.hostEvents.map(function (hostEventAst) { return ({
23328 context: dirContextExpr,
23329 eventAst: hostEventAst, dirAst: dirAst,
23330 }); });
23331 // Check index is the same as the node index during compilation
23332 // They might only differ at runtime
23333 var checkIndex = nodeIndex;
23334 this.nodes[nodeIndex] = function () { return ({
23335 sourceSpan: dirAst.sourceSpan,
23336 nodeFlags: 16384 /* TypeDirective */ | flags,
23337 nodeDef: importExpr(Identifiers.directiveDef).callFn([
23338 literal(checkIndex),
23339 literal(flags),
23340 queryMatchExprs.length ? literalArr(queryMatchExprs) : NULL_EXPR,
23341 literal(childCount),
23342 providerExpr,
23343 depsExpr,
23344 inputDefs.length ? new LiteralMapExpr(inputDefs) : NULL_EXPR,
23345 outputDefs.length ? new LiteralMapExpr(outputDefs) : NULL_EXPR,
23346 ]),
23347 updateDirectives: updateDirectiveExpressions,
23348 directive: dirAst.directive.type,
23349 }); };
23350 return { hostBindings: hostBindings, hostEvents: hostEvents };
23351 };
23352 ViewBuilder.prototype._visitProvider = function (providerAst, queryMatches) {
23353 this._addProviderNode(this._visitProviderOrDirective(providerAst, queryMatches));
23354 };
23355 ViewBuilder.prototype._visitComponentFactoryResolverProvider = function (directives) {
23356 var componentDirMeta = directives.find(function (dirAst) { return dirAst.directive.isComponent; });
23357 if (componentDirMeta && componentDirMeta.directive.entryComponents.length) {
23358 var _a = componentFactoryResolverProviderDef(this.reflector, this.outputCtx, 8192 /* PrivateProvider */, componentDirMeta.directive.entryComponents), providerExpr = _a.providerExpr, depsExpr = _a.depsExpr, flags = _a.flags, tokenExpr = _a.tokenExpr;
23359 this._addProviderNode({
23360 providerExpr: providerExpr,
23361 depsExpr: depsExpr,
23362 flags: flags,
23363 tokenExpr: tokenExpr,
23364 queryMatchExprs: [],
23365 sourceSpan: componentDirMeta.sourceSpan
23366 });
23367 }
23368 };
23369 ViewBuilder.prototype._addProviderNode = function (data) {
23370 var nodeIndex = this.nodes.length;
23371 // providerDef(
23372 // flags: NodeFlags, matchedQueries: [string, QueryValueType][], token:any,
23373 // value: any, deps: ([DepFlags, any] | any)[]): NodeDef;
23374 this.nodes.push(function () { return ({
23375 sourceSpan: data.sourceSpan,
23376 nodeFlags: data.flags,
23377 nodeDef: importExpr(Identifiers.providerDef).callFn([
23378 literal(data.flags),
23379 data.queryMatchExprs.length ? literalArr(data.queryMatchExprs) : NULL_EXPR,
23380 data.tokenExpr, data.providerExpr, data.depsExpr
23381 ])
23382 }); });
23383 };
23384 ViewBuilder.prototype._visitProviderOrDirective = function (providerAst, queryMatches) {
23385 var flags = 0 /* None */;
23386 var queryMatchExprs = [];
23387 queryMatches.forEach(function (match) {
23388 if (tokenReference(match.value) === tokenReference(providerAst.token)) {
23389 queryMatchExprs.push(literalArr([literal(match.queryId), literal(4 /* Provider */)]));
23390 }
23391 });
23392 var _a = providerDef(this.outputCtx, providerAst), providerExpr = _a.providerExpr, depsExpr = _a.depsExpr, providerFlags = _a.flags, tokenExpr = _a.tokenExpr;
23393 return {
23394 flags: flags | providerFlags,
23395 queryMatchExprs: queryMatchExprs,
23396 providerExpr: providerExpr,
23397 depsExpr: depsExpr,
23398 tokenExpr: tokenExpr,
23399 sourceSpan: providerAst.sourceSpan
23400 };
23401 };
23402 ViewBuilder.prototype.getLocal = function (name) {
23403 if (name == EventHandlerVars.event.name) {
23404 return EventHandlerVars.event;
23405 }
23406 var currViewExpr = VIEW_VAR;
23407 for (var currBuilder = this; currBuilder; currBuilder = currBuilder.parent,
23408 currViewExpr = currViewExpr.prop('parent').cast(DYNAMIC_TYPE)) {
23409 // check references
23410 var refNodeIndex = currBuilder.refNodeIndices[name];
23411 if (refNodeIndex != null) {
23412 return importExpr(Identifiers.nodeValue).callFn([currViewExpr, literal(refNodeIndex)]);
23413 }
23414 // check variables
23415 var varAst = currBuilder.variables.find(function (varAst) { return varAst.name === name; });
23416 if (varAst) {
23417 var varValue = varAst.value || IMPLICIT_TEMPLATE_VAR;
23418 return currViewExpr.prop('context').prop(varValue);
23419 }
23420 }
23421 return null;
23422 };
23423 ViewBuilder.prototype.notifyImplicitReceiverUse = function () {
23424 // Not needed in View Engine as View Engine walks through the generated
23425 // expressions to figure out if the implicit receiver is used and needs
23426 // to be generated as part of the pre-update statements.
23427 };
23428 ViewBuilder.prototype._createLiteralArrayConverter = function (sourceSpan, argCount) {
23429 if (argCount === 0) {
23430 var valueExpr_1 = importExpr(Identifiers.EMPTY_ARRAY);
23431 return function () { return valueExpr_1; };
23432 }
23433 var checkIndex = this.nodes.length;
23434 this.nodes.push(function () { return ({
23435 sourceSpan: sourceSpan,
23436 nodeFlags: 32 /* TypePureArray */,
23437 nodeDef: importExpr(Identifiers.pureArrayDef).callFn([
23438 literal(checkIndex),
23439 literal(argCount),
23440 ])
23441 }); });
23442 return function (args) { return callCheckStmt(checkIndex, args); };
23443 };
23444 ViewBuilder.prototype._createLiteralMapConverter = function (sourceSpan, keys) {
23445 if (keys.length === 0) {
23446 var valueExpr_2 = importExpr(Identifiers.EMPTY_MAP);
23447 return function () { return valueExpr_2; };
23448 }
23449 var map = literalMap(keys.map(function (e, i) { return (__assign({}, e, { value: literal(i) })); }));
23450 var checkIndex = this.nodes.length;
23451 this.nodes.push(function () { return ({
23452 sourceSpan: sourceSpan,
23453 nodeFlags: 64 /* TypePureObject */,
23454 nodeDef: importExpr(Identifiers.pureObjectDef).callFn([
23455 literal(checkIndex),
23456 map,
23457 ])
23458 }); });
23459 return function (args) { return callCheckStmt(checkIndex, args); };
23460 };
23461 ViewBuilder.prototype._createPipeConverter = function (expression, name, argCount) {
23462 var pipe = this.usedPipes.find(function (pipeSummary) { return pipeSummary.name === name; });
23463 if (pipe.pure) {
23464 var checkIndex_1 = this.nodes.length;
23465 this.nodes.push(function () { return ({
23466 sourceSpan: expression.sourceSpan,
23467 nodeFlags: 128 /* TypePurePipe */,
23468 nodeDef: importExpr(Identifiers.purePipeDef).callFn([
23469 literal(checkIndex_1),
23470 literal(argCount),
23471 ])
23472 }); });
23473 // find underlying pipe in the component view
23474 var compViewExpr = VIEW_VAR;
23475 var compBuilder = this;
23476 while (compBuilder.parent) {
23477 compBuilder = compBuilder.parent;
23478 compViewExpr = compViewExpr.prop('parent').cast(DYNAMIC_TYPE);
23479 }
23480 var pipeNodeIndex = compBuilder.purePipeNodeIndices[name];
23481 var pipeValueExpr_1 = importExpr(Identifiers.nodeValue).callFn([compViewExpr, literal(pipeNodeIndex)]);
23482 return function (args) { return callUnwrapValue(expression.nodeIndex, expression.bindingIndex, callCheckStmt(checkIndex_1, [pipeValueExpr_1].concat(args))); };
23483 }
23484 else {
23485 var nodeIndex = this._createPipe(expression.sourceSpan, pipe);
23486 var nodeValueExpr_1 = importExpr(Identifiers.nodeValue).callFn([VIEW_VAR, literal(nodeIndex)]);
23487 return function (args) { return callUnwrapValue(expression.nodeIndex, expression.bindingIndex, nodeValueExpr_1.callMethod('transform', args)); };
23488 }
23489 };
23490 ViewBuilder.prototype._createPipe = function (sourceSpan, pipe) {
23491 var _this = this;
23492 var nodeIndex = this.nodes.length;
23493 var flags = 0 /* None */;
23494 pipe.type.lifecycleHooks.forEach(function (lifecycleHook) {
23495 // for pipes, we only support ngOnDestroy
23496 if (lifecycleHook === LifecycleHooks.OnDestroy) {
23497 flags |= lifecycleHookToNodeFlag(lifecycleHook);
23498 }
23499 });
23500 var depExprs = pipe.type.diDeps.map(function (diDep) { return depDef(_this.outputCtx, diDep); });
23501 // function pipeDef(
23502 // flags: NodeFlags, ctor: any, deps: ([DepFlags, any] | any)[]): NodeDef
23503 this.nodes.push(function () { return ({
23504 sourceSpan: sourceSpan,
23505 nodeFlags: 16 /* TypePipe */,
23506 nodeDef: importExpr(Identifiers.pipeDef).callFn([
23507 literal(flags), _this.outputCtx.importExpr(pipe.type.reference), literalArr(depExprs)
23508 ])
23509 }); });
23510 return nodeIndex;
23511 };
23512 /**
23513 * For the AST in `UpdateExpression.value`:
23514 * - create nodes for pipes, literal arrays and, literal maps,
23515 * - update the AST to replace pipes, literal arrays and, literal maps with calls to check fn.
23516 *
23517 * WARNING: This might create new nodeDefs (for pipes and literal arrays and literal maps)!
23518 */
23519 ViewBuilder.prototype._preprocessUpdateExpression = function (expression) {
23520 var _this = this;
23521 return {
23522 nodeIndex: expression.nodeIndex,
23523 bindingIndex: expression.bindingIndex,
23524 sourceSpan: expression.sourceSpan,
23525 context: expression.context,
23526 value: convertPropertyBindingBuiltins({
23527 createLiteralArrayConverter: function (argCount) { return _this._createLiteralArrayConverter(expression.sourceSpan, argCount); },
23528 createLiteralMapConverter: function (keys) {
23529 return _this._createLiteralMapConverter(expression.sourceSpan, keys);
23530 },
23531 createPipeConverter: function (name, argCount) {
23532 return _this._createPipeConverter(expression, name, argCount);
23533 }
23534 }, expression.value)
23535 };
23536 };
23537 ViewBuilder.prototype._createNodeExpressions = function () {
23538 var self = this;
23539 var updateBindingCount = 0;
23540 var updateRendererStmts = [];
23541 var updateDirectivesStmts = [];
23542 var nodeDefExprs = this.nodes.map(function (factory, nodeIndex) {
23543 var _a = factory(), nodeDef = _a.nodeDef, nodeFlags = _a.nodeFlags, updateDirectives = _a.updateDirectives, updateRenderer = _a.updateRenderer, sourceSpan = _a.sourceSpan;
23544 if (updateRenderer) {
23545 updateRendererStmts.push.apply(updateRendererStmts, __spread(createUpdateStatements(nodeIndex, sourceSpan, updateRenderer, false)));
23546 }
23547 if (updateDirectives) {
23548 updateDirectivesStmts.push.apply(updateDirectivesStmts, __spread(createUpdateStatements(nodeIndex, sourceSpan, updateDirectives, (nodeFlags & (262144 /* DoCheck */ | 65536 /* OnInit */)) > 0)));
23549 }
23550 // We use a comma expression to call the log function before
23551 // the nodeDef function, but still use the result of the nodeDef function
23552 // as the value.
23553 // Note: We only add the logger to elements / text nodes,
23554 // so we don't generate too much code.
23555 var logWithNodeDef = nodeFlags & 3 /* CatRenderNode */ ?
23556 new CommaExpr([LOG_VAR$1.callFn([]).callFn([]), nodeDef]) :
23557 nodeDef;
23558 return applySourceSpanToExpressionIfNeeded(logWithNodeDef, sourceSpan);
23559 });
23560 return { updateRendererStmts: updateRendererStmts, updateDirectivesStmts: updateDirectivesStmts, nodeDefExprs: nodeDefExprs };
23561 function createUpdateStatements(nodeIndex, sourceSpan, expressions, allowEmptyExprs) {
23562 var updateStmts = [];
23563 var exprs = expressions.map(function (_a) {
23564 var sourceSpan = _a.sourceSpan, context = _a.context, value = _a.value;
23565 var bindingId = "" + updateBindingCount++;
23566 var nameResolver = context === COMP_VAR ? self : null;
23567 var _b = convertPropertyBinding(nameResolver, context, value, bindingId, BindingForm.General), stmts = _b.stmts, currValExpr = _b.currValExpr;
23568 updateStmts.push.apply(updateStmts, __spread(stmts.map(function (stmt) { return applySourceSpanToStatementIfNeeded(stmt, sourceSpan); })));
23569 return applySourceSpanToExpressionIfNeeded(currValExpr, sourceSpan);
23570 });
23571 if (expressions.length || allowEmptyExprs) {
23572 updateStmts.push(applySourceSpanToStatementIfNeeded(callCheckStmt(nodeIndex, exprs).toStmt(), sourceSpan));
23573 }
23574 return updateStmts;
23575 }
23576 };
23577 ViewBuilder.prototype._createElementHandleEventFn = function (nodeIndex, handlers) {
23578 var _this = this;
23579 var handleEventStmts = [];
23580 var handleEventBindingCount = 0;
23581 handlers.forEach(function (_a) {
23582 var context = _a.context, eventAst = _a.eventAst, dirAst = _a.dirAst;
23583 var bindingId = "" + handleEventBindingCount++;
23584 var nameResolver = context === COMP_VAR ? _this : null;
23585 var _b = convertActionBinding(nameResolver, context, eventAst.handler, bindingId), stmts = _b.stmts, allowDefault = _b.allowDefault;
23586 var trueStmts = stmts;
23587 if (allowDefault) {
23588 trueStmts.push(ALLOW_DEFAULT_VAR.set(allowDefault.and(ALLOW_DEFAULT_VAR)).toStmt());
23589 }
23590 var _c = elementEventNameAndTarget(eventAst, dirAst), eventTarget = _c.target, eventName = _c.name;
23591 var fullEventName = elementEventFullName(eventTarget, eventName);
23592 handleEventStmts.push(applySourceSpanToStatementIfNeeded(new IfStmt(literal(fullEventName).identical(EVENT_NAME_VAR), trueStmts), eventAst.sourceSpan));
23593 });
23594 var handleEventFn;
23595 if (handleEventStmts.length > 0) {
23596 var preStmts = [ALLOW_DEFAULT_VAR.set(literal(true)).toDeclStmt(BOOL_TYPE)];
23597 if (!this.component.isHost && findReadVarNames(handleEventStmts).has(COMP_VAR.name)) {
23598 preStmts.push(COMP_VAR.set(VIEW_VAR.prop('component')).toDeclStmt(this.compType));
23599 }
23600 handleEventFn = fn([
23601 new FnParam(VIEW_VAR.name, INFERRED_TYPE),
23602 new FnParam(EVENT_NAME_VAR.name, INFERRED_TYPE),
23603 new FnParam(EventHandlerVars.event.name, INFERRED_TYPE)
23604 ], __spread(preStmts, handleEventStmts, [new ReturnStatement(ALLOW_DEFAULT_VAR)]), INFERRED_TYPE);
23605 }
23606 else {
23607 handleEventFn = NULL_EXPR;
23608 }
23609 return handleEventFn;
23610 };
23611 ViewBuilder.prototype.visitDirective = function (ast, context) { };
23612 ViewBuilder.prototype.visitDirectiveProperty = function (ast, context) { };
23613 ViewBuilder.prototype.visitReference = function (ast, context) { };
23614 ViewBuilder.prototype.visitVariable = function (ast, context) { };
23615 ViewBuilder.prototype.visitEvent = function (ast, context) { };
23616 ViewBuilder.prototype.visitElementProperty = function (ast, context) { };
23617 ViewBuilder.prototype.visitAttr = function (ast, context) { };
23618 return ViewBuilder;
23619}());
23620function needsAdditionalRootNode(astNodes) {
23621 var lastAstNode = astNodes[astNodes.length - 1];
23622 if (lastAstNode instanceof EmbeddedTemplateAst) {
23623 return lastAstNode.hasViewContainer;
23624 }
23625 if (lastAstNode instanceof ElementAst) {
23626 if (isNgContainer(lastAstNode.name) && lastAstNode.children.length) {
23627 return needsAdditionalRootNode(lastAstNode.children);
23628 }
23629 return lastAstNode.hasViewContainer;
23630 }
23631 return lastAstNode instanceof NgContentAst;
23632}
23633function elementBindingDef(inputAst, dirAst) {
23634 var inputType = inputAst.type;
23635 switch (inputType) {
23636 case 1 /* Attribute */:
23637 return literalArr([
23638 literal(1 /* TypeElementAttribute */), literal(inputAst.name),
23639 literal(inputAst.securityContext)
23640 ]);
23641 case 0 /* Property */:
23642 return literalArr([
23643 literal(8 /* TypeProperty */), literal(inputAst.name),
23644 literal(inputAst.securityContext)
23645 ]);
23646 case 4 /* Animation */:
23647 var bindingType = 8 /* TypeProperty */ |
23648 (dirAst && dirAst.directive.isComponent ? 32 /* SyntheticHostProperty */ :
23649 16 /* SyntheticProperty */);
23650 return literalArr([
23651 literal(bindingType), literal('@' + inputAst.name), literal(inputAst.securityContext)
23652 ]);
23653 case 2 /* Class */:
23654 return literalArr([literal(2 /* TypeElementClass */), literal(inputAst.name), NULL_EXPR]);
23655 case 3 /* Style */:
23656 return literalArr([
23657 literal(4 /* TypeElementStyle */), literal(inputAst.name), literal(inputAst.unit)
23658 ]);
23659 default:
23660 // This default case is not needed by TypeScript compiler, as the switch is exhaustive.
23661 // However Closure Compiler does not understand that and reports an error in typed mode.
23662 // The `throw new Error` below works around the problem, and the unexpected: never variable
23663 // makes sure tsc still checks this code is unreachable.
23664 var unexpected = inputType;
23665 throw new Error("unexpected " + unexpected);
23666 }
23667}
23668function fixedAttrsDef(elementAst) {
23669 var mapResult = Object.create(null);
23670 elementAst.attrs.forEach(function (attrAst) { mapResult[attrAst.name] = attrAst.value; });
23671 elementAst.directives.forEach(function (dirAst) {
23672 Object.keys(dirAst.directive.hostAttributes).forEach(function (name) {
23673 var value = dirAst.directive.hostAttributes[name];
23674 var prevValue = mapResult[name];
23675 mapResult[name] = prevValue != null ? mergeAttributeValue(name, prevValue, value) : value;
23676 });
23677 });
23678 // Note: We need to sort to get a defined output order
23679 // for tests and for caching generated artifacts...
23680 return literalArr(Object.keys(mapResult).sort().map(function (attrName) { return literalArr([literal(attrName), literal(mapResult[attrName])]); }));
23681}
23682function mergeAttributeValue(attrName, attrValue1, attrValue2) {
23683 if (attrName == CLASS_ATTR$1 || attrName == STYLE_ATTR) {
23684 return attrValue1 + " " + attrValue2;
23685 }
23686 else {
23687 return attrValue2;
23688 }
23689}
23690function callCheckStmt(nodeIndex, exprs) {
23691 if (exprs.length > 10) {
23692 return CHECK_VAR.callFn([VIEW_VAR, literal(nodeIndex), literal(1 /* Dynamic */), literalArr(exprs)]);
23693 }
23694 else {
23695 return CHECK_VAR.callFn(__spread([VIEW_VAR, literal(nodeIndex), literal(0 /* Inline */)], exprs));
23696 }
23697}
23698function callUnwrapValue(nodeIndex, bindingIdx, expr) {
23699 return importExpr(Identifiers.unwrapValue).callFn([
23700 VIEW_VAR, literal(nodeIndex), literal(bindingIdx), expr
23701 ]);
23702}
23703function findStaticQueryIds(nodes, result) {
23704 if (result === void 0) { result = new Map(); }
23705 nodes.forEach(function (node) {
23706 var staticQueryIds = new Set();
23707 var dynamicQueryIds = new Set();
23708 var queryMatches = undefined;
23709 if (node instanceof ElementAst) {
23710 findStaticQueryIds(node.children, result);
23711 node.children.forEach(function (child) {
23712 var childData = result.get(child);
23713 childData.staticQueryIds.forEach(function (queryId) { return staticQueryIds.add(queryId); });
23714 childData.dynamicQueryIds.forEach(function (queryId) { return dynamicQueryIds.add(queryId); });
23715 });
23716 queryMatches = node.queryMatches;
23717 }
23718 else if (node instanceof EmbeddedTemplateAst) {
23719 findStaticQueryIds(node.children, result);
23720 node.children.forEach(function (child) {
23721 var childData = result.get(child);
23722 childData.staticQueryIds.forEach(function (queryId) { return dynamicQueryIds.add(queryId); });
23723 childData.dynamicQueryIds.forEach(function (queryId) { return dynamicQueryIds.add(queryId); });
23724 });
23725 queryMatches = node.queryMatches;
23726 }
23727 if (queryMatches) {
23728 queryMatches.forEach(function (match) { return staticQueryIds.add(match.queryId); });
23729 }
23730 dynamicQueryIds.forEach(function (queryId) { return staticQueryIds.delete(queryId); });
23731 result.set(node, { staticQueryIds: staticQueryIds, dynamicQueryIds: dynamicQueryIds });
23732 });
23733 return result;
23734}
23735function staticViewQueryIds(nodeStaticQueryIds) {
23736 var staticQueryIds = new Set();
23737 var dynamicQueryIds = new Set();
23738 Array.from(nodeStaticQueryIds.values()).forEach(function (entry) {
23739 entry.staticQueryIds.forEach(function (queryId) { return staticQueryIds.add(queryId); });
23740 entry.dynamicQueryIds.forEach(function (queryId) { return dynamicQueryIds.add(queryId); });
23741 });
23742 dynamicQueryIds.forEach(function (queryId) { return staticQueryIds.delete(queryId); });
23743 return { staticQueryIds: staticQueryIds, dynamicQueryIds: dynamicQueryIds };
23744}
23745function elementEventNameAndTarget(eventAst, dirAst) {
23746 if (eventAst.isAnimation) {
23747 return {
23748 name: "@" + eventAst.name + "." + eventAst.phase,
23749 target: dirAst && dirAst.directive.isComponent ? 'component' : null
23750 };
23751 }
23752 else {
23753 return eventAst;
23754 }
23755}
23756function calcStaticDynamicQueryFlags(queryIds, queryId, query) {
23757 var flags = 0 /* None */;
23758 // Note: We only make queries static that query for a single item.
23759 // This is because of backwards compatibility with the old view compiler...
23760 if (query.first && shouldResolveAsStaticQuery(queryIds, queryId, query)) {
23761 flags |= 268435456 /* StaticQuery */;
23762 }
23763 else {
23764 flags |= 536870912 /* DynamicQuery */;
23765 }
23766 return flags;
23767}
23768function shouldResolveAsStaticQuery(queryIds, queryId, query) {
23769 // If query.static has been set by the user, use that value to determine whether
23770 // the query is static. If none has been set, sort the query into static/dynamic
23771 // based on query results (i.e. dynamic if CD needs to run to get all results).
23772 return query.static ||
23773 query.static == null &&
23774 (queryIds.staticQueryIds.has(queryId) || !queryIds.dynamicQueryIds.has(queryId));
23775}
23776function elementEventFullName(target, name) {
23777 return target ? target + ":" + name : name;
23778}
23779
23780/**
23781 * @license
23782 * Copyright Google Inc. All Rights Reserved.
23783 *
23784 * Use of this source code is governed by an MIT-style license that can be
23785 * found in the LICENSE file at https://angular.io/license
23786 */
23787/**
23788 * A container for message extracted from the templates.
23789 */
23790var MessageBundle = /** @class */ (function () {
23791 function MessageBundle(_htmlParser, _implicitTags, _implicitAttrs, _locale) {
23792 if (_locale === void 0) { _locale = null; }
23793 this._htmlParser = _htmlParser;
23794 this._implicitTags = _implicitTags;
23795 this._implicitAttrs = _implicitAttrs;
23796 this._locale = _locale;
23797 this._messages = [];
23798 }
23799 MessageBundle.prototype.updateFromTemplate = function (html, url, interpolationConfig) {
23800 var _a;
23801 var htmlParserResult = this._htmlParser.parse(html, url, { tokenizeExpansionForms: true, interpolationConfig: interpolationConfig });
23802 if (htmlParserResult.errors.length) {
23803 return htmlParserResult.errors;
23804 }
23805 var i18nParserResult = extractMessages(htmlParserResult.rootNodes, interpolationConfig, this._implicitTags, this._implicitAttrs);
23806 if (i18nParserResult.errors.length) {
23807 return i18nParserResult.errors;
23808 }
23809 (_a = this._messages).push.apply(_a, __spread(i18nParserResult.messages));
23810 return [];
23811 };
23812 // Return the message in the internal format
23813 // The public (serialized) format might be different, see the `write` method.
23814 MessageBundle.prototype.getMessages = function () { return this._messages; };
23815 MessageBundle.prototype.write = function (serializer, filterSources) {
23816 var messages = {};
23817 var mapperVisitor = new MapPlaceholderNames();
23818 // Deduplicate messages based on their ID
23819 this._messages.forEach(function (message) {
23820 var _a;
23821 var id = serializer.digest(message);
23822 if (!messages.hasOwnProperty(id)) {
23823 messages[id] = message;
23824 }
23825 else {
23826 (_a = messages[id].sources).push.apply(_a, __spread(message.sources));
23827 }
23828 });
23829 // Transform placeholder names using the serializer mapping
23830 var msgList = Object.keys(messages).map(function (id) {
23831 var mapper = serializer.createNameMapper(messages[id]);
23832 var src = messages[id];
23833 var nodes = mapper ? mapperVisitor.convert(src.nodes, mapper) : src.nodes;
23834 var transformedMessage = new Message(nodes, {}, {}, src.meaning, src.description, id);
23835 transformedMessage.sources = src.sources;
23836 if (filterSources) {
23837 transformedMessage.sources.forEach(function (source) { return source.filePath = filterSources(source.filePath); });
23838 }
23839 return transformedMessage;
23840 });
23841 return serializer.write(msgList, this._locale);
23842 };
23843 return MessageBundle;
23844}());
23845// Transform an i18n AST by renaming the placeholder nodes with the given mapper
23846var MapPlaceholderNames = /** @class */ (function (_super) {
23847 __extends(MapPlaceholderNames, _super);
23848 function MapPlaceholderNames() {
23849 return _super !== null && _super.apply(this, arguments) || this;
23850 }
23851 MapPlaceholderNames.prototype.convert = function (nodes, mapper) {
23852 var _this = this;
23853 return mapper ? nodes.map(function (n) { return n.visit(_this, mapper); }) : nodes;
23854 };
23855 MapPlaceholderNames.prototype.visitTagPlaceholder = function (ph, mapper) {
23856 var _this = this;
23857 var startName = mapper.toPublicName(ph.startName);
23858 var closeName = ph.closeName ? mapper.toPublicName(ph.closeName) : ph.closeName;
23859 var children = ph.children.map(function (n) { return n.visit(_this, mapper); });
23860 return new TagPlaceholder(ph.tag, ph.attrs, startName, closeName, children, ph.isVoid, ph.sourceSpan);
23861 };
23862 MapPlaceholderNames.prototype.visitPlaceholder = function (ph, mapper) {
23863 return new Placeholder(ph.value, mapper.toPublicName(ph.name), ph.sourceSpan);
23864 };
23865 MapPlaceholderNames.prototype.visitIcuPlaceholder = function (ph, mapper) {
23866 return new IcuPlaceholder(ph.value, mapper.toPublicName(ph.name), ph.sourceSpan);
23867 };
23868 return MapPlaceholderNames;
23869}(CloneVisitor));
23870
23871/**
23872 * @license
23873 * Copyright Google Inc. All Rights Reserved.
23874 *
23875 * Use of this source code is governed by an MIT-style license that can be
23876 * found in the LICENSE file at https://angular.io/license
23877 */
23878var GeneratedFile = /** @class */ (function () {
23879 function GeneratedFile(srcFileUrl, genFileUrl, sourceOrStmts) {
23880 this.srcFileUrl = srcFileUrl;
23881 this.genFileUrl = genFileUrl;
23882 if (typeof sourceOrStmts === 'string') {
23883 this.source = sourceOrStmts;
23884 this.stmts = null;
23885 }
23886 else {
23887 this.source = null;
23888 this.stmts = sourceOrStmts;
23889 }
23890 }
23891 GeneratedFile.prototype.isEquivalent = function (other) {
23892 if (this.genFileUrl !== other.genFileUrl) {
23893 return false;
23894 }
23895 if (this.source) {
23896 return this.source === other.source;
23897 }
23898 if (other.stmts == null) {
23899 return false;
23900 }
23901 // Note: the constructor guarantees that if this.source is not filled,
23902 // then this.stmts is.
23903 return areAllEquivalent(this.stmts, other.stmts);
23904 };
23905 return GeneratedFile;
23906}());
23907function toTypeScript(file, preamble) {
23908 if (preamble === void 0) { preamble = ''; }
23909 if (!file.stmts) {
23910 throw new Error("Illegal state: No stmts present on GeneratedFile " + file.genFileUrl);
23911 }
23912 return new TypeScriptEmitter().emitStatements(file.genFileUrl, file.stmts, preamble);
23913}
23914
23915/**
23916 * @license
23917 * Copyright Google Inc. All Rights Reserved.
23918 *
23919 * Use of this source code is governed by an MIT-style license that can be
23920 * found in the LICENSE file at https://angular.io/license
23921 */
23922function listLazyRoutes(moduleMeta, reflector) {
23923 var e_1, _a, e_2, _b;
23924 var allLazyRoutes = [];
23925 try {
23926 for (var _c = __values(moduleMeta.transitiveModule.providers), _d = _c.next(); !_d.done; _d = _c.next()) {
23927 var _e = _d.value, provider = _e.provider, module = _e.module;
23928 if (tokenReference(provider.token) === reflector.ROUTES) {
23929 var loadChildren = _collectLoadChildren(provider.useValue);
23930 try {
23931 for (var loadChildren_1 = (e_2 = void 0, __values(loadChildren)), loadChildren_1_1 = loadChildren_1.next(); !loadChildren_1_1.done; loadChildren_1_1 = loadChildren_1.next()) {
23932 var route = loadChildren_1_1.value;
23933 allLazyRoutes.push(parseLazyRoute(route, reflector, module.reference));
23934 }
23935 }
23936 catch (e_2_1) { e_2 = { error: e_2_1 }; }
23937 finally {
23938 try {
23939 if (loadChildren_1_1 && !loadChildren_1_1.done && (_b = loadChildren_1.return)) _b.call(loadChildren_1);
23940 }
23941 finally { if (e_2) throw e_2.error; }
23942 }
23943 }
23944 }
23945 }
23946 catch (e_1_1) { e_1 = { error: e_1_1 }; }
23947 finally {
23948 try {
23949 if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
23950 }
23951 finally { if (e_1) throw e_1.error; }
23952 }
23953 return allLazyRoutes;
23954}
23955function _collectLoadChildren(routes, target) {
23956 var e_3, _a;
23957 if (target === void 0) { target = []; }
23958 if (typeof routes === 'string') {
23959 target.push(routes);
23960 }
23961 else if (Array.isArray(routes)) {
23962 try {
23963 for (var routes_1 = __values(routes), routes_1_1 = routes_1.next(); !routes_1_1.done; routes_1_1 = routes_1.next()) {
23964 var route = routes_1_1.value;
23965 _collectLoadChildren(route, target);
23966 }
23967 }
23968 catch (e_3_1) { e_3 = { error: e_3_1 }; }
23969 finally {
23970 try {
23971 if (routes_1_1 && !routes_1_1.done && (_a = routes_1.return)) _a.call(routes_1);
23972 }
23973 finally { if (e_3) throw e_3.error; }
23974 }
23975 }
23976 else if (routes.loadChildren) {
23977 _collectLoadChildren(routes.loadChildren, target);
23978 }
23979 else if (routes.children) {
23980 _collectLoadChildren(routes.children, target);
23981 }
23982 return target;
23983}
23984function parseLazyRoute(route, reflector, module) {
23985 var _a = __read(route.split('#'), 2), routePath = _a[0], routeName = _a[1];
23986 var referencedModule = reflector.resolveExternalReference({
23987 moduleName: routePath,
23988 name: routeName,
23989 }, module ? module.filePath : undefined);
23990 return { route: route, module: module || referencedModule, referencedModule: referencedModule };
23991}
23992
23993/**
23994 * @license
23995 * Copyright Google Inc. All Rights Reserved.
23996 *
23997 * Use of this source code is governed by an MIT-style license that can be
23998 * found in the LICENSE file at https://angular.io/license
23999 */
24000var TS = /^(?!.*\.d\.ts$).*\.ts$/;
24001var ResolvedStaticSymbol = /** @class */ (function () {
24002 function ResolvedStaticSymbol(symbol, metadata) {
24003 this.symbol = symbol;
24004 this.metadata = metadata;
24005 }
24006 return ResolvedStaticSymbol;
24007}());
24008var SUPPORTED_SCHEMA_VERSION = 4;
24009/**
24010 * This class is responsible for loading metadata per symbol,
24011 * and normalizing references between symbols.
24012 *
24013 * Internally, it only uses symbols without members,
24014 * and deduces the values for symbols with members based
24015 * on these symbols.
24016 */
24017var StaticSymbolResolver = /** @class */ (function () {
24018 function StaticSymbolResolver(host, staticSymbolCache, summaryResolver, errorRecorder) {
24019 this.host = host;
24020 this.staticSymbolCache = staticSymbolCache;
24021 this.summaryResolver = summaryResolver;
24022 this.errorRecorder = errorRecorder;
24023 this.metadataCache = new Map();
24024 // Note: this will only contain StaticSymbols without members!
24025 this.resolvedSymbols = new Map();
24026 this.resolvedFilePaths = new Set();
24027 // Note: this will only contain StaticSymbols without members!
24028 this.importAs = new Map();
24029 this.symbolResourcePaths = new Map();
24030 this.symbolFromFile = new Map();
24031 this.knownFileNameToModuleNames = new Map();
24032 }
24033 StaticSymbolResolver.prototype.resolveSymbol = function (staticSymbol) {
24034 if (staticSymbol.members.length > 0) {
24035 return this._resolveSymbolMembers(staticSymbol);
24036 }
24037 // Note: always ask for a summary first,
24038 // as we might have read shallow metadata via a .d.ts file
24039 // for the symbol.
24040 var resultFromSummary = this._resolveSymbolFromSummary(staticSymbol);
24041 if (resultFromSummary) {
24042 return resultFromSummary;
24043 }
24044 var resultFromCache = this.resolvedSymbols.get(staticSymbol);
24045 if (resultFromCache) {
24046 return resultFromCache;
24047 }
24048 // Note: Some users use libraries that were not compiled with ngc, i.e. they don't
24049 // have summaries, only .d.ts files. So we always need to check both, the summary
24050 // and metadata.
24051 this._createSymbolsOf(staticSymbol.filePath);
24052 return this.resolvedSymbols.get(staticSymbol);
24053 };
24054 /**
24055 * getImportAs produces a symbol that can be used to import the given symbol.
24056 * The import might be different than the symbol if the symbol is exported from
24057 * a library with a summary; in which case we want to import the symbol from the
24058 * ngfactory re-export instead of directly to avoid introducing a direct dependency
24059 * on an otherwise indirect dependency.
24060 *
24061 * @param staticSymbol the symbol for which to generate a import symbol
24062 */
24063 StaticSymbolResolver.prototype.getImportAs = function (staticSymbol, useSummaries) {
24064 if (useSummaries === void 0) { useSummaries = true; }
24065 if (staticSymbol.members.length) {
24066 var baseSymbol = this.getStaticSymbol(staticSymbol.filePath, staticSymbol.name);
24067 var baseImportAs = this.getImportAs(baseSymbol, useSummaries);
24068 return baseImportAs ?
24069 this.getStaticSymbol(baseImportAs.filePath, baseImportAs.name, staticSymbol.members) :
24070 null;
24071 }
24072 var summarizedFileName = stripSummaryForJitFileSuffix(staticSymbol.filePath);
24073 if (summarizedFileName !== staticSymbol.filePath) {
24074 var summarizedName = stripSummaryForJitNameSuffix(staticSymbol.name);
24075 var baseSymbol = this.getStaticSymbol(summarizedFileName, summarizedName, staticSymbol.members);
24076 var baseImportAs = this.getImportAs(baseSymbol, useSummaries);
24077 return baseImportAs ?
24078 this.getStaticSymbol(summaryForJitFileName(baseImportAs.filePath), summaryForJitName(baseImportAs.name), baseSymbol.members) :
24079 null;
24080 }
24081 var result = (useSummaries && this.summaryResolver.getImportAs(staticSymbol)) || null;
24082 if (!result) {
24083 result = this.importAs.get(staticSymbol);
24084 }
24085 return result;
24086 };
24087 /**
24088 * getResourcePath produces the path to the original location of the symbol and should
24089 * be used to determine the relative location of resource references recorded in
24090 * symbol metadata.
24091 */
24092 StaticSymbolResolver.prototype.getResourcePath = function (staticSymbol) {
24093 return this.symbolResourcePaths.get(staticSymbol) || staticSymbol.filePath;
24094 };
24095 /**
24096 * getTypeArity returns the number of generic type parameters the given symbol
24097 * has. If the symbol is not a type the result is null.
24098 */
24099 StaticSymbolResolver.prototype.getTypeArity = function (staticSymbol) {
24100 // If the file is a factory/ngsummary file, don't resolve the symbol as doing so would
24101 // cause the metadata for an factory/ngsummary file to be loaded which doesn't exist.
24102 // All references to generated classes must include the correct arity whenever
24103 // generating code.
24104 if (isGeneratedFile(staticSymbol.filePath)) {
24105 return null;
24106 }
24107 var resolvedSymbol = unwrapResolvedMetadata(this.resolveSymbol(staticSymbol));
24108 while (resolvedSymbol && resolvedSymbol.metadata instanceof StaticSymbol) {
24109 resolvedSymbol = unwrapResolvedMetadata(this.resolveSymbol(resolvedSymbol.metadata));
24110 }
24111 return (resolvedSymbol && resolvedSymbol.metadata && resolvedSymbol.metadata.arity) || null;
24112 };
24113 StaticSymbolResolver.prototype.getKnownModuleName = function (filePath) {
24114 return this.knownFileNameToModuleNames.get(filePath) || null;
24115 };
24116 StaticSymbolResolver.prototype.recordImportAs = function (sourceSymbol, targetSymbol) {
24117 sourceSymbol.assertNoMembers();
24118 targetSymbol.assertNoMembers();
24119 this.importAs.set(sourceSymbol, targetSymbol);
24120 };
24121 StaticSymbolResolver.prototype.recordModuleNameForFileName = function (fileName, moduleName) {
24122 this.knownFileNameToModuleNames.set(fileName, moduleName);
24123 };
24124 /**
24125 * Invalidate all information derived from the given file.
24126 *
24127 * @param fileName the file to invalidate
24128 */
24129 StaticSymbolResolver.prototype.invalidateFile = function (fileName) {
24130 var e_1, _a;
24131 this.metadataCache.delete(fileName);
24132 this.resolvedFilePaths.delete(fileName);
24133 var symbols = this.symbolFromFile.get(fileName);
24134 if (symbols) {
24135 this.symbolFromFile.delete(fileName);
24136 try {
24137 for (var symbols_1 = __values(symbols), symbols_1_1 = symbols_1.next(); !symbols_1_1.done; symbols_1_1 = symbols_1.next()) {
24138 var symbol = symbols_1_1.value;
24139 this.resolvedSymbols.delete(symbol);
24140 this.importAs.delete(symbol);
24141 this.symbolResourcePaths.delete(symbol);
24142 }
24143 }
24144 catch (e_1_1) { e_1 = { error: e_1_1 }; }
24145 finally {
24146 try {
24147 if (symbols_1_1 && !symbols_1_1.done && (_a = symbols_1.return)) _a.call(symbols_1);
24148 }
24149 finally { if (e_1) throw e_1.error; }
24150 }
24151 }
24152 };
24153 /** @internal */
24154 StaticSymbolResolver.prototype.ignoreErrorsFor = function (cb) {
24155 var recorder = this.errorRecorder;
24156 this.errorRecorder = function () { };
24157 try {
24158 return cb();
24159 }
24160 finally {
24161 this.errorRecorder = recorder;
24162 }
24163 };
24164 StaticSymbolResolver.prototype._resolveSymbolMembers = function (staticSymbol) {
24165 var members = staticSymbol.members;
24166 var baseResolvedSymbol = this.resolveSymbol(this.getStaticSymbol(staticSymbol.filePath, staticSymbol.name));
24167 if (!baseResolvedSymbol) {
24168 return null;
24169 }
24170 var baseMetadata = unwrapResolvedMetadata(baseResolvedSymbol.metadata);
24171 if (baseMetadata instanceof StaticSymbol) {
24172 return new ResolvedStaticSymbol(staticSymbol, this.getStaticSymbol(baseMetadata.filePath, baseMetadata.name, members));
24173 }
24174 else if (baseMetadata && baseMetadata.__symbolic === 'class') {
24175 if (baseMetadata.statics && members.length === 1) {
24176 return new ResolvedStaticSymbol(staticSymbol, baseMetadata.statics[members[0]]);
24177 }
24178 }
24179 else {
24180 var value = baseMetadata;
24181 for (var i = 0; i < members.length && value; i++) {
24182 value = value[members[i]];
24183 }
24184 return new ResolvedStaticSymbol(staticSymbol, value);
24185 }
24186 return null;
24187 };
24188 StaticSymbolResolver.prototype._resolveSymbolFromSummary = function (staticSymbol) {
24189 var summary = this.summaryResolver.resolveSummary(staticSymbol);
24190 return summary ? new ResolvedStaticSymbol(staticSymbol, summary.metadata) : null;
24191 };
24192 /**
24193 * getStaticSymbol produces a Type whose metadata is known but whose implementation is not loaded.
24194 * All types passed to the StaticResolver should be pseudo-types returned by this method.
24195 *
24196 * @param declarationFile the absolute path of the file where the symbol is declared
24197 * @param name the name of the type.
24198 * @param members a symbol for a static member of the named type
24199 */
24200 StaticSymbolResolver.prototype.getStaticSymbol = function (declarationFile, name, members) {
24201 return this.staticSymbolCache.get(declarationFile, name, members);
24202 };
24203 /**
24204 * hasDecorators checks a file's metadata for the presence of decorators without evaluating the
24205 * metadata.
24206 *
24207 * @param filePath the absolute path to examine for decorators.
24208 * @returns true if any class in the file has a decorator.
24209 */
24210 StaticSymbolResolver.prototype.hasDecorators = function (filePath) {
24211 var metadata = this.getModuleMetadata(filePath);
24212 if (metadata['metadata']) {
24213 return Object.keys(metadata['metadata']).some(function (metadataKey) {
24214 var entry = metadata['metadata'][metadataKey];
24215 return entry && entry.__symbolic === 'class' && entry.decorators;
24216 });
24217 }
24218 return false;
24219 };
24220 StaticSymbolResolver.prototype.getSymbolsOf = function (filePath) {
24221 var summarySymbols = this.summaryResolver.getSymbolsOf(filePath);
24222 if (summarySymbols) {
24223 return summarySymbols;
24224 }
24225 // Note: Some users use libraries that were not compiled with ngc, i.e. they don't
24226 // have summaries, only .d.ts files, but `summaryResolver.isLibraryFile` returns true.
24227 this._createSymbolsOf(filePath);
24228 var metadataSymbols = [];
24229 this.resolvedSymbols.forEach(function (resolvedSymbol) {
24230 if (resolvedSymbol.symbol.filePath === filePath) {
24231 metadataSymbols.push(resolvedSymbol.symbol);
24232 }
24233 });
24234 return metadataSymbols;
24235 };
24236 StaticSymbolResolver.prototype._createSymbolsOf = function (filePath) {
24237 var e_2, _a;
24238 var _this = this;
24239 if (this.resolvedFilePaths.has(filePath)) {
24240 return;
24241 }
24242 this.resolvedFilePaths.add(filePath);
24243 var resolvedSymbols = [];
24244 var metadata = this.getModuleMetadata(filePath);
24245 if (metadata['importAs']) {
24246 // Index bundle indices should use the importAs module name defined
24247 // in the bundle.
24248 this.knownFileNameToModuleNames.set(filePath, metadata['importAs']);
24249 }
24250 // handle the symbols in one of the re-export location
24251 if (metadata['exports']) {
24252 var _loop_1 = function (moduleExport) {
24253 // handle the symbols in the list of explicitly re-exported symbols.
24254 if (moduleExport.export) {
24255 moduleExport.export.forEach(function (exportSymbol) {
24256 var symbolName;
24257 if (typeof exportSymbol === 'string') {
24258 symbolName = exportSymbol;
24259 }
24260 else {
24261 symbolName = exportSymbol.as;
24262 }
24263 symbolName = unescapeIdentifier(symbolName);
24264 var symName = symbolName;
24265 if (typeof exportSymbol !== 'string') {
24266 symName = unescapeIdentifier(exportSymbol.name);
24267 }
24268 var resolvedModule = _this.resolveModule(moduleExport.from, filePath);
24269 if (resolvedModule) {
24270 var targetSymbol = _this.getStaticSymbol(resolvedModule, symName);
24271 var sourceSymbol = _this.getStaticSymbol(filePath, symbolName);
24272 resolvedSymbols.push(_this.createExport(sourceSymbol, targetSymbol));
24273 }
24274 });
24275 }
24276 else {
24277 // handle the symbols via export * directives.
24278 var resolvedModule = this_1.resolveModule(moduleExport.from, filePath);
24279 if (resolvedModule) {
24280 var nestedExports = this_1.getSymbolsOf(resolvedModule);
24281 nestedExports.forEach(function (targetSymbol) {
24282 var sourceSymbol = _this.getStaticSymbol(filePath, targetSymbol.name);
24283 resolvedSymbols.push(_this.createExport(sourceSymbol, targetSymbol));
24284 });
24285 }
24286 }
24287 };
24288 var this_1 = this;
24289 try {
24290 for (var _b = __values(metadata['exports']), _c = _b.next(); !_c.done; _c = _b.next()) {
24291 var moduleExport = _c.value;
24292 _loop_1(moduleExport);
24293 }
24294 }
24295 catch (e_2_1) { e_2 = { error: e_2_1 }; }
24296 finally {
24297 try {
24298 if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
24299 }
24300 finally { if (e_2) throw e_2.error; }
24301 }
24302 }
24303 // handle the actual metadata. Has to be after the exports
24304 // as there might be collisions in the names, and we want the symbols
24305 // of the current module to win ofter reexports.
24306 if (metadata['metadata']) {
24307 // handle direct declarations of the symbol
24308 var topLevelSymbolNames_1 = new Set(Object.keys(metadata['metadata']).map(unescapeIdentifier));
24309 var origins_1 = metadata['origins'] || {};
24310 Object.keys(metadata['metadata']).forEach(function (metadataKey) {
24311 var symbolMeta = metadata['metadata'][metadataKey];
24312 var name = unescapeIdentifier(metadataKey);
24313 var symbol = _this.getStaticSymbol(filePath, name);
24314 var origin = origins_1.hasOwnProperty(metadataKey) && origins_1[metadataKey];
24315 if (origin) {
24316 // If the symbol is from a bundled index, use the declaration location of the
24317 // symbol so relative references (such as './my.html') will be calculated
24318 // correctly.
24319 var originFilePath = _this.resolveModule(origin, filePath);
24320 if (!originFilePath) {
24321 _this.reportError(new Error("Couldn't resolve original symbol for " + origin + " from " + _this.host.getOutputName(filePath)));
24322 }
24323 else {
24324 _this.symbolResourcePaths.set(symbol, originFilePath);
24325 }
24326 }
24327 resolvedSymbols.push(_this.createResolvedSymbol(symbol, filePath, topLevelSymbolNames_1, symbolMeta));
24328 });
24329 }
24330 resolvedSymbols.forEach(function (resolvedSymbol) { return _this.resolvedSymbols.set(resolvedSymbol.symbol, resolvedSymbol); });
24331 this.symbolFromFile.set(filePath, resolvedSymbols.map(function (resolvedSymbol) { return resolvedSymbol.symbol; }));
24332 };
24333 StaticSymbolResolver.prototype.createResolvedSymbol = function (sourceSymbol, topLevelPath, topLevelSymbolNames, metadata) {
24334 var _this = this;
24335 // For classes that don't have Angular summaries / metadata,
24336 // we only keep their arity, but nothing else
24337 // (e.g. their constructor parameters).
24338 // We do this to prevent introducing deep imports
24339 // as we didn't generate .ngfactory.ts files with proper reexports.
24340 var isTsFile = TS.test(sourceSymbol.filePath);
24341 if (this.summaryResolver.isLibraryFile(sourceSymbol.filePath) && !isTsFile && metadata &&
24342 metadata['__symbolic'] === 'class') {
24343 var transformedMeta_1 = { __symbolic: 'class', arity: metadata.arity };
24344 return new ResolvedStaticSymbol(sourceSymbol, transformedMeta_1);
24345 }
24346 var _originalFileMemo;
24347 var getOriginalName = function () {
24348 if (!_originalFileMemo) {
24349 // Guess what the original file name is from the reference. If it has a `.d.ts` extension
24350 // replace it with `.ts`. If it already has `.ts` just leave it in place. If it doesn't have
24351 // .ts or .d.ts, append `.ts'. Also, if it is in `node_modules`, trim the `node_module`
24352 // location as it is not important to finding the file.
24353 _originalFileMemo =
24354 _this.host.getOutputName(topLevelPath.replace(/((\.ts)|(\.d\.ts)|)$/, '.ts')
24355 .replace(/^.*node_modules[/\\]/, ''));
24356 }
24357 return _originalFileMemo;
24358 };
24359 var self = this;
24360 var ReferenceTransformer = /** @class */ (function (_super) {
24361 __extends(ReferenceTransformer, _super);
24362 function ReferenceTransformer() {
24363 return _super !== null && _super.apply(this, arguments) || this;
24364 }
24365 ReferenceTransformer.prototype.visitStringMap = function (map, functionParams) {
24366 var symbolic = map['__symbolic'];
24367 if (symbolic === 'function') {
24368 var oldLen = functionParams.length;
24369 functionParams.push.apply(functionParams, __spread((map['parameters'] || [])));
24370 var result = _super.prototype.visitStringMap.call(this, map, functionParams);
24371 functionParams.length = oldLen;
24372 return result;
24373 }
24374 else if (symbolic === 'reference') {
24375 var module = map['module'];
24376 var name_1 = map['name'] ? unescapeIdentifier(map['name']) : map['name'];
24377 if (!name_1) {
24378 return null;
24379 }
24380 var filePath = void 0;
24381 if (module) {
24382 filePath = self.resolveModule(module, sourceSymbol.filePath);
24383 if (!filePath) {
24384 return {
24385 __symbolic: 'error',
24386 message: "Could not resolve " + module + " relative to " + self.host.getMetadataFor(sourceSymbol.filePath) + ".",
24387 line: map['line'],
24388 character: map['character'],
24389 fileName: getOriginalName()
24390 };
24391 }
24392 return {
24393 __symbolic: 'resolved',
24394 symbol: self.getStaticSymbol(filePath, name_1),
24395 line: map['line'],
24396 character: map['character'],
24397 fileName: getOriginalName()
24398 };
24399 }
24400 else if (functionParams.indexOf(name_1) >= 0) {
24401 // reference to a function parameter
24402 return { __symbolic: 'reference', name: name_1 };
24403 }
24404 else {
24405 if (topLevelSymbolNames.has(name_1)) {
24406 return self.getStaticSymbol(topLevelPath, name_1);
24407 }
24408 // ambient value
24409 null;
24410 }
24411 }
24412 else if (symbolic === 'error') {
24413 return __assign({}, map, { fileName: getOriginalName() });
24414 }
24415 else {
24416 return _super.prototype.visitStringMap.call(this, map, functionParams);
24417 }
24418 };
24419 return ReferenceTransformer;
24420 }(ValueTransformer));
24421 var transformedMeta = visitValue(metadata, new ReferenceTransformer(), []);
24422 var unwrappedTransformedMeta = unwrapResolvedMetadata(transformedMeta);
24423 if (unwrappedTransformedMeta instanceof StaticSymbol) {
24424 return this.createExport(sourceSymbol, unwrappedTransformedMeta);
24425 }
24426 return new ResolvedStaticSymbol(sourceSymbol, transformedMeta);
24427 };
24428 StaticSymbolResolver.prototype.createExport = function (sourceSymbol, targetSymbol) {
24429 sourceSymbol.assertNoMembers();
24430 targetSymbol.assertNoMembers();
24431 if (this.summaryResolver.isLibraryFile(sourceSymbol.filePath) &&
24432 this.summaryResolver.isLibraryFile(targetSymbol.filePath)) {
24433 // This case is for an ng library importing symbols from a plain ts library
24434 // transitively.
24435 // Note: We rely on the fact that we discover symbols in the direction
24436 // from source files to library files
24437 this.importAs.set(targetSymbol, this.getImportAs(sourceSymbol) || sourceSymbol);
24438 }
24439 return new ResolvedStaticSymbol(sourceSymbol, targetSymbol);
24440 };
24441 StaticSymbolResolver.prototype.reportError = function (error, context, path) {
24442 if (this.errorRecorder) {
24443 this.errorRecorder(error, (context && context.filePath) || path);
24444 }
24445 else {
24446 throw error;
24447 }
24448 };
24449 /**
24450 * @param module an absolute path to a module file.
24451 */
24452 StaticSymbolResolver.prototype.getModuleMetadata = function (module) {
24453 var moduleMetadata = this.metadataCache.get(module);
24454 if (!moduleMetadata) {
24455 var moduleMetadatas = this.host.getMetadataFor(module);
24456 if (moduleMetadatas) {
24457 var maxVersion_1 = -1;
24458 moduleMetadatas.forEach(function (md) {
24459 if (md && md['version'] > maxVersion_1) {
24460 maxVersion_1 = md['version'];
24461 moduleMetadata = md;
24462 }
24463 });
24464 }
24465 if (!moduleMetadata) {
24466 moduleMetadata =
24467 { __symbolic: 'module', version: SUPPORTED_SCHEMA_VERSION, module: module, metadata: {} };
24468 }
24469 if (moduleMetadata['version'] != SUPPORTED_SCHEMA_VERSION) {
24470 var errorMessage = moduleMetadata['version'] == 2 ?
24471 "Unsupported metadata version " + moduleMetadata['version'] + " for module " + module + ". This module should be compiled with a newer version of ngc" :
24472 "Metadata version mismatch for module " + this.host.getOutputName(module) + ", found version " + moduleMetadata['version'] + ", expected " + SUPPORTED_SCHEMA_VERSION;
24473 this.reportError(new Error(errorMessage));
24474 }
24475 this.metadataCache.set(module, moduleMetadata);
24476 }
24477 return moduleMetadata;
24478 };
24479 StaticSymbolResolver.prototype.getSymbolByModule = function (module, symbolName, containingFile) {
24480 var filePath = this.resolveModule(module, containingFile);
24481 if (!filePath) {
24482 this.reportError(new Error("Could not resolve module " + module + (containingFile ? ' relative to ' +
24483 this.host.getOutputName(containingFile) : '')));
24484 return this.getStaticSymbol("ERROR:" + module, symbolName);
24485 }
24486 return this.getStaticSymbol(filePath, symbolName);
24487 };
24488 StaticSymbolResolver.prototype.resolveModule = function (module, containingFile) {
24489 try {
24490 return this.host.moduleNameToFileName(module, containingFile);
24491 }
24492 catch (e) {
24493 console.error("Could not resolve module '" + module + "' relative to file " + containingFile);
24494 this.reportError(e, undefined, containingFile);
24495 }
24496 return null;
24497 };
24498 return StaticSymbolResolver;
24499}());
24500// Remove extra underscore from escaped identifier.
24501// See https://github.com/Microsoft/TypeScript/blob/master/src/compiler/utilities.ts
24502function unescapeIdentifier(identifier) {
24503 return identifier.startsWith('___') ? identifier.substr(1) : identifier;
24504}
24505function unwrapResolvedMetadata(metadata) {
24506 if (metadata && metadata.__symbolic === 'resolved') {
24507 return metadata.symbol;
24508 }
24509 return metadata;
24510}
24511
24512function serializeSummaries(srcFileName, forJitCtx, summaryResolver, symbolResolver, symbols, types, createExternalSymbolReexports) {
24513 if (createExternalSymbolReexports === void 0) { createExternalSymbolReexports = false; }
24514 var toJsonSerializer = new ToJsonSerializer(symbolResolver, summaryResolver, srcFileName);
24515 // for symbols, we use everything except for the class metadata itself
24516 // (we keep the statics though), as the class metadata is contained in the
24517 // CompileTypeSummary.
24518 symbols.forEach(function (resolvedSymbol) { return toJsonSerializer.addSummary({ symbol: resolvedSymbol.symbol, metadata: resolvedSymbol.metadata }); });
24519 // Add type summaries.
24520 types.forEach(function (_a) {
24521 var summary = _a.summary, metadata = _a.metadata;
24522 toJsonSerializer.addSummary({ symbol: summary.type.reference, metadata: undefined, type: summary });
24523 });
24524 var _a = toJsonSerializer.serialize(createExternalSymbolReexports), json = _a.json, exportAs = _a.exportAs;
24525 if (forJitCtx) {
24526 var forJitSerializer_1 = new ForJitSerializer(forJitCtx, symbolResolver, summaryResolver);
24527 types.forEach(function (_a) {
24528 var summary = _a.summary, metadata = _a.metadata;
24529 forJitSerializer_1.addSourceType(summary, metadata);
24530 });
24531 toJsonSerializer.unprocessedSymbolSummariesBySymbol.forEach(function (summary) {
24532 if (summaryResolver.isLibraryFile(summary.symbol.filePath) && summary.type) {
24533 forJitSerializer_1.addLibType(summary.type);
24534 }
24535 });
24536 forJitSerializer_1.serialize(exportAs);
24537 }
24538 return { json: json, exportAs: exportAs };
24539}
24540function deserializeSummaries(symbolCache, summaryResolver, libraryFileName, json) {
24541 var deserializer = new FromJsonDeserializer(symbolCache, summaryResolver);
24542 return deserializer.deserialize(libraryFileName, json);
24543}
24544function createForJitStub(outputCtx, reference) {
24545 return createSummaryForJitFunction(outputCtx, reference, NULL_EXPR);
24546}
24547function createSummaryForJitFunction(outputCtx, reference, value) {
24548 var fnName = summaryForJitName(reference.name);
24549 outputCtx.statements.push(fn([], [new ReturnStatement(value)], new ArrayType(DYNAMIC_TYPE)).toDeclStmt(fnName, [
24550 StmtModifier.Final, StmtModifier.Exported
24551 ]));
24552}
24553var ToJsonSerializer = /** @class */ (function (_super) {
24554 __extends(ToJsonSerializer, _super);
24555 function ToJsonSerializer(symbolResolver, summaryResolver, srcFileName) {
24556 var _this = _super.call(this) || this;
24557 _this.symbolResolver = symbolResolver;
24558 _this.summaryResolver = summaryResolver;
24559 _this.srcFileName = srcFileName;
24560 // Note: This only contains symbols without members.
24561 _this.symbols = [];
24562 _this.indexBySymbol = new Map();
24563 _this.reexportedBy = new Map();
24564 // This now contains a `__symbol: number` in the place of
24565 // StaticSymbols, but otherwise has the same shape as the original objects.
24566 _this.processedSummaryBySymbol = new Map();
24567 _this.processedSummaries = [];
24568 _this.unprocessedSymbolSummariesBySymbol = new Map();
24569 _this.moduleName = symbolResolver.getKnownModuleName(srcFileName);
24570 return _this;
24571 }
24572 ToJsonSerializer.prototype.addSummary = function (summary) {
24573 var _this = this;
24574 var unprocessedSummary = this.unprocessedSymbolSummariesBySymbol.get(summary.symbol);
24575 var processedSummary = this.processedSummaryBySymbol.get(summary.symbol);
24576 if (!unprocessedSummary) {
24577 unprocessedSummary = { symbol: summary.symbol, metadata: undefined };
24578 this.unprocessedSymbolSummariesBySymbol.set(summary.symbol, unprocessedSummary);
24579 processedSummary = { symbol: this.processValue(summary.symbol, 0 /* None */) };
24580 this.processedSummaries.push(processedSummary);
24581 this.processedSummaryBySymbol.set(summary.symbol, processedSummary);
24582 }
24583 if (!unprocessedSummary.metadata && summary.metadata) {
24584 var metadata_1 = summary.metadata || {};
24585 if (metadata_1.__symbolic === 'class') {
24586 // For classes, we keep everything except their class decorators.
24587 // We need to keep e.g. the ctor args, method names, method decorators
24588 // so that the class can be extended in another compilation unit.
24589 // We don't keep the class decorators as
24590 // 1) they refer to data
24591 // that should not cause a rebuild of downstream compilation units
24592 // (e.g. inline templates of @Component, or @NgModule.declarations)
24593 // 2) their data is already captured in TypeSummaries, e.g. DirectiveSummary.
24594 var clone_1 = {};
24595 Object.keys(metadata_1).forEach(function (propName) {
24596 if (propName !== 'decorators') {
24597 clone_1[propName] = metadata_1[propName];
24598 }
24599 });
24600 metadata_1 = clone_1;
24601 }
24602 else if (isCall(metadata_1)) {
24603 if (!isFunctionCall(metadata_1) && !isMethodCallOnVariable(metadata_1)) {
24604 // Don't store complex calls as we won't be able to simplify them anyways later on.
24605 metadata_1 = {
24606 __symbolic: 'error',
24607 message: 'Complex function calls are not supported.',
24608 };
24609 }
24610 }
24611 // Note: We need to keep storing ctor calls for e.g.
24612 // `export const x = new InjectionToken(...)`
24613 unprocessedSummary.metadata = metadata_1;
24614 processedSummary.metadata = this.processValue(metadata_1, 1 /* ResolveValue */);
24615 if (metadata_1 instanceof StaticSymbol &&
24616 this.summaryResolver.isLibraryFile(metadata_1.filePath)) {
24617 var declarationSymbol = this.symbols[this.indexBySymbol.get(metadata_1)];
24618 if (!isLoweredSymbol(declarationSymbol.name)) {
24619 // Note: symbols that were introduced during codegen in the user file can have a reexport
24620 // if a user used `export *`. However, we can't rely on this as tsickle will change
24621 // `export *` into named exports, using only the information from the typechecker.
24622 // As we introduce the new symbols after typecheck, Tsickle does not know about them,
24623 // and omits them when expanding `export *`.
24624 // So we have to keep reexporting these symbols manually via .ngfactory files.
24625 this.reexportedBy.set(declarationSymbol, summary.symbol);
24626 }
24627 }
24628 }
24629 if (!unprocessedSummary.type && summary.type) {
24630 unprocessedSummary.type = summary.type;
24631 // Note: We don't add the summaries of all referenced symbols as for the ResolvedSymbols,
24632 // as the type summaries already contain the transitive data that they require
24633 // (in a minimal way).
24634 processedSummary.type = this.processValue(summary.type, 0 /* None */);
24635 // except for reexported directives / pipes, so we need to store
24636 // their summaries explicitly.
24637 if (summary.type.summaryKind === CompileSummaryKind.NgModule) {
24638 var ngModuleSummary = summary.type;
24639 ngModuleSummary.exportedDirectives.concat(ngModuleSummary.exportedPipes).forEach(function (id) {
24640 var symbol = id.reference;
24641 if (_this.summaryResolver.isLibraryFile(symbol.filePath) &&
24642 !_this.unprocessedSymbolSummariesBySymbol.has(symbol)) {
24643 var summary_1 = _this.summaryResolver.resolveSummary(symbol);
24644 if (summary_1) {
24645 _this.addSummary(summary_1);
24646 }
24647 }
24648 });
24649 }
24650 }
24651 };
24652 /**
24653 * @param createExternalSymbolReexports Whether external static symbols should be re-exported.
24654 * This can be enabled if external symbols should be re-exported by the current module in
24655 * order to avoid dynamically generated module dependencies which can break strict dependency
24656 * enforcements (as in Google3). Read more here: https://github.com/angular/angular/issues/25644
24657 */
24658 ToJsonSerializer.prototype.serialize = function (createExternalSymbolReexports) {
24659 var _this = this;
24660 var exportAs = [];
24661 var json = JSON.stringify({
24662 moduleName: this.moduleName,
24663 summaries: this.processedSummaries,
24664 symbols: this.symbols.map(function (symbol, index) {
24665 symbol.assertNoMembers();
24666 var importAs = undefined;
24667 if (_this.summaryResolver.isLibraryFile(symbol.filePath)) {
24668 var reexportSymbol = _this.reexportedBy.get(symbol);
24669 if (reexportSymbol) {
24670 // In case the given external static symbol is already manually exported by the
24671 // user, we just proxy the external static symbol reference to the manual export.
24672 // This ensures that the AOT compiler imports the external symbol through the
24673 // user export and does not introduce another dependency which is not needed.
24674 importAs = _this.indexBySymbol.get(reexportSymbol);
24675 }
24676 else if (createExternalSymbolReexports) {
24677 // In this case, the given external static symbol is *not* manually exported by
24678 // the user, and we manually create a re-export in the factory file so that we
24679 // don't introduce another module dependency. This is useful when running within
24680 // Bazel so that the AOT compiler does not introduce any module dependencies
24681 // which can break the strict dependency enforcement. (e.g. as in Google3)
24682 // Read more about this here: https://github.com/angular/angular/issues/25644
24683 var summary = _this.unprocessedSymbolSummariesBySymbol.get(symbol);
24684 if (!summary || !summary.metadata || summary.metadata.__symbolic !== 'interface') {
24685 importAs = symbol.name + "_" + index;
24686 exportAs.push({ symbol: symbol, exportAs: importAs });
24687 }
24688 }
24689 }
24690 return {
24691 __symbol: index,
24692 name: symbol.name,
24693 filePath: _this.summaryResolver.toSummaryFileName(symbol.filePath, _this.srcFileName),
24694 importAs: importAs
24695 };
24696 })
24697 });
24698 return { json: json, exportAs: exportAs };
24699 };
24700 ToJsonSerializer.prototype.processValue = function (value, flags) {
24701 return visitValue(value, this, flags);
24702 };
24703 ToJsonSerializer.prototype.visitOther = function (value, context) {
24704 if (value instanceof StaticSymbol) {
24705 var baseSymbol = this.symbolResolver.getStaticSymbol(value.filePath, value.name);
24706 var index = this.visitStaticSymbol(baseSymbol, context);
24707 return { __symbol: index, members: value.members };
24708 }
24709 };
24710 /**
24711 * Strip line and character numbers from ngsummaries.
24712 * Emitting them causes white spaces changes to retrigger upstream
24713 * recompilations in bazel.
24714 * TODO: find out a way to have line and character numbers in errors without
24715 * excessive recompilation in bazel.
24716 */
24717 ToJsonSerializer.prototype.visitStringMap = function (map, context) {
24718 if (map['__symbolic'] === 'resolved') {
24719 return visitValue(map['symbol'], this, context);
24720 }
24721 if (map['__symbolic'] === 'error') {
24722 delete map['line'];
24723 delete map['character'];
24724 }
24725 return _super.prototype.visitStringMap.call(this, map, context);
24726 };
24727 /**
24728 * Returns null if the options.resolveValue is true, and the summary for the symbol
24729 * resolved to a type or could not be resolved.
24730 */
24731 ToJsonSerializer.prototype.visitStaticSymbol = function (baseSymbol, flags) {
24732 var index = this.indexBySymbol.get(baseSymbol);
24733 var summary = null;
24734 if (flags & 1 /* ResolveValue */ &&
24735 this.summaryResolver.isLibraryFile(baseSymbol.filePath)) {
24736 if (this.unprocessedSymbolSummariesBySymbol.has(baseSymbol)) {
24737 // the summary for this symbol was already added
24738 // -> nothing to do.
24739 return index;
24740 }
24741 summary = this.loadSummary(baseSymbol);
24742 if (summary && summary.metadata instanceof StaticSymbol) {
24743 // The summary is a reexport
24744 index = this.visitStaticSymbol(summary.metadata, flags);
24745 // reset the summary as it is just a reexport, so we don't want to store it.
24746 summary = null;
24747 }
24748 }
24749 else if (index != null) {
24750 // Note: == on purpose to compare with undefined!
24751 // No summary and the symbol is already added -> nothing to do.
24752 return index;
24753 }
24754 // Note: == on purpose to compare with undefined!
24755 if (index == null) {
24756 index = this.symbols.length;
24757 this.symbols.push(baseSymbol);
24758 }
24759 this.indexBySymbol.set(baseSymbol, index);
24760 if (summary) {
24761 this.addSummary(summary);
24762 }
24763 return index;
24764 };
24765 ToJsonSerializer.prototype.loadSummary = function (symbol) {
24766 var summary = this.summaryResolver.resolveSummary(symbol);
24767 if (!summary) {
24768 // some symbols might originate from a plain typescript library
24769 // that just exported .d.ts and .metadata.json files, i.e. where no summary
24770 // files were created.
24771 var resolvedSymbol = this.symbolResolver.resolveSymbol(symbol);
24772 if (resolvedSymbol) {
24773 summary = { symbol: resolvedSymbol.symbol, metadata: resolvedSymbol.metadata };
24774 }
24775 }
24776 return summary;
24777 };
24778 return ToJsonSerializer;
24779}(ValueTransformer));
24780var ForJitSerializer = /** @class */ (function () {
24781 function ForJitSerializer(outputCtx, symbolResolver, summaryResolver) {
24782 this.outputCtx = outputCtx;
24783 this.symbolResolver = symbolResolver;
24784 this.summaryResolver = summaryResolver;
24785 this.data = [];
24786 }
24787 ForJitSerializer.prototype.addSourceType = function (summary, metadata) {
24788 this.data.push({ summary: summary, metadata: metadata, isLibrary: false });
24789 };
24790 ForJitSerializer.prototype.addLibType = function (summary) {
24791 this.data.push({ summary: summary, metadata: null, isLibrary: true });
24792 };
24793 ForJitSerializer.prototype.serialize = function (exportAsArr) {
24794 var e_1, _a, e_2, _b, e_3, _c;
24795 var _this = this;
24796 var exportAsBySymbol = new Map();
24797 try {
24798 for (var exportAsArr_1 = __values(exportAsArr), exportAsArr_1_1 = exportAsArr_1.next(); !exportAsArr_1_1.done; exportAsArr_1_1 = exportAsArr_1.next()) {
24799 var _d = exportAsArr_1_1.value, symbol = _d.symbol, exportAs = _d.exportAs;
24800 exportAsBySymbol.set(symbol, exportAs);
24801 }
24802 }
24803 catch (e_1_1) { e_1 = { error: e_1_1 }; }
24804 finally {
24805 try {
24806 if (exportAsArr_1_1 && !exportAsArr_1_1.done && (_a = exportAsArr_1.return)) _a.call(exportAsArr_1);
24807 }
24808 finally { if (e_1) throw e_1.error; }
24809 }
24810 var ngModuleSymbols = new Set();
24811 try {
24812 for (var _e = __values(this.data), _f = _e.next(); !_f.done; _f = _e.next()) {
24813 var _g = _f.value, summary = _g.summary, metadata = _g.metadata, isLibrary = _g.isLibrary;
24814 if (summary.summaryKind === CompileSummaryKind.NgModule) {
24815 // collect the symbols that refer to NgModule classes.
24816 // Note: we can't just rely on `summary.type.summaryKind` to determine this as
24817 // we don't add the summaries of all referenced symbols when we serialize type summaries.
24818 // See serializeSummaries for details.
24819 ngModuleSymbols.add(summary.type.reference);
24820 var modSummary = summary;
24821 try {
24822 for (var _h = (e_3 = void 0, __values(modSummary.modules)), _j = _h.next(); !_j.done; _j = _h.next()) {
24823 var mod = _j.value;
24824 ngModuleSymbols.add(mod.reference);
24825 }
24826 }
24827 catch (e_3_1) { e_3 = { error: e_3_1 }; }
24828 finally {
24829 try {
24830 if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
24831 }
24832 finally { if (e_3) throw e_3.error; }
24833 }
24834 }
24835 if (!isLibrary) {
24836 var fnName = summaryForJitName(summary.type.reference.name);
24837 createSummaryForJitFunction(this.outputCtx, summary.type.reference, this.serializeSummaryWithDeps(summary, metadata));
24838 }
24839 }
24840 }
24841 catch (e_2_1) { e_2 = { error: e_2_1 }; }
24842 finally {
24843 try {
24844 if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
24845 }
24846 finally { if (e_2) throw e_2.error; }
24847 }
24848 ngModuleSymbols.forEach(function (ngModuleSymbol) {
24849 if (_this.summaryResolver.isLibraryFile(ngModuleSymbol.filePath)) {
24850 var exportAs = exportAsBySymbol.get(ngModuleSymbol) || ngModuleSymbol.name;
24851 var jitExportAsName = summaryForJitName(exportAs);
24852 _this.outputCtx.statements.push(variable(jitExportAsName)
24853 .set(_this.serializeSummaryRef(ngModuleSymbol))
24854 .toDeclStmt(null, [StmtModifier.Exported]));
24855 }
24856 });
24857 };
24858 ForJitSerializer.prototype.serializeSummaryWithDeps = function (summary, metadata) {
24859 var _this = this;
24860 var expressions = [this.serializeSummary(summary)];
24861 var providers = [];
24862 if (metadata instanceof CompileNgModuleMetadata) {
24863 expressions.push.apply(expressions, __spread(
24864 // For directives / pipes, we only add the declared ones,
24865 // and rely on transitively importing NgModules to get the transitive
24866 // summaries.
24867 metadata.declaredDirectives.concat(metadata.declaredPipes)
24868 .map(function (type) { return type.reference; })
24869 // For modules,
24870 // we also add the summaries for modules
24871 // from libraries.
24872 // This is ok as we produce reexports for all transitive modules.
24873 .concat(metadata.transitiveModule.modules.map(function (type) { return type.reference; })
24874 .filter(function (ref) { return ref !== metadata.type.reference; }))
24875 .map(function (ref) { return _this.serializeSummaryRef(ref); })));
24876 // Note: We don't use `NgModuleSummary.providers`, as that one is transitive,
24877 // and we already have transitive modules.
24878 providers = metadata.providers;
24879 }
24880 else if (summary.summaryKind === CompileSummaryKind.Directive) {
24881 var dirSummary = summary;
24882 providers = dirSummary.providers.concat(dirSummary.viewProviders);
24883 }
24884 // Note: We can't just refer to the `ngsummary.ts` files for `useClass` providers (as we do for
24885 // declaredDirectives / declaredPipes), as we allow
24886 // providers without ctor arguments to skip the `@Injectable` decorator,
24887 // i.e. we didn't generate .ngsummary.ts files for these.
24888 expressions.push.apply(expressions, __spread(providers.filter(function (provider) { return !!provider.useClass; }).map(function (provider) { return _this.serializeSummary({
24889 summaryKind: CompileSummaryKind.Injectable, type: provider.useClass
24890 }); })));
24891 return literalArr(expressions);
24892 };
24893 ForJitSerializer.prototype.serializeSummaryRef = function (typeSymbol) {
24894 var jitImportedSymbol = this.symbolResolver.getStaticSymbol(summaryForJitFileName(typeSymbol.filePath), summaryForJitName(typeSymbol.name));
24895 return this.outputCtx.importExpr(jitImportedSymbol);
24896 };
24897 ForJitSerializer.prototype.serializeSummary = function (data) {
24898 var outputCtx = this.outputCtx;
24899 var Transformer = /** @class */ (function () {
24900 function Transformer() {
24901 }
24902 Transformer.prototype.visitArray = function (arr, context) {
24903 var _this = this;
24904 return literalArr(arr.map(function (entry) { return visitValue(entry, _this, context); }));
24905 };
24906 Transformer.prototype.visitStringMap = function (map, context) {
24907 var _this = this;
24908 return new LiteralMapExpr(Object.keys(map).map(function (key) { return new LiteralMapEntry(key, visitValue(map[key], _this, context), false); }));
24909 };
24910 Transformer.prototype.visitPrimitive = function (value, context) { return literal(value); };
24911 Transformer.prototype.visitOther = function (value, context) {
24912 if (value instanceof StaticSymbol) {
24913 return outputCtx.importExpr(value);
24914 }
24915 else {
24916 throw new Error("Illegal State: Encountered value " + value);
24917 }
24918 };
24919 return Transformer;
24920 }());
24921 return visitValue(data, new Transformer(), null);
24922 };
24923 return ForJitSerializer;
24924}());
24925var FromJsonDeserializer = /** @class */ (function (_super) {
24926 __extends(FromJsonDeserializer, _super);
24927 function FromJsonDeserializer(symbolCache, summaryResolver) {
24928 var _this = _super.call(this) || this;
24929 _this.symbolCache = symbolCache;
24930 _this.summaryResolver = summaryResolver;
24931 return _this;
24932 }
24933 FromJsonDeserializer.prototype.deserialize = function (libraryFileName, json) {
24934 var _this = this;
24935 var data = JSON.parse(json);
24936 var allImportAs = [];
24937 this.symbols = data.symbols.map(function (serializedSymbol) { return _this.symbolCache.get(_this.summaryResolver.fromSummaryFileName(serializedSymbol.filePath, libraryFileName), serializedSymbol.name); });
24938 data.symbols.forEach(function (serializedSymbol, index) {
24939 var symbol = _this.symbols[index];
24940 var importAs = serializedSymbol.importAs;
24941 if (typeof importAs === 'number') {
24942 allImportAs.push({ symbol: symbol, importAs: _this.symbols[importAs] });
24943 }
24944 else if (typeof importAs === 'string') {
24945 allImportAs.push({ symbol: symbol, importAs: _this.symbolCache.get(ngfactoryFilePath(libraryFileName), importAs) });
24946 }
24947 });
24948 var summaries = visitValue(data.summaries, this, null);
24949 return { moduleName: data.moduleName, summaries: summaries, importAs: allImportAs };
24950 };
24951 FromJsonDeserializer.prototype.visitStringMap = function (map, context) {
24952 if ('__symbol' in map) {
24953 var baseSymbol = this.symbols[map['__symbol']];
24954 var members = map['members'];
24955 return members.length ? this.symbolCache.get(baseSymbol.filePath, baseSymbol.name, members) :
24956 baseSymbol;
24957 }
24958 else {
24959 return _super.prototype.visitStringMap.call(this, map, context);
24960 }
24961 };
24962 return FromJsonDeserializer;
24963}(ValueTransformer));
24964function isCall(metadata) {
24965 return metadata && metadata.__symbolic === 'call';
24966}
24967function isFunctionCall(metadata) {
24968 return isCall(metadata) && unwrapResolvedMetadata(metadata.expression) instanceof StaticSymbol;
24969}
24970function isMethodCallOnVariable(metadata) {
24971 return isCall(metadata) && metadata.expression && metadata.expression.__symbolic === 'select' &&
24972 unwrapResolvedMetadata(metadata.expression.expression) instanceof StaticSymbol;
24973}
24974
24975/**
24976 * @license
24977 * Copyright Google Inc. All Rights Reserved.
24978 *
24979 * Use of this source code is governed by an MIT-style license that can be
24980 * found in the LICENSE file at https://angular.io/license
24981 */
24982var AotCompiler = /** @class */ (function () {
24983 function AotCompiler(_config, _options, _host, reflector, _metadataResolver, _templateParser, _styleCompiler, _viewCompiler, _typeCheckCompiler, _ngModuleCompiler, _injectableCompiler, _outputEmitter, _summaryResolver, _symbolResolver) {
24984 this._config = _config;
24985 this._options = _options;
24986 this._host = _host;
24987 this.reflector = reflector;
24988 this._metadataResolver = _metadataResolver;
24989 this._templateParser = _templateParser;
24990 this._styleCompiler = _styleCompiler;
24991 this._viewCompiler = _viewCompiler;
24992 this._typeCheckCompiler = _typeCheckCompiler;
24993 this._ngModuleCompiler = _ngModuleCompiler;
24994 this._injectableCompiler = _injectableCompiler;
24995 this._outputEmitter = _outputEmitter;
24996 this._summaryResolver = _summaryResolver;
24997 this._symbolResolver = _symbolResolver;
24998 this._templateAstCache = new Map();
24999 this._analyzedFiles = new Map();
25000 this._analyzedFilesForInjectables = new Map();
25001 }
25002 AotCompiler.prototype.clearCache = function () { this._metadataResolver.clearCache(); };
25003 AotCompiler.prototype.analyzeModulesSync = function (rootFiles) {
25004 var _this = this;
25005 var analyzeResult = analyzeAndValidateNgModules(rootFiles, this._host, this._symbolResolver, this._metadataResolver);
25006 analyzeResult.ngModules.forEach(function (ngModule) { return _this._metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, true); });
25007 return analyzeResult;
25008 };
25009 AotCompiler.prototype.analyzeModulesAsync = function (rootFiles) {
25010 var _this = this;
25011 var analyzeResult = analyzeAndValidateNgModules(rootFiles, this._host, this._symbolResolver, this._metadataResolver);
25012 return Promise
25013 .all(analyzeResult.ngModules.map(function (ngModule) { return _this._metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, false); }))
25014 .then(function () { return analyzeResult; });
25015 };
25016 AotCompiler.prototype._analyzeFile = function (fileName) {
25017 var analyzedFile = this._analyzedFiles.get(fileName);
25018 if (!analyzedFile) {
25019 analyzedFile =
25020 analyzeFile(this._host, this._symbolResolver, this._metadataResolver, fileName);
25021 this._analyzedFiles.set(fileName, analyzedFile);
25022 }
25023 return analyzedFile;
25024 };
25025 AotCompiler.prototype._analyzeFileForInjectables = function (fileName) {
25026 var analyzedFile = this._analyzedFilesForInjectables.get(fileName);
25027 if (!analyzedFile) {
25028 analyzedFile = analyzeFileForInjectables(this._host, this._symbolResolver, this._metadataResolver, fileName);
25029 this._analyzedFilesForInjectables.set(fileName, analyzedFile);
25030 }
25031 return analyzedFile;
25032 };
25033 AotCompiler.prototype.findGeneratedFileNames = function (fileName) {
25034 var _this = this;
25035 var genFileNames = [];
25036 var file = this._analyzeFile(fileName);
25037 // Make sure we create a .ngfactory if we have a injectable/directive/pipe/NgModule
25038 // or a reference to a non source file.
25039 // Note: This is overestimating the required .ngfactory files as the real calculation is harder.
25040 // Only do this for StubEmitFlags.Basic, as adding a type check block
25041 // does not change this file (as we generate type check blocks based on NgModules).
25042 if (this._options.allowEmptyCodegenFiles || file.directives.length || file.pipes.length ||
25043 file.injectables.length || file.ngModules.length || file.exportsNonSourceFiles) {
25044 genFileNames.push(ngfactoryFilePath(file.fileName, true));
25045 if (this._options.enableSummariesForJit) {
25046 genFileNames.push(summaryForJitFileName(file.fileName, true));
25047 }
25048 }
25049 var fileSuffix = normalizeGenFileSuffix(splitTypescriptSuffix(file.fileName, true)[1]);
25050 file.directives.forEach(function (dirSymbol) {
25051 var compMeta = _this._metadataResolver.getNonNormalizedDirectiveMetadata(dirSymbol).metadata;
25052 if (!compMeta.isComponent) {
25053 return;
25054 }
25055 // Note: compMeta is a component and therefore template is non null.
25056 compMeta.template.styleUrls.forEach(function (styleUrl) {
25057 var normalizedUrl = _this._host.resourceNameToFileName(styleUrl, file.fileName);
25058 if (!normalizedUrl) {
25059 throw syntaxError("Couldn't resolve resource " + styleUrl + " relative to " + file.fileName);
25060 }
25061 var needsShim = (compMeta.template.encapsulation ||
25062 _this._config.defaultEncapsulation) === ViewEncapsulation.Emulated;
25063 genFileNames.push(_stylesModuleUrl(normalizedUrl, needsShim, fileSuffix));
25064 if (_this._options.allowEmptyCodegenFiles) {
25065 genFileNames.push(_stylesModuleUrl(normalizedUrl, !needsShim, fileSuffix));
25066 }
25067 });
25068 });
25069 return genFileNames;
25070 };
25071 AotCompiler.prototype.emitBasicStub = function (genFileName, originalFileName) {
25072 var outputCtx = this._createOutputContext(genFileName);
25073 if (genFileName.endsWith('.ngfactory.ts')) {
25074 if (!originalFileName) {
25075 throw new Error("Assertion error: require the original file for .ngfactory.ts stubs. File: " + genFileName);
25076 }
25077 var originalFile = this._analyzeFile(originalFileName);
25078 this._createNgFactoryStub(outputCtx, originalFile, 1 /* Basic */);
25079 }
25080 else if (genFileName.endsWith('.ngsummary.ts')) {
25081 if (this._options.enableSummariesForJit) {
25082 if (!originalFileName) {
25083 throw new Error("Assertion error: require the original file for .ngsummary.ts stubs. File: " + genFileName);
25084 }
25085 var originalFile = this._analyzeFile(originalFileName);
25086 _createEmptyStub(outputCtx);
25087 originalFile.ngModules.forEach(function (ngModule) {
25088 // create exports that user code can reference
25089 createForJitStub(outputCtx, ngModule.type.reference);
25090 });
25091 }
25092 }
25093 else if (genFileName.endsWith('.ngstyle.ts')) {
25094 _createEmptyStub(outputCtx);
25095 }
25096 // Note: for the stubs, we don't need a property srcFileUrl,
25097 // as later on in emitAllImpls we will create the proper GeneratedFiles with the
25098 // correct srcFileUrl.
25099 // This is good as e.g. for .ngstyle.ts files we can't derive
25100 // the url of components based on the genFileUrl.
25101 return this._codegenSourceModule('unknown', outputCtx);
25102 };
25103 AotCompiler.prototype.emitTypeCheckStub = function (genFileName, originalFileName) {
25104 var originalFile = this._analyzeFile(originalFileName);
25105 var outputCtx = this._createOutputContext(genFileName);
25106 if (genFileName.endsWith('.ngfactory.ts')) {
25107 this._createNgFactoryStub(outputCtx, originalFile, 2 /* TypeCheck */);
25108 }
25109 return outputCtx.statements.length > 0 ?
25110 this._codegenSourceModule(originalFile.fileName, outputCtx) :
25111 null;
25112 };
25113 AotCompiler.prototype.loadFilesAsync = function (fileNames, tsFiles) {
25114 var _this = this;
25115 var files = fileNames.map(function (fileName) { return _this._analyzeFile(fileName); });
25116 var loadingPromises = [];
25117 files.forEach(function (file) { return file.ngModules.forEach(function (ngModule) {
25118 return loadingPromises.push(_this._metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, false));
25119 }); });
25120 var analyzedInjectables = tsFiles.map(function (tsFile) { return _this._analyzeFileForInjectables(tsFile); });
25121 return Promise.all(loadingPromises).then(function (_) { return ({
25122 analyzedModules: mergeAndValidateNgFiles(files),
25123 analyzedInjectables: analyzedInjectables,
25124 }); });
25125 };
25126 AotCompiler.prototype.loadFilesSync = function (fileNames, tsFiles) {
25127 var _this = this;
25128 var files = fileNames.map(function (fileName) { return _this._analyzeFile(fileName); });
25129 files.forEach(function (file) { return file.ngModules.forEach(function (ngModule) { return _this._metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, true); }); });
25130 var analyzedInjectables = tsFiles.map(function (tsFile) { return _this._analyzeFileForInjectables(tsFile); });
25131 return {
25132 analyzedModules: mergeAndValidateNgFiles(files),
25133 analyzedInjectables: analyzedInjectables,
25134 };
25135 };
25136 AotCompiler.prototype._createNgFactoryStub = function (outputCtx, file, emitFlags) {
25137 var _this = this;
25138 var componentId = 0;
25139 file.ngModules.forEach(function (ngModuleMeta, ngModuleIndex) {
25140 // Note: the code below needs to executed for StubEmitFlags.Basic and StubEmitFlags.TypeCheck,
25141 // so we don't change the .ngfactory file too much when adding the type-check block.
25142 // create exports that user code can reference
25143 _this._ngModuleCompiler.createStub(outputCtx, ngModuleMeta.type.reference);
25144 // add references to the symbols from the metadata.
25145 // These can be used by the type check block for components,
25146 // and they also cause TypeScript to include these files into the program too,
25147 // which will make them part of the analyzedFiles.
25148 var externalReferences = __spread(ngModuleMeta.transitiveModule.directives.map(function (d) { return d.reference; }), ngModuleMeta.transitiveModule.pipes.map(function (d) { return d.reference; }), ngModuleMeta.importedModules.map(function (m) { return m.type.reference; }), ngModuleMeta.exportedModules.map(function (m) { return m.type.reference; }), _this._externalIdentifierReferences([Identifiers.TemplateRef, Identifiers.ElementRef]));
25149 var externalReferenceVars = new Map();
25150 externalReferences.forEach(function (ref, typeIndex) {
25151 externalReferenceVars.set(ref, "_decl" + ngModuleIndex + "_" + typeIndex);
25152 });
25153 externalReferenceVars.forEach(function (varName, reference) {
25154 outputCtx.statements.push(variable(varName)
25155 .set(NULL_EXPR.cast(DYNAMIC_TYPE))
25156 .toDeclStmt(expressionType(outputCtx.importExpr(reference, /* typeParams */ null, /* useSummaries */ false))));
25157 });
25158 if (emitFlags & 2 /* TypeCheck */) {
25159 // add the type-check block for all components of the NgModule
25160 ngModuleMeta.declaredDirectives.forEach(function (dirId) {
25161 var compMeta = _this._metadataResolver.getDirectiveMetadata(dirId.reference);
25162 if (!compMeta.isComponent) {
25163 return;
25164 }
25165 componentId++;
25166 _this._createTypeCheckBlock(outputCtx, compMeta.type.reference.name + "_Host_" + componentId, ngModuleMeta, _this._metadataResolver.getHostComponentMetadata(compMeta), [compMeta.type], externalReferenceVars);
25167 _this._createTypeCheckBlock(outputCtx, compMeta.type.reference.name + "_" + componentId, ngModuleMeta, compMeta, ngModuleMeta.transitiveModule.directives, externalReferenceVars);
25168 });
25169 }
25170 });
25171 if (outputCtx.statements.length === 0) {
25172 _createEmptyStub(outputCtx);
25173 }
25174 };
25175 AotCompiler.prototype._externalIdentifierReferences = function (references) {
25176 var e_1, _a;
25177 var result = [];
25178 try {
25179 for (var references_1 = __values(references), references_1_1 = references_1.next(); !references_1_1.done; references_1_1 = references_1.next()) {
25180 var reference = references_1_1.value;
25181 var token = createTokenForExternalReference(this.reflector, reference);
25182 if (token.identifier) {
25183 result.push(token.identifier.reference);
25184 }
25185 }
25186 }
25187 catch (e_1_1) { e_1 = { error: e_1_1 }; }
25188 finally {
25189 try {
25190 if (references_1_1 && !references_1_1.done && (_a = references_1.return)) _a.call(references_1);
25191 }
25192 finally { if (e_1) throw e_1.error; }
25193 }
25194 return result;
25195 };
25196 AotCompiler.prototype._createTypeCheckBlock = function (ctx, componentId, moduleMeta, compMeta, directives, externalReferenceVars) {
25197 var _a;
25198 var _b = this._parseTemplate(compMeta, moduleMeta, directives), parsedTemplate = _b.template, usedPipes = _b.pipes;
25199 (_a = ctx.statements).push.apply(_a, __spread(this._typeCheckCompiler.compileComponent(componentId, compMeta, parsedTemplate, usedPipes, externalReferenceVars, ctx)));
25200 };
25201 AotCompiler.prototype.emitMessageBundle = function (analyzeResult, locale) {
25202 var _this = this;
25203 var errors = [];
25204 var htmlParser = new HtmlParser();
25205 // TODO(vicb): implicit tags & attributes
25206 var messageBundle = new MessageBundle(htmlParser, [], {}, locale);
25207 analyzeResult.files.forEach(function (file) {
25208 var compMetas = [];
25209 file.directives.forEach(function (directiveType) {
25210 var dirMeta = _this._metadataResolver.getDirectiveMetadata(directiveType);
25211 if (dirMeta && dirMeta.isComponent) {
25212 compMetas.push(dirMeta);
25213 }
25214 });
25215 compMetas.forEach(function (compMeta) {
25216 var html = compMeta.template.template;
25217 // Template URL points to either an HTML or TS file depending on whether
25218 // the file is used with `templateUrl:` or `template:`, respectively.
25219 var templateUrl = compMeta.template.templateUrl;
25220 var interpolationConfig = InterpolationConfig.fromArray(compMeta.template.interpolation);
25221 errors.push.apply(errors, __spread(messageBundle.updateFromTemplate(html, templateUrl, interpolationConfig)));
25222 });
25223 });
25224 if (errors.length) {
25225 throw new Error(errors.map(function (e) { return e.toString(); }).join('\n'));
25226 }
25227 return messageBundle;
25228 };
25229 AotCompiler.prototype.emitAllPartialModules = function (_a, r3Files) {
25230 var _this = this;
25231 var ngModuleByPipeOrDirective = _a.ngModuleByPipeOrDirective, files = _a.files;
25232 var contextMap = new Map();
25233 var getContext = function (fileName) {
25234 if (!contextMap.has(fileName)) {
25235 contextMap.set(fileName, _this._createOutputContext(fileName));
25236 }
25237 return contextMap.get(fileName);
25238 };
25239 files.forEach(function (file) { return _this._compilePartialModule(file.fileName, ngModuleByPipeOrDirective, file.directives, file.pipes, file.ngModules, file.injectables, getContext(file.fileName)); });
25240 r3Files.forEach(function (file) { return _this._compileShallowModules(file.fileName, file.shallowModules, getContext(file.fileName)); });
25241 return Array.from(contextMap.values())
25242 .map(function (context) { return ({
25243 fileName: context.genFilePath,
25244 statements: __spread(context.constantPool.statements, context.statements),
25245 }); });
25246 };
25247 AotCompiler.prototype._compileShallowModules = function (fileName, shallowModules, context) {
25248 var _this = this;
25249 shallowModules.forEach(function (module) { return compileNgModuleFromRender2(context, module, _this._injectableCompiler); });
25250 };
25251 AotCompiler.prototype._compilePartialModule = function (fileName, ngModuleByPipeOrDirective, directives, pipes, ngModules, injectables, context) {
25252 var _this = this;
25253 var errors = [];
25254 var schemaRegistry = new DomElementSchemaRegistry();
25255 var hostBindingParser = new BindingParser(this._templateParser.expressionParser, DEFAULT_INTERPOLATION_CONFIG, schemaRegistry, [], errors);
25256 // Process all components and directives
25257 directives.forEach(function (directiveType) {
25258 var directiveMetadata = _this._metadataResolver.getDirectiveMetadata(directiveType);
25259 if (directiveMetadata.isComponent) {
25260 var module = ngModuleByPipeOrDirective.get(directiveType);
25261 module ||
25262 error("Cannot determine the module for component '" + identifierName(directiveMetadata.type) + "'");
25263 var htmlAst = directiveMetadata.template.htmlAst;
25264 var preserveWhitespaces = directiveMetadata.template.preserveWhitespaces;
25265 if (!preserveWhitespaces) {
25266 htmlAst = removeWhitespaces(htmlAst);
25267 }
25268 var render3Ast = htmlAstToRender3Ast(htmlAst.rootNodes, hostBindingParser);
25269 // Map of StaticType by directive selectors
25270 var directiveTypeBySel_1 = new Map();
25271 var directives_1 = module.transitiveModule.directives.map(function (dir) { return _this._metadataResolver.getDirectiveSummary(dir.reference); });
25272 directives_1.forEach(function (directive) {
25273 if (directive.selector) {
25274 directiveTypeBySel_1.set(directive.selector, directive.type.reference);
25275 }
25276 });
25277 // Map of StaticType by pipe names
25278 var pipeTypeByName_1 = new Map();
25279 var pipes_1 = module.transitiveModule.pipes.map(function (pipe) { return _this._metadataResolver.getPipeSummary(pipe.reference); });
25280 pipes_1.forEach(function (pipe) { pipeTypeByName_1.set(pipe.name, pipe.type.reference); });
25281 compileComponentFromRender2(context, directiveMetadata, render3Ast, _this.reflector, hostBindingParser, directiveTypeBySel_1, pipeTypeByName_1);
25282 }
25283 else {
25284 compileDirectiveFromRender2(context, directiveMetadata, _this.reflector, hostBindingParser);
25285 }
25286 });
25287 pipes.forEach(function (pipeType) {
25288 var pipeMetadata = _this._metadataResolver.getPipeMetadata(pipeType);
25289 if (pipeMetadata) {
25290 compilePipeFromRender2(context, pipeMetadata, _this.reflector);
25291 }
25292 });
25293 injectables.forEach(function (injectable) { return _this._injectableCompiler.compile(injectable, context); });
25294 };
25295 AotCompiler.prototype.emitAllPartialModules2 = function (files) {
25296 var _this = this;
25297 // Using reduce like this is a select many pattern (where map is a select pattern)
25298 return files.reduce(function (r, file) {
25299 r.push.apply(r, __spread(_this._emitPartialModule2(file.fileName, file.injectables)));
25300 return r;
25301 }, []);
25302 };
25303 AotCompiler.prototype._emitPartialModule2 = function (fileName, injectables) {
25304 var _this = this;
25305 var context = this._createOutputContext(fileName);
25306 injectables.forEach(function (injectable) { return _this._injectableCompiler.compile(injectable, context); });
25307 if (context.statements && context.statements.length > 0) {
25308 return [{ fileName: fileName, statements: __spread(context.constantPool.statements, context.statements) }];
25309 }
25310 return [];
25311 };
25312 AotCompiler.prototype.emitAllImpls = function (analyzeResult) {
25313 var _this = this;
25314 var ngModuleByPipeOrDirective = analyzeResult.ngModuleByPipeOrDirective, files = analyzeResult.files;
25315 var sourceModules = files.map(function (file) { return _this._compileImplFile(file.fileName, ngModuleByPipeOrDirective, file.directives, file.pipes, file.ngModules, file.injectables); });
25316 return flatten(sourceModules);
25317 };
25318 AotCompiler.prototype._compileImplFile = function (srcFileUrl, ngModuleByPipeOrDirective, directives, pipes, ngModules, injectables) {
25319 var _this = this;
25320 var fileSuffix = normalizeGenFileSuffix(splitTypescriptSuffix(srcFileUrl, true)[1]);
25321 var generatedFiles = [];
25322 var outputCtx = this._createOutputContext(ngfactoryFilePath(srcFileUrl, true));
25323 generatedFiles.push.apply(generatedFiles, __spread(this._createSummary(srcFileUrl, directives, pipes, ngModules, injectables, outputCtx)));
25324 // compile all ng modules
25325 ngModules.forEach(function (ngModuleMeta) { return _this._compileModule(outputCtx, ngModuleMeta); });
25326 // compile components
25327 directives.forEach(function (dirType) {
25328 var compMeta = _this._metadataResolver.getDirectiveMetadata(dirType);
25329 if (!compMeta.isComponent) {
25330 return;
25331 }
25332 var ngModule = ngModuleByPipeOrDirective.get(dirType);
25333 if (!ngModule) {
25334 throw new Error("Internal Error: cannot determine the module for component " + identifierName(compMeta.type) + "!");
25335 }
25336 // compile styles
25337 var componentStylesheet = _this._styleCompiler.compileComponent(outputCtx, compMeta);
25338 // Note: compMeta is a component and therefore template is non null.
25339 compMeta.template.externalStylesheets.forEach(function (stylesheetMeta) {
25340 // Note: fill non shim and shim style files as they might
25341 // be shared by component with and without ViewEncapsulation.
25342 var shim = _this._styleCompiler.needsStyleShim(compMeta);
25343 generatedFiles.push(_this._codegenStyles(srcFileUrl, compMeta, stylesheetMeta, shim, fileSuffix));
25344 if (_this._options.allowEmptyCodegenFiles) {
25345 generatedFiles.push(_this._codegenStyles(srcFileUrl, compMeta, stylesheetMeta, !shim, fileSuffix));
25346 }
25347 });
25348 // compile components
25349 var compViewVars = _this._compileComponent(outputCtx, compMeta, ngModule, ngModule.transitiveModule.directives, componentStylesheet, fileSuffix);
25350 _this._compileComponentFactory(outputCtx, compMeta, ngModule, fileSuffix);
25351 });
25352 if (outputCtx.statements.length > 0 || this._options.allowEmptyCodegenFiles) {
25353 var srcModule = this._codegenSourceModule(srcFileUrl, outputCtx);
25354 generatedFiles.unshift(srcModule);
25355 }
25356 return generatedFiles;
25357 };
25358 AotCompiler.prototype._createSummary = function (srcFileName, directives, pipes, ngModules, injectables, ngFactoryCtx) {
25359 var _this = this;
25360 var symbolSummaries = this._symbolResolver.getSymbolsOf(srcFileName)
25361 .map(function (symbol) { return _this._symbolResolver.resolveSymbol(symbol); });
25362 var typeData = __spread(ngModules.map(function (meta) { return ({
25363 summary: _this._metadataResolver.getNgModuleSummary(meta.type.reference),
25364 metadata: _this._metadataResolver.getNgModuleMetadata(meta.type.reference)
25365 }); }), directives.map(function (ref) { return ({
25366 summary: _this._metadataResolver.getDirectiveSummary(ref),
25367 metadata: _this._metadataResolver.getDirectiveMetadata(ref)
25368 }); }), pipes.map(function (ref) { return ({
25369 summary: _this._metadataResolver.getPipeSummary(ref),
25370 metadata: _this._metadataResolver.getPipeMetadata(ref)
25371 }); }), injectables.map(function (ref) { return ({
25372 summary: _this._metadataResolver.getInjectableSummary(ref.symbol),
25373 metadata: _this._metadataResolver.getInjectableSummary(ref.symbol).type
25374 }); }));
25375 var forJitOutputCtx = this._options.enableSummariesForJit ?
25376 this._createOutputContext(summaryForJitFileName(srcFileName, true)) :
25377 null;
25378 var _a = serializeSummaries(srcFileName, forJitOutputCtx, this._summaryResolver, this._symbolResolver, symbolSummaries, typeData, this._options.createExternalSymbolFactoryReexports), json = _a.json, exportAs = _a.exportAs;
25379 exportAs.forEach(function (entry) {
25380 ngFactoryCtx.statements.push(variable(entry.exportAs).set(ngFactoryCtx.importExpr(entry.symbol)).toDeclStmt(null, [
25381 StmtModifier.Exported
25382 ]));
25383 });
25384 var summaryJson = new GeneratedFile(srcFileName, summaryFileName(srcFileName), json);
25385 var result = [summaryJson];
25386 if (forJitOutputCtx) {
25387 result.push(this._codegenSourceModule(srcFileName, forJitOutputCtx));
25388 }
25389 return result;
25390 };
25391 AotCompiler.prototype._compileModule = function (outputCtx, ngModule) {
25392 var providers = [];
25393 if (this._options.locale) {
25394 var normalizedLocale = this._options.locale.replace(/_/g, '-');
25395 providers.push({
25396 token: createTokenForExternalReference(this.reflector, Identifiers.LOCALE_ID),
25397 useValue: normalizedLocale,
25398 });
25399 }
25400 if (this._options.i18nFormat) {
25401 providers.push({
25402 token: createTokenForExternalReference(this.reflector, Identifiers.TRANSLATIONS_FORMAT),
25403 useValue: this._options.i18nFormat
25404 });
25405 }
25406 this._ngModuleCompiler.compile(outputCtx, ngModule, providers);
25407 };
25408 AotCompiler.prototype._compileComponentFactory = function (outputCtx, compMeta, ngModule, fileSuffix) {
25409 var hostMeta = this._metadataResolver.getHostComponentMetadata(compMeta);
25410 var hostViewFactoryVar = this._compileComponent(outputCtx, hostMeta, ngModule, [compMeta.type], null, fileSuffix)
25411 .viewClassVar;
25412 var compFactoryVar = componentFactoryName(compMeta.type.reference);
25413 var inputsExprs = [];
25414 for (var propName in compMeta.inputs) {
25415 var templateName = compMeta.inputs[propName];
25416 // Don't quote so that the key gets minified...
25417 inputsExprs.push(new LiteralMapEntry(propName, literal(templateName), false));
25418 }
25419 var outputsExprs = [];
25420 for (var propName in compMeta.outputs) {
25421 var templateName = compMeta.outputs[propName];
25422 // Don't quote so that the key gets minified...
25423 outputsExprs.push(new LiteralMapEntry(propName, literal(templateName), false));
25424 }
25425 outputCtx.statements.push(variable(compFactoryVar)
25426 .set(importExpr(Identifiers.createComponentFactory).callFn([
25427 literal(compMeta.selector), outputCtx.importExpr(compMeta.type.reference),
25428 variable(hostViewFactoryVar), new LiteralMapExpr(inputsExprs),
25429 new LiteralMapExpr(outputsExprs),
25430 literalArr(compMeta.template.ngContentSelectors.map(function (selector) { return literal(selector); }))
25431 ]))
25432 .toDeclStmt(importType(Identifiers.ComponentFactory, [expressionType(outputCtx.importExpr(compMeta.type.reference))], [TypeModifier.Const]), [StmtModifier.Final, StmtModifier.Exported]));
25433 };
25434 AotCompiler.prototype._compileComponent = function (outputCtx, compMeta, ngModule, directiveIdentifiers, componentStyles, fileSuffix) {
25435 var _a = this._parseTemplate(compMeta, ngModule, directiveIdentifiers), parsedTemplate = _a.template, usedPipes = _a.pipes;
25436 var stylesExpr = componentStyles ? variable(componentStyles.stylesVar) : literalArr([]);
25437 var viewResult = this._viewCompiler.compileComponent(outputCtx, compMeta, parsedTemplate, stylesExpr, usedPipes);
25438 if (componentStyles) {
25439 _resolveStyleStatements(this._symbolResolver, componentStyles, this._styleCompiler.needsStyleShim(compMeta), fileSuffix);
25440 }
25441 return viewResult;
25442 };
25443 AotCompiler.prototype._parseTemplate = function (compMeta, ngModule, directiveIdentifiers) {
25444 var _this = this;
25445 if (this._templateAstCache.has(compMeta.type.reference)) {
25446 return this._templateAstCache.get(compMeta.type.reference);
25447 }
25448 var preserveWhitespaces = compMeta.template.preserveWhitespaces;
25449 var directives = directiveIdentifiers.map(function (dir) { return _this._metadataResolver.getDirectiveSummary(dir.reference); });
25450 var pipes = ngModule.transitiveModule.pipes.map(function (pipe) { return _this._metadataResolver.getPipeSummary(pipe.reference); });
25451 var result = this._templateParser.parse(compMeta, compMeta.template.htmlAst, directives, pipes, ngModule.schemas, templateSourceUrl(ngModule.type, compMeta, compMeta.template), preserveWhitespaces);
25452 this._templateAstCache.set(compMeta.type.reference, result);
25453 return result;
25454 };
25455 AotCompiler.prototype._createOutputContext = function (genFilePath) {
25456 var _this = this;
25457 var importExpr$1 = function (symbol, typeParams, useSummaries) {
25458 if (typeParams === void 0) { typeParams = null; }
25459 if (useSummaries === void 0) { useSummaries = true; }
25460 if (!(symbol instanceof StaticSymbol)) {
25461 throw new Error("Internal error: unknown identifier " + JSON.stringify(symbol));
25462 }
25463 var arity = _this._symbolResolver.getTypeArity(symbol) || 0;
25464 var _a = _this._symbolResolver.getImportAs(symbol, useSummaries) || symbol, filePath = _a.filePath, name = _a.name, members = _a.members;
25465 var importModule = _this._fileNameToModuleName(filePath, genFilePath);
25466 // It should be good enough to compare filePath to genFilePath and if they are equal
25467 // there is a self reference. However, ngfactory files generate to .ts but their
25468 // symbols have .d.ts so a simple compare is insufficient. They should be canonical
25469 // and is tracked by #17705.
25470 var selfReference = _this._fileNameToModuleName(genFilePath, genFilePath);
25471 var moduleName = importModule === selfReference ? null : importModule;
25472 // If we are in a type expression that refers to a generic type then supply
25473 // the required type parameters. If there were not enough type parameters
25474 // supplied, supply any as the type. Outside a type expression the reference
25475 // should not supply type parameters and be treated as a simple value reference
25476 // to the constructor function itself.
25477 var suppliedTypeParams = typeParams || [];
25478 var missingTypeParamsCount = arity - suppliedTypeParams.length;
25479 var allTypeParams = suppliedTypeParams.concat(new Array(missingTypeParamsCount).fill(DYNAMIC_TYPE));
25480 return members.reduce(function (expr, memberName) { return expr.prop(memberName); }, importExpr(new ExternalReference(moduleName, name, null), allTypeParams));
25481 };
25482 return { statements: [], genFilePath: genFilePath, importExpr: importExpr$1, constantPool: new ConstantPool() };
25483 };
25484 AotCompiler.prototype._fileNameToModuleName = function (importedFilePath, containingFilePath) {
25485 return this._summaryResolver.getKnownModuleName(importedFilePath) ||
25486 this._symbolResolver.getKnownModuleName(importedFilePath) ||
25487 this._host.fileNameToModuleName(importedFilePath, containingFilePath);
25488 };
25489 AotCompiler.prototype._codegenStyles = function (srcFileUrl, compMeta, stylesheetMetadata, isShimmed, fileSuffix) {
25490 var outputCtx = this._createOutputContext(_stylesModuleUrl(stylesheetMetadata.moduleUrl, isShimmed, fileSuffix));
25491 var compiledStylesheet = this._styleCompiler.compileStyles(outputCtx, compMeta, stylesheetMetadata, isShimmed);
25492 _resolveStyleStatements(this._symbolResolver, compiledStylesheet, isShimmed, fileSuffix);
25493 return this._codegenSourceModule(srcFileUrl, outputCtx);
25494 };
25495 AotCompiler.prototype._codegenSourceModule = function (srcFileUrl, ctx) {
25496 return new GeneratedFile(srcFileUrl, ctx.genFilePath, ctx.statements);
25497 };
25498 AotCompiler.prototype.listLazyRoutes = function (entryRoute, analyzedModules) {
25499 var e_2, _a, e_3, _b;
25500 var self = this;
25501 if (entryRoute) {
25502 var symbol = parseLazyRoute(entryRoute, this.reflector).referencedModule;
25503 return visitLazyRoute(symbol);
25504 }
25505 else if (analyzedModules) {
25506 var allLazyRoutes = [];
25507 try {
25508 for (var _c = __values(analyzedModules.ngModules), _d = _c.next(); !_d.done; _d = _c.next()) {
25509 var ngModule = _d.value;
25510 var lazyRoutes = listLazyRoutes(ngModule, this.reflector);
25511 try {
25512 for (var lazyRoutes_1 = (e_3 = void 0, __values(lazyRoutes)), lazyRoutes_1_1 = lazyRoutes_1.next(); !lazyRoutes_1_1.done; lazyRoutes_1_1 = lazyRoutes_1.next()) {
25513 var lazyRoute = lazyRoutes_1_1.value;
25514 allLazyRoutes.push(lazyRoute);
25515 }
25516 }
25517 catch (e_3_1) { e_3 = { error: e_3_1 }; }
25518 finally {
25519 try {
25520 if (lazyRoutes_1_1 && !lazyRoutes_1_1.done && (_b = lazyRoutes_1.return)) _b.call(lazyRoutes_1);
25521 }
25522 finally { if (e_3) throw e_3.error; }
25523 }
25524 }
25525 }
25526 catch (e_2_1) { e_2 = { error: e_2_1 }; }
25527 finally {
25528 try {
25529 if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
25530 }
25531 finally { if (e_2) throw e_2.error; }
25532 }
25533 return allLazyRoutes;
25534 }
25535 else {
25536 throw new Error("Either route or analyzedModules has to be specified!");
25537 }
25538 function visitLazyRoute(symbol, seenRoutes, allLazyRoutes) {
25539 var e_4, _a;
25540 if (seenRoutes === void 0) { seenRoutes = new Set(); }
25541 if (allLazyRoutes === void 0) { allLazyRoutes = []; }
25542 // Support pointing to default exports, but stop recursing there,
25543 // as the StaticReflector does not yet support default exports.
25544 if (seenRoutes.has(symbol) || !symbol.name) {
25545 return allLazyRoutes;
25546 }
25547 seenRoutes.add(symbol);
25548 var lazyRoutes = listLazyRoutes(self._metadataResolver.getNgModuleMetadata(symbol, true), self.reflector);
25549 try {
25550 for (var lazyRoutes_2 = __values(lazyRoutes), lazyRoutes_2_1 = lazyRoutes_2.next(); !lazyRoutes_2_1.done; lazyRoutes_2_1 = lazyRoutes_2.next()) {
25551 var lazyRoute = lazyRoutes_2_1.value;
25552 allLazyRoutes.push(lazyRoute);
25553 visitLazyRoute(lazyRoute.referencedModule, seenRoutes, allLazyRoutes);
25554 }
25555 }
25556 catch (e_4_1) { e_4 = { error: e_4_1 }; }
25557 finally {
25558 try {
25559 if (lazyRoutes_2_1 && !lazyRoutes_2_1.done && (_a = lazyRoutes_2.return)) _a.call(lazyRoutes_2);
25560 }
25561 finally { if (e_4) throw e_4.error; }
25562 }
25563 return allLazyRoutes;
25564 }
25565 };
25566 return AotCompiler;
25567}());
25568function _createEmptyStub(outputCtx) {
25569 // Note: We need to produce at least one import statement so that
25570 // TypeScript knows that the file is an es6 module. Otherwise our generated
25571 // exports / imports won't be emitted properly by TypeScript.
25572 outputCtx.statements.push(importExpr(Identifiers.ComponentFactory).toStmt());
25573}
25574function _resolveStyleStatements(symbolResolver, compileResult, needsShim, fileSuffix) {
25575 compileResult.dependencies.forEach(function (dep) {
25576 dep.setValue(symbolResolver.getStaticSymbol(_stylesModuleUrl(dep.moduleUrl, needsShim, fileSuffix), dep.name));
25577 });
25578}
25579function _stylesModuleUrl(stylesheetUrl, shim, suffix) {
25580 return "" + stylesheetUrl + (shim ? '.shim' : '') + ".ngstyle" + suffix;
25581}
25582function analyzeNgModules(fileNames, host, staticSymbolResolver, metadataResolver) {
25583 var files = _analyzeFilesIncludingNonProgramFiles(fileNames, host, staticSymbolResolver, metadataResolver);
25584 return mergeAnalyzedFiles(files);
25585}
25586function analyzeAndValidateNgModules(fileNames, host, staticSymbolResolver, metadataResolver) {
25587 return validateAnalyzedModules(analyzeNgModules(fileNames, host, staticSymbolResolver, metadataResolver));
25588}
25589function validateAnalyzedModules(analyzedModules) {
25590 if (analyzedModules.symbolsMissingModule && analyzedModules.symbolsMissingModule.length) {
25591 var messages = analyzedModules.symbolsMissingModule.map(function (s) {
25592 return "Cannot determine the module for class " + s.name + " in " + s.filePath + "! Add " + s.name + " to the NgModule to fix it.";
25593 });
25594 throw syntaxError(messages.join('\n'));
25595 }
25596 return analyzedModules;
25597}
25598// Analyzes all of the program files,
25599// including files that are not part of the program
25600// but are referenced by an NgModule.
25601function _analyzeFilesIncludingNonProgramFiles(fileNames, host, staticSymbolResolver, metadataResolver) {
25602 var seenFiles = new Set();
25603 var files = [];
25604 var visitFile = function (fileName) {
25605 if (seenFiles.has(fileName) || !host.isSourceFile(fileName)) {
25606 return false;
25607 }
25608 seenFiles.add(fileName);
25609 var analyzedFile = analyzeFile(host, staticSymbolResolver, metadataResolver, fileName);
25610 files.push(analyzedFile);
25611 analyzedFile.ngModules.forEach(function (ngModule) {
25612 ngModule.transitiveModule.modules.forEach(function (modMeta) { return visitFile(modMeta.reference.filePath); });
25613 });
25614 };
25615 fileNames.forEach(function (fileName) { return visitFile(fileName); });
25616 return files;
25617}
25618function analyzeFile(host, staticSymbolResolver, metadataResolver, fileName) {
25619 var directives = [];
25620 var pipes = [];
25621 var injectables = [];
25622 var ngModules = [];
25623 var hasDecorators = staticSymbolResolver.hasDecorators(fileName);
25624 var exportsNonSourceFiles = false;
25625 // Don't analyze .d.ts files that have no decorators as a shortcut
25626 // to speed up the analysis. This prevents us from
25627 // resolving the references in these files.
25628 // Note: exportsNonSourceFiles is only needed when compiling with summaries,
25629 // which is not the case when .d.ts files are treated as input files.
25630 if (!fileName.endsWith('.d.ts') || hasDecorators) {
25631 staticSymbolResolver.getSymbolsOf(fileName).forEach(function (symbol) {
25632 var resolvedSymbol = staticSymbolResolver.resolveSymbol(symbol);
25633 var symbolMeta = resolvedSymbol.metadata;
25634 if (!symbolMeta || symbolMeta.__symbolic === 'error') {
25635 return;
25636 }
25637 var isNgSymbol = false;
25638 if (symbolMeta.__symbolic === 'class') {
25639 if (metadataResolver.isDirective(symbol)) {
25640 isNgSymbol = true;
25641 directives.push(symbol);
25642 }
25643 else if (metadataResolver.isPipe(symbol)) {
25644 isNgSymbol = true;
25645 pipes.push(symbol);
25646 }
25647 else if (metadataResolver.isNgModule(symbol)) {
25648 var ngModule = metadataResolver.getNgModuleMetadata(symbol, false);
25649 if (ngModule) {
25650 isNgSymbol = true;
25651 ngModules.push(ngModule);
25652 }
25653 }
25654 else if (metadataResolver.isInjectable(symbol)) {
25655 isNgSymbol = true;
25656 var injectable = metadataResolver.getInjectableMetadata(symbol, null, false);
25657 if (injectable) {
25658 injectables.push(injectable);
25659 }
25660 }
25661 }
25662 if (!isNgSymbol) {
25663 exportsNonSourceFiles =
25664 exportsNonSourceFiles || isValueExportingNonSourceFile(host, symbolMeta);
25665 }
25666 });
25667 }
25668 return {
25669 fileName: fileName, directives: directives, pipes: pipes, ngModules: ngModules, injectables: injectables, exportsNonSourceFiles: exportsNonSourceFiles,
25670 };
25671}
25672function analyzeFileForInjectables(host, staticSymbolResolver, metadataResolver, fileName) {
25673 var injectables = [];
25674 var shallowModules = [];
25675 if (staticSymbolResolver.hasDecorators(fileName)) {
25676 staticSymbolResolver.getSymbolsOf(fileName).forEach(function (symbol) {
25677 var resolvedSymbol = staticSymbolResolver.resolveSymbol(symbol);
25678 var symbolMeta = resolvedSymbol.metadata;
25679 if (!symbolMeta || symbolMeta.__symbolic === 'error') {
25680 return;
25681 }
25682 if (symbolMeta.__symbolic === 'class') {
25683 if (metadataResolver.isInjectable(symbol)) {
25684 var injectable = metadataResolver.getInjectableMetadata(symbol, null, false);
25685 if (injectable) {
25686 injectables.push(injectable);
25687 }
25688 }
25689 else if (metadataResolver.isNgModule(symbol)) {
25690 var module = metadataResolver.getShallowModuleMetadata(symbol);
25691 if (module) {
25692 shallowModules.push(module);
25693 }
25694 }
25695 }
25696 });
25697 }
25698 return { fileName: fileName, injectables: injectables, shallowModules: shallowModules };
25699}
25700function isValueExportingNonSourceFile(host, metadata) {
25701 var exportsNonSourceFiles = false;
25702 var Visitor = /** @class */ (function () {
25703 function Visitor() {
25704 }
25705 Visitor.prototype.visitArray = function (arr, context) {
25706 var _this = this;
25707 arr.forEach(function (v) { return visitValue(v, _this, context); });
25708 };
25709 Visitor.prototype.visitStringMap = function (map, context) {
25710 var _this = this;
25711 Object.keys(map).forEach(function (key) { return visitValue(map[key], _this, context); });
25712 };
25713 Visitor.prototype.visitPrimitive = function (value, context) { };
25714 Visitor.prototype.visitOther = function (value, context) {
25715 if (value instanceof StaticSymbol && !host.isSourceFile(value.filePath)) {
25716 exportsNonSourceFiles = true;
25717 }
25718 };
25719 return Visitor;
25720 }());
25721 visitValue(metadata, new Visitor(), null);
25722 return exportsNonSourceFiles;
25723}
25724function mergeAnalyzedFiles(analyzedFiles) {
25725 var allNgModules = [];
25726 var ngModuleByPipeOrDirective = new Map();
25727 var allPipesAndDirectives = new Set();
25728 analyzedFiles.forEach(function (af) {
25729 af.ngModules.forEach(function (ngModule) {
25730 allNgModules.push(ngModule);
25731 ngModule.declaredDirectives.forEach(function (d) { return ngModuleByPipeOrDirective.set(d.reference, ngModule); });
25732 ngModule.declaredPipes.forEach(function (p) { return ngModuleByPipeOrDirective.set(p.reference, ngModule); });
25733 });
25734 af.directives.forEach(function (d) { return allPipesAndDirectives.add(d); });
25735 af.pipes.forEach(function (p) { return allPipesAndDirectives.add(p); });
25736 });
25737 var symbolsMissingModule = [];
25738 allPipesAndDirectives.forEach(function (ref) {
25739 if (!ngModuleByPipeOrDirective.has(ref)) {
25740 symbolsMissingModule.push(ref);
25741 }
25742 });
25743 return {
25744 ngModules: allNgModules,
25745 ngModuleByPipeOrDirective: ngModuleByPipeOrDirective,
25746 symbolsMissingModule: symbolsMissingModule,
25747 files: analyzedFiles
25748 };
25749}
25750function mergeAndValidateNgFiles(files) {
25751 return validateAnalyzedModules(mergeAnalyzedFiles(files));
25752}
25753
25754/**
25755 * @license
25756 * Copyright Google Inc. All Rights Reserved.
25757 *
25758 * Use of this source code is governed by an MIT-style license that can be
25759 * found in the LICENSE file at https://angular.io/license
25760 */
25761var FORMATTED_MESSAGE = 'ngFormattedMessage';
25762function indentStr(level) {
25763 if (level <= 0)
25764 return '';
25765 if (level < 6)
25766 return ['', ' ', ' ', ' ', ' ', ' '][level];
25767 var half = indentStr(Math.floor(level / 2));
25768 return half + half + (level % 2 === 1 ? ' ' : '');
25769}
25770function formatChain(chain, indent) {
25771 if (indent === void 0) { indent = 0; }
25772 if (!chain)
25773 return '';
25774 var position = chain.position ?
25775 chain.position.fileName + "(" + (chain.position.line + 1) + "," + (chain.position.column + 1) + ")" :
25776 '';
25777 var prefix = position && indent === 0 ? position + ": " : '';
25778 var postfix = position && indent !== 0 ? " at " + position : '';
25779 var message = "" + prefix + chain.message + postfix;
25780 return "" + indentStr(indent) + message + ((chain.next && ('\n' + formatChain(chain.next, indent + 2))) || '');
25781}
25782function formattedError(chain) {
25783 var message = formatChain(chain) + '.';
25784 var error = syntaxError(message);
25785 error[FORMATTED_MESSAGE] = true;
25786 error.chain = chain;
25787 error.position = chain.position;
25788 return error;
25789}
25790function isFormattedError(error) {
25791 return !!error[FORMATTED_MESSAGE];
25792}
25793
25794/**
25795 * @license
25796 * Copyright Google Inc. All Rights Reserved.
25797 *
25798 * Use of this source code is governed by an MIT-style license that can be
25799 * found in the LICENSE file at https://angular.io/license
25800 */
25801var ANGULAR_CORE = '@angular/core';
25802var ANGULAR_ROUTER = '@angular/router';
25803var HIDDEN_KEY = /^\$.*\$$/;
25804var IGNORE = {
25805 __symbolic: 'ignore'
25806};
25807var USE_VALUE$1 = 'useValue';
25808var PROVIDE = 'provide';
25809var REFERENCE_SET = new Set([USE_VALUE$1, 'useFactory', 'data', 'id', 'loadChildren']);
25810var TYPEGUARD_POSTFIX = 'TypeGuard';
25811var USE_IF = 'UseIf';
25812function shouldIgnore(value) {
25813 return value && value.__symbolic == 'ignore';
25814}
25815/**
25816 * A static reflector implements enough of the Reflector API that is necessary to compile
25817 * templates statically.
25818 */
25819var StaticReflector = /** @class */ (function () {
25820 function StaticReflector(summaryResolver, symbolResolver, knownMetadataClasses, knownMetadataFunctions, errorRecorder) {
25821 var _this = this;
25822 if (knownMetadataClasses === void 0) { knownMetadataClasses = []; }
25823 if (knownMetadataFunctions === void 0) { knownMetadataFunctions = []; }
25824 this.summaryResolver = summaryResolver;
25825 this.symbolResolver = symbolResolver;
25826 this.errorRecorder = errorRecorder;
25827 this.annotationCache = new Map();
25828 this.shallowAnnotationCache = new Map();
25829 this.propertyCache = new Map();
25830 this.parameterCache = new Map();
25831 this.methodCache = new Map();
25832 this.staticCache = new Map();
25833 this.conversionMap = new Map();
25834 this.resolvedExternalReferences = new Map();
25835 this.annotationForParentClassWithSummaryKind = new Map();
25836 this.initializeConversionMap();
25837 knownMetadataClasses.forEach(function (kc) { return _this._registerDecoratorOrConstructor(_this.getStaticSymbol(kc.filePath, kc.name), kc.ctor); });
25838 knownMetadataFunctions.forEach(function (kf) { return _this._registerFunction(_this.getStaticSymbol(kf.filePath, kf.name), kf.fn); });
25839 this.annotationForParentClassWithSummaryKind.set(CompileSummaryKind.Directive, [createDirective, createComponent]);
25840 this.annotationForParentClassWithSummaryKind.set(CompileSummaryKind.Pipe, [createPipe]);
25841 this.annotationForParentClassWithSummaryKind.set(CompileSummaryKind.NgModule, [createNgModule]);
25842 this.annotationForParentClassWithSummaryKind.set(CompileSummaryKind.Injectable, [createInjectable, createPipe, createDirective, createComponent, createNgModule]);
25843 }
25844 StaticReflector.prototype.componentModuleUrl = function (typeOrFunc) {
25845 var staticSymbol = this.findSymbolDeclaration(typeOrFunc);
25846 return this.symbolResolver.getResourcePath(staticSymbol);
25847 };
25848 StaticReflector.prototype.resolveExternalReference = function (ref, containingFile) {
25849 var key = undefined;
25850 if (!containingFile) {
25851 key = ref.moduleName + ":" + ref.name;
25852 var declarationSymbol_1 = this.resolvedExternalReferences.get(key);
25853 if (declarationSymbol_1)
25854 return declarationSymbol_1;
25855 }
25856 var refSymbol = this.symbolResolver.getSymbolByModule(ref.moduleName, ref.name, containingFile);
25857 var declarationSymbol = this.findSymbolDeclaration(refSymbol);
25858 if (!containingFile) {
25859 this.symbolResolver.recordModuleNameForFileName(refSymbol.filePath, ref.moduleName);
25860 this.symbolResolver.recordImportAs(declarationSymbol, refSymbol);
25861 }
25862 if (key) {
25863 this.resolvedExternalReferences.set(key, declarationSymbol);
25864 }
25865 return declarationSymbol;
25866 };
25867 StaticReflector.prototype.findDeclaration = function (moduleUrl, name, containingFile) {
25868 return this.findSymbolDeclaration(this.symbolResolver.getSymbolByModule(moduleUrl, name, containingFile));
25869 };
25870 StaticReflector.prototype.tryFindDeclaration = function (moduleUrl, name, containingFile) {
25871 var _this = this;
25872 return this.symbolResolver.ignoreErrorsFor(function () { return _this.findDeclaration(moduleUrl, name, containingFile); });
25873 };
25874 StaticReflector.prototype.findSymbolDeclaration = function (symbol) {
25875 var resolvedSymbol = this.symbolResolver.resolveSymbol(symbol);
25876 if (resolvedSymbol) {
25877 var resolvedMetadata = resolvedSymbol.metadata;
25878 if (resolvedMetadata && resolvedMetadata.__symbolic === 'resolved') {
25879 resolvedMetadata = resolvedMetadata.symbol;
25880 }
25881 if (resolvedMetadata instanceof StaticSymbol) {
25882 return this.findSymbolDeclaration(resolvedSymbol.metadata);
25883 }
25884 }
25885 return symbol;
25886 };
25887 StaticReflector.prototype.tryAnnotations = function (type) {
25888 var originalRecorder = this.errorRecorder;
25889 this.errorRecorder = function (error, fileName) { };
25890 try {
25891 return this.annotations(type);
25892 }
25893 finally {
25894 this.errorRecorder = originalRecorder;
25895 }
25896 };
25897 StaticReflector.prototype.annotations = function (type) {
25898 var _this = this;
25899 return this._annotations(type, function (type, decorators) { return _this.simplify(type, decorators); }, this.annotationCache);
25900 };
25901 StaticReflector.prototype.shallowAnnotations = function (type) {
25902 var _this = this;
25903 return this._annotations(type, function (type, decorators) { return _this.simplify(type, decorators, true); }, this.shallowAnnotationCache);
25904 };
25905 StaticReflector.prototype._annotations = function (type, simplify, annotationCache) {
25906 var annotations = annotationCache.get(type);
25907 if (!annotations) {
25908 annotations = [];
25909 var classMetadata = this.getTypeMetadata(type);
25910 var parentType = this.findParentType(type, classMetadata);
25911 if (parentType) {
25912 var parentAnnotations = this.annotations(parentType);
25913 annotations.push.apply(annotations, __spread(parentAnnotations));
25914 }
25915 var ownAnnotations_1 = [];
25916 if (classMetadata['decorators']) {
25917 ownAnnotations_1 = simplify(type, classMetadata['decorators']);
25918 if (ownAnnotations_1) {
25919 annotations.push.apply(annotations, __spread(ownAnnotations_1));
25920 }
25921 }
25922 if (parentType && !this.summaryResolver.isLibraryFile(type.filePath) &&
25923 this.summaryResolver.isLibraryFile(parentType.filePath)) {
25924 var summary = this.summaryResolver.resolveSummary(parentType);
25925 if (summary && summary.type) {
25926 var requiredAnnotationTypes = this.annotationForParentClassWithSummaryKind.get(summary.type.summaryKind);
25927 var typeHasRequiredAnnotation = requiredAnnotationTypes.some(function (requiredType) { return ownAnnotations_1.some(function (ann) { return requiredType.isTypeOf(ann); }); });
25928 if (!typeHasRequiredAnnotation) {
25929 this.reportError(formatMetadataError(metadataError("Class " + type.name + " in " + type.filePath + " extends from a " + CompileSummaryKind[summary.type.summaryKind] + " in another compilation unit without duplicating the decorator",
25930 /* summary */ undefined, "Please add a " + requiredAnnotationTypes.map(function (type) { return type.ngMetadataName; }).join(' or ') + " decorator to the class"), type), type);
25931 }
25932 }
25933 }
25934 annotationCache.set(type, annotations.filter(function (ann) { return !!ann; }));
25935 }
25936 return annotations;
25937 };
25938 StaticReflector.prototype.propMetadata = function (type) {
25939 var _this = this;
25940 var propMetadata = this.propertyCache.get(type);
25941 if (!propMetadata) {
25942 var classMetadata = this.getTypeMetadata(type);
25943 propMetadata = {};
25944 var parentType = this.findParentType(type, classMetadata);
25945 if (parentType) {
25946 var parentPropMetadata_1 = this.propMetadata(parentType);
25947 Object.keys(parentPropMetadata_1).forEach(function (parentProp) {
25948 propMetadata[parentProp] = parentPropMetadata_1[parentProp];
25949 });
25950 }
25951 var members_1 = classMetadata['members'] || {};
25952 Object.keys(members_1).forEach(function (propName) {
25953 var propData = members_1[propName];
25954 var prop = propData
25955 .find(function (a) { return a['__symbolic'] == 'property' || a['__symbolic'] == 'method'; });
25956 var decorators = [];
25957 if (propMetadata[propName]) {
25958 decorators.push.apply(decorators, __spread(propMetadata[propName]));
25959 }
25960 propMetadata[propName] = decorators;
25961 if (prop && prop['decorators']) {
25962 decorators.push.apply(decorators, __spread(_this.simplify(type, prop['decorators'])));
25963 }
25964 });
25965 this.propertyCache.set(type, propMetadata);
25966 }
25967 return propMetadata;
25968 };
25969 StaticReflector.prototype.parameters = function (type) {
25970 var _this = this;
25971 if (!(type instanceof StaticSymbol)) {
25972 this.reportError(new Error("parameters received " + JSON.stringify(type) + " which is not a StaticSymbol"), type);
25973 return [];
25974 }
25975 try {
25976 var parameters_1 = this.parameterCache.get(type);
25977 if (!parameters_1) {
25978 var classMetadata = this.getTypeMetadata(type);
25979 var parentType = this.findParentType(type, classMetadata);
25980 var members = classMetadata ? classMetadata['members'] : null;
25981 var ctorData = members ? members['__ctor__'] : null;
25982 if (ctorData) {
25983 var ctor = ctorData.find(function (a) { return a['__symbolic'] == 'constructor'; });
25984 var rawParameterTypes = ctor['parameters'] || [];
25985 var parameterDecorators_1 = this.simplify(type, ctor['parameterDecorators'] || []);
25986 parameters_1 = [];
25987 rawParameterTypes.forEach(function (rawParamType, index) {
25988 var nestedResult = [];
25989 var paramType = _this.trySimplify(type, rawParamType);
25990 if (paramType)
25991 nestedResult.push(paramType);
25992 var decorators = parameterDecorators_1 ? parameterDecorators_1[index] : null;
25993 if (decorators) {
25994 nestedResult.push.apply(nestedResult, __spread(decorators));
25995 }
25996 parameters_1.push(nestedResult);
25997 });
25998 }
25999 else if (parentType) {
26000 parameters_1 = this.parameters(parentType);
26001 }
26002 if (!parameters_1) {
26003 parameters_1 = [];
26004 }
26005 this.parameterCache.set(type, parameters_1);
26006 }
26007 return parameters_1;
26008 }
26009 catch (e) {
26010 console.error("Failed on type " + JSON.stringify(type) + " with error " + e);
26011 throw e;
26012 }
26013 };
26014 StaticReflector.prototype._methodNames = function (type) {
26015 var methodNames = this.methodCache.get(type);
26016 if (!methodNames) {
26017 var classMetadata = this.getTypeMetadata(type);
26018 methodNames = {};
26019 var parentType = this.findParentType(type, classMetadata);
26020 if (parentType) {
26021 var parentMethodNames_1 = this._methodNames(parentType);
26022 Object.keys(parentMethodNames_1).forEach(function (parentProp) {
26023 methodNames[parentProp] = parentMethodNames_1[parentProp];
26024 });
26025 }
26026 var members_2 = classMetadata['members'] || {};
26027 Object.keys(members_2).forEach(function (propName) {
26028 var propData = members_2[propName];
26029 var isMethod = propData.some(function (a) { return a['__symbolic'] == 'method'; });
26030 methodNames[propName] = methodNames[propName] || isMethod;
26031 });
26032 this.methodCache.set(type, methodNames);
26033 }
26034 return methodNames;
26035 };
26036 StaticReflector.prototype._staticMembers = function (type) {
26037 var staticMembers = this.staticCache.get(type);
26038 if (!staticMembers) {
26039 var classMetadata = this.getTypeMetadata(type);
26040 var staticMemberData = classMetadata['statics'] || {};
26041 staticMembers = Object.keys(staticMemberData);
26042 this.staticCache.set(type, staticMembers);
26043 }
26044 return staticMembers;
26045 };
26046 StaticReflector.prototype.findParentType = function (type, classMetadata) {
26047 var parentType = this.trySimplify(type, classMetadata['extends']);
26048 if (parentType instanceof StaticSymbol) {
26049 return parentType;
26050 }
26051 };
26052 StaticReflector.prototype.hasLifecycleHook = function (type, lcProperty) {
26053 if (!(type instanceof StaticSymbol)) {
26054 this.reportError(new Error("hasLifecycleHook received " + JSON.stringify(type) + " which is not a StaticSymbol"), type);
26055 }
26056 try {
26057 return !!this._methodNames(type)[lcProperty];
26058 }
26059 catch (e) {
26060 console.error("Failed on type " + JSON.stringify(type) + " with error " + e);
26061 throw e;
26062 }
26063 };
26064 StaticReflector.prototype.guards = function (type) {
26065 var e_1, _a;
26066 if (!(type instanceof StaticSymbol)) {
26067 this.reportError(new Error("guards received " + JSON.stringify(type) + " which is not a StaticSymbol"), type);
26068 return {};
26069 }
26070 var staticMembers = this._staticMembers(type);
26071 var result = {};
26072 try {
26073 for (var staticMembers_1 = __values(staticMembers), staticMembers_1_1 = staticMembers_1.next(); !staticMembers_1_1.done; staticMembers_1_1 = staticMembers_1.next()) {
26074 var name_1 = staticMembers_1_1.value;
26075 if (name_1.endsWith(TYPEGUARD_POSTFIX)) {
26076 var property = name_1.substr(0, name_1.length - TYPEGUARD_POSTFIX.length);
26077 var value = void 0;
26078 if (property.endsWith(USE_IF)) {
26079 property = name_1.substr(0, property.length - USE_IF.length);
26080 value = USE_IF;
26081 }
26082 else {
26083 value = this.getStaticSymbol(type.filePath, type.name, [name_1]);
26084 }
26085 result[property] = value;
26086 }
26087 }
26088 }
26089 catch (e_1_1) { e_1 = { error: e_1_1 }; }
26090 finally {
26091 try {
26092 if (staticMembers_1_1 && !staticMembers_1_1.done && (_a = staticMembers_1.return)) _a.call(staticMembers_1);
26093 }
26094 finally { if (e_1) throw e_1.error; }
26095 }
26096 return result;
26097 };
26098 StaticReflector.prototype._registerDecoratorOrConstructor = function (type, ctor) {
26099 this.conversionMap.set(type, function (context, args) { return new (ctor.bind.apply(ctor, __spread([void 0], args)))(); });
26100 };
26101 StaticReflector.prototype._registerFunction = function (type, fn) {
26102 this.conversionMap.set(type, function (context, args) { return fn.apply(undefined, args); });
26103 };
26104 StaticReflector.prototype.initializeConversionMap = function () {
26105 this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Injectable'), createInjectable);
26106 this.injectionToken = this.findDeclaration(ANGULAR_CORE, 'InjectionToken');
26107 this.opaqueToken = this.findDeclaration(ANGULAR_CORE, 'OpaqueToken');
26108 this.ROUTES = this.tryFindDeclaration(ANGULAR_ROUTER, 'ROUTES');
26109 this.ANALYZE_FOR_ENTRY_COMPONENTS =
26110 this.findDeclaration(ANGULAR_CORE, 'ANALYZE_FOR_ENTRY_COMPONENTS');
26111 this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Host'), createHost);
26112 this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Self'), createSelf);
26113 this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'SkipSelf'), createSkipSelf);
26114 this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Inject'), createInject);
26115 this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Optional'), createOptional);
26116 this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Attribute'), createAttribute);
26117 this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ContentChild'), createContentChild);
26118 this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ContentChildren'), createContentChildren);
26119 this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ViewChild'), createViewChild);
26120 this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ViewChildren'), createViewChildren);
26121 this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Input'), createInput);
26122 this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Output'), createOutput);
26123 this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Pipe'), createPipe);
26124 this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'HostBinding'), createHostBinding);
26125 this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'HostListener'), createHostListener);
26126 this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Directive'), createDirective);
26127 this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Component'), createComponent);
26128 this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'NgModule'), createNgModule);
26129 // Note: Some metadata classes can be used directly with Provider.deps.
26130 this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Host'), createHost);
26131 this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Self'), createSelf);
26132 this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'SkipSelf'), createSkipSelf);
26133 this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Optional'), createOptional);
26134 };
26135 /**
26136 * getStaticSymbol produces a Type whose metadata is known but whose implementation is not loaded.
26137 * All types passed to the StaticResolver should be pseudo-types returned by this method.
26138 *
26139 * @param declarationFile the absolute path of the file where the symbol is declared
26140 * @param name the name of the type.
26141 */
26142 StaticReflector.prototype.getStaticSymbol = function (declarationFile, name, members) {
26143 return this.symbolResolver.getStaticSymbol(declarationFile, name, members);
26144 };
26145 /**
26146 * Simplify but discard any errors
26147 */
26148 StaticReflector.prototype.trySimplify = function (context, value) {
26149 var originalRecorder = this.errorRecorder;
26150 this.errorRecorder = function (error, fileName) { };
26151 var result = this.simplify(context, value);
26152 this.errorRecorder = originalRecorder;
26153 return result;
26154 };
26155 /** @internal */
26156 StaticReflector.prototype.simplify = function (context, value, lazy) {
26157 if (lazy === void 0) { lazy = false; }
26158 var self = this;
26159 var scope = BindingScope$1.empty;
26160 var calling = new Map();
26161 var rootContext = context;
26162 function simplifyInContext(context, value, depth, references) {
26163 function resolveReferenceValue(staticSymbol) {
26164 var resolvedSymbol = self.symbolResolver.resolveSymbol(staticSymbol);
26165 return resolvedSymbol ? resolvedSymbol.metadata : null;
26166 }
26167 function simplifyEagerly(value) {
26168 return simplifyInContext(context, value, depth, 0);
26169 }
26170 function simplifyLazily(value) {
26171 return simplifyInContext(context, value, depth, references + 1);
26172 }
26173 function simplifyNested(nestedContext, value) {
26174 if (nestedContext === context) {
26175 // If the context hasn't changed let the exception propagate unmodified.
26176 return simplifyInContext(nestedContext, value, depth + 1, references);
26177 }
26178 try {
26179 return simplifyInContext(nestedContext, value, depth + 1, references);
26180 }
26181 catch (e) {
26182 if (isMetadataError(e)) {
26183 // Propagate the message text up but add a message to the chain that explains how we got
26184 // here.
26185 // e.chain implies e.symbol
26186 var summaryMsg = e.chain ? 'references \'' + e.symbol.name + '\'' : errorSummary(e);
26187 var summary = "'" + nestedContext.name + "' " + summaryMsg;
26188 var chain = { message: summary, position: e.position, next: e.chain };
26189 // TODO(chuckj): retrieve the position information indirectly from the collectors node
26190 // map if the metadata is from a .ts file.
26191 self.error({
26192 message: e.message,
26193 advise: e.advise,
26194 context: e.context, chain: chain,
26195 symbol: nestedContext
26196 }, context);
26197 }
26198 else {
26199 // It is probably an internal error.
26200 throw e;
26201 }
26202 }
26203 }
26204 function simplifyCall(functionSymbol, targetFunction, args, targetExpression) {
26205 if (targetFunction && targetFunction['__symbolic'] == 'function') {
26206 if (calling.get(functionSymbol)) {
26207 self.error({
26208 message: 'Recursion is not supported',
26209 summary: "called '" + functionSymbol.name + "' recursively",
26210 value: targetFunction
26211 }, functionSymbol);
26212 }
26213 try {
26214 var value_1 = targetFunction['value'];
26215 if (value_1 && (depth != 0 || value_1.__symbolic != 'error')) {
26216 var parameters = targetFunction['parameters'];
26217 var defaults = targetFunction.defaults;
26218 args = args.map(function (arg) { return simplifyNested(context, arg); })
26219 .map(function (arg) { return shouldIgnore(arg) ? undefined : arg; });
26220 if (defaults && defaults.length > args.length) {
26221 args.push.apply(args, __spread(defaults.slice(args.length).map(function (value) { return simplify(value); })));
26222 }
26223 calling.set(functionSymbol, true);
26224 var functionScope = BindingScope$1.build();
26225 for (var i = 0; i < parameters.length; i++) {
26226 functionScope.define(parameters[i], args[i]);
26227 }
26228 var oldScope = scope;
26229 var result_1;
26230 try {
26231 scope = functionScope.done();
26232 result_1 = simplifyNested(functionSymbol, value_1);
26233 }
26234 finally {
26235 scope = oldScope;
26236 }
26237 return result_1;
26238 }
26239 }
26240 finally {
26241 calling.delete(functionSymbol);
26242 }
26243 }
26244 if (depth === 0) {
26245 // If depth is 0 we are evaluating the top level expression that is describing element
26246 // decorator. In this case, it is a decorator we don't understand, such as a custom
26247 // non-angular decorator, and we should just ignore it.
26248 return IGNORE;
26249 }
26250 var position = undefined;
26251 if (targetExpression && targetExpression.__symbolic == 'resolved') {
26252 var line = targetExpression.line;
26253 var character = targetExpression.character;
26254 var fileName = targetExpression.fileName;
26255 if (fileName != null && line != null && character != null) {
26256 position = { fileName: fileName, line: line, column: character };
26257 }
26258 }
26259 self.error({
26260 message: FUNCTION_CALL_NOT_SUPPORTED,
26261 context: functionSymbol,
26262 value: targetFunction, position: position
26263 }, context);
26264 }
26265 function simplify(expression) {
26266 var e_2, _a, e_3, _b;
26267 if (isPrimitive(expression)) {
26268 return expression;
26269 }
26270 if (expression instanceof Array) {
26271 var result_2 = [];
26272 try {
26273 for (var _c = __values(expression), _d = _c.next(); !_d.done; _d = _c.next()) {
26274 var item = _d.value;
26275 // Check for a spread expression
26276 if (item && item.__symbolic === 'spread') {
26277 // We call with references as 0 because we require the actual value and cannot
26278 // tolerate a reference here.
26279 var spreadArray = simplifyEagerly(item.expression);
26280 if (Array.isArray(spreadArray)) {
26281 try {
26282 for (var spreadArray_1 = (e_3 = void 0, __values(spreadArray)), spreadArray_1_1 = spreadArray_1.next(); !spreadArray_1_1.done; spreadArray_1_1 = spreadArray_1.next()) {
26283 var spreadItem = spreadArray_1_1.value;
26284 result_2.push(spreadItem);
26285 }
26286 }
26287 catch (e_3_1) { e_3 = { error: e_3_1 }; }
26288 finally {
26289 try {
26290 if (spreadArray_1_1 && !spreadArray_1_1.done && (_b = spreadArray_1.return)) _b.call(spreadArray_1);
26291 }
26292 finally { if (e_3) throw e_3.error; }
26293 }
26294 continue;
26295 }
26296 }
26297 var value_2 = simplify(item);
26298 if (shouldIgnore(value_2)) {
26299 continue;
26300 }
26301 result_2.push(value_2);
26302 }
26303 }
26304 catch (e_2_1) { e_2 = { error: e_2_1 }; }
26305 finally {
26306 try {
26307 if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
26308 }
26309 finally { if (e_2) throw e_2.error; }
26310 }
26311 return result_2;
26312 }
26313 if (expression instanceof StaticSymbol) {
26314 // Stop simplification at builtin symbols or if we are in a reference context and
26315 // the symbol doesn't have members.
26316 if (expression === self.injectionToken || self.conversionMap.has(expression) ||
26317 (references > 0 && !expression.members.length)) {
26318 return expression;
26319 }
26320 else {
26321 var staticSymbol = expression;
26322 var declarationValue = resolveReferenceValue(staticSymbol);
26323 if (declarationValue != null) {
26324 return simplifyNested(staticSymbol, declarationValue);
26325 }
26326 else {
26327 return staticSymbol;
26328 }
26329 }
26330 }
26331 if (expression) {
26332 if (expression['__symbolic']) {
26333 var staticSymbol = void 0;
26334 switch (expression['__symbolic']) {
26335 case 'binop':
26336 var left = simplify(expression['left']);
26337 if (shouldIgnore(left))
26338 return left;
26339 var right = simplify(expression['right']);
26340 if (shouldIgnore(right))
26341 return right;
26342 switch (expression['operator']) {
26343 case '&&':
26344 return left && right;
26345 case '||':
26346 return left || right;
26347 case '|':
26348 return left | right;
26349 case '^':
26350 return left ^ right;
26351 case '&':
26352 return left & right;
26353 case '==':
26354 return left == right;
26355 case '!=':
26356 return left != right;
26357 case '===':
26358 return left === right;
26359 case '!==':
26360 return left !== right;
26361 case '<':
26362 return left < right;
26363 case '>':
26364 return left > right;
26365 case '<=':
26366 return left <= right;
26367 case '>=':
26368 return left >= right;
26369 case '<<':
26370 return left << right;
26371 case '>>':
26372 return left >> right;
26373 case '+':
26374 return left + right;
26375 case '-':
26376 return left - right;
26377 case '*':
26378 return left * right;
26379 case '/':
26380 return left / right;
26381 case '%':
26382 return left % right;
26383 }
26384 return null;
26385 case 'if':
26386 var condition = simplify(expression['condition']);
26387 return condition ? simplify(expression['thenExpression']) :
26388 simplify(expression['elseExpression']);
26389 case 'pre':
26390 var operand = simplify(expression['operand']);
26391 if (shouldIgnore(operand))
26392 return operand;
26393 switch (expression['operator']) {
26394 case '+':
26395 return operand;
26396 case '-':
26397 return -operand;
26398 case '!':
26399 return !operand;
26400 case '~':
26401 return ~operand;
26402 }
26403 return null;
26404 case 'index':
26405 var indexTarget = simplifyEagerly(expression['expression']);
26406 var index = simplifyEagerly(expression['index']);
26407 if (indexTarget && isPrimitive(index))
26408 return indexTarget[index];
26409 return null;
26410 case 'select':
26411 var member = expression['member'];
26412 var selectContext = context;
26413 var selectTarget = simplify(expression['expression']);
26414 if (selectTarget instanceof StaticSymbol) {
26415 var members = selectTarget.members.concat(member);
26416 selectContext =
26417 self.getStaticSymbol(selectTarget.filePath, selectTarget.name, members);
26418 var declarationValue = resolveReferenceValue(selectContext);
26419 if (declarationValue != null) {
26420 return simplifyNested(selectContext, declarationValue);
26421 }
26422 else {
26423 return selectContext;
26424 }
26425 }
26426 if (selectTarget && isPrimitive(member))
26427 return simplifyNested(selectContext, selectTarget[member]);
26428 return null;
26429 case 'reference':
26430 // Note: This only has to deal with variable references, as symbol references have
26431 // been converted into 'resolved'
26432 // in the StaticSymbolResolver.
26433 var name_2 = expression['name'];
26434 var localValue = scope.resolve(name_2);
26435 if (localValue != BindingScope$1.missing) {
26436 return localValue;
26437 }
26438 break;
26439 case 'resolved':
26440 try {
26441 return simplify(expression.symbol);
26442 }
26443 catch (e) {
26444 // If an error is reported evaluating the symbol record the position of the
26445 // reference in the error so it can
26446 // be reported in the error message generated from the exception.
26447 if (isMetadataError(e) && expression.fileName != null &&
26448 expression.line != null && expression.character != null) {
26449 e.position = {
26450 fileName: expression.fileName,
26451 line: expression.line,
26452 column: expression.character
26453 };
26454 }
26455 throw e;
26456 }
26457 case 'class':
26458 return context;
26459 case 'function':
26460 return context;
26461 case 'new':
26462 case 'call':
26463 // Determine if the function is a built-in conversion
26464 staticSymbol = simplifyInContext(context, expression['expression'], depth + 1, /* references */ 0);
26465 if (staticSymbol instanceof StaticSymbol) {
26466 if (staticSymbol === self.injectionToken || staticSymbol === self.opaqueToken) {
26467 // if somebody calls new InjectionToken, don't create an InjectionToken,
26468 // but rather return the symbol to which the InjectionToken is assigned to.
26469 // OpaqueToken is supported too as it is required by the language service to
26470 // support v4 and prior versions of Angular.
26471 return context;
26472 }
26473 var argExpressions = expression['arguments'] || [];
26474 var converter = self.conversionMap.get(staticSymbol);
26475 if (converter) {
26476 var args = argExpressions.map(function (arg) { return simplifyNested(context, arg); })
26477 .map(function (arg) { return shouldIgnore(arg) ? undefined : arg; });
26478 return converter(context, args);
26479 }
26480 else {
26481 // Determine if the function is one we can simplify.
26482 var targetFunction = resolveReferenceValue(staticSymbol);
26483 return simplifyCall(staticSymbol, targetFunction, argExpressions, expression['expression']);
26484 }
26485 }
26486 return IGNORE;
26487 case 'error':
26488 var message = expression.message;
26489 if (expression['line'] != null) {
26490 self.error({
26491 message: message,
26492 context: expression.context,
26493 value: expression,
26494 position: {
26495 fileName: expression['fileName'],
26496 line: expression['line'],
26497 column: expression['character']
26498 }
26499 }, context);
26500 }
26501 else {
26502 self.error({ message: message, context: expression.context }, context);
26503 }
26504 return IGNORE;
26505 case 'ignore':
26506 return expression;
26507 }
26508 return null;
26509 }
26510 return mapStringMap(expression, function (value, name) {
26511 if (REFERENCE_SET.has(name)) {
26512 if (name === USE_VALUE$1 && PROVIDE in expression) {
26513 // If this is a provider expression, check for special tokens that need the value
26514 // during analysis.
26515 var provide = simplify(expression.provide);
26516 if (provide === self.ROUTES || provide == self.ANALYZE_FOR_ENTRY_COMPONENTS) {
26517 return simplify(value);
26518 }
26519 }
26520 return simplifyLazily(value);
26521 }
26522 return simplify(value);
26523 });
26524 }
26525 return IGNORE;
26526 }
26527 return simplify(value);
26528 }
26529 var result;
26530 try {
26531 result = simplifyInContext(context, value, 0, lazy ? 1 : 0);
26532 }
26533 catch (e) {
26534 if (this.errorRecorder) {
26535 this.reportError(e, context);
26536 }
26537 else {
26538 throw formatMetadataError(e, context);
26539 }
26540 }
26541 if (shouldIgnore(result)) {
26542 return undefined;
26543 }
26544 return result;
26545 };
26546 StaticReflector.prototype.getTypeMetadata = function (type) {
26547 var resolvedSymbol = this.symbolResolver.resolveSymbol(type);
26548 return resolvedSymbol && resolvedSymbol.metadata ? resolvedSymbol.metadata :
26549 { __symbolic: 'class' };
26550 };
26551 StaticReflector.prototype.reportError = function (error, context, path) {
26552 if (this.errorRecorder) {
26553 this.errorRecorder(formatMetadataError(error, context), (context && context.filePath) || path);
26554 }
26555 else {
26556 throw error;
26557 }
26558 };
26559 StaticReflector.prototype.error = function (_a, reportingContext) {
26560 var message = _a.message, summary = _a.summary, advise = _a.advise, position = _a.position, context = _a.context, value = _a.value, symbol = _a.symbol, chain = _a.chain;
26561 this.reportError(metadataError(message, summary, advise, position, symbol, context, chain), reportingContext);
26562 };
26563 return StaticReflector;
26564}());
26565var METADATA_ERROR = 'ngMetadataError';
26566function metadataError(message, summary, advise, position, symbol, context, chain) {
26567 var error = syntaxError(message);
26568 error[METADATA_ERROR] = true;
26569 if (advise)
26570 error.advise = advise;
26571 if (position)
26572 error.position = position;
26573 if (summary)
26574 error.summary = summary;
26575 if (context)
26576 error.context = context;
26577 if (chain)
26578 error.chain = chain;
26579 if (symbol)
26580 error.symbol = symbol;
26581 return error;
26582}
26583function isMetadataError(error) {
26584 return !!error[METADATA_ERROR];
26585}
26586var REFERENCE_TO_NONEXPORTED_CLASS = 'Reference to non-exported class';
26587var VARIABLE_NOT_INITIALIZED = 'Variable not initialized';
26588var DESTRUCTURE_NOT_SUPPORTED = 'Destructuring not supported';
26589var COULD_NOT_RESOLVE_TYPE = 'Could not resolve type';
26590var FUNCTION_CALL_NOT_SUPPORTED = 'Function call not supported';
26591var REFERENCE_TO_LOCAL_SYMBOL = 'Reference to a local symbol';
26592var LAMBDA_NOT_SUPPORTED = 'Lambda not supported';
26593function expandedMessage(message, context) {
26594 switch (message) {
26595 case REFERENCE_TO_NONEXPORTED_CLASS:
26596 if (context && context.className) {
26597 return "References to a non-exported class are not supported in decorators but " + context.className + " was referenced.";
26598 }
26599 break;
26600 case VARIABLE_NOT_INITIALIZED:
26601 return 'Only initialized variables and constants can be referenced in decorators because the value of this variable is needed by the template compiler';
26602 case DESTRUCTURE_NOT_SUPPORTED:
26603 return 'Referencing an exported destructured variable or constant is not supported in decorators and this value is needed by the template compiler';
26604 case COULD_NOT_RESOLVE_TYPE:
26605 if (context && context.typeName) {
26606 return "Could not resolve type " + context.typeName;
26607 }
26608 break;
26609 case FUNCTION_CALL_NOT_SUPPORTED:
26610 if (context && context.name) {
26611 return "Function calls are not supported in decorators but '" + context.name + "' was called";
26612 }
26613 return 'Function calls are not supported in decorators';
26614 case REFERENCE_TO_LOCAL_SYMBOL:
26615 if (context && context.name) {
26616 return "Reference to a local (non-exported) symbols are not supported in decorators but '" + context.name + "' was referenced";
26617 }
26618 break;
26619 case LAMBDA_NOT_SUPPORTED:
26620 return "Function expressions are not supported in decorators";
26621 }
26622 return message;
26623}
26624function messageAdvise(message, context) {
26625 switch (message) {
26626 case REFERENCE_TO_NONEXPORTED_CLASS:
26627 if (context && context.className) {
26628 return "Consider exporting '" + context.className + "'";
26629 }
26630 break;
26631 case DESTRUCTURE_NOT_SUPPORTED:
26632 return 'Consider simplifying to avoid destructuring';
26633 case REFERENCE_TO_LOCAL_SYMBOL:
26634 if (context && context.name) {
26635 return "Consider exporting '" + context.name + "'";
26636 }
26637 break;
26638 case LAMBDA_NOT_SUPPORTED:
26639 return "Consider changing the function expression into an exported function";
26640 }
26641 return undefined;
26642}
26643function errorSummary(error) {
26644 if (error.summary) {
26645 return error.summary;
26646 }
26647 switch (error.message) {
26648 case REFERENCE_TO_NONEXPORTED_CLASS:
26649 if (error.context && error.context.className) {
26650 return "references non-exported class " + error.context.className;
26651 }
26652 break;
26653 case VARIABLE_NOT_INITIALIZED:
26654 return 'is not initialized';
26655 case DESTRUCTURE_NOT_SUPPORTED:
26656 return 'is a destructured variable';
26657 case COULD_NOT_RESOLVE_TYPE:
26658 return 'could not be resolved';
26659 case FUNCTION_CALL_NOT_SUPPORTED:
26660 if (error.context && error.context.name) {
26661 return "calls '" + error.context.name + "'";
26662 }
26663 return "calls a function";
26664 case REFERENCE_TO_LOCAL_SYMBOL:
26665 if (error.context && error.context.name) {
26666 return "references local variable " + error.context.name;
26667 }
26668 return "references a local variable";
26669 }
26670 return 'contains the error';
26671}
26672function mapStringMap(input, transform) {
26673 if (!input)
26674 return {};
26675 var result = {};
26676 Object.keys(input).forEach(function (key) {
26677 var value = transform(input[key], key);
26678 if (!shouldIgnore(value)) {
26679 if (HIDDEN_KEY.test(key)) {
26680 Object.defineProperty(result, key, { enumerable: false, configurable: true, value: value });
26681 }
26682 else {
26683 result[key] = value;
26684 }
26685 }
26686 });
26687 return result;
26688}
26689function isPrimitive(o) {
26690 return o === null || (typeof o !== 'function' && typeof o !== 'object');
26691}
26692var BindingScope$1 = /** @class */ (function () {
26693 function BindingScope() {
26694 }
26695 BindingScope.build = function () {
26696 var current = new Map();
26697 return {
26698 define: function (name, value) {
26699 current.set(name, value);
26700 return this;
26701 },
26702 done: function () {
26703 return current.size > 0 ? new PopulatedScope(current) : BindingScope.empty;
26704 }
26705 };
26706 };
26707 BindingScope.missing = {};
26708 BindingScope.empty = { resolve: function (name) { return BindingScope.missing; } };
26709 return BindingScope;
26710}());
26711var PopulatedScope = /** @class */ (function (_super) {
26712 __extends(PopulatedScope, _super);
26713 function PopulatedScope(bindings) {
26714 var _this = _super.call(this) || this;
26715 _this.bindings = bindings;
26716 return _this;
26717 }
26718 PopulatedScope.prototype.resolve = function (name) {
26719 return this.bindings.has(name) ? this.bindings.get(name) : BindingScope$1.missing;
26720 };
26721 return PopulatedScope;
26722}(BindingScope$1));
26723function formatMetadataMessageChain(chain, advise) {
26724 var expanded = expandedMessage(chain.message, chain.context);
26725 var nesting = chain.symbol ? " in '" + chain.symbol.name + "'" : '';
26726 var message = "" + expanded + nesting;
26727 var position = chain.position;
26728 var next = chain.next ?
26729 formatMetadataMessageChain(chain.next, advise) :
26730 advise ? { message: advise } : undefined;
26731 return { message: message, position: position, next: next };
26732}
26733function formatMetadataError(e, context) {
26734 if (isMetadataError(e)) {
26735 // Produce a formatted version of the and leaving enough information in the original error
26736 // to recover the formatting information to eventually produce a diagnostic error message.
26737 var position = e.position;
26738 var chain = {
26739 message: "Error during template compile of '" + context.name + "'",
26740 position: position,
26741 next: { message: e.message, next: e.chain, context: e.context, symbol: e.symbol }
26742 };
26743 var advise = e.advise || messageAdvise(e.message, e.context);
26744 return formattedError(formatMetadataMessageChain(chain, advise));
26745 }
26746 return e;
26747}
26748
26749/**
26750 * @license
26751 * Copyright Google Inc. All Rights Reserved.
26752 *
26753 * Use of this source code is governed by an MIT-style license that can be
26754 * found in the LICENSE file at https://angular.io/license
26755 */
26756var AotSummaryResolver = /** @class */ (function () {
26757 function AotSummaryResolver(host, staticSymbolCache) {
26758 this.host = host;
26759 this.staticSymbolCache = staticSymbolCache;
26760 // Note: this will only contain StaticSymbols without members!
26761 this.summaryCache = new Map();
26762 this.loadedFilePaths = new Map();
26763 // Note: this will only contain StaticSymbols without members!
26764 this.importAs = new Map();
26765 this.knownFileNameToModuleNames = new Map();
26766 }
26767 AotSummaryResolver.prototype.isLibraryFile = function (filePath) {
26768 // Note: We need to strip the .ngfactory. file path,
26769 // so this method also works for generated files
26770 // (for which host.isSourceFile will always return false).
26771 return !this.host.isSourceFile(stripGeneratedFileSuffix(filePath));
26772 };
26773 AotSummaryResolver.prototype.toSummaryFileName = function (filePath, referringSrcFileName) {
26774 return this.host.toSummaryFileName(filePath, referringSrcFileName);
26775 };
26776 AotSummaryResolver.prototype.fromSummaryFileName = function (fileName, referringLibFileName) {
26777 return this.host.fromSummaryFileName(fileName, referringLibFileName);
26778 };
26779 AotSummaryResolver.prototype.resolveSummary = function (staticSymbol) {
26780 var rootSymbol = staticSymbol.members.length ?
26781 this.staticSymbolCache.get(staticSymbol.filePath, staticSymbol.name) :
26782 staticSymbol;
26783 var summary = this.summaryCache.get(rootSymbol);
26784 if (!summary) {
26785 this._loadSummaryFile(staticSymbol.filePath);
26786 summary = this.summaryCache.get(staticSymbol);
26787 }
26788 return (rootSymbol === staticSymbol && summary) || null;
26789 };
26790 AotSummaryResolver.prototype.getSymbolsOf = function (filePath) {
26791 if (this._loadSummaryFile(filePath)) {
26792 return Array.from(this.summaryCache.keys()).filter(function (symbol) { return symbol.filePath === filePath; });
26793 }
26794 return null;
26795 };
26796 AotSummaryResolver.prototype.getImportAs = function (staticSymbol) {
26797 staticSymbol.assertNoMembers();
26798 return this.importAs.get(staticSymbol);
26799 };
26800 /**
26801 * Converts a file path to a module name that can be used as an `import`.
26802 */
26803 AotSummaryResolver.prototype.getKnownModuleName = function (importedFilePath) {
26804 return this.knownFileNameToModuleNames.get(importedFilePath) || null;
26805 };
26806 AotSummaryResolver.prototype.addSummary = function (summary) { this.summaryCache.set(summary.symbol, summary); };
26807 AotSummaryResolver.prototype._loadSummaryFile = function (filePath) {
26808 var _this = this;
26809 var hasSummary = this.loadedFilePaths.get(filePath);
26810 if (hasSummary != null) {
26811 return hasSummary;
26812 }
26813 var json = null;
26814 if (this.isLibraryFile(filePath)) {
26815 var summaryFilePath = summaryFileName(filePath);
26816 try {
26817 json = this.host.loadSummary(summaryFilePath);
26818 }
26819 catch (e) {
26820 console.error("Error loading summary file " + summaryFilePath);
26821 throw e;
26822 }
26823 }
26824 hasSummary = json != null;
26825 this.loadedFilePaths.set(filePath, hasSummary);
26826 if (json) {
26827 var _a = deserializeSummaries(this.staticSymbolCache, this, filePath, json), moduleName = _a.moduleName, summaries = _a.summaries, importAs = _a.importAs;
26828 summaries.forEach(function (summary) { return _this.summaryCache.set(summary.symbol, summary); });
26829 if (moduleName) {
26830 this.knownFileNameToModuleNames.set(filePath, moduleName);
26831 }
26832 importAs.forEach(function (importAs) { _this.importAs.set(importAs.symbol, importAs.importAs); });
26833 }
26834 return hasSummary;
26835 };
26836 return AotSummaryResolver;
26837}());
26838
26839/**
26840 * @license
26841 * Copyright Google Inc. All Rights Reserved.
26842 *
26843 * Use of this source code is governed by an MIT-style license that can be
26844 * found in the LICENSE file at https://angular.io/license
26845 */
26846function createAotUrlResolver(host) {
26847 return {
26848 resolve: function (basePath, url) {
26849 var filePath = host.resourceNameToFileName(url, basePath);
26850 if (!filePath) {
26851 throw syntaxError("Couldn't resolve resource " + url + " from " + basePath);
26852 }
26853 return filePath;
26854 }
26855 };
26856}
26857/**
26858 * Creates a new AotCompiler based on options and a host.
26859 */
26860function createAotCompiler(compilerHost, options, errorCollector) {
26861 var translations = options.translations || '';
26862 var urlResolver = createAotUrlResolver(compilerHost);
26863 var symbolCache = new StaticSymbolCache();
26864 var summaryResolver = new AotSummaryResolver(compilerHost, symbolCache);
26865 var symbolResolver = new StaticSymbolResolver(compilerHost, symbolCache, summaryResolver);
26866 var staticReflector = new StaticReflector(summaryResolver, symbolResolver, [], [], errorCollector);
26867 var htmlParser;
26868 if (!!options.enableIvy) {
26869 // Ivy handles i18n at the compiler level so we must use a regular parser
26870 htmlParser = new HtmlParser();
26871 }
26872 else {
26873 htmlParser = new I18NHtmlParser(new HtmlParser(), translations, options.i18nFormat, options.missingTranslation, console);
26874 }
26875 var config = new CompilerConfig({
26876 defaultEncapsulation: ViewEncapsulation.Emulated,
26877 useJit: false,
26878 missingTranslation: options.missingTranslation,
26879 preserveWhitespaces: options.preserveWhitespaces,
26880 strictInjectionParameters: options.strictInjectionParameters,
26881 });
26882 var normalizer = new DirectiveNormalizer({ get: function (url) { return compilerHost.loadResource(url); } }, urlResolver, htmlParser, config);
26883 var expressionParser = new Parser$1(new Lexer());
26884 var elementSchemaRegistry = new DomElementSchemaRegistry();
26885 var tmplParser = new TemplateParser(config, staticReflector, expressionParser, elementSchemaRegistry, htmlParser, console, []);
26886 var resolver = new CompileMetadataResolver(config, htmlParser, new NgModuleResolver(staticReflector), new DirectiveResolver(staticReflector), new PipeResolver(staticReflector), summaryResolver, elementSchemaRegistry, normalizer, console, symbolCache, staticReflector, errorCollector);
26887 // TODO(vicb): do not pass options.i18nFormat here
26888 var viewCompiler = new ViewCompiler(staticReflector);
26889 var typeCheckCompiler = new TypeCheckCompiler(options, staticReflector);
26890 var compiler = new AotCompiler(config, options, compilerHost, staticReflector, resolver, tmplParser, new StyleCompiler(urlResolver), viewCompiler, typeCheckCompiler, new NgModuleCompiler(staticReflector), new InjectableCompiler(staticReflector, !!options.enableIvy), new TypeScriptEmitter(), summaryResolver, symbolResolver);
26891 return { compiler: compiler, reflector: staticReflector };
26892}
26893
26894var SummaryResolver = /** @class */ (function () {
26895 function SummaryResolver() {
26896 }
26897 return SummaryResolver;
26898}());
26899var JitSummaryResolver = /** @class */ (function () {
26900 function JitSummaryResolver() {
26901 this._summaries = new Map();
26902 }
26903 JitSummaryResolver.prototype.isLibraryFile = function () { return false; };
26904 JitSummaryResolver.prototype.toSummaryFileName = function (fileName) { return fileName; };
26905 JitSummaryResolver.prototype.fromSummaryFileName = function (fileName) { return fileName; };
26906 JitSummaryResolver.prototype.resolveSummary = function (reference) {
26907 return this._summaries.get(reference) || null;
26908 };
26909 JitSummaryResolver.prototype.getSymbolsOf = function () { return []; };
26910 JitSummaryResolver.prototype.getImportAs = function (reference) { return reference; };
26911 JitSummaryResolver.prototype.getKnownModuleName = function (fileName) { return null; };
26912 JitSummaryResolver.prototype.addSummary = function (summary) { this._summaries.set(summary.symbol, summary); };
26913 return JitSummaryResolver;
26914}());
26915
26916/**
26917 * @license
26918 * Copyright Google Inc. All Rights Reserved.
26919 *
26920 * Use of this source code is governed by an MIT-style license that can be
26921 * found in the LICENSE file at https://angular.io/license
26922 */
26923function interpretStatements(statements, reflector) {
26924 var ctx = new _ExecutionContext(null, null, null, new Map());
26925 var visitor = new StatementInterpreter(reflector);
26926 visitor.visitAllStatements(statements, ctx);
26927 var result = {};
26928 ctx.exports.forEach(function (exportName) { result[exportName] = ctx.vars.get(exportName); });
26929 return result;
26930}
26931function _executeFunctionStatements(varNames, varValues, statements, ctx, visitor) {
26932 var childCtx = ctx.createChildWihtLocalVars();
26933 for (var i = 0; i < varNames.length; i++) {
26934 childCtx.vars.set(varNames[i], varValues[i]);
26935 }
26936 var result = visitor.visitAllStatements(statements, childCtx);
26937 return result ? result.value : null;
26938}
26939var _ExecutionContext = /** @class */ (function () {
26940 function _ExecutionContext(parent, instance, className, vars) {
26941 this.parent = parent;
26942 this.instance = instance;
26943 this.className = className;
26944 this.vars = vars;
26945 this.exports = [];
26946 }
26947 _ExecutionContext.prototype.createChildWihtLocalVars = function () {
26948 return new _ExecutionContext(this, this.instance, this.className, new Map());
26949 };
26950 return _ExecutionContext;
26951}());
26952var ReturnValue = /** @class */ (function () {
26953 function ReturnValue(value) {
26954 this.value = value;
26955 }
26956 return ReturnValue;
26957}());
26958function createDynamicClass(_classStmt, _ctx, _visitor) {
26959 var propertyDescriptors = {};
26960 _classStmt.getters.forEach(function (getter) {
26961 // Note: use `function` instead of arrow function to capture `this`
26962 propertyDescriptors[getter.name] = {
26963 configurable: false,
26964 get: function () {
26965 var instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
26966 return _executeFunctionStatements([], [], getter.body, instanceCtx, _visitor);
26967 }
26968 };
26969 });
26970 _classStmt.methods.forEach(function (method) {
26971 var paramNames = method.params.map(function (param) { return param.name; });
26972 // Note: use `function` instead of arrow function to capture `this`
26973 propertyDescriptors[method.name] = {
26974 writable: false,
26975 configurable: false,
26976 value: function () {
26977 var args = [];
26978 for (var _i = 0; _i < arguments.length; _i++) {
26979 args[_i] = arguments[_i];
26980 }
26981 var instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
26982 return _executeFunctionStatements(paramNames, args, method.body, instanceCtx, _visitor);
26983 }
26984 };
26985 });
26986 var ctorParamNames = _classStmt.constructorMethod.params.map(function (param) { return param.name; });
26987 // Note: use `function` instead of arrow function to capture `this`
26988 var ctor = function () {
26989 var _this = this;
26990 var args = [];
26991 for (var _i = 0; _i < arguments.length; _i++) {
26992 args[_i] = arguments[_i];
26993 }
26994 var instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
26995 _classStmt.fields.forEach(function (field) { _this[field.name] = undefined; });
26996 _executeFunctionStatements(ctorParamNames, args, _classStmt.constructorMethod.body, instanceCtx, _visitor);
26997 };
26998 var superClass = _classStmt.parent ? _classStmt.parent.visitExpression(_visitor, _ctx) : Object;
26999 ctor.prototype = Object.create(superClass.prototype, propertyDescriptors);
27000 return ctor;
27001}
27002var StatementInterpreter = /** @class */ (function () {
27003 function StatementInterpreter(reflector) {
27004 this.reflector = reflector;
27005 }
27006 StatementInterpreter.prototype.debugAst = function (ast) { return debugOutputAstAsTypeScript(ast); };
27007 StatementInterpreter.prototype.visitDeclareVarStmt = function (stmt, ctx) {
27008 var initialValue = stmt.value ? stmt.value.visitExpression(this, ctx) : undefined;
27009 ctx.vars.set(stmt.name, initialValue);
27010 if (stmt.hasModifier(StmtModifier.Exported)) {
27011 ctx.exports.push(stmt.name);
27012 }
27013 return null;
27014 };
27015 StatementInterpreter.prototype.visitWriteVarExpr = function (expr, ctx) {
27016 var value = expr.value.visitExpression(this, ctx);
27017 var currCtx = ctx;
27018 while (currCtx != null) {
27019 if (currCtx.vars.has(expr.name)) {
27020 currCtx.vars.set(expr.name, value);
27021 return value;
27022 }
27023 currCtx = currCtx.parent;
27024 }
27025 throw new Error("Not declared variable " + expr.name);
27026 };
27027 StatementInterpreter.prototype.visitWrappedNodeExpr = function (ast, ctx) {
27028 throw new Error('Cannot interpret a WrappedNodeExpr.');
27029 };
27030 StatementInterpreter.prototype.visitTypeofExpr = function (ast, ctx) {
27031 throw new Error('Cannot interpret a TypeofExpr');
27032 };
27033 StatementInterpreter.prototype.visitReadVarExpr = function (ast, ctx) {
27034 var varName = ast.name;
27035 if (ast.builtin != null) {
27036 switch (ast.builtin) {
27037 case BuiltinVar.Super:
27038 return Object.getPrototypeOf(ctx.instance);
27039 case BuiltinVar.This:
27040 return ctx.instance;
27041 case BuiltinVar.CatchError:
27042 varName = CATCH_ERROR_VAR$2;
27043 break;
27044 case BuiltinVar.CatchStack:
27045 varName = CATCH_STACK_VAR$2;
27046 break;
27047 default:
27048 throw new Error("Unknown builtin variable " + ast.builtin);
27049 }
27050 }
27051 var currCtx = ctx;
27052 while (currCtx != null) {
27053 if (currCtx.vars.has(varName)) {
27054 return currCtx.vars.get(varName);
27055 }
27056 currCtx = currCtx.parent;
27057 }
27058 throw new Error("Not declared variable " + varName);
27059 };
27060 StatementInterpreter.prototype.visitWriteKeyExpr = function (expr, ctx) {
27061 var receiver = expr.receiver.visitExpression(this, ctx);
27062 var index = expr.index.visitExpression(this, ctx);
27063 var value = expr.value.visitExpression(this, ctx);
27064 receiver[index] = value;
27065 return value;
27066 };
27067 StatementInterpreter.prototype.visitWritePropExpr = function (expr, ctx) {
27068 var receiver = expr.receiver.visitExpression(this, ctx);
27069 var value = expr.value.visitExpression(this, ctx);
27070 receiver[expr.name] = value;
27071 return value;
27072 };
27073 StatementInterpreter.prototype.visitInvokeMethodExpr = function (expr, ctx) {
27074 var receiver = expr.receiver.visitExpression(this, ctx);
27075 var args = this.visitAllExpressions(expr.args, ctx);
27076 var result;
27077 if (expr.builtin != null) {
27078 switch (expr.builtin) {
27079 case BuiltinMethod.ConcatArray:
27080 result = receiver.concat.apply(receiver, __spread(args));
27081 break;
27082 case BuiltinMethod.SubscribeObservable:
27083 result = receiver.subscribe({ next: args[0] });
27084 break;
27085 case BuiltinMethod.Bind:
27086 result = receiver.bind.apply(receiver, __spread(args));
27087 break;
27088 default:
27089 throw new Error("Unknown builtin method " + expr.builtin);
27090 }
27091 }
27092 else {
27093 result = receiver[expr.name].apply(receiver, args);
27094 }
27095 return result;
27096 };
27097 StatementInterpreter.prototype.visitInvokeFunctionExpr = function (stmt, ctx) {
27098 var args = this.visitAllExpressions(stmt.args, ctx);
27099 var fnExpr = stmt.fn;
27100 if (fnExpr instanceof ReadVarExpr && fnExpr.builtin === BuiltinVar.Super) {
27101 ctx.instance.constructor.prototype.constructor.apply(ctx.instance, args);
27102 return null;
27103 }
27104 else {
27105 var fn = stmt.fn.visitExpression(this, ctx);
27106 return fn.apply(null, args);
27107 }
27108 };
27109 StatementInterpreter.prototype.visitReturnStmt = function (stmt, ctx) {
27110 return new ReturnValue(stmt.value.visitExpression(this, ctx));
27111 };
27112 StatementInterpreter.prototype.visitDeclareClassStmt = function (stmt, ctx) {
27113 var clazz = createDynamicClass(stmt, ctx, this);
27114 ctx.vars.set(stmt.name, clazz);
27115 if (stmt.hasModifier(StmtModifier.Exported)) {
27116 ctx.exports.push(stmt.name);
27117 }
27118 return null;
27119 };
27120 StatementInterpreter.prototype.visitExpressionStmt = function (stmt, ctx) {
27121 return stmt.expr.visitExpression(this, ctx);
27122 };
27123 StatementInterpreter.prototype.visitIfStmt = function (stmt, ctx) {
27124 var condition = stmt.condition.visitExpression(this, ctx);
27125 if (condition) {
27126 return this.visitAllStatements(stmt.trueCase, ctx);
27127 }
27128 else if (stmt.falseCase != null) {
27129 return this.visitAllStatements(stmt.falseCase, ctx);
27130 }
27131 return null;
27132 };
27133 StatementInterpreter.prototype.visitTryCatchStmt = function (stmt, ctx) {
27134 try {
27135 return this.visitAllStatements(stmt.bodyStmts, ctx);
27136 }
27137 catch (e) {
27138 var childCtx = ctx.createChildWihtLocalVars();
27139 childCtx.vars.set(CATCH_ERROR_VAR$2, e);
27140 childCtx.vars.set(CATCH_STACK_VAR$2, e.stack);
27141 return this.visitAllStatements(stmt.catchStmts, childCtx);
27142 }
27143 };
27144 StatementInterpreter.prototype.visitThrowStmt = function (stmt, ctx) {
27145 throw stmt.error.visitExpression(this, ctx);
27146 };
27147 StatementInterpreter.prototype.visitCommentStmt = function (stmt, context) { return null; };
27148 StatementInterpreter.prototype.visitJSDocCommentStmt = function (stmt, context) { return null; };
27149 StatementInterpreter.prototype.visitInstantiateExpr = function (ast, ctx) {
27150 var args = this.visitAllExpressions(ast.args, ctx);
27151 var clazz = ast.classExpr.visitExpression(this, ctx);
27152 return new (clazz.bind.apply(clazz, __spread([void 0], args)))();
27153 };
27154 StatementInterpreter.prototype.visitLiteralExpr = function (ast, ctx) { return ast.value; };
27155 StatementInterpreter.prototype.visitExternalExpr = function (ast, ctx) {
27156 return this.reflector.resolveExternalReference(ast.value);
27157 };
27158 StatementInterpreter.prototype.visitConditionalExpr = function (ast, ctx) {
27159 if (ast.condition.visitExpression(this, ctx)) {
27160 return ast.trueCase.visitExpression(this, ctx);
27161 }
27162 else if (ast.falseCase != null) {
27163 return ast.falseCase.visitExpression(this, ctx);
27164 }
27165 return null;
27166 };
27167 StatementInterpreter.prototype.visitNotExpr = function (ast, ctx) {
27168 return !ast.condition.visitExpression(this, ctx);
27169 };
27170 StatementInterpreter.prototype.visitAssertNotNullExpr = function (ast, ctx) {
27171 return ast.condition.visitExpression(this, ctx);
27172 };
27173 StatementInterpreter.prototype.visitCastExpr = function (ast, ctx) {
27174 return ast.value.visitExpression(this, ctx);
27175 };
27176 StatementInterpreter.prototype.visitFunctionExpr = function (ast, ctx) {
27177 var paramNames = ast.params.map(function (param) { return param.name; });
27178 return _declareFn(paramNames, ast.statements, ctx, this);
27179 };
27180 StatementInterpreter.prototype.visitDeclareFunctionStmt = function (stmt, ctx) {
27181 var paramNames = stmt.params.map(function (param) { return param.name; });
27182 ctx.vars.set(stmt.name, _declareFn(paramNames, stmt.statements, ctx, this));
27183 if (stmt.hasModifier(StmtModifier.Exported)) {
27184 ctx.exports.push(stmt.name);
27185 }
27186 return null;
27187 };
27188 StatementInterpreter.prototype.visitBinaryOperatorExpr = function (ast, ctx) {
27189 var _this = this;
27190 var lhs = function () { return ast.lhs.visitExpression(_this, ctx); };
27191 var rhs = function () { return ast.rhs.visitExpression(_this, ctx); };
27192 switch (ast.operator) {
27193 case BinaryOperator.Equals:
27194 return lhs() == rhs();
27195 case BinaryOperator.Identical:
27196 return lhs() === rhs();
27197 case BinaryOperator.NotEquals:
27198 return lhs() != rhs();
27199 case BinaryOperator.NotIdentical:
27200 return lhs() !== rhs();
27201 case BinaryOperator.And:
27202 return lhs() && rhs();
27203 case BinaryOperator.Or:
27204 return lhs() || rhs();
27205 case BinaryOperator.Plus:
27206 return lhs() + rhs();
27207 case BinaryOperator.Minus:
27208 return lhs() - rhs();
27209 case BinaryOperator.Divide:
27210 return lhs() / rhs();
27211 case BinaryOperator.Multiply:
27212 return lhs() * rhs();
27213 case BinaryOperator.Modulo:
27214 return lhs() % rhs();
27215 case BinaryOperator.Lower:
27216 return lhs() < rhs();
27217 case BinaryOperator.LowerEquals:
27218 return lhs() <= rhs();
27219 case BinaryOperator.Bigger:
27220 return lhs() > rhs();
27221 case BinaryOperator.BiggerEquals:
27222 return lhs() >= rhs();
27223 default:
27224 throw new Error("Unknown operator " + ast.operator);
27225 }
27226 };
27227 StatementInterpreter.prototype.visitReadPropExpr = function (ast, ctx) {
27228 var result;
27229 var receiver = ast.receiver.visitExpression(this, ctx);
27230 result = receiver[ast.name];
27231 return result;
27232 };
27233 StatementInterpreter.prototype.visitReadKeyExpr = function (ast, ctx) {
27234 var receiver = ast.receiver.visitExpression(this, ctx);
27235 var prop = ast.index.visitExpression(this, ctx);
27236 return receiver[prop];
27237 };
27238 StatementInterpreter.prototype.visitLiteralArrayExpr = function (ast, ctx) {
27239 return this.visitAllExpressions(ast.entries, ctx);
27240 };
27241 StatementInterpreter.prototype.visitLiteralMapExpr = function (ast, ctx) {
27242 var _this = this;
27243 var result = {};
27244 ast.entries.forEach(function (entry) { return result[entry.key] = entry.value.visitExpression(_this, ctx); });
27245 return result;
27246 };
27247 StatementInterpreter.prototype.visitCommaExpr = function (ast, context) {
27248 var values = this.visitAllExpressions(ast.parts, context);
27249 return values[values.length - 1];
27250 };
27251 StatementInterpreter.prototype.visitAllExpressions = function (expressions, ctx) {
27252 var _this = this;
27253 return expressions.map(function (expr) { return expr.visitExpression(_this, ctx); });
27254 };
27255 StatementInterpreter.prototype.visitAllStatements = function (statements, ctx) {
27256 for (var i = 0; i < statements.length; i++) {
27257 var stmt = statements[i];
27258 var val = stmt.visitStatement(this, ctx);
27259 if (val instanceof ReturnValue) {
27260 return val;
27261 }
27262 }
27263 return null;
27264 };
27265 return StatementInterpreter;
27266}());
27267function _declareFn(varNames, statements, ctx, visitor) {
27268 return function () {
27269 var args = [];
27270 for (var _i = 0; _i < arguments.length; _i++) {
27271 args[_i] = arguments[_i];
27272 }
27273 return _executeFunctionStatements(varNames, args, statements, ctx, visitor);
27274 };
27275}
27276var CATCH_ERROR_VAR$2 = 'error';
27277var CATCH_STACK_VAR$2 = 'stack';
27278
27279/**
27280 * @license
27281 * Copyright Google Inc. All Rights Reserved.
27282 *
27283 * Use of this source code is governed by an MIT-style license that can be
27284 * found in the LICENSE file at https://angular.io/license
27285 */
27286/**
27287 * An internal module of the Angular compiler that begins with component types,
27288 * extracts templates, and eventually produces a compiled version of the component
27289 * ready for linking into an application.
27290 *
27291 * @security When compiling templates at runtime, you must ensure that the entire template comes
27292 * from a trusted source. Attacker-controlled data introduced by a template could expose your
27293 * application to XSS risks. For more detail, see the [Security Guide](http://g.co/ng/security).
27294 */
27295var JitCompiler = /** @class */ (function () {
27296 function JitCompiler(_metadataResolver, _templateParser, _styleCompiler, _viewCompiler, _ngModuleCompiler, _summaryResolver, _reflector, _jitEvaluator, _compilerConfig, _console, getExtraNgModuleProviders) {
27297 this._metadataResolver = _metadataResolver;
27298 this._templateParser = _templateParser;
27299 this._styleCompiler = _styleCompiler;
27300 this._viewCompiler = _viewCompiler;
27301 this._ngModuleCompiler = _ngModuleCompiler;
27302 this._summaryResolver = _summaryResolver;
27303 this._reflector = _reflector;
27304 this._jitEvaluator = _jitEvaluator;
27305 this._compilerConfig = _compilerConfig;
27306 this._console = _console;
27307 this.getExtraNgModuleProviders = getExtraNgModuleProviders;
27308 this._compiledTemplateCache = new Map();
27309 this._compiledHostTemplateCache = new Map();
27310 this._compiledDirectiveWrapperCache = new Map();
27311 this._compiledNgModuleCache = new Map();
27312 this._sharedStylesheetCount = 0;
27313 this._addedAotSummaries = new Set();
27314 }
27315 JitCompiler.prototype.compileModuleSync = function (moduleType) {
27316 return SyncAsync.assertSync(this._compileModuleAndComponents(moduleType, true));
27317 };
27318 JitCompiler.prototype.compileModuleAsync = function (moduleType) {
27319 return Promise.resolve(this._compileModuleAndComponents(moduleType, false));
27320 };
27321 JitCompiler.prototype.compileModuleAndAllComponentsSync = function (moduleType) {
27322 return SyncAsync.assertSync(this._compileModuleAndAllComponents(moduleType, true));
27323 };
27324 JitCompiler.prototype.compileModuleAndAllComponentsAsync = function (moduleType) {
27325 return Promise.resolve(this._compileModuleAndAllComponents(moduleType, false));
27326 };
27327 JitCompiler.prototype.getComponentFactory = function (component) {
27328 var summary = this._metadataResolver.getDirectiveSummary(component);
27329 return summary.componentFactory;
27330 };
27331 JitCompiler.prototype.loadAotSummaries = function (summaries) {
27332 this.clearCache();
27333 this._addAotSummaries(summaries);
27334 };
27335 JitCompiler.prototype._addAotSummaries = function (fn) {
27336 if (this._addedAotSummaries.has(fn)) {
27337 return;
27338 }
27339 this._addedAotSummaries.add(fn);
27340 var summaries = fn();
27341 for (var i = 0; i < summaries.length; i++) {
27342 var entry = summaries[i];
27343 if (typeof entry === 'function') {
27344 this._addAotSummaries(entry);
27345 }
27346 else {
27347 var summary = entry;
27348 this._summaryResolver.addSummary({ symbol: summary.type.reference, metadata: null, type: summary });
27349 }
27350 }
27351 };
27352 JitCompiler.prototype.hasAotSummary = function (ref) { return !!this._summaryResolver.resolveSummary(ref); };
27353 JitCompiler.prototype._filterJitIdentifiers = function (ids) {
27354 var _this = this;
27355 return ids.map(function (mod) { return mod.reference; }).filter(function (ref) { return !_this.hasAotSummary(ref); });
27356 };
27357 JitCompiler.prototype._compileModuleAndComponents = function (moduleType, isSync) {
27358 var _this = this;
27359 return SyncAsync.then(this._loadModules(moduleType, isSync), function () {
27360 _this._compileComponents(moduleType, null);
27361 return _this._compileModule(moduleType);
27362 });
27363 };
27364 JitCompiler.prototype._compileModuleAndAllComponents = function (moduleType, isSync) {
27365 var _this = this;
27366 return SyncAsync.then(this._loadModules(moduleType, isSync), function () {
27367 var componentFactories = [];
27368 _this._compileComponents(moduleType, componentFactories);
27369 return {
27370 ngModuleFactory: _this._compileModule(moduleType),
27371 componentFactories: componentFactories
27372 };
27373 });
27374 };
27375 JitCompiler.prototype._loadModules = function (mainModule, isSync) {
27376 var _this = this;
27377 var loading = [];
27378 var mainNgModule = this._metadataResolver.getNgModuleMetadata(mainModule);
27379 // Note: for runtime compilation, we want to transitively compile all modules,
27380 // so we also need to load the declared directives / pipes for all nested modules.
27381 this._filterJitIdentifiers(mainNgModule.transitiveModule.modules).forEach(function (nestedNgModule) {
27382 // getNgModuleMetadata only returns null if the value passed in is not an NgModule
27383 var moduleMeta = _this._metadataResolver.getNgModuleMetadata(nestedNgModule);
27384 _this._filterJitIdentifiers(moduleMeta.declaredDirectives).forEach(function (ref) {
27385 var promise = _this._metadataResolver.loadDirectiveMetadata(moduleMeta.type.reference, ref, isSync);
27386 if (promise) {
27387 loading.push(promise);
27388 }
27389 });
27390 _this._filterJitIdentifiers(moduleMeta.declaredPipes)
27391 .forEach(function (ref) { return _this._metadataResolver.getOrLoadPipeMetadata(ref); });
27392 });
27393 return SyncAsync.all(loading);
27394 };
27395 JitCompiler.prototype._compileModule = function (moduleType) {
27396 var ngModuleFactory = this._compiledNgModuleCache.get(moduleType);
27397 if (!ngModuleFactory) {
27398 var moduleMeta = this._metadataResolver.getNgModuleMetadata(moduleType);
27399 // Always provide a bound Compiler
27400 var extraProviders = this.getExtraNgModuleProviders(moduleMeta.type.reference);
27401 var outputCtx = createOutputContext();
27402 var compileResult = this._ngModuleCompiler.compile(outputCtx, moduleMeta, extraProviders);
27403 ngModuleFactory = this._interpretOrJit(ngModuleJitUrl(moduleMeta), outputCtx.statements)[compileResult.ngModuleFactoryVar];
27404 this._compiledNgModuleCache.set(moduleMeta.type.reference, ngModuleFactory);
27405 }
27406 return ngModuleFactory;
27407 };
27408 /**
27409 * @internal
27410 */
27411 JitCompiler.prototype._compileComponents = function (mainModule, allComponentFactories) {
27412 var _this = this;
27413 var ngModule = this._metadataResolver.getNgModuleMetadata(mainModule);
27414 var moduleByJitDirective = new Map();
27415 var templates = new Set();
27416 var transJitModules = this._filterJitIdentifiers(ngModule.transitiveModule.modules);
27417 transJitModules.forEach(function (localMod) {
27418 var localModuleMeta = _this._metadataResolver.getNgModuleMetadata(localMod);
27419 _this._filterJitIdentifiers(localModuleMeta.declaredDirectives).forEach(function (dirRef) {
27420 moduleByJitDirective.set(dirRef, localModuleMeta);
27421 var dirMeta = _this._metadataResolver.getDirectiveMetadata(dirRef);
27422 if (dirMeta.isComponent) {
27423 templates.add(_this._createCompiledTemplate(dirMeta, localModuleMeta));
27424 if (allComponentFactories) {
27425 var template = _this._createCompiledHostTemplate(dirMeta.type.reference, localModuleMeta);
27426 templates.add(template);
27427 allComponentFactories.push(dirMeta.componentFactory);
27428 }
27429 }
27430 });
27431 });
27432 transJitModules.forEach(function (localMod) {
27433 var localModuleMeta = _this._metadataResolver.getNgModuleMetadata(localMod);
27434 _this._filterJitIdentifiers(localModuleMeta.declaredDirectives).forEach(function (dirRef) {
27435 var dirMeta = _this._metadataResolver.getDirectiveMetadata(dirRef);
27436 if (dirMeta.isComponent) {
27437 dirMeta.entryComponents.forEach(function (entryComponentType) {
27438 var moduleMeta = moduleByJitDirective.get(entryComponentType.componentType);
27439 templates.add(_this._createCompiledHostTemplate(entryComponentType.componentType, moduleMeta));
27440 });
27441 }
27442 });
27443 localModuleMeta.entryComponents.forEach(function (entryComponentType) {
27444 if (!_this.hasAotSummary(entryComponentType.componentType)) {
27445 var moduleMeta = moduleByJitDirective.get(entryComponentType.componentType);
27446 templates.add(_this._createCompiledHostTemplate(entryComponentType.componentType, moduleMeta));
27447 }
27448 });
27449 });
27450 templates.forEach(function (template) { return _this._compileTemplate(template); });
27451 };
27452 JitCompiler.prototype.clearCacheFor = function (type) {
27453 this._compiledNgModuleCache.delete(type);
27454 this._metadataResolver.clearCacheFor(type);
27455 this._compiledHostTemplateCache.delete(type);
27456 var compiledTemplate = this._compiledTemplateCache.get(type);
27457 if (compiledTemplate) {
27458 this._compiledTemplateCache.delete(type);
27459 }
27460 };
27461 JitCompiler.prototype.clearCache = function () {
27462 // Note: don't clear the _addedAotSummaries, as they don't change!
27463 this._metadataResolver.clearCache();
27464 this._compiledTemplateCache.clear();
27465 this._compiledHostTemplateCache.clear();
27466 this._compiledNgModuleCache.clear();
27467 };
27468 JitCompiler.prototype._createCompiledHostTemplate = function (compType, ngModule) {
27469 if (!ngModule) {
27470 throw new Error("Component " + stringify(compType) + " is not part of any NgModule or the module has not been imported into your module.");
27471 }
27472 var compiledTemplate = this._compiledHostTemplateCache.get(compType);
27473 if (!compiledTemplate) {
27474 var compMeta = this._metadataResolver.getDirectiveMetadata(compType);
27475 assertComponent(compMeta);
27476 var hostMeta = this._metadataResolver.getHostComponentMetadata(compMeta, compMeta.componentFactory.viewDefFactory);
27477 compiledTemplate =
27478 new CompiledTemplate(true, compMeta.type, hostMeta, ngModule, [compMeta.type]);
27479 this._compiledHostTemplateCache.set(compType, compiledTemplate);
27480 }
27481 return compiledTemplate;
27482 };
27483 JitCompiler.prototype._createCompiledTemplate = function (compMeta, ngModule) {
27484 var compiledTemplate = this._compiledTemplateCache.get(compMeta.type.reference);
27485 if (!compiledTemplate) {
27486 assertComponent(compMeta);
27487 compiledTemplate = new CompiledTemplate(false, compMeta.type, compMeta, ngModule, ngModule.transitiveModule.directives);
27488 this._compiledTemplateCache.set(compMeta.type.reference, compiledTemplate);
27489 }
27490 return compiledTemplate;
27491 };
27492 JitCompiler.prototype._compileTemplate = function (template) {
27493 var _this = this;
27494 if (template.isCompiled) {
27495 return;
27496 }
27497 var compMeta = template.compMeta;
27498 var externalStylesheetsByModuleUrl = new Map();
27499 var outputContext = createOutputContext();
27500 var componentStylesheet = this._styleCompiler.compileComponent(outputContext, compMeta);
27501 compMeta.template.externalStylesheets.forEach(function (stylesheetMeta) {
27502 var compiledStylesheet = _this._styleCompiler.compileStyles(createOutputContext(), compMeta, stylesheetMeta);
27503 externalStylesheetsByModuleUrl.set(stylesheetMeta.moduleUrl, compiledStylesheet);
27504 });
27505 this._resolveStylesCompileResult(componentStylesheet, externalStylesheetsByModuleUrl);
27506 var pipes = template.ngModule.transitiveModule.pipes.map(function (pipe) { return _this._metadataResolver.getPipeSummary(pipe.reference); });
27507 var _a = this._parseTemplate(compMeta, template.ngModule, template.directives), parsedTemplate = _a.template, usedPipes = _a.pipes;
27508 var compileResult = this._viewCompiler.compileComponent(outputContext, compMeta, parsedTemplate, variable(componentStylesheet.stylesVar), usedPipes);
27509 var evalResult = this._interpretOrJit(templateJitUrl(template.ngModule.type, template.compMeta), outputContext.statements);
27510 var viewClass = evalResult[compileResult.viewClassVar];
27511 var rendererType = evalResult[compileResult.rendererTypeVar];
27512 template.compiled(viewClass, rendererType);
27513 };
27514 JitCompiler.prototype._parseTemplate = function (compMeta, ngModule, directiveIdentifiers) {
27515 var _this = this;
27516 // Note: ! is ok here as components always have a template.
27517 var preserveWhitespaces = compMeta.template.preserveWhitespaces;
27518 var directives = directiveIdentifiers.map(function (dir) { return _this._metadataResolver.getDirectiveSummary(dir.reference); });
27519 var pipes = ngModule.transitiveModule.pipes.map(function (pipe) { return _this._metadataResolver.getPipeSummary(pipe.reference); });
27520 return this._templateParser.parse(compMeta, compMeta.template.htmlAst, directives, pipes, ngModule.schemas, templateSourceUrl(ngModule.type, compMeta, compMeta.template), preserveWhitespaces);
27521 };
27522 JitCompiler.prototype._resolveStylesCompileResult = function (result, externalStylesheetsByModuleUrl) {
27523 var _this = this;
27524 result.dependencies.forEach(function (dep, i) {
27525 var nestedCompileResult = externalStylesheetsByModuleUrl.get(dep.moduleUrl);
27526 var nestedStylesArr = _this._resolveAndEvalStylesCompileResult(nestedCompileResult, externalStylesheetsByModuleUrl);
27527 dep.setValue(nestedStylesArr);
27528 });
27529 };
27530 JitCompiler.prototype._resolveAndEvalStylesCompileResult = function (result, externalStylesheetsByModuleUrl) {
27531 this._resolveStylesCompileResult(result, externalStylesheetsByModuleUrl);
27532 return this._interpretOrJit(sharedStylesheetJitUrl(result.meta, this._sharedStylesheetCount++), result.outputCtx.statements)[result.stylesVar];
27533 };
27534 JitCompiler.prototype._interpretOrJit = function (sourceUrl, statements) {
27535 if (!this._compilerConfig.useJit) {
27536 return interpretStatements(statements, this._reflector);
27537 }
27538 else {
27539 return this._jitEvaluator.evaluateStatements(sourceUrl, statements, this._reflector, this._compilerConfig.jitDevMode);
27540 }
27541 };
27542 return JitCompiler;
27543}());
27544var CompiledTemplate = /** @class */ (function () {
27545 function CompiledTemplate(isHost, compType, compMeta, ngModule, directives) {
27546 this.isHost = isHost;
27547 this.compType = compType;
27548 this.compMeta = compMeta;
27549 this.ngModule = ngModule;
27550 this.directives = directives;
27551 this._viewClass = null;
27552 this.isCompiled = false;
27553 }
27554 CompiledTemplate.prototype.compiled = function (viewClass, rendererType) {
27555 this._viewClass = viewClass;
27556 this.compMeta.componentViewType.setDelegate(viewClass);
27557 for (var prop in rendererType) {
27558 this.compMeta.rendererType[prop] = rendererType[prop];
27559 }
27560 this.isCompiled = true;
27561 };
27562 return CompiledTemplate;
27563}());
27564function assertComponent(meta) {
27565 if (!meta.isComponent) {
27566 throw new Error("Could not compile '" + identifierName(meta.type) + "' because it is not a component.");
27567 }
27568}
27569function createOutputContext() {
27570 var importExpr$1 = function (symbol) {
27571 return importExpr({ name: identifierName(symbol), moduleName: null, runtime: symbol });
27572 };
27573 return { statements: [], genFilePath: '', importExpr: importExpr$1, constantPool: new ConstantPool() };
27574}
27575
27576/**
27577 * @license
27578 * Copyright Google Inc. All Rights Reserved.
27579 *
27580 * Use of this source code is governed by an MIT-style license that can be
27581 * found in the LICENSE file at https://angular.io/license
27582 */
27583/**
27584 * Provides access to reflection data about symbols that the compiler needs.
27585 */
27586var CompileReflector = /** @class */ (function () {
27587 function CompileReflector() {
27588 }
27589 return CompileReflector;
27590}());
27591
27592/**
27593 * @license
27594 * Copyright Google Inc. All Rights Reserved.
27595 *
27596 * Use of this source code is governed by an MIT-style license that can be
27597 * found in the LICENSE file at https://angular.io/license
27598 */
27599/**
27600 * Create a {@link UrlResolver} with no package prefix.
27601 */
27602function createUrlResolverWithoutPackagePrefix() {
27603 return new UrlResolver();
27604}
27605function createOfflineCompileUrlResolver() {
27606 return new UrlResolver('.');
27607}
27608var UrlResolver = /** @class */ (function () {
27609 function UrlResolverImpl(_packagePrefix) {
27610 if (_packagePrefix === void 0) { _packagePrefix = null; }
27611 this._packagePrefix = _packagePrefix;
27612 }
27613 /**
27614 * Resolves the `url` given the `baseUrl`:
27615 * - when the `url` is null, the `baseUrl` is returned,
27616 * - if `url` is relative ('path/to/here', './path/to/here'), the resolved url is a combination of
27617 * `baseUrl` and `url`,
27618 * - if `url` is absolute (it has a scheme: 'http://', 'https://' or start with '/'), the `url` is
27619 * returned as is (ignoring the `baseUrl`)
27620 */
27621 UrlResolverImpl.prototype.resolve = function (baseUrl, url) {
27622 var resolvedUrl = url;
27623 if (baseUrl != null && baseUrl.length > 0) {
27624 resolvedUrl = _resolveUrl(baseUrl, resolvedUrl);
27625 }
27626 var resolvedParts = _split(resolvedUrl);
27627 var prefix = this._packagePrefix;
27628 if (prefix != null && resolvedParts != null &&
27629 resolvedParts[_ComponentIndex.Scheme] == 'package') {
27630 var path = resolvedParts[_ComponentIndex.Path];
27631 prefix = prefix.replace(/\/+$/, '');
27632 path = path.replace(/^\/+/, '');
27633 return prefix + "/" + path;
27634 }
27635 return resolvedUrl;
27636 };
27637 return UrlResolverImpl;
27638}());
27639/**
27640 * Extract the scheme of a URL.
27641 */
27642function getUrlScheme(url) {
27643 var match = _split(url);
27644 return (match && match[_ComponentIndex.Scheme]) || '';
27645}
27646// The code below is adapted from Traceur:
27647// https://github.com/google/traceur-compiler/blob/9511c1dafa972bf0de1202a8a863bad02f0f95a8/src/runtime/url.js
27648/**
27649 * Builds a URI string from already-encoded parts.
27650 *
27651 * No encoding is performed. Any component may be omitted as either null or
27652 * undefined.
27653 *
27654 * @param opt_scheme The scheme such as 'http'.
27655 * @param opt_userInfo The user name before the '@'.
27656 * @param opt_domain The domain such as 'www.google.com', already
27657 * URI-encoded.
27658 * @param opt_port The port number.
27659 * @param opt_path The path, already URI-encoded. If it is not
27660 * empty, it must begin with a slash.
27661 * @param opt_queryData The URI-encoded query data.
27662 * @param opt_fragment The URI-encoded fragment identifier.
27663 * @return The fully combined URI.
27664 */
27665function _buildFromEncodedParts(opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) {
27666 var out = [];
27667 if (opt_scheme != null) {
27668 out.push(opt_scheme + ':');
27669 }
27670 if (opt_domain != null) {
27671 out.push('//');
27672 if (opt_userInfo != null) {
27673 out.push(opt_userInfo + '@');
27674 }
27675 out.push(opt_domain);
27676 if (opt_port != null) {
27677 out.push(':' + opt_port);
27678 }
27679 }
27680 if (opt_path != null) {
27681 out.push(opt_path);
27682 }
27683 if (opt_queryData != null) {
27684 out.push('?' + opt_queryData);
27685 }
27686 if (opt_fragment != null) {
27687 out.push('#' + opt_fragment);
27688 }
27689 return out.join('');
27690}
27691/**
27692 * A regular expression for breaking a URI into its component parts.
27693 *
27694 * {@link http://www.gbiv.com/protocols/uri/rfc/rfc3986.html#RFC2234} says
27695 * As the "first-match-wins" algorithm is identical to the "greedy"
27696 * disambiguation method used by POSIX regular expressions, it is natural and
27697 * commonplace to use a regular expression for parsing the potential five
27698 * components of a URI reference.
27699 *
27700 * The following line is the regular expression for breaking-down a
27701 * well-formed URI reference into its components.
27702 *
27703 * <pre>
27704 * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
27705 * 12 3 4 5 6 7 8 9
27706 * </pre>
27707 *
27708 * The numbers in the second line above are only to assist readability; they
27709 * indicate the reference points for each subexpression (i.e., each paired
27710 * parenthesis). We refer to the value matched for subexpression <n> as $<n>.
27711 * For example, matching the above expression to
27712 * <pre>
27713 * http://www.ics.uci.edu/pub/ietf/uri/#Related
27714 * </pre>
27715 * results in the following subexpression matches:
27716 * <pre>
27717 * $1 = http:
27718 * $2 = http
27719 * $3 = //www.ics.uci.edu
27720 * $4 = www.ics.uci.edu
27721 * $5 = /pub/ietf/uri/
27722 * $6 = <undefined>
27723 * $7 = <undefined>
27724 * $8 = #Related
27725 * $9 = Related
27726 * </pre>
27727 * where <undefined> indicates that the component is not present, as is the
27728 * case for the query component in the above example. Therefore, we can
27729 * determine the value of the five components as
27730 * <pre>
27731 * scheme = $2
27732 * authority = $4
27733 * path = $5
27734 * query = $7
27735 * fragment = $9
27736 * </pre>
27737 *
27738 * The regular expression has been modified slightly to expose the
27739 * userInfo, domain, and port separately from the authority.
27740 * The modified version yields
27741 * <pre>
27742 * $1 = http scheme
27743 * $2 = <undefined> userInfo -\
27744 * $3 = www.ics.uci.edu domain | authority
27745 * $4 = <undefined> port -/
27746 * $5 = /pub/ietf/uri/ path
27747 * $6 = <undefined> query without ?
27748 * $7 = Related fragment without #
27749 * </pre>
27750 * @internal
27751 */
27752var _splitRe = new RegExp('^' +
27753 '(?:' +
27754 '([^:/?#.]+)' + // scheme - ignore special characters
27755 // used by other URL parts such as :,
27756 // ?, /, #, and .
27757 ':)?' +
27758 '(?://' +
27759 '(?:([^/?#]*)@)?' + // userInfo
27760 '([\\w\\d\\-\\u0100-\\uffff.%]*)' + // domain - restrict to letters,
27761 // digits, dashes, dots, percent
27762 // escapes, and unicode characters.
27763 '(?::([0-9]+))?' + // port
27764 ')?' +
27765 '([^?#]+)?' + // path
27766 '(?:\\?([^#]*))?' + // query
27767 '(?:#(.*))?' + // fragment
27768 '$');
27769/**
27770 * The index of each URI component in the return value of goog.uri.utils.split.
27771 * @enum {number}
27772 */
27773var _ComponentIndex;
27774(function (_ComponentIndex) {
27775 _ComponentIndex[_ComponentIndex["Scheme"] = 1] = "Scheme";
27776 _ComponentIndex[_ComponentIndex["UserInfo"] = 2] = "UserInfo";
27777 _ComponentIndex[_ComponentIndex["Domain"] = 3] = "Domain";
27778 _ComponentIndex[_ComponentIndex["Port"] = 4] = "Port";
27779 _ComponentIndex[_ComponentIndex["Path"] = 5] = "Path";
27780 _ComponentIndex[_ComponentIndex["QueryData"] = 6] = "QueryData";
27781 _ComponentIndex[_ComponentIndex["Fragment"] = 7] = "Fragment";
27782})(_ComponentIndex || (_ComponentIndex = {}));
27783/**
27784 * Splits a URI into its component parts.
27785 *
27786 * Each component can be accessed via the component indices; for example:
27787 * <pre>
27788 * goog.uri.utils.split(someStr)[goog.uri.utils.CompontentIndex.QUERY_DATA];
27789 * </pre>
27790 *
27791 * @param uri The URI string to examine.
27792 * @return Each component still URI-encoded.
27793 * Each component that is present will contain the encoded value, whereas
27794 * components that are not present will be undefined or empty, depending
27795 * on the browser's regular expression implementation. Never null, since
27796 * arbitrary strings may still look like path names.
27797 */
27798function _split(uri) {
27799 return uri.match(_splitRe);
27800}
27801/**
27802 * Removes dot segments in given path component, as described in
27803 * RFC 3986, section 5.2.4.
27804 *
27805 * @param path A non-empty path component.
27806 * @return Path component with removed dot segments.
27807 */
27808function _removeDotSegments(path) {
27809 if (path == '/')
27810 return '/';
27811 var leadingSlash = path[0] == '/' ? '/' : '';
27812 var trailingSlash = path[path.length - 1] === '/' ? '/' : '';
27813 var segments = path.split('/');
27814 var out = [];
27815 var up = 0;
27816 for (var pos = 0; pos < segments.length; pos++) {
27817 var segment = segments[pos];
27818 switch (segment) {
27819 case '':
27820 case '.':
27821 break;
27822 case '..':
27823 if (out.length > 0) {
27824 out.pop();
27825 }
27826 else {
27827 up++;
27828 }
27829 break;
27830 default:
27831 out.push(segment);
27832 }
27833 }
27834 if (leadingSlash == '') {
27835 while (up-- > 0) {
27836 out.unshift('..');
27837 }
27838 if (out.length === 0)
27839 out.push('.');
27840 }
27841 return leadingSlash + out.join('/') + trailingSlash;
27842}
27843/**
27844 * Takes an array of the parts from split and canonicalizes the path part
27845 * and then joins all the parts.
27846 */
27847function _joinAndCanonicalizePath(parts) {
27848 var path = parts[_ComponentIndex.Path];
27849 path = path == null ? '' : _removeDotSegments(path);
27850 parts[_ComponentIndex.Path] = path;
27851 return _buildFromEncodedParts(parts[_ComponentIndex.Scheme], parts[_ComponentIndex.UserInfo], parts[_ComponentIndex.Domain], parts[_ComponentIndex.Port], path, parts[_ComponentIndex.QueryData], parts[_ComponentIndex.Fragment]);
27852}
27853/**
27854 * Resolves a URL.
27855 * @param base The URL acting as the base URL.
27856 * @param to The URL to resolve.
27857 */
27858function _resolveUrl(base, url) {
27859 var parts = _split(encodeURI(url));
27860 var baseParts = _split(base);
27861 if (parts[_ComponentIndex.Scheme] != null) {
27862 return _joinAndCanonicalizePath(parts);
27863 }
27864 else {
27865 parts[_ComponentIndex.Scheme] = baseParts[_ComponentIndex.Scheme];
27866 }
27867 for (var i = _ComponentIndex.Scheme; i <= _ComponentIndex.Port; i++) {
27868 if (parts[i] == null) {
27869 parts[i] = baseParts[i];
27870 }
27871 }
27872 if (parts[_ComponentIndex.Path][0] == '/') {
27873 return _joinAndCanonicalizePath(parts);
27874 }
27875 var path = baseParts[_ComponentIndex.Path];
27876 if (path == null)
27877 path = '/';
27878 var index = path.lastIndexOf('/');
27879 path = path.substring(0, index + 1) + parts[_ComponentIndex.Path];
27880 parts[_ComponentIndex.Path] = path;
27881 return _joinAndCanonicalizePath(parts);
27882}
27883
27884/**
27885 * @license
27886 * Copyright Google Inc. All Rights Reserved.
27887 *
27888 * Use of this source code is governed by an MIT-style license that can be
27889 * found in the LICENSE file at https://angular.io/license
27890 */
27891var Extractor = /** @class */ (function () {
27892 function Extractor(host, staticSymbolResolver, messageBundle, metadataResolver) {
27893 this.host = host;
27894 this.staticSymbolResolver = staticSymbolResolver;
27895 this.messageBundle = messageBundle;
27896 this.metadataResolver = metadataResolver;
27897 }
27898 Extractor.prototype.extract = function (rootFiles) {
27899 var _this = this;
27900 var _a = analyzeAndValidateNgModules(rootFiles, this.host, this.staticSymbolResolver, this.metadataResolver), files = _a.files, ngModules = _a.ngModules;
27901 return Promise
27902 .all(ngModules.map(function (ngModule) { return _this.metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, false); }))
27903 .then(function () {
27904 var errors = [];
27905 files.forEach(function (file) {
27906 var compMetas = [];
27907 file.directives.forEach(function (directiveType) {
27908 var dirMeta = _this.metadataResolver.getDirectiveMetadata(directiveType);
27909 if (dirMeta && dirMeta.isComponent) {
27910 compMetas.push(dirMeta);
27911 }
27912 });
27913 compMetas.forEach(function (compMeta) {
27914 var html = compMeta.template.template;
27915 // Template URL points to either an HTML or TS file depending on
27916 // whether the file is used with `templateUrl:` or `template:`,
27917 // respectively.
27918 var templateUrl = compMeta.template.templateUrl;
27919 var interpolationConfig = InterpolationConfig.fromArray(compMeta.template.interpolation);
27920 errors.push.apply(errors, __spread(_this.messageBundle.updateFromTemplate(html, templateUrl, interpolationConfig)));
27921 });
27922 });
27923 if (errors.length) {
27924 throw new Error(errors.map(function (e) { return e.toString(); }).join('\n'));
27925 }
27926 return _this.messageBundle;
27927 });
27928 };
27929 Extractor.create = function (host, locale) {
27930 var htmlParser = new HtmlParser();
27931 var urlResolver = createAotUrlResolver(host);
27932 var symbolCache = new StaticSymbolCache();
27933 var summaryResolver = new AotSummaryResolver(host, symbolCache);
27934 var staticSymbolResolver = new StaticSymbolResolver(host, symbolCache, summaryResolver);
27935 var staticReflector = new StaticReflector(summaryResolver, staticSymbolResolver);
27936 var config = new CompilerConfig({ defaultEncapsulation: ViewEncapsulation.Emulated, useJit: false });
27937 var normalizer = new DirectiveNormalizer({ get: function (url) { return host.loadResource(url); } }, urlResolver, htmlParser, config);
27938 var elementSchemaRegistry = new DomElementSchemaRegistry();
27939 var resolver = new CompileMetadataResolver(config, htmlParser, new NgModuleResolver(staticReflector), new DirectiveResolver(staticReflector), new PipeResolver(staticReflector), summaryResolver, elementSchemaRegistry, normalizer, console, symbolCache, staticReflector);
27940 // TODO(vicb): implicit tags & attributes
27941 var messageBundle = new MessageBundle(htmlParser, [], {}, locale);
27942 var extractor = new Extractor(host, staticSymbolResolver, messageBundle, resolver);
27943 return { extractor: extractor, staticReflector: staticReflector };
27944 };
27945 return Extractor;
27946}());
27947
27948/**
27949 * @license
27950 * Copyright Google Inc. All Rights Reserved.
27951 *
27952 * Use of this source code is governed by an MIT-style license that can be
27953 * found in the LICENSE file at https://angular.io/license
27954 */
27955
27956/**
27957 * @license
27958 * Copyright Google Inc. All Rights Reserved.
27959 *
27960 * Use of this source code is governed by an MIT-style license that can be
27961 * found in the LICENSE file at https://angular.io/license
27962 */
27963/**
27964 * Processes `Target`s with a given set of directives and performs a binding operation, which
27965 * returns an object similar to TypeScript's `ts.TypeChecker` that contains knowledge about the
27966 * target.
27967 */
27968var R3TargetBinder = /** @class */ (function () {
27969 function R3TargetBinder(directiveMatcher) {
27970 this.directiveMatcher = directiveMatcher;
27971 }
27972 /**
27973 * Perform a binding operation on the given `Target` and return a `BoundTarget` which contains
27974 * metadata about the types referenced in the template.
27975 */
27976 R3TargetBinder.prototype.bind = function (target) {
27977 if (!target.template) {
27978 // TODO(alxhub): handle targets which contain things like HostBindings, etc.
27979 throw new Error('Binding without a template not yet supported');
27980 }
27981 // First, parse the template into a `Scope` structure. This operation captures the syntactic
27982 // scopes in the template and makes them available for later use.
27983 var scope = Scope.apply(target.template);
27984 // Next, perform directive matching on the template using the `DirectiveBinder`. This returns:
27985 // - directives: Map of nodes (elements & ng-templates) to the directives on them.
27986 // - bindings: Map of inputs, outputs, and attributes to the directive/element that claims
27987 // them. TODO(alxhub): handle multiple directives claiming an input/output/etc.
27988 // - references: Map of #references to their targets.
27989 var _a = DirectiveBinder.apply(target.template, this.directiveMatcher), directives = _a.directives, bindings = _a.bindings, references = _a.references;
27990 // Finally, run the TemplateBinder to bind references, variables, and other entities within the
27991 // template. This extracts all the metadata that doesn't depend on directive matching.
27992 var _b = TemplateBinder.apply(target.template, scope), expressions = _b.expressions, symbols = _b.symbols, nestingLevel = _b.nestingLevel, usedPipes = _b.usedPipes;
27993 return new R3BoundTarget(target, directives, bindings, references, expressions, symbols, nestingLevel, usedPipes);
27994 };
27995 return R3TargetBinder;
27996}());
27997/**
27998 * Represents a binding scope within a template.
27999 *
28000 * Any variables, references, or other named entities declared within the template will
28001 * be captured and available by name in `namedEntities`. Additionally, child templates will
28002 * be analyzed and have their child `Scope`s available in `childScopes`.
28003 */
28004var Scope = /** @class */ (function () {
28005 function Scope(parentScope) {
28006 this.parentScope = parentScope;
28007 /**
28008 * Named members of the `Scope`, such as `Reference`s or `Variable`s.
28009 */
28010 this.namedEntities = new Map();
28011 /**
28012 * Child `Scope`s for immediately nested `Template`s.
28013 */
28014 this.childScopes = new Map();
28015 }
28016 /**
28017 * Process a template (either as a `Template` sub-template with variables, or a plain array of
28018 * template `Node`s) and construct its `Scope`.
28019 */
28020 Scope.apply = function (template) {
28021 var scope = new Scope();
28022 scope.ingest(template);
28023 return scope;
28024 };
28025 /**
28026 * Internal method to process the template and populate the `Scope`.
28027 */
28028 Scope.prototype.ingest = function (template) {
28029 var _this = this;
28030 if (template instanceof Template) {
28031 // Variables on an <ng-template> are defined in the inner scope.
28032 template.variables.forEach(function (node) { return _this.visitVariable(node); });
28033 // Process the nodes of the template.
28034 template.children.forEach(function (node) { return node.visit(_this); });
28035 }
28036 else {
28037 // No overarching `Template` instance, so process the nodes directly.
28038 template.forEach(function (node) { return node.visit(_this); });
28039 }
28040 };
28041 Scope.prototype.visitElement = function (element) {
28042 var _this = this;
28043 // `Element`s in the template may have `Reference`s which are captured in the scope.
28044 element.references.forEach(function (node) { return _this.visitReference(node); });
28045 // Recurse into the `Element`'s children.
28046 element.children.forEach(function (node) { return node.visit(_this); });
28047 };
28048 Scope.prototype.visitTemplate = function (template) {
28049 var _this = this;
28050 // References on a <ng-template> are defined in the outer scope, so capture them before
28051 // processing the template's child scope.
28052 template.references.forEach(function (node) { return _this.visitReference(node); });
28053 // Next, create an inner scope and process the template within it.
28054 var scope = new Scope(this);
28055 scope.ingest(template);
28056 this.childScopes.set(template, scope);
28057 };
28058 Scope.prototype.visitVariable = function (variable) {
28059 // Declare the variable if it's not already.
28060 this.maybeDeclare(variable);
28061 };
28062 Scope.prototype.visitReference = function (reference) {
28063 // Declare the variable if it's not already.
28064 this.maybeDeclare(reference);
28065 };
28066 // Unused visitors.
28067 Scope.prototype.visitContent = function (content) { };
28068 Scope.prototype.visitBoundAttribute = function (attr) { };
28069 Scope.prototype.visitBoundEvent = function (event) { };
28070 Scope.prototype.visitBoundText = function (text) { };
28071 Scope.prototype.visitText = function (text) { };
28072 Scope.prototype.visitTextAttribute = function (attr) { };
28073 Scope.prototype.visitIcu = function (icu) { };
28074 Scope.prototype.maybeDeclare = function (thing) {
28075 // Declare something with a name, as long as that name isn't taken.
28076 if (!this.namedEntities.has(thing.name)) {
28077 this.namedEntities.set(thing.name, thing);
28078 }
28079 };
28080 /**
28081 * Look up a variable within this `Scope`.
28082 *
28083 * This can recurse into a parent `Scope` if it's available.
28084 */
28085 Scope.prototype.lookup = function (name) {
28086 if (this.namedEntities.has(name)) {
28087 // Found in the local scope.
28088 return this.namedEntities.get(name);
28089 }
28090 else if (this.parentScope !== undefined) {
28091 // Not in the local scope, but there's a parent scope so check there.
28092 return this.parentScope.lookup(name);
28093 }
28094 else {
28095 // At the top level and it wasn't found.
28096 return null;
28097 }
28098 };
28099 /**
28100 * Get the child scope for a `Template`.
28101 *
28102 * This should always be defined.
28103 */
28104 Scope.prototype.getChildScope = function (template) {
28105 var res = this.childScopes.get(template);
28106 if (res === undefined) {
28107 throw new Error("Assertion error: child scope for " + template + " not found");
28108 }
28109 return res;
28110 };
28111 return Scope;
28112}());
28113/**
28114 * Processes a template and matches directives on nodes (elements and templates).
28115 *
28116 * Usually used via the static `apply()` method.
28117 */
28118var DirectiveBinder = /** @class */ (function () {
28119 function DirectiveBinder(matcher, directives, bindings, references) {
28120 this.matcher = matcher;
28121 this.directives = directives;
28122 this.bindings = bindings;
28123 this.references = references;
28124 }
28125 /**
28126 * Process a template (list of `Node`s) and perform directive matching against each node.
28127 *
28128 * @param template the list of template `Node`s to match (recursively).
28129 * @param selectorMatcher a `SelectorMatcher` containing the directives that are in scope for
28130 * this template.
28131 * @returns three maps which contain information about directives in the template: the
28132 * `directives` map which lists directives matched on each node, the `bindings` map which
28133 * indicates which directives claimed which bindings (inputs, outputs, etc), and the `references`
28134 * map which resolves #references (`Reference`s) within the template to the named directive or
28135 * template node.
28136 */
28137 DirectiveBinder.apply = function (template, selectorMatcher) {
28138 var directives = new Map();
28139 var bindings = new Map();
28140 var references = new Map();
28141 var matcher = new DirectiveBinder(selectorMatcher, directives, bindings, references);
28142 matcher.ingest(template);
28143 return { directives: directives, bindings: bindings, references: references };
28144 };
28145 DirectiveBinder.prototype.ingest = function (template) {
28146 var _this = this;
28147 template.forEach(function (node) { return node.visit(_this); });
28148 };
28149 DirectiveBinder.prototype.visitElement = function (element) { this.visitElementOrTemplate(element.name, element); };
28150 DirectiveBinder.prototype.visitTemplate = function (template) { this.visitElementOrTemplate('ng-template', template); };
28151 DirectiveBinder.prototype.visitElementOrTemplate = function (tag, node) {
28152 var _this = this;
28153 // First, determine the HTML shape of the node for the purpose of directive matching.
28154 // Do this by building up a `CssSelector` for the node.
28155 var cssSelector = new CssSelector();
28156 cssSelector.setElement(tag);
28157 // Add attributes to the CSS selector.
28158 var attrs = getAttrsForDirectiveMatching(node);
28159 Object.getOwnPropertyNames(attrs).forEach(function (name) {
28160 var value = attrs[name];
28161 cssSelector.addAttribute(name, value);
28162 // Treat the 'class' attribute specially.
28163 if (name.toLowerCase() === 'class') {
28164 var classes = value.trim().split(/\s+/g);
28165 classes.forEach(function (className) { return cssSelector.addClassName(className); });
28166 }
28167 });
28168 // Next, use the `SelectorMatcher` to get the list of directives on the node.
28169 var directives = [];
28170 this.matcher.match(cssSelector, function (_, directive) { return directives.push(directive); });
28171 if (directives.length > 0) {
28172 this.directives.set(node, directives);
28173 }
28174 // Resolve any references that are created on this node.
28175 node.references.forEach(function (ref) {
28176 var dirTarget = null;
28177 // If the reference expression is empty, then it matches the "primary" directive on the node
28178 // (if there is one). Otherwise it matches the host node itself (either an element or
28179 // <ng-template> node).
28180 if (ref.value.trim() === '') {
28181 // This could be a reference to a component if there is one.
28182 dirTarget = directives.find(function (dir) { return dir.isComponent; }) || null;
28183 }
28184 else {
28185 // This is a reference to a directive exported via exportAs. One should exist.
28186 dirTarget =
28187 directives.find(function (dir) { return dir.exportAs !== null && dir.exportAs.some(function (value) { return value === ref.value; }); }) ||
28188 null;
28189 // Check if a matching directive was found, and error if it wasn't.
28190 if (dirTarget === null) {
28191 // TODO(alxhub): Return an error value here that can be used for template validation.
28192 throw new Error("Assertion error: failed to find directive with exportAs: " + ref.value);
28193 }
28194 }
28195 if (dirTarget !== null) {
28196 // This reference points to a directive.
28197 _this.references.set(ref, { directive: dirTarget, node: node });
28198 }
28199 else {
28200 // This reference points to the node itself.
28201 _this.references.set(ref, node);
28202 }
28203 });
28204 // Associate attributes/bindings on the node with directives or with the node itself.
28205 var processAttribute = function (attribute) {
28206 var dir = directives.find(function (dir) { return dir.inputs.hasOwnProperty(attribute.name); });
28207 if (dir !== undefined) {
28208 _this.bindings.set(attribute, dir);
28209 }
28210 else {
28211 _this.bindings.set(attribute, node);
28212 }
28213 };
28214 node.attributes.forEach(processAttribute);
28215 node.inputs.forEach(processAttribute);
28216 node.outputs.forEach(processAttribute);
28217 if (node instanceof Template) {
28218 node.templateAttrs.forEach(processAttribute);
28219 }
28220 // Recurse into the node's children.
28221 node.children.forEach(function (child) { return child.visit(_this); });
28222 };
28223 // Unused visitors.
28224 DirectiveBinder.prototype.visitContent = function (content) { };
28225 DirectiveBinder.prototype.visitVariable = function (variable) { };
28226 DirectiveBinder.prototype.visitReference = function (reference) { };
28227 DirectiveBinder.prototype.visitTextAttribute = function (attribute) { };
28228 DirectiveBinder.prototype.visitBoundAttribute = function (attribute) { };
28229 DirectiveBinder.prototype.visitBoundEvent = function (attribute) { };
28230 DirectiveBinder.prototype.visitBoundAttributeOrEvent = function (node) { };
28231 DirectiveBinder.prototype.visitText = function (text) { };
28232 DirectiveBinder.prototype.visitBoundText = function (text) { };
28233 DirectiveBinder.prototype.visitIcu = function (icu) { };
28234 return DirectiveBinder;
28235}());
28236/**
28237 * Processes a template and extract metadata about expressions and symbols within.
28238 *
28239 * This is a companion to the `DirectiveBinder` that doesn't require knowledge of directives matched
28240 * within the template in order to operate.
28241 *
28242 * Expressions are visited by the superclass `RecursiveAstVisitor`, with custom logic provided
28243 * by overridden methods from that visitor.
28244 */
28245var TemplateBinder = /** @class */ (function (_super) {
28246 __extends(TemplateBinder, _super);
28247 function TemplateBinder(bindings, symbols, usedPipes, nestingLevel, scope, template, level) {
28248 var _this = _super.call(this) || this;
28249 _this.bindings = bindings;
28250 _this.symbols = symbols;
28251 _this.usedPipes = usedPipes;
28252 _this.nestingLevel = nestingLevel;
28253 _this.scope = scope;
28254 _this.template = template;
28255 _this.level = level;
28256 _this.pipesUsed = [];
28257 // Save a bit of processing time by constructing this closure in advance.
28258 _this.visitNode = function (node) { return node.visit(_this); };
28259 return _this;
28260 }
28261 /**
28262 * Process a template and extract metadata about expressions and symbols within.
28263 *
28264 * @param template the nodes of the template to process
28265 * @param scope the `Scope` of the template being processed.
28266 * @returns three maps which contain metadata about the template: `expressions` which interprets
28267 * special `AST` nodes in expressions as pointing to references or variables declared within the
28268 * template, `symbols` which maps those variables and references to the nested `Template` which
28269 * declares them, if any, and `nestingLevel` which associates each `Template` with a integer
28270 * nesting level (how many levels deep within the template structure the `Template` is), starting
28271 * at 1.
28272 */
28273 TemplateBinder.apply = function (template, scope) {
28274 var expressions = new Map();
28275 var symbols = new Map();
28276 var nestingLevel = new Map();
28277 var usedPipes = new Set();
28278 // The top-level template has nesting level 0.
28279 var binder = new TemplateBinder(expressions, symbols, usedPipes, nestingLevel, scope, template instanceof Template ? template : null, 0);
28280 binder.ingest(template);
28281 return { expressions: expressions, symbols: symbols, nestingLevel: nestingLevel, usedPipes: usedPipes };
28282 };
28283 TemplateBinder.prototype.ingest = function (template) {
28284 if (template instanceof Template) {
28285 // For <ng-template>s, process only variables and child nodes. Inputs, outputs, templateAttrs,
28286 // and references were all processed in the scope of the containing template.
28287 template.variables.forEach(this.visitNode);
28288 template.children.forEach(this.visitNode);
28289 // Set the nesting level.
28290 this.nestingLevel.set(template, this.level);
28291 }
28292 else {
28293 // Visit each node from the top-level template.
28294 template.forEach(this.visitNode);
28295 }
28296 };
28297 TemplateBinder.prototype.visitElement = function (element) {
28298 // Visit the inputs, outputs, and children of the element.
28299 element.inputs.forEach(this.visitNode);
28300 element.outputs.forEach(this.visitNode);
28301 element.children.forEach(this.visitNode);
28302 };
28303 TemplateBinder.prototype.visitTemplate = function (template) {
28304 // First, visit inputs, outputs and template attributes of the template node.
28305 template.inputs.forEach(this.visitNode);
28306 template.outputs.forEach(this.visitNode);
28307 template.templateAttrs.forEach(this.visitNode);
28308 // References are also evaluated in the outer context.
28309 template.references.forEach(this.visitNode);
28310 // Next, recurse into the template using its scope, and bumping the nesting level up by one.
28311 var childScope = this.scope.getChildScope(template);
28312 var binder = new TemplateBinder(this.bindings, this.symbols, this.usedPipes, this.nestingLevel, childScope, template, this.level + 1);
28313 binder.ingest(template);
28314 };
28315 TemplateBinder.prototype.visitVariable = function (variable) {
28316 // Register the `Variable` as a symbol in the current `Template`.
28317 if (this.template !== null) {
28318 this.symbols.set(variable, this.template);
28319 }
28320 };
28321 TemplateBinder.prototype.visitReference = function (reference) {
28322 // Register the `Reference` as a symbol in the current `Template`.
28323 if (this.template !== null) {
28324 this.symbols.set(reference, this.template);
28325 }
28326 };
28327 // Unused template visitors
28328 TemplateBinder.prototype.visitText = function (text) { };
28329 TemplateBinder.prototype.visitContent = function (content) { };
28330 TemplateBinder.prototype.visitTextAttribute = function (attribute) { };
28331 TemplateBinder.prototype.visitIcu = function (icu) { };
28332 // The remaining visitors are concerned with processing AST expressions within template bindings
28333 TemplateBinder.prototype.visitBoundAttribute = function (attribute) { attribute.value.visit(this); };
28334 TemplateBinder.prototype.visitBoundEvent = function (event) { event.handler.visit(this); };
28335 TemplateBinder.prototype.visitBoundText = function (text) { text.value.visit(this); };
28336 TemplateBinder.prototype.visitPipe = function (ast, context) {
28337 this.usedPipes.add(ast.name);
28338 return _super.prototype.visitPipe.call(this, ast, context);
28339 };
28340 // These five types of AST expressions can refer to expression roots, which could be variables
28341 // or references in the current scope.
28342 TemplateBinder.prototype.visitPropertyRead = function (ast, context) {
28343 this.maybeMap(context, ast, ast.name);
28344 return _super.prototype.visitPropertyRead.call(this, ast, context);
28345 };
28346 TemplateBinder.prototype.visitSafePropertyRead = function (ast, context) {
28347 this.maybeMap(context, ast, ast.name);
28348 return _super.prototype.visitSafePropertyRead.call(this, ast, context);
28349 };
28350 TemplateBinder.prototype.visitPropertyWrite = function (ast, context) {
28351 this.maybeMap(context, ast, ast.name);
28352 return _super.prototype.visitPropertyWrite.call(this, ast, context);
28353 };
28354 TemplateBinder.prototype.visitMethodCall = function (ast, context) {
28355 this.maybeMap(context, ast, ast.name);
28356 return _super.prototype.visitMethodCall.call(this, ast, context);
28357 };
28358 TemplateBinder.prototype.visitSafeMethodCall = function (ast, context) {
28359 this.maybeMap(context, ast, ast.name);
28360 return _super.prototype.visitSafeMethodCall.call(this, ast, context);
28361 };
28362 TemplateBinder.prototype.maybeMap = function (scope, ast, name) {
28363 // If the receiver of the expression isn't the `ImplicitReceiver`, this isn't the root of an
28364 // `AST` expression that maps to a `Variable` or `Reference`.
28365 if (!(ast.receiver instanceof ImplicitReceiver)) {
28366 return;
28367 }
28368 // Check whether the name exists in the current scope. If so, map it. Otherwise, the name is
28369 // probably a property on the top-level component context.
28370 var target = this.scope.lookup(name);
28371 if (target !== null) {
28372 this.bindings.set(ast, target);
28373 }
28374 };
28375 return TemplateBinder;
28376}(RecursiveAstVisitor$1));
28377/**
28378 * Metadata container for a `Target` that allows queries for specific bits of metadata.
28379 *
28380 * See `BoundTarget` for documentation on the individual methods.
28381 */
28382var R3BoundTarget = /** @class */ (function () {
28383 function R3BoundTarget(target, directives, bindings, references, exprTargets, symbols, nestingLevel, usedPipes) {
28384 this.target = target;
28385 this.directives = directives;
28386 this.bindings = bindings;
28387 this.references = references;
28388 this.exprTargets = exprTargets;
28389 this.symbols = symbols;
28390 this.nestingLevel = nestingLevel;
28391 this.usedPipes = usedPipes;
28392 }
28393 R3BoundTarget.prototype.getDirectivesOfNode = function (node) {
28394 return this.directives.get(node) || null;
28395 };
28396 R3BoundTarget.prototype.getReferenceTarget = function (ref) {
28397 return this.references.get(ref) || null;
28398 };
28399 R3BoundTarget.prototype.getConsumerOfBinding = function (binding) {
28400 return this.bindings.get(binding) || null;
28401 };
28402 R3BoundTarget.prototype.getExpressionTarget = function (expr) {
28403 return this.exprTargets.get(expr) || null;
28404 };
28405 R3BoundTarget.prototype.getTemplateOfSymbol = function (symbol) {
28406 return this.symbols.get(symbol) || null;
28407 };
28408 R3BoundTarget.prototype.getNestingLevel = function (template) { return this.nestingLevel.get(template) || 0; };
28409 R3BoundTarget.prototype.getUsedDirectives = function () {
28410 var set = new Set();
28411 this.directives.forEach(function (dirs) { return dirs.forEach(function (dir) { return set.add(dir); }); });
28412 return Array.from(set.values());
28413 };
28414 R3BoundTarget.prototype.getUsedPipes = function () { return Array.from(this.usedPipes); };
28415 return R3BoundTarget;
28416}());
28417
28418/**
28419 * @license
28420 * Copyright Google Inc. All Rights Reserved.
28421 *
28422 * Use of this source code is governed by an MIT-style license that can be
28423 * found in the LICENSE file at https://angular.io/license
28424 */
28425// This file only reexports content of the `src` folder. Keep it that way.
28426// This function call has a global side effects and publishes the compiler into global namespace for
28427// the late binding of the Compiler to the @angular/core for jit compilation.
28428publishFacade(_global);
28429
28430/**
28431 * @license
28432 * Copyright Google Inc. 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// This file only reexports content of the `src` folder. Keep it that way.
28438
28439/**
28440 * @license
28441 * Copyright Google Inc. All Rights Reserved.
28442 *
28443 * Use of this source code is governed by an MIT-style license that can be
28444 * found in the LICENSE file at https://angular.io/license
28445 */
28446
28447/**
28448 * @license
28449 * Copyright Google Inc. All Rights Reserved.
28450 *
28451 * Use of this source code is governed by an MIT-style license that can be
28452 * found in the LICENSE file at https://angular.io/license
28453 */
28454
28455export { core, CompilerConfig, preserveWhitespacesDefault, isLoweredSymbol, createLoweredSymbol, Identifiers, JitCompiler, ConstantPool, DirectiveResolver, PipeResolver, NgModuleResolver, DEFAULT_INTERPOLATION_CONFIG, InterpolationConfig, NgModuleCompiler, ArrayType, AssertNotNull, DYNAMIC_TYPE, BinaryOperator, BinaryOperatorExpr, BuiltinMethod, BuiltinType, BuiltinTypeName, BuiltinVar, CastExpr, ClassField, ClassMethod, ClassStmt, CommaExpr, CommentStmt, ConditionalExpr, DeclareFunctionStmt, DeclareVarStmt, Expression, ExpressionStatement, ExpressionType, ExternalExpr, ExternalReference, literalMap, FunctionExpr, IfStmt, InstantiateExpr, InvokeFunctionExpr, InvokeMethodExpr, JSDocCommentStmt, LiteralArrayExpr, LiteralExpr, LiteralMapExpr, MapType, NotExpr, ReadKeyExpr, ReadPropExpr, ReadVarExpr, ReturnStatement, ThrowStmt, TryCatchStmt, Type$1 as Type, WrappedNodeExpr, WriteKeyExpr, WritePropExpr, WriteVarExpr, StmtModifier, Statement, STRING_TYPE, TypeofExpr, collectExternalReferences, EmitterVisitorContext, JitEvaluator, ViewCompiler, findStaticQueryIds, staticViewQueryIds, getParseErrors, isSyntaxError, syntaxError, Version, BoundAttribute as TmplAstBoundAttribute, BoundEvent as TmplAstBoundEvent, BoundText as TmplAstBoundText, Content as TmplAstContent, Element as TmplAstElement, RecursiveVisitor as TmplAstRecursiveVisitor, Reference as TmplAstReference, Template as TmplAstTemplate, Text as TmplAstText, TextAttribute as TmplAstTextAttribute, Variable as TmplAstVariable, Identifiers$1 as R3Identifiers, R3ResolvedDependencyType, compileInjector, compileNgModule, compilePipeFromMetadata, makeBindingParser, parseTemplate, compileBaseDefFromMetadata, compileComponentFromMetadata, compileDirectiveFromMetadata, parseHostBindings, verifyHostBindings, publishFacade, VERSION$1 as VERSION, TextAst, BoundTextAst, AttrAst, BoundElementPropertyAst, BoundEventAst, ReferenceAst, VariableAst, ElementAst, EmbeddedTemplateAst, BoundDirectivePropertyAst, DirectiveAst, ProviderAst, ProviderAstType, NgContentAst, NullTemplateVisitor, RecursiveTemplateAstVisitor, templateVisitAll, sanitizeIdentifier, identifierName, identifierModuleUrl, viewClassName, rendererTypeName, hostViewClassName, componentFactoryName, CompileSummaryKind, tokenName, tokenReference, CompileStylesheetMetadata, CompileTemplateMetadata, CompileDirectiveMetadata, CompilePipeMetadata, CompileShallowModuleMetadata, CompileNgModuleMetadata, TransitiveCompileNgModuleMetadata, ProviderMeta, flatten, templateSourceUrl, sharedStylesheetJitUrl, ngModuleJitUrl, templateJitUrl, createAotUrlResolver, createAotCompiler, AotCompiler, analyzeNgModules, analyzeAndValidateNgModules, analyzeFile, analyzeFileForInjectables, mergeAnalyzedFiles, GeneratedFile, toTypeScript, formattedError, isFormattedError, StaticReflector, StaticSymbol, StaticSymbolCache, ResolvedStaticSymbol, StaticSymbolResolver, unescapeIdentifier, unwrapResolvedMetadata, AotSummaryResolver, AstPath, SummaryResolver, JitSummaryResolver, CompileReflector, createUrlResolverWithoutPackagePrefix, createOfflineCompileUrlResolver, UrlResolver, getUrlScheme, ResourceLoader, ElementSchemaRegistry, Extractor, I18NHtmlParser, MessageBundle, Serializer, Xliff, Xliff2, Xmb, Xtb, DirectiveNormalizer, ParserError, ParseSpan, AST, Quote, EmptyExpr, ImplicitReceiver, Chain, Conditional, PropertyRead, PropertyWrite, SafePropertyRead, KeyedRead, KeyedWrite, BindingPipe, LiteralPrimitive, LiteralArray, LiteralMap, Interpolation, Binary, PrefixNot, NonNullAssert, MethodCall, SafeMethodCall, FunctionCall, AbsoluteSourceSpan, ASTWithSource, TemplateBinding, NullAstVisitor, RecursiveAstVisitor$1 as RecursiveAstVisitor, AstTransformer$1 as AstTransformer, AstMemoryEfficientTransformer, visitAstChildren, ParsedProperty, ParsedPropertyType, ParsedEvent, ParsedVariable, BoundElementProperty, TokenType$1 as TokenType, Lexer, Token$1 as Token, EOF, isIdentifier, isQuote, SplitInterpolation, TemplateBindingParseResult, Parser$1 as Parser, _ParseAST, ERROR_COMPONENT_TYPE, CompileMetadataResolver, Text$3 as Text, Expansion, ExpansionCase, Attribute, Element$1 as Element, Comment, visitAll$1 as visitAll, RecursiveVisitor$1 as RecursiveVisitor, findNode, HtmlParser, ParseTreeResult, TreeError, HtmlTagDefinition, getHtmlTagDefinition, TagContentType, splitNsName, isNgContainer, isNgContent, isNgTemplate, getNsPrefix, mergeNsAndName, NAMED_ENTITIES, NGSP_UNICODE, debugOutputAstAsTypeScript, TypeScriptEmitter, ParseLocation, ParseSourceFile, ParseSourceSpan, EMPTY_PARSE_LOCATION, EMPTY_SOURCE_SPAN, ParseErrorLevel, ParseError, typeSourceSpan, r3JitTypeSourceSpan, DomElementSchemaRegistry, CssSelector, SelectorMatcher, SelectorListContext, SelectorContext, HOST_ATTR, CONTENT_ATTR, StylesCompileDependency, CompiledStylesheet, StyleCompiler, TemplateParseError, TemplateParseResult, TemplateParser, splitClasses, createElementCssSelector, removeSummaryDuplicates, isEmptyExpression, compileInjectable, R3TargetBinder, R3BoundTarget };
28456//# sourceMappingURL=compiler.js.map