/** * @license Angular v9.0.7 * (c) 2010-2020 Google LLC. https://angular.io/ * License: MIT */ import { __assign, __spread, __extends, __values, __read } from 'tslib'; /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var TagContentType; (function (TagContentType) { TagContentType[TagContentType["RAW_TEXT"] = 0] = "RAW_TEXT"; TagContentType[TagContentType["ESCAPABLE_RAW_TEXT"] = 1] = "ESCAPABLE_RAW_TEXT"; TagContentType[TagContentType["PARSABLE_DATA"] = 2] = "PARSABLE_DATA"; })(TagContentType || (TagContentType = {})); function splitNsName(elementName) { if (elementName[0] != ':') { return [null, elementName]; } var colonIndex = elementName.indexOf(':', 1); if (colonIndex == -1) { throw new Error("Unsupported format \"" + elementName + "\" expecting \":namespace:name\""); } return [elementName.slice(1, colonIndex), elementName.slice(colonIndex + 1)]; } // `` tags work the same regardless the namespace function isNgContainer(tagName) { return splitNsName(tagName)[1] === 'ng-container'; } // `` tags work the same regardless the namespace function isNgContent(tagName) { return splitNsName(tagName)[1] === 'ng-content'; } // `` tags work the same regardless the namespace function isNgTemplate(tagName) { return splitNsName(tagName)[1] === 'ng-template'; } function getNsPrefix(fullName) { return fullName === null ? null : splitNsName(fullName)[0]; } function mergeNsAndName(prefix, localName) { return prefix ? ":" + prefix + ":" + localName : localName; } // see http://www.w3.org/TR/html51/syntax.html#named-character-references // see https://html.spec.whatwg.org/multipage/entities.json // This list is not exhaustive to keep the compiler footprint low. // The `{` / `ƫ` syntax should be used when the named character reference does not // exist. var NAMED_ENTITIES = { 'Aacute': '\u00C1', 'aacute': '\u00E1', 'Acirc': '\u00C2', 'acirc': '\u00E2', 'acute': '\u00B4', 'AElig': '\u00C6', 'aelig': '\u00E6', 'Agrave': '\u00C0', 'agrave': '\u00E0', 'alefsym': '\u2135', 'Alpha': '\u0391', 'alpha': '\u03B1', 'amp': '&', 'and': '\u2227', 'ang': '\u2220', 'apos': '\u0027', 'Aring': '\u00C5', 'aring': '\u00E5', 'asymp': '\u2248', 'Atilde': '\u00C3', 'atilde': '\u00E3', 'Auml': '\u00C4', 'auml': '\u00E4', 'bdquo': '\u201E', 'Beta': '\u0392', 'beta': '\u03B2', 'brvbar': '\u00A6', 'bull': '\u2022', 'cap': '\u2229', 'Ccedil': '\u00C7', 'ccedil': '\u00E7', 'cedil': '\u00B8', 'cent': '\u00A2', 'Chi': '\u03A7', 'chi': '\u03C7', 'circ': '\u02C6', 'clubs': '\u2663', 'cong': '\u2245', 'copy': '\u00A9', 'crarr': '\u21B5', 'cup': '\u222A', 'curren': '\u00A4', 'dagger': '\u2020', 'Dagger': '\u2021', 'darr': '\u2193', 'dArr': '\u21D3', 'deg': '\u00B0', 'Delta': '\u0394', 'delta': '\u03B4', 'diams': '\u2666', 'divide': '\u00F7', 'Eacute': '\u00C9', 'eacute': '\u00E9', 'Ecirc': '\u00CA', 'ecirc': '\u00EA', 'Egrave': '\u00C8', 'egrave': '\u00E8', 'empty': '\u2205', 'emsp': '\u2003', 'ensp': '\u2002', 'Epsilon': '\u0395', 'epsilon': '\u03B5', 'equiv': '\u2261', 'Eta': '\u0397', 'eta': '\u03B7', 'ETH': '\u00D0', 'eth': '\u00F0', 'Euml': '\u00CB', 'euml': '\u00EB', 'euro': '\u20AC', 'exist': '\u2203', 'fnof': '\u0192', 'forall': '\u2200', 'frac12': '\u00BD', 'frac14': '\u00BC', 'frac34': '\u00BE', 'frasl': '\u2044', 'Gamma': '\u0393', 'gamma': '\u03B3', 'ge': '\u2265', 'gt': '>', 'harr': '\u2194', 'hArr': '\u21D4', 'hearts': '\u2665', 'hellip': '\u2026', 'Iacute': '\u00CD', 'iacute': '\u00ED', 'Icirc': '\u00CE', 'icirc': '\u00EE', 'iexcl': '\u00A1', 'Igrave': '\u00CC', 'igrave': '\u00EC', 'image': '\u2111', 'infin': '\u221E', 'int': '\u222B', 'Iota': '\u0399', 'iota': '\u03B9', 'iquest': '\u00BF', 'isin': '\u2208', 'Iuml': '\u00CF', 'iuml': '\u00EF', 'Kappa': '\u039A', 'kappa': '\u03BA', 'Lambda': '\u039B', 'lambda': '\u03BB', 'lang': '\u27E8', 'laquo': '\u00AB', 'larr': '\u2190', 'lArr': '\u21D0', 'lceil': '\u2308', 'ldquo': '\u201C', 'le': '\u2264', 'lfloor': '\u230A', 'lowast': '\u2217', 'loz': '\u25CA', 'lrm': '\u200E', 'lsaquo': '\u2039', 'lsquo': '\u2018', 'lt': '<', 'macr': '\u00AF', 'mdash': '\u2014', 'micro': '\u00B5', 'middot': '\u00B7', 'minus': '\u2212', 'Mu': '\u039C', 'mu': '\u03BC', 'nabla': '\u2207', 'nbsp': '\u00A0', 'ndash': '\u2013', 'ne': '\u2260', 'ni': '\u220B', 'not': '\u00AC', 'notin': '\u2209', 'nsub': '\u2284', 'Ntilde': '\u00D1', 'ntilde': '\u00F1', 'Nu': '\u039D', 'nu': '\u03BD', 'Oacute': '\u00D3', 'oacute': '\u00F3', 'Ocirc': '\u00D4', 'ocirc': '\u00F4', 'OElig': '\u0152', 'oelig': '\u0153', 'Ograve': '\u00D2', 'ograve': '\u00F2', 'oline': '\u203E', 'Omega': '\u03A9', 'omega': '\u03C9', 'Omicron': '\u039F', 'omicron': '\u03BF', 'oplus': '\u2295', 'or': '\u2228', 'ordf': '\u00AA', 'ordm': '\u00BA', 'Oslash': '\u00D8', 'oslash': '\u00F8', 'Otilde': '\u00D5', 'otilde': '\u00F5', 'otimes': '\u2297', 'Ouml': '\u00D6', 'ouml': '\u00F6', 'para': '\u00B6', 'permil': '\u2030', 'perp': '\u22A5', 'Phi': '\u03A6', 'phi': '\u03C6', 'Pi': '\u03A0', 'pi': '\u03C0', 'piv': '\u03D6', 'plusmn': '\u00B1', 'pound': '\u00A3', 'prime': '\u2032', 'Prime': '\u2033', 'prod': '\u220F', 'prop': '\u221D', 'Psi': '\u03A8', 'psi': '\u03C8', 'quot': '\u0022', 'radic': '\u221A', 'rang': '\u27E9', 'raquo': '\u00BB', 'rarr': '\u2192', 'rArr': '\u21D2', 'rceil': '\u2309', 'rdquo': '\u201D', 'real': '\u211C', 'reg': '\u00AE', 'rfloor': '\u230B', 'Rho': '\u03A1', 'rho': '\u03C1', 'rlm': '\u200F', 'rsaquo': '\u203A', 'rsquo': '\u2019', 'sbquo': '\u201A', 'Scaron': '\u0160', 'scaron': '\u0161', 'sdot': '\u22C5', 'sect': '\u00A7', 'shy': '\u00AD', 'Sigma': '\u03A3', 'sigma': '\u03C3', 'sigmaf': '\u03C2', 'sim': '\u223C', 'spades': '\u2660', 'sub': '\u2282', 'sube': '\u2286', 'sum': '\u2211', 'sup': '\u2283', 'sup1': '\u00B9', 'sup2': '\u00B2', 'sup3': '\u00B3', 'supe': '\u2287', 'szlig': '\u00DF', 'Tau': '\u03A4', 'tau': '\u03C4', 'there4': '\u2234', 'Theta': '\u0398', 'theta': '\u03B8', 'thetasym': '\u03D1', 'thinsp': '\u2009', 'THORN': '\u00DE', 'thorn': '\u00FE', 'tilde': '\u02DC', 'times': '\u00D7', 'trade': '\u2122', 'Uacute': '\u00DA', 'uacute': '\u00FA', 'uarr': '\u2191', 'uArr': '\u21D1', 'Ucirc': '\u00DB', 'ucirc': '\u00FB', 'Ugrave': '\u00D9', 'ugrave': '\u00F9', 'uml': '\u00A8', 'upsih': '\u03D2', 'Upsilon': '\u03A5', 'upsilon': '\u03C5', 'Uuml': '\u00DC', 'uuml': '\u00FC', 'weierp': '\u2118', 'Xi': '\u039E', 'xi': '\u03BE', 'Yacute': '\u00DD', 'yacute': '\u00FD', 'yen': '\u00A5', 'yuml': '\u00FF', 'Yuml': '\u0178', 'Zeta': '\u0396', 'zeta': '\u03B6', 'zwj': '\u200D', 'zwnj': '\u200C', }; // The &ngsp; pseudo-entity is denoting a space. see: // https://github.com/dart-lang/angular/blob/0bb611387d29d65b5af7f9d2515ab571fd3fbee4/_tests/test/compiler/preserve_whitespace_test.dart var NGSP_UNICODE = '\uE500'; NAMED_ENTITIES['ngsp'] = NGSP_UNICODE; /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var HtmlTagDefinition = /** @class */ (function () { function HtmlTagDefinition(_a) { var _this = this; 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; this.closedByChildren = {}; this.closedByParent = false; this.canSelfClose = false; if (closedByChildren && closedByChildren.length > 0) { closedByChildren.forEach(function (tagName) { return _this.closedByChildren[tagName] = true; }); } this.isVoid = isVoid; this.closedByParent = closedByParent || isVoid; this.implicitNamespacePrefix = implicitNamespacePrefix || null; this.contentType = contentType; this.ignoreFirstLf = ignoreFirstLf; } HtmlTagDefinition.prototype.isClosedByChild = function (name) { return this.isVoid || name.toLowerCase() in this.closedByChildren; }; return HtmlTagDefinition; }()); var _DEFAULT_TAG_DEFINITION; // see http://www.w3.org/TR/html51/syntax.html#optional-tags // This implementation does not fully conform to the HTML5 spec. var TAG_DEFINITIONS; function getHtmlTagDefinition(tagName) { if (!TAG_DEFINITIONS) { _DEFAULT_TAG_DEFINITION = new HtmlTagDefinition(); TAG_DEFINITIONS = { 'base': new HtmlTagDefinition({ isVoid: true }), 'meta': new HtmlTagDefinition({ isVoid: true }), 'area': new HtmlTagDefinition({ isVoid: true }), 'embed': new HtmlTagDefinition({ isVoid: true }), 'link': new HtmlTagDefinition({ isVoid: true }), 'img': new HtmlTagDefinition({ isVoid: true }), 'input': new HtmlTagDefinition({ isVoid: true }), 'param': new HtmlTagDefinition({ isVoid: true }), 'hr': new HtmlTagDefinition({ isVoid: true }), 'br': new HtmlTagDefinition({ isVoid: true }), 'source': new HtmlTagDefinition({ isVoid: true }), 'track': new HtmlTagDefinition({ isVoid: true }), 'wbr': new HtmlTagDefinition({ isVoid: true }), 'p': new HtmlTagDefinition({ closedByChildren: [ 'address', 'article', 'aside', 'blockquote', 'div', 'dl', 'fieldset', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'main', 'nav', 'ol', 'p', 'pre', 'section', 'table', 'ul' ], closedByParent: true }), 'thead': new HtmlTagDefinition({ closedByChildren: ['tbody', 'tfoot'] }), 'tbody': new HtmlTagDefinition({ closedByChildren: ['tbody', 'tfoot'], closedByParent: true }), 'tfoot': new HtmlTagDefinition({ closedByChildren: ['tbody'], closedByParent: true }), 'tr': new HtmlTagDefinition({ closedByChildren: ['tr'], closedByParent: true }), 'td': new HtmlTagDefinition({ closedByChildren: ['td', 'th'], closedByParent: true }), 'th': new HtmlTagDefinition({ closedByChildren: ['td', 'th'], closedByParent: true }), 'col': new HtmlTagDefinition({ isVoid: true }), 'svg': new HtmlTagDefinition({ implicitNamespacePrefix: 'svg' }), 'math': new HtmlTagDefinition({ implicitNamespacePrefix: 'math' }), 'li': new HtmlTagDefinition({ closedByChildren: ['li'], closedByParent: true }), 'dt': new HtmlTagDefinition({ closedByChildren: ['dt', 'dd'] }), 'dd': new HtmlTagDefinition({ closedByChildren: ['dt', 'dd'], closedByParent: true }), 'rb': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }), 'rt': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }), 'rtc': new HtmlTagDefinition({ closedByChildren: ['rb', 'rtc', 'rp'], closedByParent: true }), 'rp': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }), 'optgroup': new HtmlTagDefinition({ closedByChildren: ['optgroup'], closedByParent: true }), 'option': new HtmlTagDefinition({ closedByChildren: ['option', 'optgroup'], closedByParent: true }), 'pre': new HtmlTagDefinition({ ignoreFirstLf: true }), 'listing': new HtmlTagDefinition({ ignoreFirstLf: true }), 'style': new HtmlTagDefinition({ contentType: TagContentType.RAW_TEXT }), 'script': new HtmlTagDefinition({ contentType: TagContentType.RAW_TEXT }), 'title': new HtmlTagDefinition({ contentType: TagContentType.ESCAPABLE_RAW_TEXT }), 'textarea': new HtmlTagDefinition({ contentType: TagContentType.ESCAPABLE_RAW_TEXT, ignoreFirstLf: true }), }; } return TAG_DEFINITIONS[tagName.toLowerCase()] || _DEFAULT_TAG_DEFINITION; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var _SELECTOR_REGEXP = new RegExp('(\\:not\\()|' + // 1: ":not(" '(([\\.\\#]?)[-\\w]+)|' + // 2: "tag"; 3: "."/"#"; // "-" should appear first in the regexp below as FF31 parses "[.-\w]" as a range // 4: attribute; 5: attribute_string; 6: attribute_value '(?:\\[([-.\\w*]+)(?:=([\"\']?)([^\\]\"\']*)\\5)?\\])|' + // "[name]", "[name=value]", // "[name="value"]", // "[name='value']" '(\\))|' + // 7: ")" '(\\s*,\\s*)', // 8: "," 'g'); /** * A css selector contains an element name, * css classes and attribute/value pairs with the purpose * of selecting subsets out of them. */ var CssSelector = /** @class */ (function () { function CssSelector() { this.element = null; this.classNames = []; /** * The selectors are encoded in pairs where: * - even locations are attribute names * - odd locations are attribute values. * * Example: * Selector: `[key1=value1][key2]` would parse to: * ``` * ['key1', 'value1', 'key2', ''] * ``` */ this.attrs = []; this.notSelectors = []; } CssSelector.parse = function (selector) { var results = []; var _addResult = function (res, cssSel) { if (cssSel.notSelectors.length > 0 && !cssSel.element && cssSel.classNames.length == 0 && cssSel.attrs.length == 0) { cssSel.element = '*'; } res.push(cssSel); }; var cssSelector = new CssSelector(); var match; var current = cssSelector; var inNot = false; _SELECTOR_REGEXP.lastIndex = 0; while (match = _SELECTOR_REGEXP.exec(selector)) { if (match[1 /* NOT */]) { if (inNot) { throw new Error('Nesting :not in a selector is not allowed'); } inNot = true; current = new CssSelector(); cssSelector.notSelectors.push(current); } var tag = match[2 /* TAG */]; if (tag) { var prefix = match[3 /* PREFIX */]; if (prefix === '#') { // #hash current.addAttribute('id', tag.substr(1)); } else if (prefix === '.') { // Class current.addClassName(tag.substr(1)); } else { // Element current.setElement(tag); } } var attribute = match[4 /* ATTRIBUTE */]; if (attribute) { current.addAttribute(attribute, match[6 /* ATTRIBUTE_VALUE */]); } if (match[7 /* NOT_END */]) { inNot = false; current = cssSelector; } if (match[8 /* SEPARATOR */]) { if (inNot) { throw new Error('Multiple selectors in :not are not supported'); } _addResult(results, cssSelector); cssSelector = current = new CssSelector(); } } _addResult(results, cssSelector); return results; }; CssSelector.prototype.isElementSelector = function () { return this.hasElementSelector() && this.classNames.length == 0 && this.attrs.length == 0 && this.notSelectors.length === 0; }; CssSelector.prototype.hasElementSelector = function () { return !!this.element; }; CssSelector.prototype.setElement = function (element) { if (element === void 0) { element = null; } this.element = element; }; /** Gets a template string for an element that matches the selector. */ CssSelector.prototype.getMatchingElementTemplate = function () { var tagName = this.element || 'div'; var classAttr = this.classNames.length > 0 ? " class=\"" + this.classNames.join(' ') + "\"" : ''; var attrs = ''; for (var i = 0; i < this.attrs.length; i += 2) { var attrName = this.attrs[i]; var attrValue = this.attrs[i + 1] !== '' ? "=\"" + this.attrs[i + 1] + "\"" : ''; attrs += " " + attrName + attrValue; } return getHtmlTagDefinition(tagName).isVoid ? "<" + tagName + classAttr + attrs + "/>" : "<" + tagName + classAttr + attrs + ">"; }; CssSelector.prototype.getAttrs = function () { var result = []; if (this.classNames.length > 0) { result.push('class', this.classNames.join(' ')); } return result.concat(this.attrs); }; CssSelector.prototype.addAttribute = function (name, value) { if (value === void 0) { value = ''; } this.attrs.push(name, value && value.toLowerCase() || ''); }; CssSelector.prototype.addClassName = function (name) { this.classNames.push(name.toLowerCase()); }; CssSelector.prototype.toString = function () { var res = this.element || ''; if (this.classNames) { this.classNames.forEach(function (klass) { return res += "." + klass; }); } if (this.attrs) { for (var i = 0; i < this.attrs.length; i += 2) { var name_1 = this.attrs[i]; var value = this.attrs[i + 1]; res += "[" + name_1 + (value ? '=' + value : '') + "]"; } } this.notSelectors.forEach(function (notSelector) { return res += ":not(" + notSelector + ")"; }); return res; }; return CssSelector; }()); /** * Reads a list of CssSelectors and allows to calculate which ones * are contained in a given CssSelector. */ var SelectorMatcher = /** @class */ (function () { function SelectorMatcher() { this._elementMap = new Map(); this._elementPartialMap = new Map(); this._classMap = new Map(); this._classPartialMap = new Map(); this._attrValueMap = new Map(); this._attrValuePartialMap = new Map(); this._listContexts = []; } SelectorMatcher.createNotMatcher = function (notSelectors) { var notMatcher = new SelectorMatcher(); notMatcher.addSelectables(notSelectors, null); return notMatcher; }; SelectorMatcher.prototype.addSelectables = function (cssSelectors, callbackCtxt) { var listContext = null; if (cssSelectors.length > 1) { listContext = new SelectorListContext(cssSelectors); this._listContexts.push(listContext); } for (var i = 0; i < cssSelectors.length; i++) { this._addSelectable(cssSelectors[i], callbackCtxt, listContext); } }; /** * Add an object that can be found later on by calling `match`. * @param cssSelector A css selector * @param callbackCtxt An opaque object that will be given to the callback of the `match` function */ SelectorMatcher.prototype._addSelectable = function (cssSelector, callbackCtxt, listContext) { var matcher = this; var element = cssSelector.element; var classNames = cssSelector.classNames; var attrs = cssSelector.attrs; var selectable = new SelectorContext(cssSelector, callbackCtxt, listContext); if (element) { var isTerminal = attrs.length === 0 && classNames.length === 0; if (isTerminal) { this._addTerminal(matcher._elementMap, element, selectable); } else { matcher = this._addPartial(matcher._elementPartialMap, element); } } if (classNames) { for (var i = 0; i < classNames.length; i++) { var isTerminal = attrs.length === 0 && i === classNames.length - 1; var className = classNames[i]; if (isTerminal) { this._addTerminal(matcher._classMap, className, selectable); } else { matcher = this._addPartial(matcher._classPartialMap, className); } } } if (attrs) { for (var i = 0; i < attrs.length; i += 2) { var isTerminal = i === attrs.length - 2; var name_2 = attrs[i]; var value = attrs[i + 1]; if (isTerminal) { var terminalMap = matcher._attrValueMap; var terminalValuesMap = terminalMap.get(name_2); if (!terminalValuesMap) { terminalValuesMap = new Map(); terminalMap.set(name_2, terminalValuesMap); } this._addTerminal(terminalValuesMap, value, selectable); } else { var partialMap = matcher._attrValuePartialMap; var partialValuesMap = partialMap.get(name_2); if (!partialValuesMap) { partialValuesMap = new Map(); partialMap.set(name_2, partialValuesMap); } matcher = this._addPartial(partialValuesMap, value); } } } }; SelectorMatcher.prototype._addTerminal = function (map, name, selectable) { var terminalList = map.get(name); if (!terminalList) { terminalList = []; map.set(name, terminalList); } terminalList.push(selectable); }; SelectorMatcher.prototype._addPartial = function (map, name) { var matcher = map.get(name); if (!matcher) { matcher = new SelectorMatcher(); map.set(name, matcher); } return matcher; }; /** * Find the objects that have been added via `addSelectable` * whose css selector is contained in the given css selector. * @param cssSelector A css selector * @param matchedCallback This callback will be called with the object handed into `addSelectable` * @return boolean true if a match was found */ SelectorMatcher.prototype.match = function (cssSelector, matchedCallback) { var result = false; var element = cssSelector.element; var classNames = cssSelector.classNames; var attrs = cssSelector.attrs; for (var i = 0; i < this._listContexts.length; i++) { this._listContexts[i].alreadyMatched = false; } result = this._matchTerminal(this._elementMap, element, cssSelector, matchedCallback) || result; result = this._matchPartial(this._elementPartialMap, element, cssSelector, matchedCallback) || result; if (classNames) { for (var i = 0; i < classNames.length; i++) { var className = classNames[i]; result = this._matchTerminal(this._classMap, className, cssSelector, matchedCallback) || result; result = this._matchPartial(this._classPartialMap, className, cssSelector, matchedCallback) || result; } } if (attrs) { for (var i = 0; i < attrs.length; i += 2) { var name_3 = attrs[i]; var value = attrs[i + 1]; var terminalValuesMap = this._attrValueMap.get(name_3); if (value) { result = this._matchTerminal(terminalValuesMap, '', cssSelector, matchedCallback) || result; } result = this._matchTerminal(terminalValuesMap, value, cssSelector, matchedCallback) || result; var partialValuesMap = this._attrValuePartialMap.get(name_3); if (value) { result = this._matchPartial(partialValuesMap, '', cssSelector, matchedCallback) || result; } result = this._matchPartial(partialValuesMap, value, cssSelector, matchedCallback) || result; } } return result; }; /** @internal */ SelectorMatcher.prototype._matchTerminal = function (map, name, cssSelector, matchedCallback) { if (!map || typeof name !== 'string') { return false; } var selectables = map.get(name) || []; var starSelectables = map.get('*'); if (starSelectables) { selectables = selectables.concat(starSelectables); } if (selectables.length === 0) { return false; } var selectable; var result = false; for (var i = 0; i < selectables.length; i++) { selectable = selectables[i]; result = selectable.finalize(cssSelector, matchedCallback) || result; } return result; }; /** @internal */ SelectorMatcher.prototype._matchPartial = function (map, name, cssSelector, matchedCallback) { if (!map || typeof name !== 'string') { return false; } var nestedSelector = map.get(name); if (!nestedSelector) { return false; } // TODO(perf): get rid of recursion and measure again // TODO(perf): don't pass the whole selector into the recursion, // but only the not processed parts return nestedSelector.match(cssSelector, matchedCallback); }; return SelectorMatcher; }()); var SelectorListContext = /** @class */ (function () { function SelectorListContext(selectors) { this.selectors = selectors; this.alreadyMatched = false; } return SelectorListContext; }()); // Store context to pass back selector and context when a selector is matched var SelectorContext = /** @class */ (function () { function SelectorContext(selector, cbContext, listContext) { this.selector = selector; this.cbContext = cbContext; this.listContext = listContext; this.notSelectors = selector.notSelectors; } SelectorContext.prototype.finalize = function (cssSelector, callback) { var result = true; if (this.notSelectors.length > 0 && (!this.listContext || !this.listContext.alreadyMatched)) { var notMatcher = SelectorMatcher.createNotMatcher(this.notSelectors); result = !notMatcher.match(cssSelector, null); } if (result && callback && (!this.listContext || !this.listContext.alreadyMatched)) { if (this.listContext) { this.listContext.alreadyMatched = true; } callback(this.selector, this.cbContext); } return result; }; return SelectorContext; }()); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var createInject = makeMetadataFactory('Inject', function (token) { return ({ token: token }); }); var createInjectionToken = makeMetadataFactory('InjectionToken', function (desc) { return ({ _desc: desc, ɵprov: undefined }); }); var createAttribute = makeMetadataFactory('Attribute', function (attributeName) { return ({ attributeName: attributeName }); }); var createContentChildren = makeMetadataFactory('ContentChildren', function (selector, data) { if (data === void 0) { data = {}; } return (__assign({ selector: selector, first: false, isViewQuery: false, descendants: false }, data)); }); var createContentChild = makeMetadataFactory('ContentChild', function (selector, data) { if (data === void 0) { data = {}; } return (__assign({ selector: selector, first: true, isViewQuery: false, descendants: true }, data)); }); var createViewChildren = makeMetadataFactory('ViewChildren', function (selector, data) { if (data === void 0) { data = {}; } return (__assign({ selector: selector, first: false, isViewQuery: true, descendants: true }, data)); }); var createViewChild = makeMetadataFactory('ViewChild', function (selector, data) { return (__assign({ selector: selector, first: true, isViewQuery: true, descendants: true }, data)); }); var createDirective = makeMetadataFactory('Directive', function (dir) { if (dir === void 0) { dir = {}; } return dir; }); var ViewEncapsulation; (function (ViewEncapsulation) { ViewEncapsulation[ViewEncapsulation["Emulated"] = 0] = "Emulated"; ViewEncapsulation[ViewEncapsulation["Native"] = 1] = "Native"; ViewEncapsulation[ViewEncapsulation["None"] = 2] = "None"; ViewEncapsulation[ViewEncapsulation["ShadowDom"] = 3] = "ShadowDom"; })(ViewEncapsulation || (ViewEncapsulation = {})); var ChangeDetectionStrategy; (function (ChangeDetectionStrategy) { ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush"; ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default"; })(ChangeDetectionStrategy || (ChangeDetectionStrategy = {})); var createComponent = makeMetadataFactory('Component', function (c) { if (c === void 0) { c = {}; } return (__assign({ changeDetection: ChangeDetectionStrategy.Default }, c)); }); var createPipe = makeMetadataFactory('Pipe', function (p) { return (__assign({ pure: true }, p)); }); var createInput = makeMetadataFactory('Input', function (bindingPropertyName) { return ({ bindingPropertyName: bindingPropertyName }); }); var createOutput = makeMetadataFactory('Output', function (bindingPropertyName) { return ({ bindingPropertyName: bindingPropertyName }); }); var createHostBinding = makeMetadataFactory('HostBinding', function (hostPropertyName) { return ({ hostPropertyName: hostPropertyName }); }); var createHostListener = makeMetadataFactory('HostListener', function (eventName, args) { return ({ eventName: eventName, args: args }); }); var createNgModule = makeMetadataFactory('NgModule', function (ngModule) { return ngModule; }); var createInjectable = makeMetadataFactory('Injectable', function (injectable) { if (injectable === void 0) { injectable = {}; } return injectable; }); var CUSTOM_ELEMENTS_SCHEMA = { name: 'custom-elements' }; var NO_ERRORS_SCHEMA = { name: 'no-errors-schema' }; var createOptional = makeMetadataFactory('Optional'); var createSelf = makeMetadataFactory('Self'); var createSkipSelf = makeMetadataFactory('SkipSelf'); var createHost = makeMetadataFactory('Host'); var Type = Function; var SecurityContext; (function (SecurityContext) { SecurityContext[SecurityContext["NONE"] = 0] = "NONE"; SecurityContext[SecurityContext["HTML"] = 1] = "HTML"; SecurityContext[SecurityContext["STYLE"] = 2] = "STYLE"; SecurityContext[SecurityContext["SCRIPT"] = 3] = "SCRIPT"; SecurityContext[SecurityContext["URL"] = 4] = "URL"; SecurityContext[SecurityContext["RESOURCE_URL"] = 5] = "RESOURCE_URL"; })(SecurityContext || (SecurityContext = {})); var MissingTranslationStrategy; (function (MissingTranslationStrategy) { MissingTranslationStrategy[MissingTranslationStrategy["Error"] = 0] = "Error"; MissingTranslationStrategy[MissingTranslationStrategy["Warning"] = 1] = "Warning"; MissingTranslationStrategy[MissingTranslationStrategy["Ignore"] = 2] = "Ignore"; })(MissingTranslationStrategy || (MissingTranslationStrategy = {})); function makeMetadataFactory(name, props) { // This must be declared as a function, not a fat arrow, so that ES2015 devmode produces code // that works with the static_reflector.ts in the ViewEngine compiler. // In particular, `_registerDecoratorOrConstructor` assumes that the value returned here can be // new'ed. function factory() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var values = props ? props.apply(void 0, __spread(args)) : {}; return __assign({ ngMetadataName: name }, values); } factory.isTypeOf = function (obj) { return obj && obj.ngMetadataName === name; }; factory.ngMetadataName = name; return factory; } function parserSelectorToSimpleSelector(selector) { var classes = selector.classNames && selector.classNames.length ? __spread([8 /* CLASS */], selector.classNames) : []; var elementName = selector.element && selector.element !== '*' ? selector.element : ''; return __spread([elementName], selector.attrs, classes); } function parserSelectorToNegativeSelector(selector) { var classes = selector.classNames && selector.classNames.length ? __spread([8 /* CLASS */], selector.classNames) : []; if (selector.element) { return __spread([ 1 /* NOT */ | 4 /* ELEMENT */, selector.element ], selector.attrs, classes); } else if (selector.attrs.length) { return __spread([1 /* NOT */ | 2 /* ATTRIBUTE */], selector.attrs, classes); } else { return selector.classNames && selector.classNames.length ? __spread([1 /* NOT */ | 8 /* CLASS */], selector.classNames) : []; } } function parserSelectorToR3Selector(selector) { var positive = parserSelectorToSimpleSelector(selector); var negative = selector.notSelectors && selector.notSelectors.length ? selector.notSelectors.map(function (notSelector) { return parserSelectorToNegativeSelector(notSelector); }) : []; return positive.concat.apply(positive, __spread(negative)); } function parseSelectorToR3Selector(selector) { return selector ? CssSelector.parse(selector).map(parserSelectorToR3Selector) : []; } var core = /*#__PURE__*/Object.freeze({ __proto__: null, createInject: createInject, createInjectionToken: createInjectionToken, createAttribute: createAttribute, createContentChildren: createContentChildren, createContentChild: createContentChild, createViewChildren: createViewChildren, createViewChild: createViewChild, createDirective: createDirective, get ViewEncapsulation () { return ViewEncapsulation; }, get ChangeDetectionStrategy () { return ChangeDetectionStrategy; }, createComponent: createComponent, createPipe: createPipe, createInput: createInput, createOutput: createOutput, createHostBinding: createHostBinding, createHostListener: createHostListener, createNgModule: createNgModule, createInjectable: createInjectable, CUSTOM_ELEMENTS_SCHEMA: CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA: NO_ERRORS_SCHEMA, createOptional: createOptional, createSelf: createSelf, createSkipSelf: createSkipSelf, createHost: createHost, Type: Type, get SecurityContext () { return SecurityContext; }, get MissingTranslationStrategy () { return MissingTranslationStrategy; }, parseSelectorToR3Selector: parseSelectorToR3Selector }); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ //// Types var TypeModifier; (function (TypeModifier) { TypeModifier[TypeModifier["Const"] = 0] = "Const"; })(TypeModifier || (TypeModifier = {})); var Type$1 = /** @class */ (function () { function Type(modifiers) { if (modifiers === void 0) { modifiers = null; } this.modifiers = modifiers; if (!modifiers) { this.modifiers = []; } } Type.prototype.hasModifier = function (modifier) { return this.modifiers.indexOf(modifier) !== -1; }; return Type; }()); var BuiltinTypeName; (function (BuiltinTypeName) { BuiltinTypeName[BuiltinTypeName["Dynamic"] = 0] = "Dynamic"; BuiltinTypeName[BuiltinTypeName["Bool"] = 1] = "Bool"; BuiltinTypeName[BuiltinTypeName["String"] = 2] = "String"; BuiltinTypeName[BuiltinTypeName["Int"] = 3] = "Int"; BuiltinTypeName[BuiltinTypeName["Number"] = 4] = "Number"; BuiltinTypeName[BuiltinTypeName["Function"] = 5] = "Function"; BuiltinTypeName[BuiltinTypeName["Inferred"] = 6] = "Inferred"; BuiltinTypeName[BuiltinTypeName["None"] = 7] = "None"; })(BuiltinTypeName || (BuiltinTypeName = {})); var BuiltinType = /** @class */ (function (_super) { __extends(BuiltinType, _super); function BuiltinType(name, modifiers) { if (modifiers === void 0) { modifiers = null; } var _this = _super.call(this, modifiers) || this; _this.name = name; return _this; } BuiltinType.prototype.visitType = function (visitor, context) { return visitor.visitBuiltinType(this, context); }; return BuiltinType; }(Type$1)); var ExpressionType = /** @class */ (function (_super) { __extends(ExpressionType, _super); function ExpressionType(value, modifiers, typeParams) { if (modifiers === void 0) { modifiers = null; } if (typeParams === void 0) { typeParams = null; } var _this = _super.call(this, modifiers) || this; _this.value = value; _this.typeParams = typeParams; return _this; } ExpressionType.prototype.visitType = function (visitor, context) { return visitor.visitExpressionType(this, context); }; return ExpressionType; }(Type$1)); var ArrayType = /** @class */ (function (_super) { __extends(ArrayType, _super); function ArrayType(of, modifiers) { if (modifiers === void 0) { modifiers = null; } var _this = _super.call(this, modifiers) || this; _this.of = of; return _this; } ArrayType.prototype.visitType = function (visitor, context) { return visitor.visitArrayType(this, context); }; return ArrayType; }(Type$1)); var MapType = /** @class */ (function (_super) { __extends(MapType, _super); function MapType(valueType, modifiers) { if (modifiers === void 0) { modifiers = null; } var _this = _super.call(this, modifiers) || this; _this.valueType = valueType || null; return _this; } MapType.prototype.visitType = function (visitor, context) { return visitor.visitMapType(this, context); }; return MapType; }(Type$1)); var DYNAMIC_TYPE = new BuiltinType(BuiltinTypeName.Dynamic); var INFERRED_TYPE = new BuiltinType(BuiltinTypeName.Inferred); var BOOL_TYPE = new BuiltinType(BuiltinTypeName.Bool); var INT_TYPE = new BuiltinType(BuiltinTypeName.Int); var NUMBER_TYPE = new BuiltinType(BuiltinTypeName.Number); var STRING_TYPE = new BuiltinType(BuiltinTypeName.String); var FUNCTION_TYPE = new BuiltinType(BuiltinTypeName.Function); var NONE_TYPE = new BuiltinType(BuiltinTypeName.None); ///// Expressions var BinaryOperator; (function (BinaryOperator) { BinaryOperator[BinaryOperator["Equals"] = 0] = "Equals"; BinaryOperator[BinaryOperator["NotEquals"] = 1] = "NotEquals"; BinaryOperator[BinaryOperator["Identical"] = 2] = "Identical"; BinaryOperator[BinaryOperator["NotIdentical"] = 3] = "NotIdentical"; BinaryOperator[BinaryOperator["Minus"] = 4] = "Minus"; BinaryOperator[BinaryOperator["Plus"] = 5] = "Plus"; BinaryOperator[BinaryOperator["Divide"] = 6] = "Divide"; BinaryOperator[BinaryOperator["Multiply"] = 7] = "Multiply"; BinaryOperator[BinaryOperator["Modulo"] = 8] = "Modulo"; BinaryOperator[BinaryOperator["And"] = 9] = "And"; BinaryOperator[BinaryOperator["Or"] = 10] = "Or"; BinaryOperator[BinaryOperator["BitwiseAnd"] = 11] = "BitwiseAnd"; BinaryOperator[BinaryOperator["Lower"] = 12] = "Lower"; BinaryOperator[BinaryOperator["LowerEquals"] = 13] = "LowerEquals"; BinaryOperator[BinaryOperator["Bigger"] = 14] = "Bigger"; BinaryOperator[BinaryOperator["BiggerEquals"] = 15] = "BiggerEquals"; })(BinaryOperator || (BinaryOperator = {})); function nullSafeIsEquivalent(base, other) { if (base == null || other == null) { return base == other; } return base.isEquivalent(other); } function areAllEquivalent(base, other) { var len = base.length; if (len !== other.length) { return false; } for (var i = 0; i < len; i++) { if (!base[i].isEquivalent(other[i])) { return false; } } return true; } var Expression = /** @class */ (function () { function Expression(type, sourceSpan) { this.type = type || null; this.sourceSpan = sourceSpan || null; } Expression.prototype.prop = function (name, sourceSpan) { return new ReadPropExpr(this, name, null, sourceSpan); }; Expression.prototype.key = function (index, type, sourceSpan) { return new ReadKeyExpr(this, index, type, sourceSpan); }; Expression.prototype.callMethod = function (name, params, sourceSpan) { return new InvokeMethodExpr(this, name, params, null, sourceSpan); }; Expression.prototype.callFn = function (params, sourceSpan) { return new InvokeFunctionExpr(this, params, null, sourceSpan); }; Expression.prototype.instantiate = function (params, type, sourceSpan) { return new InstantiateExpr(this, params, type, sourceSpan); }; Expression.prototype.conditional = function (trueCase, falseCase, sourceSpan) { if (falseCase === void 0) { falseCase = null; } return new ConditionalExpr(this, trueCase, falseCase, null, sourceSpan); }; Expression.prototype.equals = function (rhs, sourceSpan) { return new BinaryOperatorExpr(BinaryOperator.Equals, this, rhs, null, sourceSpan); }; Expression.prototype.notEquals = function (rhs, sourceSpan) { return new BinaryOperatorExpr(BinaryOperator.NotEquals, this, rhs, null, sourceSpan); }; Expression.prototype.identical = function (rhs, sourceSpan) { return new BinaryOperatorExpr(BinaryOperator.Identical, this, rhs, null, sourceSpan); }; Expression.prototype.notIdentical = function (rhs, sourceSpan) { return new BinaryOperatorExpr(BinaryOperator.NotIdentical, this, rhs, null, sourceSpan); }; Expression.prototype.minus = function (rhs, sourceSpan) { return new BinaryOperatorExpr(BinaryOperator.Minus, this, rhs, null, sourceSpan); }; Expression.prototype.plus = function (rhs, sourceSpan) { return new BinaryOperatorExpr(BinaryOperator.Plus, this, rhs, null, sourceSpan); }; Expression.prototype.divide = function (rhs, sourceSpan) { return new BinaryOperatorExpr(BinaryOperator.Divide, this, rhs, null, sourceSpan); }; Expression.prototype.multiply = function (rhs, sourceSpan) { return new BinaryOperatorExpr(BinaryOperator.Multiply, this, rhs, null, sourceSpan); }; Expression.prototype.modulo = function (rhs, sourceSpan) { return new BinaryOperatorExpr(BinaryOperator.Modulo, this, rhs, null, sourceSpan); }; Expression.prototype.and = function (rhs, sourceSpan) { return new BinaryOperatorExpr(BinaryOperator.And, this, rhs, null, sourceSpan); }; Expression.prototype.bitwiseAnd = function (rhs, sourceSpan, parens) { if (parens === void 0) { parens = true; } return new BinaryOperatorExpr(BinaryOperator.BitwiseAnd, this, rhs, null, sourceSpan, parens); }; Expression.prototype.or = function (rhs, sourceSpan) { return new BinaryOperatorExpr(BinaryOperator.Or, this, rhs, null, sourceSpan); }; Expression.prototype.lower = function (rhs, sourceSpan) { return new BinaryOperatorExpr(BinaryOperator.Lower, this, rhs, null, sourceSpan); }; Expression.prototype.lowerEquals = function (rhs, sourceSpan) { return new BinaryOperatorExpr(BinaryOperator.LowerEquals, this, rhs, null, sourceSpan); }; Expression.prototype.bigger = function (rhs, sourceSpan) { return new BinaryOperatorExpr(BinaryOperator.Bigger, this, rhs, null, sourceSpan); }; Expression.prototype.biggerEquals = function (rhs, sourceSpan) { return new BinaryOperatorExpr(BinaryOperator.BiggerEquals, this, rhs, null, sourceSpan); }; Expression.prototype.isBlank = function (sourceSpan) { // Note: We use equals by purpose here to compare to null and undefined in JS. // We use the typed null to allow strictNullChecks to narrow types. return this.equals(TYPED_NULL_EXPR, sourceSpan); }; Expression.prototype.cast = function (type, sourceSpan) { return new CastExpr(this, type, sourceSpan); }; Expression.prototype.toStmt = function () { return new ExpressionStatement(this, null); }; return Expression; }()); var BuiltinVar; (function (BuiltinVar) { BuiltinVar[BuiltinVar["This"] = 0] = "This"; BuiltinVar[BuiltinVar["Super"] = 1] = "Super"; BuiltinVar[BuiltinVar["CatchError"] = 2] = "CatchError"; BuiltinVar[BuiltinVar["CatchStack"] = 3] = "CatchStack"; })(BuiltinVar || (BuiltinVar = {})); var ReadVarExpr = /** @class */ (function (_super) { __extends(ReadVarExpr, _super); function ReadVarExpr(name, type, sourceSpan) { var _this = _super.call(this, type, sourceSpan) || this; if (typeof name === 'string') { _this.name = name; _this.builtin = null; } else { _this.name = null; _this.builtin = name; } return _this; } ReadVarExpr.prototype.isEquivalent = function (e) { return e instanceof ReadVarExpr && this.name === e.name && this.builtin === e.builtin; }; ReadVarExpr.prototype.isConstant = function () { return false; }; ReadVarExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitReadVarExpr(this, context); }; ReadVarExpr.prototype.set = function (value) { if (!this.name) { throw new Error("Built in variable " + this.builtin + " can not be assigned to."); } return new WriteVarExpr(this.name, value, null, this.sourceSpan); }; return ReadVarExpr; }(Expression)); var TypeofExpr = /** @class */ (function (_super) { __extends(TypeofExpr, _super); function TypeofExpr(expr, type, sourceSpan) { var _this = _super.call(this, type, sourceSpan) || this; _this.expr = expr; return _this; } TypeofExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitTypeofExpr(this, context); }; TypeofExpr.prototype.isEquivalent = function (e) { return e instanceof TypeofExpr && e.expr.isEquivalent(this.expr); }; TypeofExpr.prototype.isConstant = function () { return this.expr.isConstant(); }; return TypeofExpr; }(Expression)); var WrappedNodeExpr = /** @class */ (function (_super) { __extends(WrappedNodeExpr, _super); function WrappedNodeExpr(node, type, sourceSpan) { var _this = _super.call(this, type, sourceSpan) || this; _this.node = node; return _this; } WrappedNodeExpr.prototype.isEquivalent = function (e) { return e instanceof WrappedNodeExpr && this.node === e.node; }; WrappedNodeExpr.prototype.isConstant = function () { return false; }; WrappedNodeExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitWrappedNodeExpr(this, context); }; return WrappedNodeExpr; }(Expression)); var WriteVarExpr = /** @class */ (function (_super) { __extends(WriteVarExpr, _super); function WriteVarExpr(name, value, type, sourceSpan) { var _this = _super.call(this, type || value.type, sourceSpan) || this; _this.name = name; _this.value = value; return _this; } WriteVarExpr.prototype.isEquivalent = function (e) { return e instanceof WriteVarExpr && this.name === e.name && this.value.isEquivalent(e.value); }; WriteVarExpr.prototype.isConstant = function () { return false; }; WriteVarExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitWriteVarExpr(this, context); }; WriteVarExpr.prototype.toDeclStmt = function (type, modifiers) { return new DeclareVarStmt(this.name, this.value, type, modifiers, this.sourceSpan); }; WriteVarExpr.prototype.toConstDecl = function () { return this.toDeclStmt(INFERRED_TYPE, [StmtModifier.Final]); }; return WriteVarExpr; }(Expression)); var WriteKeyExpr = /** @class */ (function (_super) { __extends(WriteKeyExpr, _super); function WriteKeyExpr(receiver, index, value, type, sourceSpan) { var _this = _super.call(this, type || value.type, sourceSpan) || this; _this.receiver = receiver; _this.index = index; _this.value = value; return _this; } WriteKeyExpr.prototype.isEquivalent = function (e) { return e instanceof WriteKeyExpr && this.receiver.isEquivalent(e.receiver) && this.index.isEquivalent(e.index) && this.value.isEquivalent(e.value); }; WriteKeyExpr.prototype.isConstant = function () { return false; }; WriteKeyExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitWriteKeyExpr(this, context); }; return WriteKeyExpr; }(Expression)); var WritePropExpr = /** @class */ (function (_super) { __extends(WritePropExpr, _super); function WritePropExpr(receiver, name, value, type, sourceSpan) { var _this = _super.call(this, type || value.type, sourceSpan) || this; _this.receiver = receiver; _this.name = name; _this.value = value; return _this; } WritePropExpr.prototype.isEquivalent = function (e) { return e instanceof WritePropExpr && this.receiver.isEquivalent(e.receiver) && this.name === e.name && this.value.isEquivalent(e.value); }; WritePropExpr.prototype.isConstant = function () { return false; }; WritePropExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitWritePropExpr(this, context); }; return WritePropExpr; }(Expression)); var BuiltinMethod; (function (BuiltinMethod) { BuiltinMethod[BuiltinMethod["ConcatArray"] = 0] = "ConcatArray"; BuiltinMethod[BuiltinMethod["SubscribeObservable"] = 1] = "SubscribeObservable"; BuiltinMethod[BuiltinMethod["Bind"] = 2] = "Bind"; })(BuiltinMethod || (BuiltinMethod = {})); var InvokeMethodExpr = /** @class */ (function (_super) { __extends(InvokeMethodExpr, _super); function InvokeMethodExpr(receiver, method, args, type, sourceSpan) { var _this = _super.call(this, type, sourceSpan) || this; _this.receiver = receiver; _this.args = args; if (typeof method === 'string') { _this.name = method; _this.builtin = null; } else { _this.name = null; _this.builtin = method; } return _this; } InvokeMethodExpr.prototype.isEquivalent = function (e) { return e instanceof InvokeMethodExpr && this.receiver.isEquivalent(e.receiver) && this.name === e.name && this.builtin === e.builtin && areAllEquivalent(this.args, e.args); }; InvokeMethodExpr.prototype.isConstant = function () { return false; }; InvokeMethodExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitInvokeMethodExpr(this, context); }; return InvokeMethodExpr; }(Expression)); var InvokeFunctionExpr = /** @class */ (function (_super) { __extends(InvokeFunctionExpr, _super); function InvokeFunctionExpr(fn, args, type, sourceSpan, pure) { if (pure === void 0) { pure = false; } var _this = _super.call(this, type, sourceSpan) || this; _this.fn = fn; _this.args = args; _this.pure = pure; return _this; } InvokeFunctionExpr.prototype.isEquivalent = function (e) { return e instanceof InvokeFunctionExpr && this.fn.isEquivalent(e.fn) && areAllEquivalent(this.args, e.args) && this.pure === e.pure; }; InvokeFunctionExpr.prototype.isConstant = function () { return false; }; InvokeFunctionExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitInvokeFunctionExpr(this, context); }; return InvokeFunctionExpr; }(Expression)); var InstantiateExpr = /** @class */ (function (_super) { __extends(InstantiateExpr, _super); function InstantiateExpr(classExpr, args, type, sourceSpan) { var _this = _super.call(this, type, sourceSpan) || this; _this.classExpr = classExpr; _this.args = args; return _this; } InstantiateExpr.prototype.isEquivalent = function (e) { return e instanceof InstantiateExpr && this.classExpr.isEquivalent(e.classExpr) && areAllEquivalent(this.args, e.args); }; InstantiateExpr.prototype.isConstant = function () { return false; }; InstantiateExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitInstantiateExpr(this, context); }; return InstantiateExpr; }(Expression)); var LiteralExpr = /** @class */ (function (_super) { __extends(LiteralExpr, _super); function LiteralExpr(value, type, sourceSpan) { var _this = _super.call(this, type, sourceSpan) || this; _this.value = value; return _this; } LiteralExpr.prototype.isEquivalent = function (e) { return e instanceof LiteralExpr && this.value === e.value; }; LiteralExpr.prototype.isConstant = function () { return true; }; LiteralExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitLiteralExpr(this, context); }; return LiteralExpr; }(Expression)); var LocalizedString = /** @class */ (function (_super) { __extends(LocalizedString, _super); function LocalizedString(metaBlock, messageParts, placeHolderNames, expressions, sourceSpan) { var _this = _super.call(this, STRING_TYPE, sourceSpan) || this; _this.metaBlock = metaBlock; _this.messageParts = messageParts; _this.placeHolderNames = placeHolderNames; _this.expressions = expressions; return _this; } LocalizedString.prototype.isEquivalent = function (e) { // return e instanceof LocalizedString && this.message === e.message; return false; }; LocalizedString.prototype.isConstant = function () { return false; }; LocalizedString.prototype.visitExpression = function (visitor, context) { return visitor.visitLocalizedString(this, context); }; /** * Serialize the given `meta` and `messagePart` into "cooked" and "raw" strings that can be used * in a `$localize` tagged string. The format of the metadata is the same as that parsed by * `parseI18nMeta()`. * * @param meta The metadata to serialize * @param messagePart The first part of the tagged string */ LocalizedString.prototype.serializeI18nHead = function () { var MEANING_SEPARATOR = '|'; var ID_SEPARATOR = '@@'; var LEGACY_ID_INDICATOR = '␟'; var metaBlock = this.metaBlock.description || ''; if (this.metaBlock.meaning) { metaBlock = "" + this.metaBlock.meaning + MEANING_SEPARATOR + metaBlock; } if (this.metaBlock.customId) { metaBlock = "" + metaBlock + ID_SEPARATOR + this.metaBlock.customId; } if (this.metaBlock.legacyIds) { this.metaBlock.legacyIds.forEach(function (legacyId) { metaBlock = "" + metaBlock + LEGACY_ID_INDICATOR + legacyId; }); } return createCookedRawString(metaBlock, this.messageParts[0]); }; /** * Serialize the given `placeholderName` and `messagePart` into "cooked" and "raw" strings that * can be used in a `$localize` tagged string. * * @param placeholderName The placeholder name to serialize * @param messagePart The following message string after this placeholder */ LocalizedString.prototype.serializeI18nTemplatePart = function (partIndex) { var placeholderName = this.placeHolderNames[partIndex - 1]; var messagePart = this.messageParts[partIndex]; return createCookedRawString(placeholderName, messagePart); }; return LocalizedString; }(Expression)); var escapeSlashes = function (str) { return str.replace(/\\/g, '\\\\'); }; var escapeStartingColon = function (str) { return str.replace(/^:/, '\\:'); }; var escapeColons = function (str) { return str.replace(/:/g, '\\:'); }; var escapeForMessagePart = function (str) { return str.replace(/`/g, '\\`').replace(/\${/g, '$\\{'); }; /** * Creates a `{cooked, raw}` object from the `metaBlock` and `messagePart`. * * The `raw` text must have various character sequences escaped: * * "\" would otherwise indicate that the next character is a control character. * * "`" and "${" are template string control sequences that would otherwise prematurely indicate * the end of a message part. * * ":" inside a metablock would prematurely indicate the end of the metablock. * * ":" at the start of a messagePart with no metablock would erroneously indicate the start of a * metablock. * * @param metaBlock Any metadata that should be prepended to the string * @param messagePart The message part of the string */ function createCookedRawString(metaBlock, messagePart) { if (metaBlock === '') { return { cooked: messagePart, raw: escapeForMessagePart(escapeStartingColon(escapeSlashes(messagePart))) }; } else { return { cooked: ":" + metaBlock + ":" + messagePart, raw: escapeForMessagePart(":" + escapeColons(escapeSlashes(metaBlock)) + ":" + escapeSlashes(messagePart)) }; } } var ExternalExpr = /** @class */ (function (_super) { __extends(ExternalExpr, _super); function ExternalExpr(value, type, typeParams, sourceSpan) { if (typeParams === void 0) { typeParams = null; } var _this = _super.call(this, type, sourceSpan) || this; _this.value = value; _this.typeParams = typeParams; return _this; } ExternalExpr.prototype.isEquivalent = function (e) { return e instanceof ExternalExpr && this.value.name === e.value.name && this.value.moduleName === e.value.moduleName && this.value.runtime === e.value.runtime; }; ExternalExpr.prototype.isConstant = function () { return false; }; ExternalExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitExternalExpr(this, context); }; return ExternalExpr; }(Expression)); var ExternalReference = /** @class */ (function () { function ExternalReference(moduleName, name, runtime) { this.moduleName = moduleName; this.name = name; this.runtime = runtime; } return ExternalReference; }()); var ConditionalExpr = /** @class */ (function (_super) { __extends(ConditionalExpr, _super); function ConditionalExpr(condition, trueCase, falseCase, type, sourceSpan) { if (falseCase === void 0) { falseCase = null; } var _this = _super.call(this, type || trueCase.type, sourceSpan) || this; _this.condition = condition; _this.falseCase = falseCase; _this.trueCase = trueCase; return _this; } ConditionalExpr.prototype.isEquivalent = function (e) { return e instanceof ConditionalExpr && this.condition.isEquivalent(e.condition) && this.trueCase.isEquivalent(e.trueCase) && nullSafeIsEquivalent(this.falseCase, e.falseCase); }; ConditionalExpr.prototype.isConstant = function () { return false; }; ConditionalExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitConditionalExpr(this, context); }; return ConditionalExpr; }(Expression)); var NotExpr = /** @class */ (function (_super) { __extends(NotExpr, _super); function NotExpr(condition, sourceSpan) { var _this = _super.call(this, BOOL_TYPE, sourceSpan) || this; _this.condition = condition; return _this; } NotExpr.prototype.isEquivalent = function (e) { return e instanceof NotExpr && this.condition.isEquivalent(e.condition); }; NotExpr.prototype.isConstant = function () { return false; }; NotExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitNotExpr(this, context); }; return NotExpr; }(Expression)); var AssertNotNull = /** @class */ (function (_super) { __extends(AssertNotNull, _super); function AssertNotNull(condition, sourceSpan) { var _this = _super.call(this, condition.type, sourceSpan) || this; _this.condition = condition; return _this; } AssertNotNull.prototype.isEquivalent = function (e) { return e instanceof AssertNotNull && this.condition.isEquivalent(e.condition); }; AssertNotNull.prototype.isConstant = function () { return false; }; AssertNotNull.prototype.visitExpression = function (visitor, context) { return visitor.visitAssertNotNullExpr(this, context); }; return AssertNotNull; }(Expression)); var CastExpr = /** @class */ (function (_super) { __extends(CastExpr, _super); function CastExpr(value, type, sourceSpan) { var _this = _super.call(this, type, sourceSpan) || this; _this.value = value; return _this; } CastExpr.prototype.isEquivalent = function (e) { return e instanceof CastExpr && this.value.isEquivalent(e.value); }; CastExpr.prototype.isConstant = function () { return false; }; CastExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitCastExpr(this, context); }; return CastExpr; }(Expression)); var FnParam = /** @class */ (function () { function FnParam(name, type) { if (type === void 0) { type = null; } this.name = name; this.type = type; } FnParam.prototype.isEquivalent = function (param) { return this.name === param.name; }; return FnParam; }()); var FunctionExpr = /** @class */ (function (_super) { __extends(FunctionExpr, _super); function FunctionExpr(params, statements, type, sourceSpan, name) { var _this = _super.call(this, type, sourceSpan) || this; _this.params = params; _this.statements = statements; _this.name = name; return _this; } FunctionExpr.prototype.isEquivalent = function (e) { return e instanceof FunctionExpr && areAllEquivalent(this.params, e.params) && areAllEquivalent(this.statements, e.statements); }; FunctionExpr.prototype.isConstant = function () { return false; }; FunctionExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitFunctionExpr(this, context); }; FunctionExpr.prototype.toDeclStmt = function (name, modifiers) { if (modifiers === void 0) { modifiers = null; } return new DeclareFunctionStmt(name, this.params, this.statements, this.type, modifiers, this.sourceSpan); }; return FunctionExpr; }(Expression)); var BinaryOperatorExpr = /** @class */ (function (_super) { __extends(BinaryOperatorExpr, _super); function BinaryOperatorExpr(operator, lhs, rhs, type, sourceSpan, parens) { if (parens === void 0) { parens = true; } var _this = _super.call(this, type || lhs.type, sourceSpan) || this; _this.operator = operator; _this.rhs = rhs; _this.parens = parens; _this.lhs = lhs; return _this; } BinaryOperatorExpr.prototype.isEquivalent = function (e) { return e instanceof BinaryOperatorExpr && this.operator === e.operator && this.lhs.isEquivalent(e.lhs) && this.rhs.isEquivalent(e.rhs); }; BinaryOperatorExpr.prototype.isConstant = function () { return false; }; BinaryOperatorExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitBinaryOperatorExpr(this, context); }; return BinaryOperatorExpr; }(Expression)); var ReadPropExpr = /** @class */ (function (_super) { __extends(ReadPropExpr, _super); function ReadPropExpr(receiver, name, type, sourceSpan) { var _this = _super.call(this, type, sourceSpan) || this; _this.receiver = receiver; _this.name = name; return _this; } ReadPropExpr.prototype.isEquivalent = function (e) { return e instanceof ReadPropExpr && this.receiver.isEquivalent(e.receiver) && this.name === e.name; }; ReadPropExpr.prototype.isConstant = function () { return false; }; ReadPropExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitReadPropExpr(this, context); }; ReadPropExpr.prototype.set = function (value) { return new WritePropExpr(this.receiver, this.name, value, null, this.sourceSpan); }; return ReadPropExpr; }(Expression)); var ReadKeyExpr = /** @class */ (function (_super) { __extends(ReadKeyExpr, _super); function ReadKeyExpr(receiver, index, type, sourceSpan) { var _this = _super.call(this, type, sourceSpan) || this; _this.receiver = receiver; _this.index = index; return _this; } ReadKeyExpr.prototype.isEquivalent = function (e) { return e instanceof ReadKeyExpr && this.receiver.isEquivalent(e.receiver) && this.index.isEquivalent(e.index); }; ReadKeyExpr.prototype.isConstant = function () { return false; }; ReadKeyExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitReadKeyExpr(this, context); }; ReadKeyExpr.prototype.set = function (value) { return new WriteKeyExpr(this.receiver, this.index, value, null, this.sourceSpan); }; return ReadKeyExpr; }(Expression)); var LiteralArrayExpr = /** @class */ (function (_super) { __extends(LiteralArrayExpr, _super); function LiteralArrayExpr(entries, type, sourceSpan) { var _this = _super.call(this, type, sourceSpan) || this; _this.entries = entries; return _this; } LiteralArrayExpr.prototype.isConstant = function () { return this.entries.every(function (e) { return e.isConstant(); }); }; LiteralArrayExpr.prototype.isEquivalent = function (e) { return e instanceof LiteralArrayExpr && areAllEquivalent(this.entries, e.entries); }; LiteralArrayExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitLiteralArrayExpr(this, context); }; return LiteralArrayExpr; }(Expression)); var LiteralMapEntry = /** @class */ (function () { function LiteralMapEntry(key, value, quoted) { this.key = key; this.value = value; this.quoted = quoted; } LiteralMapEntry.prototype.isEquivalent = function (e) { return this.key === e.key && this.value.isEquivalent(e.value); }; return LiteralMapEntry; }()); var LiteralMapExpr = /** @class */ (function (_super) { __extends(LiteralMapExpr, _super); function LiteralMapExpr(entries, type, sourceSpan) { var _this = _super.call(this, type, sourceSpan) || this; _this.entries = entries; _this.valueType = null; if (type) { _this.valueType = type.valueType; } return _this; } LiteralMapExpr.prototype.isEquivalent = function (e) { return e instanceof LiteralMapExpr && areAllEquivalent(this.entries, e.entries); }; LiteralMapExpr.prototype.isConstant = function () { return this.entries.every(function (e) { return e.value.isConstant(); }); }; LiteralMapExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitLiteralMapExpr(this, context); }; return LiteralMapExpr; }(Expression)); var CommaExpr = /** @class */ (function (_super) { __extends(CommaExpr, _super); function CommaExpr(parts, sourceSpan) { var _this = _super.call(this, parts[parts.length - 1].type, sourceSpan) || this; _this.parts = parts; return _this; } CommaExpr.prototype.isEquivalent = function (e) { return e instanceof CommaExpr && areAllEquivalent(this.parts, e.parts); }; CommaExpr.prototype.isConstant = function () { return false; }; CommaExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitCommaExpr(this, context); }; return CommaExpr; }(Expression)); var THIS_EXPR = new ReadVarExpr(BuiltinVar.This, null, null); var SUPER_EXPR = new ReadVarExpr(BuiltinVar.Super, null, null); var CATCH_ERROR_VAR = new ReadVarExpr(BuiltinVar.CatchError, null, null); var CATCH_STACK_VAR = new ReadVarExpr(BuiltinVar.CatchStack, null, null); var NULL_EXPR = new LiteralExpr(null, null, null); var TYPED_NULL_EXPR = new LiteralExpr(null, INFERRED_TYPE, null); //// Statements var StmtModifier; (function (StmtModifier) { StmtModifier[StmtModifier["Final"] = 0] = "Final"; StmtModifier[StmtModifier["Private"] = 1] = "Private"; StmtModifier[StmtModifier["Exported"] = 2] = "Exported"; StmtModifier[StmtModifier["Static"] = 3] = "Static"; })(StmtModifier || (StmtModifier = {})); var Statement = /** @class */ (function () { function Statement(modifiers, sourceSpan) { this.modifiers = modifiers || []; this.sourceSpan = sourceSpan || null; } Statement.prototype.hasModifier = function (modifier) { return this.modifiers.indexOf(modifier) !== -1; }; return Statement; }()); var DeclareVarStmt = /** @class */ (function (_super) { __extends(DeclareVarStmt, _super); function DeclareVarStmt(name, value, type, modifiers, sourceSpan) { if (modifiers === void 0) { modifiers = null; } var _this = _super.call(this, modifiers, sourceSpan) || this; _this.name = name; _this.value = value; _this.type = type || (value && value.type) || null; return _this; } DeclareVarStmt.prototype.isEquivalent = function (stmt) { return stmt instanceof DeclareVarStmt && this.name === stmt.name && (this.value ? !!stmt.value && this.value.isEquivalent(stmt.value) : !stmt.value); }; DeclareVarStmt.prototype.visitStatement = function (visitor, context) { return visitor.visitDeclareVarStmt(this, context); }; return DeclareVarStmt; }(Statement)); var DeclareFunctionStmt = /** @class */ (function (_super) { __extends(DeclareFunctionStmt, _super); function DeclareFunctionStmt(name, params, statements, type, modifiers, sourceSpan) { if (modifiers === void 0) { modifiers = null; } var _this = _super.call(this, modifiers, sourceSpan) || this; _this.name = name; _this.params = params; _this.statements = statements; _this.type = type || null; return _this; } DeclareFunctionStmt.prototype.isEquivalent = function (stmt) { return stmt instanceof DeclareFunctionStmt && areAllEquivalent(this.params, stmt.params) && areAllEquivalent(this.statements, stmt.statements); }; DeclareFunctionStmt.prototype.visitStatement = function (visitor, context) { return visitor.visitDeclareFunctionStmt(this, context); }; return DeclareFunctionStmt; }(Statement)); var ExpressionStatement = /** @class */ (function (_super) { __extends(ExpressionStatement, _super); function ExpressionStatement(expr, sourceSpan) { var _this = _super.call(this, null, sourceSpan) || this; _this.expr = expr; return _this; } ExpressionStatement.prototype.isEquivalent = function (stmt) { return stmt instanceof ExpressionStatement && this.expr.isEquivalent(stmt.expr); }; ExpressionStatement.prototype.visitStatement = function (visitor, context) { return visitor.visitExpressionStmt(this, context); }; return ExpressionStatement; }(Statement)); var ReturnStatement = /** @class */ (function (_super) { __extends(ReturnStatement, _super); function ReturnStatement(value, sourceSpan) { var _this = _super.call(this, null, sourceSpan) || this; _this.value = value; return _this; } ReturnStatement.prototype.isEquivalent = function (stmt) { return stmt instanceof ReturnStatement && this.value.isEquivalent(stmt.value); }; ReturnStatement.prototype.visitStatement = function (visitor, context) { return visitor.visitReturnStmt(this, context); }; return ReturnStatement; }(Statement)); var AbstractClassPart = /** @class */ (function () { function AbstractClassPart(type, modifiers) { this.modifiers = modifiers; if (!modifiers) { this.modifiers = []; } this.type = type || null; } AbstractClassPart.prototype.hasModifier = function (modifier) { return this.modifiers.indexOf(modifier) !== -1; }; return AbstractClassPart; }()); var ClassField = /** @class */ (function (_super) { __extends(ClassField, _super); function ClassField(name, type, modifiers, initializer) { if (modifiers === void 0) { modifiers = null; } var _this = _super.call(this, type, modifiers) || this; _this.name = name; _this.initializer = initializer; return _this; } ClassField.prototype.isEquivalent = function (f) { return this.name === f.name; }; return ClassField; }(AbstractClassPart)); var ClassMethod = /** @class */ (function (_super) { __extends(ClassMethod, _super); function ClassMethod(name, params, body, type, modifiers) { if (modifiers === void 0) { modifiers = null; } var _this = _super.call(this, type, modifiers) || this; _this.name = name; _this.params = params; _this.body = body; return _this; } ClassMethod.prototype.isEquivalent = function (m) { return this.name === m.name && areAllEquivalent(this.body, m.body); }; return ClassMethod; }(AbstractClassPart)); var ClassGetter = /** @class */ (function (_super) { __extends(ClassGetter, _super); function ClassGetter(name, body, type, modifiers) { if (modifiers === void 0) { modifiers = null; } var _this = _super.call(this, type, modifiers) || this; _this.name = name; _this.body = body; return _this; } ClassGetter.prototype.isEquivalent = function (m) { return this.name === m.name && areAllEquivalent(this.body, m.body); }; return ClassGetter; }(AbstractClassPart)); var ClassStmt = /** @class */ (function (_super) { __extends(ClassStmt, _super); function ClassStmt(name, parent, fields, getters, constructorMethod, methods, modifiers, sourceSpan) { if (modifiers === void 0) { modifiers = null; } var _this = _super.call(this, modifiers, sourceSpan) || this; _this.name = name; _this.parent = parent; _this.fields = fields; _this.getters = getters; _this.constructorMethod = constructorMethod; _this.methods = methods; return _this; } ClassStmt.prototype.isEquivalent = function (stmt) { return stmt instanceof ClassStmt && this.name === stmt.name && nullSafeIsEquivalent(this.parent, stmt.parent) && areAllEquivalent(this.fields, stmt.fields) && areAllEquivalent(this.getters, stmt.getters) && this.constructorMethod.isEquivalent(stmt.constructorMethod) && areAllEquivalent(this.methods, stmt.methods); }; ClassStmt.prototype.visitStatement = function (visitor, context) { return visitor.visitDeclareClassStmt(this, context); }; return ClassStmt; }(Statement)); var IfStmt = /** @class */ (function (_super) { __extends(IfStmt, _super); function IfStmt(condition, trueCase, falseCase, sourceSpan) { if (falseCase === void 0) { falseCase = []; } var _this = _super.call(this, null, sourceSpan) || this; _this.condition = condition; _this.trueCase = trueCase; _this.falseCase = falseCase; return _this; } IfStmt.prototype.isEquivalent = function (stmt) { return stmt instanceof IfStmt && this.condition.isEquivalent(stmt.condition) && areAllEquivalent(this.trueCase, stmt.trueCase) && areAllEquivalent(this.falseCase, stmt.falseCase); }; IfStmt.prototype.visitStatement = function (visitor, context) { return visitor.visitIfStmt(this, context); }; return IfStmt; }(Statement)); var CommentStmt = /** @class */ (function (_super) { __extends(CommentStmt, _super); function CommentStmt(comment, multiline, sourceSpan) { if (multiline === void 0) { multiline = false; } var _this = _super.call(this, null, sourceSpan) || this; _this.comment = comment; _this.multiline = multiline; return _this; } CommentStmt.prototype.isEquivalent = function (stmt) { return stmt instanceof CommentStmt; }; CommentStmt.prototype.visitStatement = function (visitor, context) { return visitor.visitCommentStmt(this, context); }; return CommentStmt; }(Statement)); var JSDocCommentStmt = /** @class */ (function (_super) { __extends(JSDocCommentStmt, _super); function JSDocCommentStmt(tags, sourceSpan) { if (tags === void 0) { tags = []; } var _this = _super.call(this, null, sourceSpan) || this; _this.tags = tags; return _this; } JSDocCommentStmt.prototype.isEquivalent = function (stmt) { return stmt instanceof JSDocCommentStmt && this.toString() === stmt.toString(); }; JSDocCommentStmt.prototype.visitStatement = function (visitor, context) { return visitor.visitJSDocCommentStmt(this, context); }; JSDocCommentStmt.prototype.toString = function () { return serializeTags(this.tags); }; return JSDocCommentStmt; }(Statement)); var TryCatchStmt = /** @class */ (function (_super) { __extends(TryCatchStmt, _super); function TryCatchStmt(bodyStmts, catchStmts, sourceSpan) { var _this = _super.call(this, null, sourceSpan) || this; _this.bodyStmts = bodyStmts; _this.catchStmts = catchStmts; return _this; } TryCatchStmt.prototype.isEquivalent = function (stmt) { return stmt instanceof TryCatchStmt && areAllEquivalent(this.bodyStmts, stmt.bodyStmts) && areAllEquivalent(this.catchStmts, stmt.catchStmts); }; TryCatchStmt.prototype.visitStatement = function (visitor, context) { return visitor.visitTryCatchStmt(this, context); }; return TryCatchStmt; }(Statement)); var ThrowStmt = /** @class */ (function (_super) { __extends(ThrowStmt, _super); function ThrowStmt(error, sourceSpan) { var _this = _super.call(this, null, sourceSpan) || this; _this.error = error; return _this; } ThrowStmt.prototype.isEquivalent = function (stmt) { return stmt instanceof TryCatchStmt && this.error.isEquivalent(stmt.error); }; ThrowStmt.prototype.visitStatement = function (visitor, context) { return visitor.visitThrowStmt(this, context); }; return ThrowStmt; }(Statement)); var AstTransformer = /** @class */ (function () { function AstTransformer() { } AstTransformer.prototype.transformExpr = function (expr, context) { return expr; }; AstTransformer.prototype.transformStmt = function (stmt, context) { return stmt; }; AstTransformer.prototype.visitReadVarExpr = function (ast, context) { return this.transformExpr(ast, context); }; AstTransformer.prototype.visitWrappedNodeExpr = function (ast, context) { return this.transformExpr(ast, context); }; AstTransformer.prototype.visitTypeofExpr = function (expr, context) { return this.transformExpr(new TypeofExpr(expr.expr.visitExpression(this, context), expr.type, expr.sourceSpan), context); }; AstTransformer.prototype.visitWriteVarExpr = function (expr, context) { return this.transformExpr(new WriteVarExpr(expr.name, expr.value.visitExpression(this, context), expr.type, expr.sourceSpan), context); }; AstTransformer.prototype.visitWriteKeyExpr = function (expr, context) { 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); }; AstTransformer.prototype.visitWritePropExpr = function (expr, context) { return this.transformExpr(new WritePropExpr(expr.receiver.visitExpression(this, context), expr.name, expr.value.visitExpression(this, context), expr.type, expr.sourceSpan), context); }; AstTransformer.prototype.visitInvokeMethodExpr = function (ast, context) { var method = ast.builtin || ast.name; return this.transformExpr(new InvokeMethodExpr(ast.receiver.visitExpression(this, context), method, this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context); }; AstTransformer.prototype.visitInvokeFunctionExpr = function (ast, context) { return this.transformExpr(new InvokeFunctionExpr(ast.fn.visitExpression(this, context), this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context); }; AstTransformer.prototype.visitInstantiateExpr = function (ast, context) { return this.transformExpr(new InstantiateExpr(ast.classExpr.visitExpression(this, context), this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context); }; AstTransformer.prototype.visitLiteralExpr = function (ast, context) { return this.transformExpr(ast, context); }; AstTransformer.prototype.visitLocalizedString = function (ast, context) { return this.transformExpr(new LocalizedString(ast.metaBlock, ast.messageParts, ast.placeHolderNames, this.visitAllExpressions(ast.expressions, context), ast.sourceSpan), context); }; AstTransformer.prototype.visitExternalExpr = function (ast, context) { return this.transformExpr(ast, context); }; AstTransformer.prototype.visitConditionalExpr = function (ast, context) { 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); }; AstTransformer.prototype.visitNotExpr = function (ast, context) { return this.transformExpr(new NotExpr(ast.condition.visitExpression(this, context), ast.sourceSpan), context); }; AstTransformer.prototype.visitAssertNotNullExpr = function (ast, context) { return this.transformExpr(new AssertNotNull(ast.condition.visitExpression(this, context), ast.sourceSpan), context); }; AstTransformer.prototype.visitCastExpr = function (ast, context) { return this.transformExpr(new CastExpr(ast.value.visitExpression(this, context), ast.type, ast.sourceSpan), context); }; AstTransformer.prototype.visitFunctionExpr = function (ast, context) { return this.transformExpr(new FunctionExpr(ast.params, this.visitAllStatements(ast.statements, context), ast.type, ast.sourceSpan), context); }; AstTransformer.prototype.visitBinaryOperatorExpr = function (ast, context) { return this.transformExpr(new BinaryOperatorExpr(ast.operator, ast.lhs.visitExpression(this, context), ast.rhs.visitExpression(this, context), ast.type, ast.sourceSpan), context); }; AstTransformer.prototype.visitReadPropExpr = function (ast, context) { return this.transformExpr(new ReadPropExpr(ast.receiver.visitExpression(this, context), ast.name, ast.type, ast.sourceSpan), context); }; AstTransformer.prototype.visitReadKeyExpr = function (ast, context) { return this.transformExpr(new ReadKeyExpr(ast.receiver.visitExpression(this, context), ast.index.visitExpression(this, context), ast.type, ast.sourceSpan), context); }; AstTransformer.prototype.visitLiteralArrayExpr = function (ast, context) { return this.transformExpr(new LiteralArrayExpr(this.visitAllExpressions(ast.entries, context), ast.type, ast.sourceSpan), context); }; AstTransformer.prototype.visitLiteralMapExpr = function (ast, context) { var _this = this; var entries = ast.entries.map(function (entry) { return new LiteralMapEntry(entry.key, entry.value.visitExpression(_this, context), entry.quoted); }); var mapType = new MapType(ast.valueType, null); return this.transformExpr(new LiteralMapExpr(entries, mapType, ast.sourceSpan), context); }; AstTransformer.prototype.visitCommaExpr = function (ast, context) { return this.transformExpr(new CommaExpr(this.visitAllExpressions(ast.parts, context), ast.sourceSpan), context); }; AstTransformer.prototype.visitAllExpressions = function (exprs, context) { var _this = this; return exprs.map(function (expr) { return expr.visitExpression(_this, context); }); }; AstTransformer.prototype.visitDeclareVarStmt = function (stmt, context) { var value = stmt.value && stmt.value.visitExpression(this, context); return this.transformStmt(new DeclareVarStmt(stmt.name, value, stmt.type, stmt.modifiers, stmt.sourceSpan), context); }; AstTransformer.prototype.visitDeclareFunctionStmt = function (stmt, context) { return this.transformStmt(new DeclareFunctionStmt(stmt.name, stmt.params, this.visitAllStatements(stmt.statements, context), stmt.type, stmt.modifiers, stmt.sourceSpan), context); }; AstTransformer.prototype.visitExpressionStmt = function (stmt, context) { return this.transformStmt(new ExpressionStatement(stmt.expr.visitExpression(this, context), stmt.sourceSpan), context); }; AstTransformer.prototype.visitReturnStmt = function (stmt, context) { return this.transformStmt(new ReturnStatement(stmt.value.visitExpression(this, context), stmt.sourceSpan), context); }; AstTransformer.prototype.visitDeclareClassStmt = function (stmt, context) { var _this = this; var parent = stmt.parent.visitExpression(this, context); var getters = stmt.getters.map(function (getter) { return new ClassGetter(getter.name, _this.visitAllStatements(getter.body, context), getter.type, getter.modifiers); }); var ctorMethod = stmt.constructorMethod && new ClassMethod(stmt.constructorMethod.name, stmt.constructorMethod.params, this.visitAllStatements(stmt.constructorMethod.body, context), stmt.constructorMethod.type, stmt.constructorMethod.modifiers); var methods = stmt.methods.map(function (method) { return new ClassMethod(method.name, method.params, _this.visitAllStatements(method.body, context), method.type, method.modifiers); }); return this.transformStmt(new ClassStmt(stmt.name, parent, stmt.fields, getters, ctorMethod, methods, stmt.modifiers, stmt.sourceSpan), context); }; AstTransformer.prototype.visitIfStmt = function (stmt, context) { return this.transformStmt(new IfStmt(stmt.condition.visitExpression(this, context), this.visitAllStatements(stmt.trueCase, context), this.visitAllStatements(stmt.falseCase, context), stmt.sourceSpan), context); }; AstTransformer.prototype.visitTryCatchStmt = function (stmt, context) { return this.transformStmt(new TryCatchStmt(this.visitAllStatements(stmt.bodyStmts, context), this.visitAllStatements(stmt.catchStmts, context), stmt.sourceSpan), context); }; AstTransformer.prototype.visitThrowStmt = function (stmt, context) { return this.transformStmt(new ThrowStmt(stmt.error.visitExpression(this, context), stmt.sourceSpan), context); }; AstTransformer.prototype.visitCommentStmt = function (stmt, context) { return this.transformStmt(stmt, context); }; AstTransformer.prototype.visitJSDocCommentStmt = function (stmt, context) { return this.transformStmt(stmt, context); }; AstTransformer.prototype.visitAllStatements = function (stmts, context) { var _this = this; return stmts.map(function (stmt) { return stmt.visitStatement(_this, context); }); }; return AstTransformer; }()); var RecursiveAstVisitor = /** @class */ (function () { function RecursiveAstVisitor() { } RecursiveAstVisitor.prototype.visitType = function (ast, context) { return ast; }; RecursiveAstVisitor.prototype.visitExpression = function (ast, context) { if (ast.type) { ast.type.visitType(this, context); } return ast; }; RecursiveAstVisitor.prototype.visitBuiltinType = function (type, context) { return this.visitType(type, context); }; RecursiveAstVisitor.prototype.visitExpressionType = function (type, context) { var _this = this; type.value.visitExpression(this, context); if (type.typeParams !== null) { type.typeParams.forEach(function (param) { return _this.visitType(param, context); }); } return this.visitType(type, context); }; RecursiveAstVisitor.prototype.visitArrayType = function (type, context) { return this.visitType(type, context); }; RecursiveAstVisitor.prototype.visitMapType = function (type, context) { return this.visitType(type, context); }; RecursiveAstVisitor.prototype.visitWrappedNodeExpr = function (ast, context) { return ast; }; RecursiveAstVisitor.prototype.visitTypeofExpr = function (ast, context) { return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitReadVarExpr = function (ast, context) { return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitWriteVarExpr = function (ast, context) { ast.value.visitExpression(this, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitWriteKeyExpr = function (ast, context) { ast.receiver.visitExpression(this, context); ast.index.visitExpression(this, context); ast.value.visitExpression(this, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitWritePropExpr = function (ast, context) { ast.receiver.visitExpression(this, context); ast.value.visitExpression(this, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitInvokeMethodExpr = function (ast, context) { ast.receiver.visitExpression(this, context); this.visitAllExpressions(ast.args, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitInvokeFunctionExpr = function (ast, context) { ast.fn.visitExpression(this, context); this.visitAllExpressions(ast.args, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitInstantiateExpr = function (ast, context) { ast.classExpr.visitExpression(this, context); this.visitAllExpressions(ast.args, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitLiteralExpr = function (ast, context) { return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitLocalizedString = function (ast, context) { return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitExternalExpr = function (ast, context) { var _this = this; if (ast.typeParams) { ast.typeParams.forEach(function (type) { return type.visitType(_this, context); }); } return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitConditionalExpr = function (ast, context) { ast.condition.visitExpression(this, context); ast.trueCase.visitExpression(this, context); ast.falseCase.visitExpression(this, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitNotExpr = function (ast, context) { ast.condition.visitExpression(this, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitAssertNotNullExpr = function (ast, context) { ast.condition.visitExpression(this, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitCastExpr = function (ast, context) { ast.value.visitExpression(this, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitFunctionExpr = function (ast, context) { this.visitAllStatements(ast.statements, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitBinaryOperatorExpr = function (ast, context) { ast.lhs.visitExpression(this, context); ast.rhs.visitExpression(this, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitReadPropExpr = function (ast, context) { ast.receiver.visitExpression(this, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitReadKeyExpr = function (ast, context) { ast.receiver.visitExpression(this, context); ast.index.visitExpression(this, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitLiteralArrayExpr = function (ast, context) { this.visitAllExpressions(ast.entries, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitLiteralMapExpr = function (ast, context) { var _this = this; ast.entries.forEach(function (entry) { return entry.value.visitExpression(_this, context); }); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitCommaExpr = function (ast, context) { this.visitAllExpressions(ast.parts, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitAllExpressions = function (exprs, context) { var _this = this; exprs.forEach(function (expr) { return expr.visitExpression(_this, context); }); }; RecursiveAstVisitor.prototype.visitDeclareVarStmt = function (stmt, context) { if (stmt.value) { stmt.value.visitExpression(this, context); } if (stmt.type) { stmt.type.visitType(this, context); } return stmt; }; RecursiveAstVisitor.prototype.visitDeclareFunctionStmt = function (stmt, context) { this.visitAllStatements(stmt.statements, context); if (stmt.type) { stmt.type.visitType(this, context); } return stmt; }; RecursiveAstVisitor.prototype.visitExpressionStmt = function (stmt, context) { stmt.expr.visitExpression(this, context); return stmt; }; RecursiveAstVisitor.prototype.visitReturnStmt = function (stmt, context) { stmt.value.visitExpression(this, context); return stmt; }; RecursiveAstVisitor.prototype.visitDeclareClassStmt = function (stmt, context) { var _this = this; stmt.parent.visitExpression(this, context); stmt.getters.forEach(function (getter) { return _this.visitAllStatements(getter.body, context); }); if (stmt.constructorMethod) { this.visitAllStatements(stmt.constructorMethod.body, context); } stmt.methods.forEach(function (method) { return _this.visitAllStatements(method.body, context); }); return stmt; }; RecursiveAstVisitor.prototype.visitIfStmt = function (stmt, context) { stmt.condition.visitExpression(this, context); this.visitAllStatements(stmt.trueCase, context); this.visitAllStatements(stmt.falseCase, context); return stmt; }; RecursiveAstVisitor.prototype.visitTryCatchStmt = function (stmt, context) { this.visitAllStatements(stmt.bodyStmts, context); this.visitAllStatements(stmt.catchStmts, context); return stmt; }; RecursiveAstVisitor.prototype.visitThrowStmt = function (stmt, context) { stmt.error.visitExpression(this, context); return stmt; }; RecursiveAstVisitor.prototype.visitCommentStmt = function (stmt, context) { return stmt; }; RecursiveAstVisitor.prototype.visitJSDocCommentStmt = function (stmt, context) { return stmt; }; RecursiveAstVisitor.prototype.visitAllStatements = function (stmts, context) { var _this = this; stmts.forEach(function (stmt) { return stmt.visitStatement(_this, context); }); }; return RecursiveAstVisitor; }()); function findReadVarNames(stmts) { var visitor = new _ReadVarVisitor(); visitor.visitAllStatements(stmts, null); return visitor.varNames; } var _ReadVarVisitor = /** @class */ (function (_super) { __extends(_ReadVarVisitor, _super); function _ReadVarVisitor() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.varNames = new Set(); return _this; } _ReadVarVisitor.prototype.visitDeclareFunctionStmt = function (stmt, context) { // Don't descend into nested functions return stmt; }; _ReadVarVisitor.prototype.visitDeclareClassStmt = function (stmt, context) { // Don't descend into nested classes return stmt; }; _ReadVarVisitor.prototype.visitReadVarExpr = function (ast, context) { if (ast.name) { this.varNames.add(ast.name); } return null; }; return _ReadVarVisitor; }(RecursiveAstVisitor)); function collectExternalReferences(stmts) { var visitor = new _FindExternalReferencesVisitor(); visitor.visitAllStatements(stmts, null); return visitor.externalReferences; } var _FindExternalReferencesVisitor = /** @class */ (function (_super) { __extends(_FindExternalReferencesVisitor, _super); function _FindExternalReferencesVisitor() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.externalReferences = []; return _this; } _FindExternalReferencesVisitor.prototype.visitExternalExpr = function (e, context) { this.externalReferences.push(e.value); return _super.prototype.visitExternalExpr.call(this, e, context); }; return _FindExternalReferencesVisitor; }(RecursiveAstVisitor)); function applySourceSpanToStatementIfNeeded(stmt, sourceSpan) { if (!sourceSpan) { return stmt; } var transformer = new _ApplySourceSpanTransformer(sourceSpan); return stmt.visitStatement(transformer, null); } function applySourceSpanToExpressionIfNeeded(expr, sourceSpan) { if (!sourceSpan) { return expr; } var transformer = new _ApplySourceSpanTransformer(sourceSpan); return expr.visitExpression(transformer, null); } var _ApplySourceSpanTransformer = /** @class */ (function (_super) { __extends(_ApplySourceSpanTransformer, _super); function _ApplySourceSpanTransformer(sourceSpan) { var _this = _super.call(this) || this; _this.sourceSpan = sourceSpan; return _this; } _ApplySourceSpanTransformer.prototype._clone = function (obj) { var e_1, _a; var clone = Object.create(obj.constructor.prototype); try { for (var _b = __values(Object.keys(obj)), _c = _b.next(); !_c.done; _c = _b.next()) { var prop = _c.value; clone[prop] = obj[prop]; } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) _a.call(_b); } finally { if (e_1) throw e_1.error; } } return clone; }; _ApplySourceSpanTransformer.prototype.transformExpr = function (expr, context) { if (!expr.sourceSpan) { expr = this._clone(expr); expr.sourceSpan = this.sourceSpan; } return expr; }; _ApplySourceSpanTransformer.prototype.transformStmt = function (stmt, context) { if (!stmt.sourceSpan) { stmt = this._clone(stmt); stmt.sourceSpan = this.sourceSpan; } return stmt; }; return _ApplySourceSpanTransformer; }(AstTransformer)); function variable(name, type, sourceSpan) { return new ReadVarExpr(name, type, sourceSpan); } function importExpr(id, typeParams, sourceSpan) { if (typeParams === void 0) { typeParams = null; } return new ExternalExpr(id, null, typeParams, sourceSpan); } function importType(id, typeParams, typeModifiers) { if (typeParams === void 0) { typeParams = null; } if (typeModifiers === void 0) { typeModifiers = null; } return id != null ? expressionType(importExpr(id, typeParams, null), typeModifiers) : null; } function expressionType(expr, typeModifiers, typeParams) { if (typeModifiers === void 0) { typeModifiers = null; } if (typeParams === void 0) { typeParams = null; } return new ExpressionType(expr, typeModifiers, typeParams); } function typeofExpr(expr) { return new TypeofExpr(expr); } function literalArr(values, type, sourceSpan) { return new LiteralArrayExpr(values, type, sourceSpan); } function literalMap(values, type) { if (type === void 0) { type = null; } return new LiteralMapExpr(values.map(function (e) { return new LiteralMapEntry(e.key, e.value, e.quoted); }), type, null); } function not(expr, sourceSpan) { return new NotExpr(expr, sourceSpan); } function assertNotNull(expr, sourceSpan) { return new AssertNotNull(expr, sourceSpan); } function fn(params, body, type, sourceSpan, name) { return new FunctionExpr(params, body, type, sourceSpan, name); } function ifStmt(condition, thenClause, elseClause) { return new IfStmt(condition, thenClause, elseClause); } function literal(value, type, sourceSpan) { return new LiteralExpr(value, type, sourceSpan); } function localizedString(metaBlock, messageParts, placeholderNames, expressions, sourceSpan) { return new LocalizedString(metaBlock, messageParts, placeholderNames, expressions, sourceSpan); } function isNull(exp) { return exp instanceof LiteralExpr && exp.value === null; } /* * Serializes a `Tag` into a string. * Returns a string like " @foo {bar} baz" (note the leading whitespace before `@foo`). */ function tagToString(tag) { var out = ''; if (tag.tagName) { out += " @" + tag.tagName; } if (tag.text) { if (tag.text.match(/\/\*|\*\//)) { throw new Error('JSDoc text cannot contain "/*" and "*/"'); } out += ' ' + tag.text.replace(/@/g, '\\@'); } return out; } function serializeTags(tags) { var e_2, _a; if (tags.length === 0) return ''; var out = '*\n'; try { for (var tags_1 = __values(tags), tags_1_1 = tags_1.next(); !tags_1_1.done; tags_1_1 = tags_1.next()) { var tag = tags_1_1.value; out += ' *'; // If the tagToString is multi-line, insert " * " prefixes on subsequent lines. out += tagToString(tag).replace(/\n/g, '\n * '); out += '\n'; } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (tags_1_1 && !tags_1_1.done && (_a = tags_1.return)) _a.call(tags_1); } finally { if (e_2) throw e_2.error; } } out += ' '; return out; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var DASH_CASE_REGEXP = /-+([a-z0-9])/g; function dashCaseToCamelCase(input) { return input.replace(DASH_CASE_REGEXP, function () { var m = []; for (var _i = 0; _i < arguments.length; _i++) { m[_i] = arguments[_i]; } return m[1].toUpperCase(); }); } function splitAtColon(input, defaultValues) { return _splitAt(input, ':', defaultValues); } function splitAtPeriod(input, defaultValues) { return _splitAt(input, '.', defaultValues); } function _splitAt(input, character, defaultValues) { var characterIndex = input.indexOf(character); if (characterIndex == -1) return defaultValues; return [input.slice(0, characterIndex).trim(), input.slice(characterIndex + 1).trim()]; } function visitValue(value, visitor, context) { if (Array.isArray(value)) { return visitor.visitArray(value, context); } if (isStrictStringMap(value)) { return visitor.visitStringMap(value, context); } if (value == null || typeof value == 'string' || typeof value == 'number' || typeof value == 'boolean') { return visitor.visitPrimitive(value, context); } return visitor.visitOther(value, context); } function isDefined(val) { return val !== null && val !== undefined; } function noUndefined(val) { return val === undefined ? null : val; } var ValueTransformer = /** @class */ (function () { function ValueTransformer() { } ValueTransformer.prototype.visitArray = function (arr, context) { var _this = this; return arr.map(function (value) { return visitValue(value, _this, context); }); }; ValueTransformer.prototype.visitStringMap = function (map, context) { var _this = this; var result = {}; Object.keys(map).forEach(function (key) { result[key] = visitValue(map[key], _this, context); }); return result; }; ValueTransformer.prototype.visitPrimitive = function (value, context) { return value; }; ValueTransformer.prototype.visitOther = function (value, context) { return value; }; return ValueTransformer; }()); var SyncAsync = { assertSync: function (value) { if (isPromise(value)) { throw new Error("Illegal state: value cannot be a promise"); } return value; }, then: function (value, cb) { return isPromise(value) ? value.then(cb) : cb(value); }, all: function (syncAsyncValues) { return syncAsyncValues.some(isPromise) ? Promise.all(syncAsyncValues) : syncAsyncValues; } }; function error(msg) { throw new Error("Internal Error: " + msg); } function syntaxError(msg, parseErrors) { var error = Error(msg); error[ERROR_SYNTAX_ERROR] = true; if (parseErrors) error[ERROR_PARSE_ERRORS] = parseErrors; return error; } var ERROR_SYNTAX_ERROR = 'ngSyntaxError'; var ERROR_PARSE_ERRORS = 'ngParseErrors'; function isSyntaxError(error) { return error[ERROR_SYNTAX_ERROR]; } function getParseErrors(error) { return error[ERROR_PARSE_ERRORS] || []; } // Escape characters that have a special meaning in Regular Expressions function escapeRegExp(s) { return s.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); } var STRING_MAP_PROTO = Object.getPrototypeOf({}); function isStrictStringMap(obj) { return typeof obj === 'object' && obj !== null && Object.getPrototypeOf(obj) === STRING_MAP_PROTO; } function utf8Encode(str) { var encoded = ''; for (var index = 0; index < str.length; index++) { var codePoint = str.charCodeAt(index); // decode surrogate // see https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae if (codePoint >= 0xd800 && codePoint <= 0xdbff && str.length > (index + 1)) { var low = str.charCodeAt(index + 1); if (low >= 0xdc00 && low <= 0xdfff) { index++; codePoint = ((codePoint - 0xd800) << 10) + low - 0xdc00 + 0x10000; } } if (codePoint <= 0x7f) { encoded += String.fromCharCode(codePoint); } else if (codePoint <= 0x7ff) { encoded += String.fromCharCode(((codePoint >> 6) & 0x1F) | 0xc0, (codePoint & 0x3f) | 0x80); } else if (codePoint <= 0xffff) { encoded += String.fromCharCode((codePoint >> 12) | 0xe0, ((codePoint >> 6) & 0x3f) | 0x80, (codePoint & 0x3f) | 0x80); } else if (codePoint <= 0x1fffff) { encoded += String.fromCharCode(((codePoint >> 18) & 0x07) | 0xf0, ((codePoint >> 12) & 0x3f) | 0x80, ((codePoint >> 6) & 0x3f) | 0x80, (codePoint & 0x3f) | 0x80); } } return encoded; } function stringify(token) { if (typeof token === 'string') { return token; } if (Array.isArray(token)) { return '[' + token.map(stringify).join(', ') + ']'; } if (token == null) { return '' + token; } if (token.overriddenName) { return "" + token.overriddenName; } if (token.name) { return "" + token.name; } if (!token.toString) { return 'object'; } // WARNING: do not try to `JSON.stringify(token)` here // see https://github.com/angular/angular/issues/23440 var res = token.toString(); if (res == null) { return '' + res; } var newLineIndex = res.indexOf('\n'); return newLineIndex === -1 ? res : res.substring(0, newLineIndex); } /** * Lazily retrieves the reference value from a forwardRef. */ function resolveForwardRef(type) { if (typeof type === 'function' && type.hasOwnProperty('__forward_ref__')) { return type(); } else { return type; } } /** * Determine if the argument is shaped like a Promise */ function isPromise(obj) { // allow any Promise/A+ compliant thenable. // It's up to the caller to ensure that obj.then conforms to the spec return !!obj && typeof obj.then === 'function'; } var Version = /** @class */ (function () { function Version(full) { this.full = full; var splits = full.split('.'); this.major = splits[0]; this.minor = splits[1]; this.patch = splits.slice(2).join('.'); } return Version; }()); var __window = typeof window !== 'undefined' && window; var __self = typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope && self; var __global = typeof global !== 'undefined' && global; // Check __global first, because in Node tests both __global and __window may be defined and _global // should be __global in that case. var _global = __global || __window || __self; function newArray(size, value) { var list = []; for (var i = 0; i < size; i++) { list.push(value); } return list; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var CONSTANT_PREFIX = '_c'; /** * `ConstantPool` tries to reuse literal factories when two or more literals are identical. * We determine whether literals are identical by creating a key out of their AST using the * `KeyVisitor`. This constant is used to replace dynamic expressions which can't be safely * converted into a key. E.g. given an expression `{foo: bar()}`, since we don't know what * the result of `bar` will be, we create a key that looks like `{foo: }`. Note * that we use a variable, rather than something like `null` in order to avoid collisions. */ var UNKNOWN_VALUE_KEY = variable(''); /** * Context to use when producing a key. * * This ensures we see the constant not the reference variable when producing * a key. */ var KEY_CONTEXT = {}; /** * A node that is a place-holder that allows the node to be replaced when the actual * node is known. * * This allows the constant pool to change an expression from a direct reference to * a constant to a shared constant. It returns a fix-up node that is later allowed to * change the referenced expression. */ var FixupExpression = /** @class */ (function (_super) { __extends(FixupExpression, _super); function FixupExpression(resolved) { var _this = _super.call(this, resolved.type) || this; _this.resolved = resolved; _this.original = resolved; return _this; } FixupExpression.prototype.visitExpression = function (visitor, context) { if (context === KEY_CONTEXT) { // When producing a key we want to traverse the constant not the // variable used to refer to it. return this.original.visitExpression(visitor, context); } else { return this.resolved.visitExpression(visitor, context); } }; FixupExpression.prototype.isEquivalent = function (e) { return e instanceof FixupExpression && this.resolved.isEquivalent(e.resolved); }; FixupExpression.prototype.isConstant = function () { return true; }; FixupExpression.prototype.fixup = function (expression) { this.resolved = expression; this.shared = true; }; return FixupExpression; }(Expression)); /** * A constant pool allows a code emitter to share constant in an output context. * * The constant pool also supports sharing access to ivy definitions references. */ var ConstantPool = /** @class */ (function () { function ConstantPool() { this.statements = []; this.literals = new Map(); this.literalFactories = new Map(); this.injectorDefinitions = new Map(); this.directiveDefinitions = new Map(); this.componentDefinitions = new Map(); this.pipeDefinitions = new Map(); this.nextNameIndex = 0; } ConstantPool.prototype.getConstLiteral = function (literal, forceShared) { if (literal instanceof LiteralExpr || literal instanceof FixupExpression) { // Do no put simple literals into the constant pool or try to produce a constant for a // reference to a constant. return literal; } var key = this.keyOf(literal); var fixup = this.literals.get(key); var newValue = false; if (!fixup) { fixup = new FixupExpression(literal); this.literals.set(key, fixup); newValue = true; } if ((!newValue && !fixup.shared) || (newValue && forceShared)) { // Replace the expression with a variable var name_1 = this.freshName(); this.statements.push(variable(name_1).set(literal).toDeclStmt(INFERRED_TYPE, [StmtModifier.Final])); fixup.fixup(variable(name_1)); } return fixup; }; ConstantPool.prototype.getDefinition = function (type, kind, ctx, forceShared) { if (forceShared === void 0) { forceShared = false; } var definitions = this.definitionsOf(kind); var fixup = definitions.get(type); var newValue = false; if (!fixup) { var property = this.propertyNameOf(kind); fixup = new FixupExpression(ctx.importExpr(type).prop(property)); definitions.set(type, fixup); newValue = true; } if ((!newValue && !fixup.shared) || (newValue && forceShared)) { var name_2 = this.freshName(); this.statements.push(variable(name_2).set(fixup.resolved).toDeclStmt(INFERRED_TYPE, [StmtModifier.Final])); fixup.fixup(variable(name_2)); } return fixup; }; ConstantPool.prototype.getLiteralFactory = function (literal) { // Create a pure function that builds an array of a mix of constant and variable expressions if (literal instanceof LiteralArrayExpr) { var argumentsForKey = literal.entries.map(function (e) { return e.isConstant() ? e : UNKNOWN_VALUE_KEY; }); var key = this.keyOf(literalArr(argumentsForKey)); return this._getLiteralFactory(key, literal.entries, function (entries) { return literalArr(entries); }); } else { var expressionForKey = literalMap(literal.entries.map(function (e) { return ({ key: e.key, value: e.value.isConstant() ? e.value : UNKNOWN_VALUE_KEY, quoted: e.quoted }); })); var key = this.keyOf(expressionForKey); return this._getLiteralFactory(key, literal.entries.map(function (e) { return e.value; }), function (entries) { return literalMap(entries.map(function (value, index) { return ({ key: literal.entries[index].key, value: value, quoted: literal.entries[index].quoted }); })); }); } }; ConstantPool.prototype._getLiteralFactory = function (key, values, resultMap) { var _this = this; var literalFactory = this.literalFactories.get(key); var literalFactoryArguments = values.filter((function (e) { return !e.isConstant(); })); if (!literalFactory) { var resultExpressions = values.map(function (e, index) { return e.isConstant() ? _this.getConstLiteral(e, true) : variable("a" + index); }); var parameters = resultExpressions.filter(isVariable).map(function (e) { return new FnParam(e.name, DYNAMIC_TYPE); }); var pureFunctionDeclaration = fn(parameters, [new ReturnStatement(resultMap(resultExpressions))], INFERRED_TYPE); var name_3 = this.freshName(); this.statements.push(variable(name_3).set(pureFunctionDeclaration).toDeclStmt(INFERRED_TYPE, [ StmtModifier.Final ])); literalFactory = variable(name_3); this.literalFactories.set(key, literalFactory); } return { literalFactory: literalFactory, literalFactoryArguments: literalFactoryArguments }; }; /** * Produce a unique name. * * The name might be unique among different prefixes if any of the prefixes end in * a digit so the prefix should be a constant string (not based on user input) and * must not end in a digit. */ ConstantPool.prototype.uniqueName = function (prefix) { return "" + prefix + this.nextNameIndex++; }; ConstantPool.prototype.definitionsOf = function (kind) { switch (kind) { case 2 /* Component */: return this.componentDefinitions; case 1 /* Directive */: return this.directiveDefinitions; case 0 /* Injector */: return this.injectorDefinitions; case 3 /* Pipe */: return this.pipeDefinitions; } error("Unknown definition kind " + kind); return this.componentDefinitions; }; ConstantPool.prototype.propertyNameOf = function (kind) { switch (kind) { case 2 /* Component */: return 'ɵcmp'; case 1 /* Directive */: return 'ɵdir'; case 0 /* Injector */: return 'ɵinj'; case 3 /* Pipe */: return 'ɵpipe'; } error("Unknown definition kind " + kind); return ''; }; ConstantPool.prototype.freshName = function () { return this.uniqueName(CONSTANT_PREFIX); }; ConstantPool.prototype.keyOf = function (expression) { return expression.visitExpression(new KeyVisitor(), KEY_CONTEXT); }; return ConstantPool; }()); /** * Visitor used to determine if 2 expressions are equivalent and can be shared in the * `ConstantPool`. * * When the id (string) generated by the visitor is equal, expressions are considered equivalent. */ var KeyVisitor = /** @class */ (function () { function KeyVisitor() { this.visitWrappedNodeExpr = invalid; this.visitWriteVarExpr = invalid; this.visitWriteKeyExpr = invalid; this.visitWritePropExpr = invalid; this.visitInvokeMethodExpr = invalid; this.visitInvokeFunctionExpr = invalid; this.visitInstantiateExpr = invalid; this.visitConditionalExpr = invalid; this.visitNotExpr = invalid; this.visitAssertNotNullExpr = invalid; this.visitCastExpr = invalid; this.visitFunctionExpr = invalid; this.visitBinaryOperatorExpr = invalid; this.visitReadPropExpr = invalid; this.visitReadKeyExpr = invalid; this.visitCommaExpr = invalid; this.visitLocalizedString = invalid; } KeyVisitor.prototype.visitLiteralExpr = function (ast) { return "" + (typeof ast.value === 'string' ? '"' + ast.value + '"' : ast.value); }; KeyVisitor.prototype.visitLiteralArrayExpr = function (ast, context) { var _this = this; return "[" + ast.entries.map(function (entry) { return entry.visitExpression(_this, context); }).join(',') + "]"; }; KeyVisitor.prototype.visitLiteralMapExpr = function (ast, context) { var _this = this; var mapKey = function (entry) { var quote = entry.quoted ? '"' : ''; return "" + quote + entry.key + quote; }; var mapEntry = function (entry) { return mapKey(entry) + ":" + entry.value.visitExpression(_this, context); }; return "{" + ast.entries.map(mapEntry).join(','); }; KeyVisitor.prototype.visitExternalExpr = function (ast) { return ast.value.moduleName ? "EX:" + ast.value.moduleName + ":" + ast.value.name : "EX:" + ast.value.runtime.name; }; KeyVisitor.prototype.visitReadVarExpr = function (node) { return "VAR:" + node.name; }; KeyVisitor.prototype.visitTypeofExpr = function (node, context) { return "TYPEOF:" + node.expr.visitExpression(this, context); }; return KeyVisitor; }()); function invalid(arg) { throw new Error("Invalid state: Visitor " + this.constructor.name + " doesn't handle " + arg.constructor.name); } function isVariable(e) { return e instanceof ReadVarExpr; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var CORE = '@angular/core'; var Identifiers = /** @class */ (function () { function Identifiers() { } Identifiers.ANALYZE_FOR_ENTRY_COMPONENTS = { name: 'ANALYZE_FOR_ENTRY_COMPONENTS', moduleName: CORE, }; Identifiers.ElementRef = { name: 'ElementRef', moduleName: CORE }; Identifiers.NgModuleRef = { name: 'NgModuleRef', moduleName: CORE }; Identifiers.ViewContainerRef = { name: 'ViewContainerRef', moduleName: CORE }; Identifiers.ChangeDetectorRef = { name: 'ChangeDetectorRef', moduleName: CORE, }; Identifiers.QueryList = { name: 'QueryList', moduleName: CORE }; Identifiers.TemplateRef = { name: 'TemplateRef', moduleName: CORE }; Identifiers.Renderer2 = { name: 'Renderer2', moduleName: CORE }; Identifiers.CodegenComponentFactoryResolver = { name: 'ɵCodegenComponentFactoryResolver', moduleName: CORE, }; Identifiers.ComponentFactoryResolver = { name: 'ComponentFactoryResolver', moduleName: CORE, }; Identifiers.ComponentFactory = { name: 'ComponentFactory', moduleName: CORE }; Identifiers.ComponentRef = { name: 'ComponentRef', moduleName: CORE }; Identifiers.NgModuleFactory = { name: 'NgModuleFactory', moduleName: CORE }; Identifiers.createModuleFactory = { name: 'ɵcmf', moduleName: CORE, }; Identifiers.moduleDef = { name: 'ɵmod', moduleName: CORE, }; Identifiers.moduleProviderDef = { name: 'ɵmpd', moduleName: CORE, }; Identifiers.RegisterModuleFactoryFn = { name: 'ɵregisterModuleFactory', moduleName: CORE, }; Identifiers.inject = { name: 'ɵɵinject', moduleName: CORE }; Identifiers.directiveInject = { name: 'ɵɵdirectiveInject', moduleName: CORE }; Identifiers.INJECTOR = { name: 'INJECTOR', moduleName: CORE }; Identifiers.Injector = { name: 'Injector', moduleName: CORE }; Identifiers.ɵɵdefineInjectable = { name: 'ɵɵdefineInjectable', moduleName: CORE }; Identifiers.InjectableDef = { name: 'ɵɵInjectableDef', moduleName: CORE }; Identifiers.ViewEncapsulation = { name: 'ViewEncapsulation', moduleName: CORE, }; Identifiers.ChangeDetectionStrategy = { name: 'ChangeDetectionStrategy', moduleName: CORE, }; Identifiers.SecurityContext = { name: 'SecurityContext', moduleName: CORE, }; Identifiers.LOCALE_ID = { name: 'LOCALE_ID', moduleName: CORE }; Identifiers.TRANSLATIONS_FORMAT = { name: 'TRANSLATIONS_FORMAT', moduleName: CORE, }; Identifiers.inlineInterpolate = { name: 'ɵinlineInterpolate', moduleName: CORE, }; Identifiers.interpolate = { name: 'ɵinterpolate', moduleName: CORE }; Identifiers.EMPTY_ARRAY = { name: 'ɵEMPTY_ARRAY', moduleName: CORE }; Identifiers.EMPTY_MAP = { name: 'ɵEMPTY_MAP', moduleName: CORE }; Identifiers.Renderer = { name: 'Renderer', moduleName: CORE }; Identifiers.viewDef = { name: 'ɵvid', moduleName: CORE }; Identifiers.elementDef = { name: 'ɵeld', moduleName: CORE }; Identifiers.anchorDef = { name: 'ɵand', moduleName: CORE }; Identifiers.textDef = { name: 'ɵted', moduleName: CORE }; Identifiers.directiveDef = { name: 'ɵdid', moduleName: CORE }; Identifiers.providerDef = { name: 'ɵprd', moduleName: CORE }; Identifiers.queryDef = { name: 'ɵqud', moduleName: CORE }; Identifiers.pureArrayDef = { name: 'ɵpad', moduleName: CORE }; Identifiers.pureObjectDef = { name: 'ɵpod', moduleName: CORE }; Identifiers.purePipeDef = { name: 'ɵppd', moduleName: CORE }; Identifiers.pipeDef = { name: 'ɵpid', moduleName: CORE }; Identifiers.nodeValue = { name: 'ɵnov', moduleName: CORE }; Identifiers.ngContentDef = { name: 'ɵncd', moduleName: CORE }; Identifiers.unwrapValue = { name: 'ɵunv', moduleName: CORE }; Identifiers.createRendererType2 = { name: 'ɵcrt', moduleName: CORE }; // type only Identifiers.RendererType2 = { name: 'RendererType2', moduleName: CORE, }; // type only Identifiers.ViewDefinition = { name: 'ɵViewDefinition', moduleName: CORE, }; Identifiers.createComponentFactory = { name: 'ɵccf', moduleName: CORE }; Identifiers.setClassMetadata = { name: 'ɵsetClassMetadata', moduleName: CORE }; return Identifiers; }()); function createTokenForReference(reference) { return { identifier: { reference: reference } }; } function createTokenForExternalReference(reflector, reference) { return createTokenForReference(reflector.resolveExternalReference(reference)); } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * A token representing the a reference to a static type. * * This token is unique for a filePath and name and can be used as a hash table key. */ var StaticSymbol = /** @class */ (function () { function StaticSymbol(filePath, name, members) { this.filePath = filePath; this.name = name; this.members = members; } StaticSymbol.prototype.assertNoMembers = function () { if (this.members.length) { throw new Error("Illegal state: symbol without members expected, but got " + JSON.stringify(this) + "."); } }; return StaticSymbol; }()); /** * A cache of static symbol used by the StaticReflector to return the same symbol for the * same symbol values. */ var StaticSymbolCache = /** @class */ (function () { function StaticSymbolCache() { this.cache = new Map(); } StaticSymbolCache.prototype.get = function (declarationFile, name, members) { members = members || []; var memberSuffix = members.length ? "." + members.join('.') : ''; var key = "\"" + declarationFile + "\"." + name + memberSuffix; var result = this.cache.get(key); if (!result) { result = new StaticSymbol(declarationFile, name, members); this.cache.set(key, result); } return result; }; return StaticSymbolCache; }()); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // group 0: "[prop] or (event) or @trigger" // group 1: "prop" from "[prop]" // group 2: "event" from "(event)" // group 3: "@trigger" from "@trigger" var HOST_REG_EXP = /^(?:(?:\[([^\]]+)\])|(?:\(([^\)]+)\)))|(\@[-\w]+)$/; function sanitizeIdentifier(name) { return name.replace(/\W/g, '_'); } var _anonymousTypeIndex = 0; function identifierName(compileIdentifier) { if (!compileIdentifier || !compileIdentifier.reference) { return null; } var ref = compileIdentifier.reference; if (ref instanceof StaticSymbol) { return ref.name; } if (ref['__anonymousType']) { return ref['__anonymousType']; } var identifier = stringify(ref); if (identifier.indexOf('(') >= 0) { // case: anonymous functions! identifier = "anonymous_" + _anonymousTypeIndex++; ref['__anonymousType'] = identifier; } else { identifier = sanitizeIdentifier(identifier); } return identifier; } function identifierModuleUrl(compileIdentifier) { var ref = compileIdentifier.reference; if (ref instanceof StaticSymbol) { return ref.filePath; } // Runtime type return "./" + stringify(ref); } function viewClassName(compType, embeddedTemplateIndex) { return "View_" + identifierName({ reference: compType }) + "_" + embeddedTemplateIndex; } function rendererTypeName(compType) { return "RenderType_" + identifierName({ reference: compType }); } function hostViewClassName(compType) { return "HostView_" + identifierName({ reference: compType }); } function componentFactoryName(compType) { return identifierName({ reference: compType }) + "NgFactory"; } var CompileSummaryKind; (function (CompileSummaryKind) { CompileSummaryKind[CompileSummaryKind["Pipe"] = 0] = "Pipe"; CompileSummaryKind[CompileSummaryKind["Directive"] = 1] = "Directive"; CompileSummaryKind[CompileSummaryKind["NgModule"] = 2] = "NgModule"; CompileSummaryKind[CompileSummaryKind["Injectable"] = 3] = "Injectable"; })(CompileSummaryKind || (CompileSummaryKind = {})); function tokenName(token) { return token.value != null ? sanitizeIdentifier(token.value) : identifierName(token.identifier); } function tokenReference(token) { if (token.identifier != null) { return token.identifier.reference; } else { return token.value; } } /** * Metadata about a stylesheet */ var CompileStylesheetMetadata = /** @class */ (function () { function CompileStylesheetMetadata(_a) { var _b = _a === void 0 ? {} : _a, moduleUrl = _b.moduleUrl, styles = _b.styles, styleUrls = _b.styleUrls; this.moduleUrl = moduleUrl || null; this.styles = _normalizeArray(styles); this.styleUrls = _normalizeArray(styleUrls); } return CompileStylesheetMetadata; }()); /** * Metadata regarding compilation of a template. */ var CompileTemplateMetadata = /** @class */ (function () { function CompileTemplateMetadata(_a) { 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; this.encapsulation = encapsulation; this.template = template; this.templateUrl = templateUrl; this.htmlAst = htmlAst; this.styles = _normalizeArray(styles); this.styleUrls = _normalizeArray(styleUrls); this.externalStylesheets = _normalizeArray(externalStylesheets); this.animations = animations ? flatten(animations) : []; this.ngContentSelectors = ngContentSelectors || []; if (interpolation && interpolation.length != 2) { throw new Error("'interpolation' should have a start and an end symbol."); } this.interpolation = interpolation; this.isInline = isInline; this.preserveWhitespaces = preserveWhitespaces; } CompileTemplateMetadata.prototype.toSummary = function () { return { ngContentSelectors: this.ngContentSelectors, encapsulation: this.encapsulation, styles: this.styles, animations: this.animations }; }; return CompileTemplateMetadata; }()); /** * Metadata regarding compilation of a directive. */ var CompileDirectiveMetadata = /** @class */ (function () { function CompileDirectiveMetadata(_a) { 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; this.isHost = !!isHost; this.type = type; this.isComponent = isComponent; this.selector = selector; this.exportAs = exportAs; this.changeDetection = changeDetection; this.inputs = inputs; this.outputs = outputs; this.hostListeners = hostListeners; this.hostProperties = hostProperties; this.hostAttributes = hostAttributes; this.providers = _normalizeArray(providers); this.viewProviders = _normalizeArray(viewProviders); this.queries = _normalizeArray(queries); this.guards = guards; this.viewQueries = _normalizeArray(viewQueries); this.entryComponents = _normalizeArray(entryComponents); this.template = template; this.componentViewType = componentViewType; this.rendererType = rendererType; this.componentFactory = componentFactory; } CompileDirectiveMetadata.create = function (_a) { 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; var hostListeners = {}; var hostProperties = {}; var hostAttributes = {}; if (host != null) { Object.keys(host).forEach(function (key) { var value = host[key]; var matches = key.match(HOST_REG_EXP); if (matches === null) { hostAttributes[key] = value; } else if (matches[1] != null) { hostProperties[matches[1]] = value; } else if (matches[2] != null) { hostListeners[matches[2]] = value; } }); } var inputsMap = {}; if (inputs != null) { inputs.forEach(function (bindConfig) { // canonical syntax: `dirProp: elProp` // if there is no `:`, use dirProp = elProp var parts = splitAtColon(bindConfig, [bindConfig, bindConfig]); inputsMap[parts[0]] = parts[1]; }); } var outputsMap = {}; if (outputs != null) { outputs.forEach(function (bindConfig) { // canonical syntax: `dirProp: elProp` // if there is no `:`, use dirProp = elProp var parts = splitAtColon(bindConfig, [bindConfig, bindConfig]); outputsMap[parts[0]] = parts[1]; }); } return new CompileDirectiveMetadata({ isHost: isHost, type: type, isComponent: !!isComponent, selector: selector, exportAs: exportAs, changeDetection: changeDetection, inputs: inputsMap, outputs: outputsMap, hostListeners: hostListeners, hostProperties: hostProperties, hostAttributes: hostAttributes, providers: providers, viewProviders: viewProviders, queries: queries, guards: guards, viewQueries: viewQueries, entryComponents: entryComponents, template: template, componentViewType: componentViewType, rendererType: rendererType, componentFactory: componentFactory, }); }; CompileDirectiveMetadata.prototype.toSummary = function () { return { summaryKind: CompileSummaryKind.Directive, type: this.type, isComponent: this.isComponent, selector: this.selector, exportAs: this.exportAs, inputs: this.inputs, outputs: this.outputs, hostListeners: this.hostListeners, hostProperties: this.hostProperties, hostAttributes: this.hostAttributes, providers: this.providers, viewProviders: this.viewProviders, queries: this.queries, guards: this.guards, viewQueries: this.viewQueries, entryComponents: this.entryComponents, changeDetection: this.changeDetection, template: this.template && this.template.toSummary(), componentViewType: this.componentViewType, rendererType: this.rendererType, componentFactory: this.componentFactory }; }; return CompileDirectiveMetadata; }()); var CompilePipeMetadata = /** @class */ (function () { function CompilePipeMetadata(_a) { var type = _a.type, name = _a.name, pure = _a.pure; this.type = type; this.name = name; this.pure = !!pure; } CompilePipeMetadata.prototype.toSummary = function () { return { summaryKind: CompileSummaryKind.Pipe, type: this.type, name: this.name, pure: this.pure }; }; return CompilePipeMetadata; }()); var CompileShallowModuleMetadata = /** @class */ (function () { function CompileShallowModuleMetadata() { } return CompileShallowModuleMetadata; }()); /** * Metadata regarding compilation of a module. */ var CompileNgModuleMetadata = /** @class */ (function () { function CompileNgModuleMetadata(_a) { 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; this.type = type || null; this.declaredDirectives = _normalizeArray(declaredDirectives); this.exportedDirectives = _normalizeArray(exportedDirectives); this.declaredPipes = _normalizeArray(declaredPipes); this.exportedPipes = _normalizeArray(exportedPipes); this.providers = _normalizeArray(providers); this.entryComponents = _normalizeArray(entryComponents); this.bootstrapComponents = _normalizeArray(bootstrapComponents); this.importedModules = _normalizeArray(importedModules); this.exportedModules = _normalizeArray(exportedModules); this.schemas = _normalizeArray(schemas); this.id = id || null; this.transitiveModule = transitiveModule || null; } CompileNgModuleMetadata.prototype.toSummary = function () { var module = this.transitiveModule; return { summaryKind: CompileSummaryKind.NgModule, type: this.type, entryComponents: module.entryComponents, providers: module.providers, modules: module.modules, exportedDirectives: module.exportedDirectives, exportedPipes: module.exportedPipes }; }; return CompileNgModuleMetadata; }()); var TransitiveCompileNgModuleMetadata = /** @class */ (function () { function TransitiveCompileNgModuleMetadata() { this.directivesSet = new Set(); this.directives = []; this.exportedDirectivesSet = new Set(); this.exportedDirectives = []; this.pipesSet = new Set(); this.pipes = []; this.exportedPipesSet = new Set(); this.exportedPipes = []; this.modulesSet = new Set(); this.modules = []; this.entryComponentsSet = new Set(); this.entryComponents = []; this.providers = []; } TransitiveCompileNgModuleMetadata.prototype.addProvider = function (provider, module) { this.providers.push({ provider: provider, module: module }); }; TransitiveCompileNgModuleMetadata.prototype.addDirective = function (id) { if (!this.directivesSet.has(id.reference)) { this.directivesSet.add(id.reference); this.directives.push(id); } }; TransitiveCompileNgModuleMetadata.prototype.addExportedDirective = function (id) { if (!this.exportedDirectivesSet.has(id.reference)) { this.exportedDirectivesSet.add(id.reference); this.exportedDirectives.push(id); } }; TransitiveCompileNgModuleMetadata.prototype.addPipe = function (id) { if (!this.pipesSet.has(id.reference)) { this.pipesSet.add(id.reference); this.pipes.push(id); } }; TransitiveCompileNgModuleMetadata.prototype.addExportedPipe = function (id) { if (!this.exportedPipesSet.has(id.reference)) { this.exportedPipesSet.add(id.reference); this.exportedPipes.push(id); } }; TransitiveCompileNgModuleMetadata.prototype.addModule = function (id) { if (!this.modulesSet.has(id.reference)) { this.modulesSet.add(id.reference); this.modules.push(id); } }; TransitiveCompileNgModuleMetadata.prototype.addEntryComponent = function (ec) { if (!this.entryComponentsSet.has(ec.componentType)) { this.entryComponentsSet.add(ec.componentType); this.entryComponents.push(ec); } }; return TransitiveCompileNgModuleMetadata; }()); function _normalizeArray(obj) { return obj || []; } var ProviderMeta = /** @class */ (function () { function ProviderMeta(token, _a) { var useClass = _a.useClass, useValue = _a.useValue, useExisting = _a.useExisting, useFactory = _a.useFactory, deps = _a.deps, multi = _a.multi; this.token = token; this.useClass = useClass || null; this.useValue = useValue; this.useExisting = useExisting; this.useFactory = useFactory || null; this.dependencies = deps || null; this.multi = !!multi; } return ProviderMeta; }()); function flatten(list) { return list.reduce(function (flat, item) { var flatItem = Array.isArray(item) ? flatten(item) : item; return flat.concat(flatItem); }, []); } function jitSourceUrl(url) { // Note: We need 3 "/" so that ng shows up as a separate domain // in the chrome dev tools. return url.replace(/(\w+:\/\/[\w:-]+)?(\/+)?/, 'ng:///'); } function templateSourceUrl(ngModuleType, compMeta, templateMeta) { var url; if (templateMeta.isInline) { if (compMeta.type.reference instanceof StaticSymbol) { // Note: a .ts file might contain multiple components with inline templates, // so we need to give them unique urls, as these will be used for sourcemaps. url = compMeta.type.reference.filePath + "." + compMeta.type.reference.name + ".html"; } else { url = identifierName(ngModuleType) + "/" + identifierName(compMeta.type) + ".html"; } } else { url = templateMeta.templateUrl; } return compMeta.type.reference instanceof StaticSymbol ? url : jitSourceUrl(url); } function sharedStylesheetJitUrl(meta, id) { var pathParts = meta.moduleUrl.split(/\/\\/g); var baseName = pathParts[pathParts.length - 1]; return jitSourceUrl("css/" + id + baseName + ".ngstyle.js"); } function ngModuleJitUrl(moduleMeta) { return jitSourceUrl(identifierName(moduleMeta.type) + "/module.ngfactory.js"); } function templateJitUrl(ngModuleType, compMeta) { return jitSourceUrl(identifierName(ngModuleType) + "/" + identifierName(compMeta.type) + ".ngfactory.js"); } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var CORE$1 = '@angular/core'; var Identifiers$1 = /** @class */ (function () { function Identifiers() { } /* Methods */ Identifiers.NEW_METHOD = 'factory'; Identifiers.TRANSFORM_METHOD = 'transform'; Identifiers.PATCH_DEPS = 'patchedDeps'; /* Instructions */ Identifiers.namespaceHTML = { name: 'ɵɵnamespaceHTML', moduleName: CORE$1 }; Identifiers.namespaceMathML = { name: 'ɵɵnamespaceMathML', moduleName: CORE$1 }; Identifiers.namespaceSVG = { name: 'ɵɵnamespaceSVG', moduleName: CORE$1 }; Identifiers.element = { name: 'ɵɵelement', moduleName: CORE$1 }; Identifiers.elementStart = { name: 'ɵɵelementStart', moduleName: CORE$1 }; Identifiers.elementEnd = { name: 'ɵɵelementEnd', moduleName: CORE$1 }; Identifiers.select = { name: 'ɵɵselect', moduleName: CORE$1 }; Identifiers.advance = { name: 'ɵɵadvance', moduleName: CORE$1 }; Identifiers.updateSyntheticHostBinding = { name: 'ɵɵupdateSyntheticHostBinding', moduleName: CORE$1 }; Identifiers.componentHostSyntheticListener = { name: 'ɵɵcomponentHostSyntheticListener', moduleName: CORE$1 }; Identifiers.attribute = { name: 'ɵɵattribute', moduleName: CORE$1 }; Identifiers.attributeInterpolate1 = { name: 'ɵɵattributeInterpolate1', moduleName: CORE$1 }; Identifiers.attributeInterpolate2 = { name: 'ɵɵattributeInterpolate2', moduleName: CORE$1 }; Identifiers.attributeInterpolate3 = { name: 'ɵɵattributeInterpolate3', moduleName: CORE$1 }; Identifiers.attributeInterpolate4 = { name: 'ɵɵattributeInterpolate4', moduleName: CORE$1 }; Identifiers.attributeInterpolate5 = { name: 'ɵɵattributeInterpolate5', moduleName: CORE$1 }; Identifiers.attributeInterpolate6 = { name: 'ɵɵattributeInterpolate6', moduleName: CORE$1 }; Identifiers.attributeInterpolate7 = { name: 'ɵɵattributeInterpolate7', moduleName: CORE$1 }; Identifiers.attributeInterpolate8 = { name: 'ɵɵattributeInterpolate8', moduleName: CORE$1 }; Identifiers.attributeInterpolateV = { name: 'ɵɵattributeInterpolateV', moduleName: CORE$1 }; Identifiers.classProp = { name: 'ɵɵclassProp', moduleName: CORE$1 }; Identifiers.elementContainerStart = { name: 'ɵɵelementContainerStart', moduleName: CORE$1 }; Identifiers.elementContainerEnd = { name: 'ɵɵelementContainerEnd', moduleName: CORE$1 }; Identifiers.elementContainer = { name: 'ɵɵelementContainer', moduleName: CORE$1 }; Identifiers.styleMap = { name: 'ɵɵstyleMap', moduleName: CORE$1 }; Identifiers.styleMapInterpolate1 = { name: 'ɵɵstyleMapInterpolate1', moduleName: CORE$1 }; Identifiers.styleMapInterpolate2 = { name: 'ɵɵstyleMapInterpolate2', moduleName: CORE$1 }; Identifiers.styleMapInterpolate3 = { name: 'ɵɵstyleMapInterpolate3', moduleName: CORE$1 }; Identifiers.styleMapInterpolate4 = { name: 'ɵɵstyleMapInterpolate4', moduleName: CORE$1 }; Identifiers.styleMapInterpolate5 = { name: 'ɵɵstyleMapInterpolate5', moduleName: CORE$1 }; Identifiers.styleMapInterpolate6 = { name: 'ɵɵstyleMapInterpolate6', moduleName: CORE$1 }; Identifiers.styleMapInterpolate7 = { name: 'ɵɵstyleMapInterpolate7', moduleName: CORE$1 }; Identifiers.styleMapInterpolate8 = { name: 'ɵɵstyleMapInterpolate8', moduleName: CORE$1 }; Identifiers.styleMapInterpolateV = { name: 'ɵɵstyleMapInterpolateV', moduleName: CORE$1 }; Identifiers.classMap = { name: 'ɵɵclassMap', moduleName: CORE$1 }; Identifiers.classMapInterpolate1 = { name: 'ɵɵclassMapInterpolate1', moduleName: CORE$1 }; Identifiers.classMapInterpolate2 = { name: 'ɵɵclassMapInterpolate2', moduleName: CORE$1 }; Identifiers.classMapInterpolate3 = { name: 'ɵɵclassMapInterpolate3', moduleName: CORE$1 }; Identifiers.classMapInterpolate4 = { name: 'ɵɵclassMapInterpolate4', moduleName: CORE$1 }; Identifiers.classMapInterpolate5 = { name: 'ɵɵclassMapInterpolate5', moduleName: CORE$1 }; Identifiers.classMapInterpolate6 = { name: 'ɵɵclassMapInterpolate6', moduleName: CORE$1 }; Identifiers.classMapInterpolate7 = { name: 'ɵɵclassMapInterpolate7', moduleName: CORE$1 }; Identifiers.classMapInterpolate8 = { name: 'ɵɵclassMapInterpolate8', moduleName: CORE$1 }; Identifiers.classMapInterpolateV = { name: 'ɵɵclassMapInterpolateV', moduleName: CORE$1 }; Identifiers.styleProp = { name: 'ɵɵstyleProp', moduleName: CORE$1 }; Identifiers.stylePropInterpolate1 = { name: 'ɵɵstylePropInterpolate1', moduleName: CORE$1 }; Identifiers.stylePropInterpolate2 = { name: 'ɵɵstylePropInterpolate2', moduleName: CORE$1 }; Identifiers.stylePropInterpolate3 = { name: 'ɵɵstylePropInterpolate3', moduleName: CORE$1 }; Identifiers.stylePropInterpolate4 = { name: 'ɵɵstylePropInterpolate4', moduleName: CORE$1 }; Identifiers.stylePropInterpolate5 = { name: 'ɵɵstylePropInterpolate5', moduleName: CORE$1 }; Identifiers.stylePropInterpolate6 = { name: 'ɵɵstylePropInterpolate6', moduleName: CORE$1 }; Identifiers.stylePropInterpolate7 = { name: 'ɵɵstylePropInterpolate7', moduleName: CORE$1 }; Identifiers.stylePropInterpolate8 = { name: 'ɵɵstylePropInterpolate8', moduleName: CORE$1 }; Identifiers.stylePropInterpolateV = { name: 'ɵɵstylePropInterpolateV', moduleName: CORE$1 }; Identifiers.containerCreate = { name: 'ɵɵcontainer', moduleName: CORE$1 }; Identifiers.nextContext = { name: 'ɵɵnextContext', moduleName: CORE$1 }; Identifiers.templateCreate = { name: 'ɵɵtemplate', moduleName: CORE$1 }; Identifiers.text = { name: 'ɵɵtext', moduleName: CORE$1 }; Identifiers.enableBindings = { name: 'ɵɵenableBindings', moduleName: CORE$1 }; Identifiers.disableBindings = { name: 'ɵɵdisableBindings', moduleName: CORE$1 }; Identifiers.getCurrentView = { name: 'ɵɵgetCurrentView', moduleName: CORE$1 }; Identifiers.textInterpolate = { name: 'ɵɵtextInterpolate', moduleName: CORE$1 }; Identifiers.textInterpolate1 = { name: 'ɵɵtextInterpolate1', moduleName: CORE$1 }; Identifiers.textInterpolate2 = { name: 'ɵɵtextInterpolate2', moduleName: CORE$1 }; Identifiers.textInterpolate3 = { name: 'ɵɵtextInterpolate3', moduleName: CORE$1 }; Identifiers.textInterpolate4 = { name: 'ɵɵtextInterpolate4', moduleName: CORE$1 }; Identifiers.textInterpolate5 = { name: 'ɵɵtextInterpolate5', moduleName: CORE$1 }; Identifiers.textInterpolate6 = { name: 'ɵɵtextInterpolate6', moduleName: CORE$1 }; Identifiers.textInterpolate7 = { name: 'ɵɵtextInterpolate7', moduleName: CORE$1 }; Identifiers.textInterpolate8 = { name: 'ɵɵtextInterpolate8', moduleName: CORE$1 }; Identifiers.textInterpolateV = { name: 'ɵɵtextInterpolateV', moduleName: CORE$1 }; Identifiers.restoreView = { name: 'ɵɵrestoreView', moduleName: CORE$1 }; Identifiers.pureFunction0 = { name: 'ɵɵpureFunction0', moduleName: CORE$1 }; Identifiers.pureFunction1 = { name: 'ɵɵpureFunction1', moduleName: CORE$1 }; Identifiers.pureFunction2 = { name: 'ɵɵpureFunction2', moduleName: CORE$1 }; Identifiers.pureFunction3 = { name: 'ɵɵpureFunction3', moduleName: CORE$1 }; Identifiers.pureFunction4 = { name: 'ɵɵpureFunction4', moduleName: CORE$1 }; Identifiers.pureFunction5 = { name: 'ɵɵpureFunction5', moduleName: CORE$1 }; Identifiers.pureFunction6 = { name: 'ɵɵpureFunction6', moduleName: CORE$1 }; Identifiers.pureFunction7 = { name: 'ɵɵpureFunction7', moduleName: CORE$1 }; Identifiers.pureFunction8 = { name: 'ɵɵpureFunction8', moduleName: CORE$1 }; Identifiers.pureFunctionV = { name: 'ɵɵpureFunctionV', moduleName: CORE$1 }; Identifiers.pipeBind1 = { name: 'ɵɵpipeBind1', moduleName: CORE$1 }; Identifiers.pipeBind2 = { name: 'ɵɵpipeBind2', moduleName: CORE$1 }; Identifiers.pipeBind3 = { name: 'ɵɵpipeBind3', moduleName: CORE$1 }; Identifiers.pipeBind4 = { name: 'ɵɵpipeBind4', moduleName: CORE$1 }; Identifiers.pipeBindV = { name: 'ɵɵpipeBindV', moduleName: CORE$1 }; Identifiers.hostProperty = { name: 'ɵɵhostProperty', moduleName: CORE$1 }; Identifiers.property = { name: 'ɵɵproperty', moduleName: CORE$1 }; Identifiers.propertyInterpolate = { name: 'ɵɵpropertyInterpolate', moduleName: CORE$1 }; Identifiers.propertyInterpolate1 = { name: 'ɵɵpropertyInterpolate1', moduleName: CORE$1 }; Identifiers.propertyInterpolate2 = { name: 'ɵɵpropertyInterpolate2', moduleName: CORE$1 }; Identifiers.propertyInterpolate3 = { name: 'ɵɵpropertyInterpolate3', moduleName: CORE$1 }; Identifiers.propertyInterpolate4 = { name: 'ɵɵpropertyInterpolate4', moduleName: CORE$1 }; Identifiers.propertyInterpolate5 = { name: 'ɵɵpropertyInterpolate5', moduleName: CORE$1 }; Identifiers.propertyInterpolate6 = { name: 'ɵɵpropertyInterpolate6', moduleName: CORE$1 }; Identifiers.propertyInterpolate7 = { name: 'ɵɵpropertyInterpolate7', moduleName: CORE$1 }; Identifiers.propertyInterpolate8 = { name: 'ɵɵpropertyInterpolate8', moduleName: CORE$1 }; Identifiers.propertyInterpolateV = { name: 'ɵɵpropertyInterpolateV', moduleName: CORE$1 }; Identifiers.i18n = { name: 'ɵɵi18n', moduleName: CORE$1 }; Identifiers.i18nAttributes = { name: 'ɵɵi18nAttributes', moduleName: CORE$1 }; Identifiers.i18nExp = { name: 'ɵɵi18nExp', moduleName: CORE$1 }; Identifiers.i18nStart = { name: 'ɵɵi18nStart', moduleName: CORE$1 }; Identifiers.i18nEnd = { name: 'ɵɵi18nEnd', moduleName: CORE$1 }; Identifiers.i18nApply = { name: 'ɵɵi18nApply', moduleName: CORE$1 }; Identifiers.i18nPostprocess = { name: 'ɵɵi18nPostprocess', moduleName: CORE$1 }; Identifiers.pipe = { name: 'ɵɵpipe', moduleName: CORE$1 }; Identifiers.projection = { name: 'ɵɵprojection', moduleName: CORE$1 }; Identifiers.projectionDef = { name: 'ɵɵprojectionDef', moduleName: CORE$1 }; Identifiers.reference = { name: 'ɵɵreference', moduleName: CORE$1 }; Identifiers.inject = { name: 'ɵɵinject', moduleName: CORE$1 }; Identifiers.injectAttribute = { name: 'ɵɵinjectAttribute', moduleName: CORE$1 }; Identifiers.injectPipeChangeDetectorRef = { name: 'ɵɵinjectPipeChangeDetectorRef', moduleName: CORE$1 }; Identifiers.directiveInject = { name: 'ɵɵdirectiveInject', moduleName: CORE$1 }; Identifiers.invalidFactory = { name: 'ɵɵinvalidFactory', moduleName: CORE$1 }; Identifiers.invalidFactoryDep = { name: 'ɵɵinvalidFactoryDep', moduleName: CORE$1 }; Identifiers.templateRefExtractor = { name: 'ɵɵtemplateRefExtractor', moduleName: CORE$1 }; Identifiers.resolveWindow = { name: 'ɵɵresolveWindow', moduleName: CORE$1 }; Identifiers.resolveDocument = { name: 'ɵɵresolveDocument', moduleName: CORE$1 }; Identifiers.resolveBody = { name: 'ɵɵresolveBody', moduleName: CORE$1 }; Identifiers.defineComponent = { name: 'ɵɵdefineComponent', moduleName: CORE$1 }; Identifiers.setComponentScope = { name: 'ɵɵsetComponentScope', moduleName: CORE$1 }; Identifiers.ComponentDefWithMeta = { name: 'ɵɵComponentDefWithMeta', moduleName: CORE$1, }; Identifiers.FactoryDef = { name: 'ɵɵFactoryDef', moduleName: CORE$1, }; Identifiers.defineDirective = { name: 'ɵɵdefineDirective', moduleName: CORE$1, }; Identifiers.DirectiveDefWithMeta = { name: 'ɵɵDirectiveDefWithMeta', moduleName: CORE$1, }; Identifiers.InjectorDef = { name: 'ɵɵInjectorDef', moduleName: CORE$1, }; Identifiers.defineInjector = { name: 'ɵɵdefineInjector', moduleName: CORE$1, }; Identifiers.NgModuleDefWithMeta = { name: 'ɵɵNgModuleDefWithMeta', moduleName: CORE$1, }; Identifiers.ModuleWithProviders = { name: 'ModuleWithProviders', moduleName: CORE$1, }; Identifiers.defineNgModule = { name: 'ɵɵdefineNgModule', moduleName: CORE$1 }; Identifiers.setNgModuleScope = { name: 'ɵɵsetNgModuleScope', moduleName: CORE$1 }; Identifiers.PipeDefWithMeta = { name: 'ɵɵPipeDefWithMeta', moduleName: CORE$1 }; Identifiers.definePipe = { name: 'ɵɵdefinePipe', moduleName: CORE$1 }; Identifiers.queryRefresh = { name: 'ɵɵqueryRefresh', moduleName: CORE$1 }; Identifiers.viewQuery = { name: 'ɵɵviewQuery', moduleName: CORE$1 }; Identifiers.staticViewQuery = { name: 'ɵɵstaticViewQuery', moduleName: CORE$1 }; Identifiers.staticContentQuery = { name: 'ɵɵstaticContentQuery', moduleName: CORE$1 }; Identifiers.loadQuery = { name: 'ɵɵloadQuery', moduleName: CORE$1 }; Identifiers.contentQuery = { name: 'ɵɵcontentQuery', moduleName: CORE$1 }; Identifiers.NgOnChangesFeature = { name: 'ɵɵNgOnChangesFeature', moduleName: CORE$1 }; Identifiers.InheritDefinitionFeature = { name: 'ɵɵInheritDefinitionFeature', moduleName: CORE$1 }; Identifiers.CopyDefinitionFeature = { name: 'ɵɵCopyDefinitionFeature', moduleName: CORE$1 }; Identifiers.ProvidersFeature = { name: 'ɵɵProvidersFeature', moduleName: CORE$1 }; Identifiers.listener = { name: 'ɵɵlistener', moduleName: CORE$1 }; Identifiers.getFactoryOf = { name: 'ɵɵgetFactoryOf', moduleName: CORE$1, }; Identifiers.getInheritedFactory = { name: 'ɵɵgetInheritedFactory', moduleName: CORE$1, }; // sanitization-related functions Identifiers.sanitizeHtml = { name: 'ɵɵsanitizeHtml', moduleName: CORE$1 }; Identifiers.sanitizeStyle = { name: 'ɵɵsanitizeStyle', moduleName: CORE$1 }; Identifiers.defaultStyleSanitizer = { name: 'ɵɵdefaultStyleSanitizer', moduleName: CORE$1 }; Identifiers.sanitizeResourceUrl = { name: 'ɵɵsanitizeResourceUrl', moduleName: CORE$1 }; Identifiers.sanitizeScript = { name: 'ɵɵsanitizeScript', moduleName: CORE$1 }; Identifiers.sanitizeUrl = { name: 'ɵɵsanitizeUrl', moduleName: CORE$1 }; Identifiers.sanitizeUrlOrResourceUrl = { name: 'ɵɵsanitizeUrlOrResourceUrl', moduleName: CORE$1 }; return Identifiers; }()); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Convert an object map with `Expression` values into a `LiteralMapExpr`. */ function mapToMapExpression(map) { var result = Object.keys(map).map(function (key) { return ({ key: key, // The assertion here is because really TypeScript doesn't allow us to express that if the // key is present, it will have a value, but this is true in reality. value: map[key], quoted: false, }); }); return literalMap(result); } /** * Convert metadata into an `Expression` in the given `OutputContext`. * * This operation will handle arrays, references to symbols, or literal `null` or `undefined`. */ function convertMetaToOutput(meta, ctx) { if (Array.isArray(meta)) { return literalArr(meta.map(function (entry) { return convertMetaToOutput(entry, ctx); })); } if (meta instanceof StaticSymbol) { return ctx.importExpr(meta); } if (meta == null) { return literal(meta); } throw new Error("Internal error: Unsupported or unknown metadata: " + meta); } function typeWithParameters(type, numParams) { var params = null; if (numParams > 0) { params = []; for (var i = 0; i < numParams; i++) { params.push(DYNAMIC_TYPE); } } return expressionType(type, null, params); } var ANIMATE_SYMBOL_PREFIX = '@'; function prepareSyntheticPropertyName(name) { return "" + ANIMATE_SYMBOL_PREFIX + name; } function prepareSyntheticListenerName(name, phase) { return "" + ANIMATE_SYMBOL_PREFIX + name + "." + phase; } function isSyntheticPropertyOrListener(name) { return name.charAt(0) == ANIMATE_SYMBOL_PREFIX; } function getSyntheticPropertyName(name) { // this will strip out listener phase values... // @foo.start => @foo var i = name.indexOf('.'); name = i > 0 ? name.substring(0, i) : name; if (name.charAt(0) !== ANIMATE_SYMBOL_PREFIX) { name = ANIMATE_SYMBOL_PREFIX + name; } return name; } function prepareSyntheticListenerFunctionName(name, phase) { return "animation_" + name + "_" + phase; } function jitOnlyGuardedExpression(expr) { var ngJitMode = new ExternalExpr({ name: 'ngJitMode', moduleName: null }); var jitFlagNotDefined = new BinaryOperatorExpr(BinaryOperator.Identical, new TypeofExpr(ngJitMode), literal('undefined')); var jitFlagUndefinedOrTrue = new BinaryOperatorExpr(BinaryOperator.Or, jitFlagNotDefined, ngJitMode, /* type */ undefined, /* sourceSpan */ undefined, true); return new BinaryOperatorExpr(BinaryOperator.And, jitFlagUndefinedOrTrue, expr); } function wrapReference(value) { var wrapped = new WrappedNodeExpr(value); return { value: wrapped, type: wrapped }; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var $EOF = 0; var $BSPACE = 8; var $TAB = 9; var $LF = 10; var $VTAB = 11; var $FF = 12; var $CR = 13; var $SPACE = 32; var $BANG = 33; var $DQ = 34; var $HASH = 35; var $$ = 36; var $PERCENT = 37; var $AMPERSAND = 38; var $SQ = 39; var $LPAREN = 40; var $RPAREN = 41; var $STAR = 42; var $PLUS = 43; var $COMMA = 44; var $MINUS = 45; var $PERIOD = 46; var $SLASH = 47; var $COLON = 58; var $SEMICOLON = 59; var $LT = 60; var $EQ = 61; var $GT = 62; var $QUESTION = 63; var $0 = 48; var $7 = 55; var $9 = 57; var $A = 65; var $E = 69; var $F = 70; var $X = 88; var $Z = 90; var $LBRACKET = 91; var $BACKSLASH = 92; var $RBRACKET = 93; var $CARET = 94; var $_ = 95; var $a = 97; var $b = 98; var $e = 101; var $f = 102; var $n = 110; var $r = 114; var $t = 116; var $u = 117; var $v = 118; var $x = 120; var $z = 122; var $LBRACE = 123; var $BAR = 124; var $RBRACE = 125; var $NBSP = 160; var $PIPE = 124; var $TILDA = 126; var $AT = 64; var $BT = 96; function isWhitespace(code) { return (code >= $TAB && code <= $SPACE) || (code == $NBSP); } function isDigit(code) { return $0 <= code && code <= $9; } function isAsciiLetter(code) { return code >= $a && code <= $z || code >= $A && code <= $Z; } function isAsciiHexDigit(code) { return code >= $a && code <= $f || code >= $A && code <= $F || isDigit(code); } function isNewLine(code) { return code === $LF || code === $CR; } function isOctalDigit(code) { return $0 <= code && code <= $7; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var ParseLocation = /** @class */ (function () { function ParseLocation(file, offset, line, col) { this.file = file; this.offset = offset; this.line = line; this.col = col; } ParseLocation.prototype.toString = function () { return this.offset != null ? this.file.url + "@" + this.line + ":" + this.col : this.file.url; }; ParseLocation.prototype.moveBy = function (delta) { var source = this.file.content; var len = source.length; var offset = this.offset; var line = this.line; var col = this.col; while (offset > 0 && delta < 0) { offset--; delta++; var ch = source.charCodeAt(offset); if (ch == $LF) { line--; var priorLine = source.substr(0, offset - 1).lastIndexOf(String.fromCharCode($LF)); col = priorLine > 0 ? offset - priorLine : offset; } else { col--; } } while (offset < len && delta > 0) { var ch = source.charCodeAt(offset); offset++; delta--; if (ch == $LF) { line++; col = 0; } else { col++; } } return new ParseLocation(this.file, offset, line, col); }; // Return the source around the location // Up to `maxChars` or `maxLines` on each side of the location ParseLocation.prototype.getContext = function (maxChars, maxLines) { var content = this.file.content; var startOffset = this.offset; if (startOffset != null) { if (startOffset > content.length - 1) { startOffset = content.length - 1; } var endOffset = startOffset; var ctxChars = 0; var ctxLines = 0; while (ctxChars < maxChars && startOffset > 0) { startOffset--; ctxChars++; if (content[startOffset] == '\n') { if (++ctxLines == maxLines) { break; } } } ctxChars = 0; ctxLines = 0; while (ctxChars < maxChars && endOffset < content.length - 1) { endOffset++; ctxChars++; if (content[endOffset] == '\n') { if (++ctxLines == maxLines) { break; } } } return { before: content.substring(startOffset, this.offset), after: content.substring(this.offset, endOffset + 1), }; } return null; }; return ParseLocation; }()); var ParseSourceFile = /** @class */ (function () { function ParseSourceFile(content, url) { this.content = content; this.url = url; } return ParseSourceFile; }()); var ParseSourceSpan = /** @class */ (function () { function ParseSourceSpan(start, end, details) { if (details === void 0) { details = null; } this.start = start; this.end = end; this.details = details; } ParseSourceSpan.prototype.toString = function () { return this.start.file.content.substring(this.start.offset, this.end.offset); }; return ParseSourceSpan; }()); var EMPTY_PARSE_LOCATION = new ParseLocation(new ParseSourceFile('', ''), 0, 0, 0); var EMPTY_SOURCE_SPAN = new ParseSourceSpan(EMPTY_PARSE_LOCATION, EMPTY_PARSE_LOCATION); var ParseErrorLevel; (function (ParseErrorLevel) { ParseErrorLevel[ParseErrorLevel["WARNING"] = 0] = "WARNING"; ParseErrorLevel[ParseErrorLevel["ERROR"] = 1] = "ERROR"; })(ParseErrorLevel || (ParseErrorLevel = {})); var ParseError = /** @class */ (function () { function ParseError(span, msg, level) { if (level === void 0) { level = ParseErrorLevel.ERROR; } this.span = span; this.msg = msg; this.level = level; } ParseError.prototype.contextualMessage = function () { var ctx = this.span.start.getContext(100, 3); return ctx ? this.msg + " (\"" + ctx.before + "[" + ParseErrorLevel[this.level] + " ->]" + ctx.after + "\")" : this.msg; }; ParseError.prototype.toString = function () { var details = this.span.details ? ", " + this.span.details : ''; return this.contextualMessage() + ": " + this.span.start + details; }; return ParseError; }()); function typeSourceSpan(kind, type) { var moduleUrl = identifierModuleUrl(type); var sourceFileName = moduleUrl != null ? "in " + kind + " " + identifierName(type) + " in " + moduleUrl : "in " + kind + " " + identifierName(type); var sourceFile = new ParseSourceFile('', sourceFileName); return new ParseSourceSpan(new ParseLocation(sourceFile, -1, -1, -1), new ParseLocation(sourceFile, -1, -1, -1)); } /** * Generates Source Span object for a given R3 Type for JIT mode. * * @param kind Component or Directive. * @param typeName name of the Component or Directive. * @param sourceUrl reference to Component or Directive source. * @returns instance of ParseSourceSpan that represent a given Component or Directive. */ function r3JitTypeSourceSpan(kind, typeName, sourceUrl) { var sourceFileName = "in " + kind + " " + typeName + " in " + sourceUrl; var sourceFile = new ParseSourceFile('', sourceFileName); return new ParseSourceSpan(new ParseLocation(sourceFile, -1, -1, -1), new ParseLocation(sourceFile, -1, -1, -1)); } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var Text = /** @class */ (function () { function Text(value, sourceSpan) { this.value = value; this.sourceSpan = sourceSpan; } Text.prototype.visit = function (visitor) { return visitor.visitText(this); }; return Text; }()); var BoundText = /** @class */ (function () { function BoundText(value, sourceSpan, i18n) { this.value = value; this.sourceSpan = sourceSpan; this.i18n = i18n; } BoundText.prototype.visit = function (visitor) { return visitor.visitBoundText(this); }; return BoundText; }()); var TextAttribute = /** @class */ (function () { function TextAttribute(name, value, sourceSpan, valueSpan, i18n) { this.name = name; this.value = value; this.sourceSpan = sourceSpan; this.valueSpan = valueSpan; this.i18n = i18n; } TextAttribute.prototype.visit = function (visitor) { return visitor.visitTextAttribute(this); }; return TextAttribute; }()); var BoundAttribute = /** @class */ (function () { function BoundAttribute(name, type, securityContext, value, unit, sourceSpan, valueSpan, i18n) { this.name = name; this.type = type; this.securityContext = securityContext; this.value = value; this.unit = unit; this.sourceSpan = sourceSpan; this.valueSpan = valueSpan; this.i18n = i18n; } BoundAttribute.fromBoundElementProperty = function (prop, i18n) { return new BoundAttribute(prop.name, prop.type, prop.securityContext, prop.value, prop.unit, prop.sourceSpan, prop.valueSpan, i18n); }; BoundAttribute.prototype.visit = function (visitor) { return visitor.visitBoundAttribute(this); }; return BoundAttribute; }()); var BoundEvent = /** @class */ (function () { function BoundEvent(name, type, handler, target, phase, sourceSpan, handlerSpan) { this.name = name; this.type = type; this.handler = handler; this.target = target; this.phase = phase; this.sourceSpan = sourceSpan; this.handlerSpan = handlerSpan; } BoundEvent.fromParsedEvent = function (event) { var target = event.type === 0 /* Regular */ ? event.targetOrPhase : null; var phase = event.type === 1 /* Animation */ ? event.targetOrPhase : null; return new BoundEvent(event.name, event.type, event.handler, target, phase, event.sourceSpan, event.handlerSpan); }; BoundEvent.prototype.visit = function (visitor) { return visitor.visitBoundEvent(this); }; return BoundEvent; }()); var Element = /** @class */ (function () { function Element(name, attributes, inputs, outputs, children, references, sourceSpan, startSourceSpan, endSourceSpan, i18n) { this.name = name; this.attributes = attributes; this.inputs = inputs; this.outputs = outputs; this.children = children; this.references = references; this.sourceSpan = sourceSpan; this.startSourceSpan = startSourceSpan; this.endSourceSpan = endSourceSpan; this.i18n = i18n; // If the element is empty then the source span should include any closing tag if (children.length === 0 && startSourceSpan && endSourceSpan) { this.sourceSpan = new ParseSourceSpan(sourceSpan.start, endSourceSpan.end); } } Element.prototype.visit = function (visitor) { return visitor.visitElement(this); }; return Element; }()); var Template = /** @class */ (function () { function Template(tagName, attributes, inputs, outputs, templateAttrs, children, references, variables, sourceSpan, startSourceSpan, endSourceSpan, i18n) { this.tagName = tagName; this.attributes = attributes; this.inputs = inputs; this.outputs = outputs; this.templateAttrs = templateAttrs; this.children = children; this.references = references; this.variables = variables; this.sourceSpan = sourceSpan; this.startSourceSpan = startSourceSpan; this.endSourceSpan = endSourceSpan; this.i18n = i18n; } Template.prototype.visit = function (visitor) { return visitor.visitTemplate(this); }; return Template; }()); var Content = /** @class */ (function () { function Content(selector, attributes, sourceSpan, i18n) { this.selector = selector; this.attributes = attributes; this.sourceSpan = sourceSpan; this.i18n = i18n; } Content.prototype.visit = function (visitor) { return visitor.visitContent(this); }; return Content; }()); var Variable = /** @class */ (function () { function Variable(name, value, sourceSpan, valueSpan) { this.name = name; this.value = value; this.sourceSpan = sourceSpan; this.valueSpan = valueSpan; } Variable.prototype.visit = function (visitor) { return visitor.visitVariable(this); }; return Variable; }()); var Reference = /** @class */ (function () { function Reference(name, value, sourceSpan, valueSpan) { this.name = name; this.value = value; this.sourceSpan = sourceSpan; this.valueSpan = valueSpan; } Reference.prototype.visit = function (visitor) { return visitor.visitReference(this); }; return Reference; }()); var Icu = /** @class */ (function () { function Icu(vars, placeholders, sourceSpan, i18n) { this.vars = vars; this.placeholders = placeholders; this.sourceSpan = sourceSpan; this.i18n = i18n; } Icu.prototype.visit = function (visitor) { return visitor.visitIcu(this); }; return Icu; }()); var NullVisitor = /** @class */ (function () { function NullVisitor() { } NullVisitor.prototype.visitElement = function (element) { }; NullVisitor.prototype.visitTemplate = function (template) { }; NullVisitor.prototype.visitContent = function (content) { }; NullVisitor.prototype.visitVariable = function (variable) { }; NullVisitor.prototype.visitReference = function (reference) { }; NullVisitor.prototype.visitTextAttribute = function (attribute) { }; NullVisitor.prototype.visitBoundAttribute = function (attribute) { }; NullVisitor.prototype.visitBoundEvent = function (attribute) { }; NullVisitor.prototype.visitText = function (text) { }; NullVisitor.prototype.visitBoundText = function (text) { }; NullVisitor.prototype.visitIcu = function (icu) { }; return NullVisitor; }()); var RecursiveVisitor = /** @class */ (function () { function RecursiveVisitor() { } RecursiveVisitor.prototype.visitElement = function (element) { visitAll(this, element.attributes); visitAll(this, element.children); visitAll(this, element.references); }; RecursiveVisitor.prototype.visitTemplate = function (template) { visitAll(this, template.attributes); visitAll(this, template.children); visitAll(this, template.references); visitAll(this, template.variables); }; RecursiveVisitor.prototype.visitContent = function (content) { }; RecursiveVisitor.prototype.visitVariable = function (variable) { }; RecursiveVisitor.prototype.visitReference = function (reference) { }; RecursiveVisitor.prototype.visitTextAttribute = function (attribute) { }; RecursiveVisitor.prototype.visitBoundAttribute = function (attribute) { }; RecursiveVisitor.prototype.visitBoundEvent = function (attribute) { }; RecursiveVisitor.prototype.visitText = function (text) { }; RecursiveVisitor.prototype.visitBoundText = function (text) { }; RecursiveVisitor.prototype.visitIcu = function (icu) { }; return RecursiveVisitor; }()); var TransformVisitor = /** @class */ (function () { function TransformVisitor() { } TransformVisitor.prototype.visitElement = function (element) { var newAttributes = transformAll(this, element.attributes); var newInputs = transformAll(this, element.inputs); var newOutputs = transformAll(this, element.outputs); var newChildren = transformAll(this, element.children); var newReferences = transformAll(this, element.references); if (newAttributes != element.attributes || newInputs != element.inputs || newOutputs != element.outputs || newChildren != element.children || newReferences != element.references) { return new Element(element.name, newAttributes, newInputs, newOutputs, newChildren, newReferences, element.sourceSpan, element.startSourceSpan, element.endSourceSpan); } return element; }; TransformVisitor.prototype.visitTemplate = function (template) { var newAttributes = transformAll(this, template.attributes); var newInputs = transformAll(this, template.inputs); var newOutputs = transformAll(this, template.outputs); var newTemplateAttrs = transformAll(this, template.templateAttrs); var newChildren = transformAll(this, template.children); var newReferences = transformAll(this, template.references); var newVariables = transformAll(this, template.variables); if (newAttributes != template.attributes || newInputs != template.inputs || newOutputs != template.outputs || newTemplateAttrs != template.templateAttrs || newChildren != template.children || newReferences != template.references || newVariables != template.variables) { return new Template(template.tagName, newAttributes, newInputs, newOutputs, newTemplateAttrs, newChildren, newReferences, newVariables, template.sourceSpan, template.startSourceSpan, template.endSourceSpan); } return template; }; TransformVisitor.prototype.visitContent = function (content) { return content; }; TransformVisitor.prototype.visitVariable = function (variable) { return variable; }; TransformVisitor.prototype.visitReference = function (reference) { return reference; }; TransformVisitor.prototype.visitTextAttribute = function (attribute) { return attribute; }; TransformVisitor.prototype.visitBoundAttribute = function (attribute) { return attribute; }; TransformVisitor.prototype.visitBoundEvent = function (attribute) { return attribute; }; TransformVisitor.prototype.visitText = function (text) { return text; }; TransformVisitor.prototype.visitBoundText = function (text) { return text; }; TransformVisitor.prototype.visitIcu = function (icu) { return icu; }; return TransformVisitor; }()); function visitAll(visitor, nodes) { var e_1, _a, e_2, _b; var result = []; if (visitor.visit) { try { for (var nodes_1 = __values(nodes), nodes_1_1 = nodes_1.next(); !nodes_1_1.done; nodes_1_1 = nodes_1.next()) { var node = nodes_1_1.value; var newNode = visitor.visit(node) || node.visit(visitor); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (nodes_1_1 && !nodes_1_1.done && (_a = nodes_1.return)) _a.call(nodes_1); } finally { if (e_1) throw e_1.error; } } } else { try { for (var nodes_2 = __values(nodes), nodes_2_1 = nodes_2.next(); !nodes_2_1.done; nodes_2_1 = nodes_2.next()) { var node = nodes_2_1.value; var newNode = node.visit(visitor); if (newNode) { result.push(newNode); } } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (nodes_2_1 && !nodes_2_1.done && (_b = nodes_2.return)) _b.call(nodes_2); } finally { if (e_2) throw e_2.error; } } } return result; } function transformAll(visitor, nodes) { var e_3, _a; var result = []; var changed = false; try { for (var nodes_3 = __values(nodes), nodes_3_1 = nodes_3.next(); !nodes_3_1.done; nodes_3_1 = nodes_3.next()) { var node = nodes_3_1.value; var newNode = node.visit(visitor); if (newNode) { result.push(newNode); } changed = changed || newNode != node; } } catch (e_3_1) { e_3 = { error: e_3_1 }; } finally { try { if (nodes_3_1 && !nodes_3_1.done && (_a = nodes_3.return)) _a.call(nodes_3); } finally { if (e_3) throw e_3.error; } } return changed ? result : nodes; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var Message = /** @class */ (function () { /** * @param nodes message AST * @param placeholders maps placeholder names to static content * @param placeholderToMessage maps placeholder names to messages (used for nested ICU messages) * @param meaning * @param description * @param customId */ function Message(nodes, placeholders, placeholderToMessage, meaning, description, customId) { this.nodes = nodes; this.placeholders = placeholders; this.placeholderToMessage = placeholderToMessage; this.meaning = meaning; this.description = description; this.customId = customId; this.id = this.customId; /** The ids to use if there are no custom id and if `i18nLegacyMessageIdFormat` is not empty */ this.legacyIds = []; if (nodes.length) { this.sources = [{ filePath: nodes[0].sourceSpan.start.file.url, startLine: nodes[0].sourceSpan.start.line + 1, startCol: nodes[0].sourceSpan.start.col + 1, endLine: nodes[nodes.length - 1].sourceSpan.end.line + 1, endCol: nodes[0].sourceSpan.start.col + 1 }]; } else { this.sources = []; } } return Message; }()); var Text$1 = /** @class */ (function () { function Text(value, sourceSpan) { this.value = value; this.sourceSpan = sourceSpan; } Text.prototype.visit = function (visitor, context) { return visitor.visitText(this, context); }; return Text; }()); // TODO(vicb): do we really need this node (vs an array) ? var Container = /** @class */ (function () { function Container(children, sourceSpan) { this.children = children; this.sourceSpan = sourceSpan; } Container.prototype.visit = function (visitor, context) { return visitor.visitContainer(this, context); }; return Container; }()); var Icu$1 = /** @class */ (function () { function Icu(expression, type, cases, sourceSpan) { this.expression = expression; this.type = type; this.cases = cases; this.sourceSpan = sourceSpan; } Icu.prototype.visit = function (visitor, context) { return visitor.visitIcu(this, context); }; return Icu; }()); var TagPlaceholder = /** @class */ (function () { function TagPlaceholder(tag, attrs, startName, closeName, children, isVoid, sourceSpan) { this.tag = tag; this.attrs = attrs; this.startName = startName; this.closeName = closeName; this.children = children; this.isVoid = isVoid; this.sourceSpan = sourceSpan; } TagPlaceholder.prototype.visit = function (visitor, context) { return visitor.visitTagPlaceholder(this, context); }; return TagPlaceholder; }()); var Placeholder = /** @class */ (function () { function Placeholder(value, name, sourceSpan) { this.value = value; this.name = name; this.sourceSpan = sourceSpan; } Placeholder.prototype.visit = function (visitor, context) { return visitor.visitPlaceholder(this, context); }; return Placeholder; }()); var IcuPlaceholder = /** @class */ (function () { function IcuPlaceholder(value, name, sourceSpan) { this.value = value; this.name = name; this.sourceSpan = sourceSpan; } IcuPlaceholder.prototype.visit = function (visitor, context) { return visitor.visitIcuPlaceholder(this, context); }; return IcuPlaceholder; }()); // Clone the AST var CloneVisitor = /** @class */ (function () { function CloneVisitor() { } CloneVisitor.prototype.visitText = function (text, context) { return new Text$1(text.value, text.sourceSpan); }; CloneVisitor.prototype.visitContainer = function (container, context) { var _this = this; var children = container.children.map(function (n) { return n.visit(_this, context); }); return new Container(children, container.sourceSpan); }; CloneVisitor.prototype.visitIcu = function (icu, context) { var _this = this; var cases = {}; Object.keys(icu.cases).forEach(function (key) { return cases[key] = icu.cases[key].visit(_this, context); }); var msg = new Icu$1(icu.expression, icu.type, cases, icu.sourceSpan); msg.expressionPlaceholder = icu.expressionPlaceholder; return msg; }; CloneVisitor.prototype.visitTagPlaceholder = function (ph, context) { var _this = this; var children = ph.children.map(function (n) { return n.visit(_this, context); }); return new TagPlaceholder(ph.tag, ph.attrs, ph.startName, ph.closeName, children, ph.isVoid, ph.sourceSpan); }; CloneVisitor.prototype.visitPlaceholder = function (ph, context) { return new Placeholder(ph.value, ph.name, ph.sourceSpan); }; CloneVisitor.prototype.visitIcuPlaceholder = function (ph, context) { return new IcuPlaceholder(ph.value, ph.name, ph.sourceSpan); }; return CloneVisitor; }()); // Visit all the nodes recursively var RecurseVisitor = /** @class */ (function () { function RecurseVisitor() { } RecurseVisitor.prototype.visitText = function (text, context) { }; RecurseVisitor.prototype.visitContainer = function (container, context) { var _this = this; container.children.forEach(function (child) { return child.visit(_this); }); }; RecurseVisitor.prototype.visitIcu = function (icu, context) { var _this = this; Object.keys(icu.cases).forEach(function (k) { icu.cases[k].visit(_this); }); }; RecurseVisitor.prototype.visitTagPlaceholder = function (ph, context) { var _this = this; ph.children.forEach(function (child) { return child.visit(_this); }); }; RecurseVisitor.prototype.visitPlaceholder = function (ph, context) { }; RecurseVisitor.prototype.visitIcuPlaceholder = function (ph, context) { }; return RecurseVisitor; }()); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Return the message id or compute it using the XLIFF1 digest. */ function digest(message) { return message.id || computeDigest(message); } /** * Compute the message id using the XLIFF1 digest. */ function computeDigest(message) { return sha1(serializeNodes(message.nodes).join('') + ("[" + message.meaning + "]")); } /** * Return the message id or compute it using the XLIFF2/XMB/$localize digest. */ function decimalDigest(message) { return message.id || computeDecimalDigest(message); } /** * Compute the message id using the XLIFF2/XMB/$localize digest. */ function computeDecimalDigest(message) { var visitor = new _SerializerIgnoreIcuExpVisitor(); var parts = message.nodes.map(function (a) { return a.visit(visitor, null); }); return computeMsgId(parts.join(''), message.meaning); } /** * Serialize the i18n ast to something xml-like in order to generate an UID. * * The visitor is also used in the i18n parser tests * * @internal */ var _SerializerVisitor = /** @class */ (function () { function _SerializerVisitor() { } _SerializerVisitor.prototype.visitText = function (text, context) { return text.value; }; _SerializerVisitor.prototype.visitContainer = function (container, context) { var _this = this; return "[" + container.children.map(function (child) { return child.visit(_this); }).join(', ') + "]"; }; _SerializerVisitor.prototype.visitIcu = function (icu, context) { var _this = this; var strCases = Object.keys(icu.cases).map(function (k) { return k + " {" + icu.cases[k].visit(_this) + "}"; }); return "{" + icu.expression + ", " + icu.type + ", " + strCases.join(', ') + "}"; }; _SerializerVisitor.prototype.visitTagPlaceholder = function (ph, context) { var _this = this; return ph.isVoid ? "" : "" + ph.children.map(function (child) { return child.visit(_this); }).join(', ') + ""; }; _SerializerVisitor.prototype.visitPlaceholder = function (ph, context) { return ph.value ? "" + ph.value + "" : ""; }; _SerializerVisitor.prototype.visitIcuPlaceholder = function (ph, context) { return "" + ph.value.visit(this) + ""; }; return _SerializerVisitor; }()); var serializerVisitor = new _SerializerVisitor(); function serializeNodes(nodes) { return nodes.map(function (a) { return a.visit(serializerVisitor, null); }); } /** * Serialize the i18n ast to something xml-like in order to generate an UID. * * Ignore the ICU expressions so that message IDs stays identical if only the expression changes. * * @internal */ var _SerializerIgnoreIcuExpVisitor = /** @class */ (function (_super) { __extends(_SerializerIgnoreIcuExpVisitor, _super); function _SerializerIgnoreIcuExpVisitor() { return _super !== null && _super.apply(this, arguments) || this; } _SerializerIgnoreIcuExpVisitor.prototype.visitIcu = function (icu, context) { var _this = this; var strCases = Object.keys(icu.cases).map(function (k) { return k + " {" + icu.cases[k].visit(_this) + "}"; }); // Do not take the expression into account return "{" + icu.type + ", " + strCases.join(', ') + "}"; }; return _SerializerIgnoreIcuExpVisitor; }(_SerializerVisitor)); /** * Compute the SHA1 of the given string * * see http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf * * WARNING: this function has not been designed not tested with security in mind. * DO NOT USE IT IN A SECURITY SENSITIVE CONTEXT. */ function sha1(str) { var utf8 = utf8Encode(str); var words32 = stringToWords32(utf8, Endian.Big); var len = utf8.length * 8; var w = newArray(80); var a = 0x67452301, b = 0xefcdab89, c = 0x98badcfe, d = 0x10325476, e = 0xc3d2e1f0; words32[len >> 5] |= 0x80 << (24 - len % 32); words32[((len + 64 >> 9) << 4) + 15] = len; for (var i = 0; i < words32.length; i += 16) { var h0 = a, h1 = b, h2 = c, h3 = d, h4 = e; for (var j = 0; j < 80; j++) { if (j < 16) { w[j] = words32[i + j]; } else { w[j] = rol32(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1); } var fkVal = fk(j, b, c, d); var f = fkVal[0]; var k = fkVal[1]; var temp = [rol32(a, 5), f, e, k, w[j]].reduce(add32); e = d; d = c; c = rol32(b, 30); b = a; a = temp; } a = add32(a, h0); b = add32(b, h1); c = add32(c, h2); d = add32(d, h3); e = add32(e, h4); } return byteStringToHexString(words32ToByteString([a, b, c, d, e])); } function fk(index, b, c, d) { if (index < 20) { return [(b & c) | (~b & d), 0x5a827999]; } if (index < 40) { return [b ^ c ^ d, 0x6ed9eba1]; } if (index < 60) { return [(b & c) | (b & d) | (c & d), 0x8f1bbcdc]; } return [b ^ c ^ d, 0xca62c1d6]; } /** * Compute the fingerprint of the given string * * The output is 64 bit number encoded as a decimal string * * based on: * https://github.com/google/closure-compiler/blob/master/src/com/google/javascript/jscomp/GoogleJsMessageIdGenerator.java */ function fingerprint(str) { var utf8 = utf8Encode(str); var hi = hash32(utf8, 0); var lo = hash32(utf8, 102072); if (hi == 0 && (lo == 0 || lo == 1)) { hi = hi ^ 0x130f9bef; lo = lo ^ -0x6b5f56d8; } return [hi, lo]; } function computeMsgId(msg, meaning) { if (meaning === void 0) { meaning = ''; } var msgFingerprint = fingerprint(msg); if (meaning) { var meaningFingerprint = fingerprint(meaning); msgFingerprint = add64(rol64(msgFingerprint, 1), meaningFingerprint); } var hi = msgFingerprint[0]; var lo = msgFingerprint[1]; return byteStringToDecString(words32ToByteString([hi & 0x7fffffff, lo])); } function hash32(str, c) { var a = 0x9e3779b9, b = 0x9e3779b9; var i; var len = str.length; for (i = 0; i + 12 <= len; i += 12) { a = add32(a, wordAt(str, i, Endian.Little)); b = add32(b, wordAt(str, i + 4, Endian.Little)); c = add32(c, wordAt(str, i + 8, Endian.Little)); var res = mix(a, b, c); a = res[0], b = res[1], c = res[2]; } a = add32(a, wordAt(str, i, Endian.Little)); b = add32(b, wordAt(str, i + 4, Endian.Little)); // the first byte of c is reserved for the length c = add32(c, len); c = add32(c, wordAt(str, i + 8, Endian.Little) << 8); return mix(a, b, c)[2]; } // clang-format off function mix(a, b, c) { a = sub32(a, b); a = sub32(a, c); a ^= c >>> 13; b = sub32(b, c); b = sub32(b, a); b ^= a << 8; c = sub32(c, a); c = sub32(c, b); c ^= b >>> 13; a = sub32(a, b); a = sub32(a, c); a ^= c >>> 12; b = sub32(b, c); b = sub32(b, a); b ^= a << 16; c = sub32(c, a); c = sub32(c, b); c ^= b >>> 5; a = sub32(a, b); a = sub32(a, c); a ^= c >>> 3; b = sub32(b, c); b = sub32(b, a); b ^= a << 10; c = sub32(c, a); c = sub32(c, b); c ^= b >>> 15; return [a, b, c]; } // clang-format on // Utils var Endian; (function (Endian) { Endian[Endian["Little"] = 0] = "Little"; Endian[Endian["Big"] = 1] = "Big"; })(Endian || (Endian = {})); function add32(a, b) { return add32to64(a, b)[1]; } function add32to64(a, b) { var low = (a & 0xffff) + (b & 0xffff); var high = (a >>> 16) + (b >>> 16) + (low >>> 16); return [high >>> 16, (high << 16) | (low & 0xffff)]; } function add64(a, b) { var ah = a[0], al = a[1]; var bh = b[0], bl = b[1]; var result = add32to64(al, bl); var carry = result[0]; var l = result[1]; var h = add32(add32(ah, bh), carry); return [h, l]; } function sub32(a, b) { var low = (a & 0xffff) - (b & 0xffff); var high = (a >> 16) - (b >> 16) + (low >> 16); return (high << 16) | (low & 0xffff); } // Rotate a 32b number left `count` position function rol32(a, count) { return (a << count) | (a >>> (32 - count)); } // Rotate a 64b number left `count` position function rol64(num, count) { var hi = num[0], lo = num[1]; var h = (hi << count) | (lo >>> (32 - count)); var l = (lo << count) | (hi >>> (32 - count)); return [h, l]; } function stringToWords32(str, endian) { var size = (str.length + 3) >>> 2; var words32 = []; for (var i = 0; i < size; i++) { words32[i] = wordAt(str, i * 4, endian); } return words32; } function byteAt(str, index) { return index >= str.length ? 0 : str.charCodeAt(index) & 0xff; } function wordAt(str, index, endian) { var word = 0; if (endian === Endian.Big) { for (var i = 0; i < 4; i++) { word += byteAt(str, index + i) << (24 - 8 * i); } } else { for (var i = 0; i < 4; i++) { word += byteAt(str, index + i) << 8 * i; } } return word; } function words32ToByteString(words32) { return words32.reduce(function (str, word) { return str + word32ToByteString(word); }, ''); } function word32ToByteString(word) { var str = ''; for (var i = 0; i < 4; i++) { str += String.fromCharCode((word >>> 8 * (3 - i)) & 0xff); } return str; } function byteStringToHexString(str) { var hex = ''; for (var i = 0; i < str.length; i++) { var b = byteAt(str, i); hex += (b >>> 4).toString(16) + (b & 0x0f).toString(16); } return hex.toLowerCase(); } // based on http://www.danvk.org/hex2dec.html (JS can not handle more than 56b) function byteStringToDecString(str) { var decimal = ''; var toThePower = '1'; for (var i = str.length - 1; i >= 0; i--) { decimal = addBigInt(decimal, numberTimesBigInt(byteAt(str, i), toThePower)); toThePower = numberTimesBigInt(256, toThePower); } return decimal.split('').reverse().join(''); } // x and y decimal, lowest significant digit first function addBigInt(x, y) { var sum = ''; var len = Math.max(x.length, y.length); for (var i = 0, carry = 0; i < len || carry; i++) { var tmpSum = carry + +(x[i] || 0) + +(y[i] || 0); if (tmpSum >= 10) { carry = 1; sum += tmpSum - 10; } else { carry = 0; sum += tmpSum; } } return sum; } function numberTimesBigInt(num, b) { var product = ''; var bToThePower = b; for (; num !== 0; num = num >>> 1) { if (num & 1) product = addBigInt(product, bToThePower); bToThePower = addBigInt(bToThePower, bToThePower); } return product; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var Serializer = /** @class */ (function () { function Serializer() { } // Creates a name mapper, see `PlaceholderMapper` // Returning `null` means that no name mapping is used. Serializer.prototype.createNameMapper = function (message) { return null; }; return Serializer; }()); /** * A simple mapper that take a function to transform an internal name to a public name */ var SimplePlaceholderMapper = /** @class */ (function (_super) { __extends(SimplePlaceholderMapper, _super); // create a mapping from the message function SimplePlaceholderMapper(message, mapName) { var _this = _super.call(this) || this; _this.mapName = mapName; _this.internalToPublic = {}; _this.publicToNextId = {}; _this.publicToInternal = {}; message.nodes.forEach(function (node) { return node.visit(_this); }); return _this; } SimplePlaceholderMapper.prototype.toPublicName = function (internalName) { return this.internalToPublic.hasOwnProperty(internalName) ? this.internalToPublic[internalName] : null; }; SimplePlaceholderMapper.prototype.toInternalName = function (publicName) { return this.publicToInternal.hasOwnProperty(publicName) ? this.publicToInternal[publicName] : null; }; SimplePlaceholderMapper.prototype.visitText = function (text, context) { return null; }; SimplePlaceholderMapper.prototype.visitTagPlaceholder = function (ph, context) { this.visitPlaceholderName(ph.startName); _super.prototype.visitTagPlaceholder.call(this, ph, context); this.visitPlaceholderName(ph.closeName); }; SimplePlaceholderMapper.prototype.visitPlaceholder = function (ph, context) { this.visitPlaceholderName(ph.name); }; SimplePlaceholderMapper.prototype.visitIcuPlaceholder = function (ph, context) { this.visitPlaceholderName(ph.name); }; // XMB placeholders could only contains A-Z, 0-9 and _ SimplePlaceholderMapper.prototype.visitPlaceholderName = function (internalName) { if (!internalName || this.internalToPublic.hasOwnProperty(internalName)) { return; } var publicName = this.mapName(internalName); if (this.publicToInternal.hasOwnProperty(publicName)) { // Create a new XMB when it has already been used var nextId = this.publicToNextId[publicName]; this.publicToNextId[publicName] = nextId + 1; publicName = publicName + "_" + nextId; } else { this.publicToNextId[publicName] = 1; } this.internalToPublic[internalName] = publicName; this.publicToInternal[publicName] = internalName; }; return SimplePlaceholderMapper; }(RecurseVisitor)); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var _Visitor = /** @class */ (function () { function _Visitor() { } _Visitor.prototype.visitTag = function (tag) { var _this = this; var strAttrs = this._serializeAttributes(tag.attrs); if (tag.children.length == 0) { return "<" + tag.name + strAttrs + "/>"; } var strChildren = tag.children.map(function (node) { return node.visit(_this); }); return "<" + tag.name + strAttrs + ">" + strChildren.join('') + ""; }; _Visitor.prototype.visitText = function (text) { return text.value; }; _Visitor.prototype.visitDeclaration = function (decl) { return ""; }; _Visitor.prototype._serializeAttributes = function (attrs) { var strAttrs = Object.keys(attrs).map(function (name) { return name + "=\"" + attrs[name] + "\""; }).join(' '); return strAttrs.length > 0 ? ' ' + strAttrs : ''; }; _Visitor.prototype.visitDoctype = function (doctype) { return ""; }; return _Visitor; }()); var _visitor = new _Visitor(); function serialize(nodes) { return nodes.map(function (node) { return node.visit(_visitor); }).join(''); } var Declaration = /** @class */ (function () { function Declaration(unescapedAttrs) { var _this = this; this.attrs = {}; Object.keys(unescapedAttrs).forEach(function (k) { _this.attrs[k] = escapeXml(unescapedAttrs[k]); }); } Declaration.prototype.visit = function (visitor) { return visitor.visitDeclaration(this); }; return Declaration; }()); var Doctype = /** @class */ (function () { function Doctype(rootTag, dtd) { this.rootTag = rootTag; this.dtd = dtd; } Doctype.prototype.visit = function (visitor) { return visitor.visitDoctype(this); }; return Doctype; }()); var Tag = /** @class */ (function () { function Tag(name, unescapedAttrs, children) { var _this = this; if (unescapedAttrs === void 0) { unescapedAttrs = {}; } if (children === void 0) { children = []; } this.name = name; this.children = children; this.attrs = {}; Object.keys(unescapedAttrs).forEach(function (k) { _this.attrs[k] = escapeXml(unescapedAttrs[k]); }); } Tag.prototype.visit = function (visitor) { return visitor.visitTag(this); }; return Tag; }()); var Text$2 = /** @class */ (function () { function Text(unescapedValue) { this.value = escapeXml(unescapedValue); } Text.prototype.visit = function (visitor) { return visitor.visitText(this); }; return Text; }()); var CR = /** @class */ (function (_super) { __extends(CR, _super); function CR(ws) { if (ws === void 0) { ws = 0; } return _super.call(this, "\n" + new Array(ws + 1).join(' ')) || this; } return CR; }(Text$2)); var _ESCAPED_CHARS = [ [/&/g, '&'], [/"/g, '"'], [/'/g, '''], [//g, '>'], ]; // Escape `_ESCAPED_CHARS` characters in the given text with encoded entities function escapeXml(text) { return _ESCAPED_CHARS.reduce(function (text, entry) { return text.replace(entry[0], entry[1]); }, text); } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var _MESSAGES_TAG = 'messagebundle'; var _MESSAGE_TAG = 'msg'; var _PLACEHOLDER_TAG = 'ph'; var _EXAMPLE_TAG = 'ex'; var _SOURCE_TAG = 'source'; var _DOCTYPE = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"; var Xmb = /** @class */ (function (_super) { __extends(Xmb, _super); function Xmb() { return _super !== null && _super.apply(this, arguments) || this; } Xmb.prototype.write = function (messages, locale) { var exampleVisitor = new ExampleVisitor(); var visitor = new _Visitor$1(); var rootNode = new Tag(_MESSAGES_TAG); messages.forEach(function (message) { var attrs = { id: message.id }; if (message.description) { attrs['desc'] = message.description; } if (message.meaning) { attrs['meaning'] = message.meaning; } var sourceTags = []; message.sources.forEach(function (source) { sourceTags.push(new Tag(_SOURCE_TAG, {}, [ new Text$2(source.filePath + ":" + source.startLine + (source.endLine !== source.startLine ? ',' + source.endLine : '')) ])); }); rootNode.children.push(new CR(2), new Tag(_MESSAGE_TAG, attrs, __spread(sourceTags, visitor.serialize(message.nodes)))); }); rootNode.children.push(new CR()); return serialize([ new Declaration({ version: '1.0', encoding: 'UTF-8' }), new CR(), new Doctype(_MESSAGES_TAG, _DOCTYPE), new CR(), exampleVisitor.addDefaultExamples(rootNode), new CR(), ]); }; Xmb.prototype.load = function (content, url) { throw new Error('Unsupported'); }; Xmb.prototype.digest = function (message) { return digest$1(message); }; Xmb.prototype.createNameMapper = function (message) { return new SimplePlaceholderMapper(message, toPublicName); }; return Xmb; }(Serializer)); var _Visitor$1 = /** @class */ (function () { function _Visitor() { } _Visitor.prototype.visitText = function (text, context) { return [new Text$2(text.value)]; }; _Visitor.prototype.visitContainer = function (container, context) { var _this = this; var nodes = []; container.children.forEach(function (node) { return nodes.push.apply(nodes, __spread(node.visit(_this))); }); return nodes; }; _Visitor.prototype.visitIcu = function (icu, context) { var _this = this; var nodes = [new Text$2("{" + icu.expressionPlaceholder + ", " + icu.type + ", ")]; Object.keys(icu.cases).forEach(function (c) { nodes.push.apply(nodes, __spread([new Text$2(c + " {")], icu.cases[c].visit(_this), [new Text$2("} ")])); }); nodes.push(new Text$2("}")); return nodes; }; _Visitor.prototype.visitTagPlaceholder = function (ph, context) { var startTagAsText = new Text$2("<" + ph.tag + ">"); var startEx = new Tag(_EXAMPLE_TAG, {}, [startTagAsText]); // TC requires PH to have a non empty EX, and uses the text node to show the "original" value. var startTagPh = new Tag(_PLACEHOLDER_TAG, { name: ph.startName }, [startEx, startTagAsText]); if (ph.isVoid) { // void tags have no children nor closing tags return [startTagPh]; } var closeTagAsText = new Text$2(""); var closeEx = new Tag(_EXAMPLE_TAG, {}, [closeTagAsText]); // TC requires PH to have a non empty EX, and uses the text node to show the "original" value. var closeTagPh = new Tag(_PLACEHOLDER_TAG, { name: ph.closeName }, [closeEx, closeTagAsText]); return __spread([startTagPh], this.serialize(ph.children), [closeTagPh]); }; _Visitor.prototype.visitPlaceholder = function (ph, context) { var interpolationAsText = new Text$2("{{" + ph.value + "}}"); // Example tag needs to be not-empty for TC. var exTag = new Tag(_EXAMPLE_TAG, {}, [interpolationAsText]); return [ // TC requires PH to have a non empty EX, and uses the text node to show the "original" value. new Tag(_PLACEHOLDER_TAG, { name: ph.name }, [exTag, interpolationAsText]) ]; }; _Visitor.prototype.visitIcuPlaceholder = function (ph, context) { var icuExpression = ph.value.expression; var icuType = ph.value.type; var icuCases = Object.keys(ph.value.cases).map(function (value) { return value + ' {...}'; }).join(' '); var icuAsText = new Text$2("{" + icuExpression + ", " + icuType + ", " + icuCases + "}"); var exTag = new Tag(_EXAMPLE_TAG, {}, [icuAsText]); return [ // TC requires PH to have a non empty EX, and uses the text node to show the "original" value. new Tag(_PLACEHOLDER_TAG, { name: ph.name }, [exTag, icuAsText]) ]; }; _Visitor.prototype.serialize = function (nodes) { var _this = this; return [].concat.apply([], __spread(nodes.map(function (node) { return node.visit(_this); }))); }; return _Visitor; }()); function digest$1(message) { return decimalDigest(message); } // TC requires at least one non-empty example on placeholders var ExampleVisitor = /** @class */ (function () { function ExampleVisitor() { } ExampleVisitor.prototype.addDefaultExamples = function (node) { node.visit(this); return node; }; ExampleVisitor.prototype.visitTag = function (tag) { var _this = this; if (tag.name === _PLACEHOLDER_TAG) { if (!tag.children || tag.children.length == 0) { var exText = new Text$2(tag.attrs['name'] || '...'); tag.children = [new Tag(_EXAMPLE_TAG, {}, [exText])]; } } else if (tag.children) { tag.children.forEach(function (node) { return node.visit(_this); }); } }; ExampleVisitor.prototype.visitText = function (text) { }; ExampleVisitor.prototype.visitDeclaration = function (decl) { }; ExampleVisitor.prototype.visitDoctype = function (doctype) { }; return ExampleVisitor; }()); // XMB/XTB placeholders can only contain A-Z, 0-9 and _ function toPublicName(internalName) { return internalName.toUpperCase().replace(/[^A-Z0-9_]/g, '_'); } /* Closure variables holding messages must be named `MSG_[A-Z0-9]+` */ var CLOSURE_TRANSLATION_PREFIX = 'MSG_'; /* Prefix for non-`goog.getMsg` i18n-related vars */ var TRANSLATION_PREFIX = 'I18N_'; /** Name of the i18n attributes **/ var I18N_ATTR = 'i18n'; var I18N_ATTR_PREFIX = 'i18n-'; /** Prefix of var expressions used in ICUs */ var I18N_ICU_VAR_PREFIX = 'VAR_'; /** Prefix of ICU expressions for post processing */ var I18N_ICU_MAPPING_PREFIX = 'I18N_EXP_'; /** Placeholder wrapper for i18n expressions **/ var I18N_PLACEHOLDER_SYMBOL = '�'; function isI18nAttribute(name) { return name === I18N_ATTR || name.startsWith(I18N_ATTR_PREFIX); } function isI18nRootNode(meta) { return meta instanceof Message; } function isSingleI18nIcu(meta) { return isI18nRootNode(meta) && meta.nodes.length === 1 && meta.nodes[0] instanceof Icu$1; } function hasI18nAttrs(element) { return element.attrs.some(function (attr) { return isI18nAttribute(attr.name); }); } function icuFromI18nMessage(message) { return message.nodes[0]; } function wrapI18nPlaceholder(content, contextId) { if (contextId === void 0) { contextId = 0; } var blockId = contextId > 0 ? ":" + contextId : ''; return "" + I18N_PLACEHOLDER_SYMBOL + content + blockId + I18N_PLACEHOLDER_SYMBOL; } function assembleI18nBoundString(strings, bindingStartIndex, contextId) { if (bindingStartIndex === void 0) { bindingStartIndex = 0; } if (contextId === void 0) { contextId = 0; } if (!strings.length) return ''; var acc = ''; var lastIdx = strings.length - 1; for (var i = 0; i < lastIdx; i++) { acc += "" + strings[i] + wrapI18nPlaceholder(bindingStartIndex + i, contextId); } acc += strings[lastIdx]; return acc; } function getSeqNumberGenerator(startsAt) { if (startsAt === void 0) { startsAt = 0; } var current = startsAt; return function () { return current++; }; } function placeholdersToParams(placeholders) { var params = {}; placeholders.forEach(function (values, key) { params[key] = literal(values.length > 1 ? "[" + values.join('|') + "]" : values[0]); }); return params; } function updatePlaceholderMap(map, name) { var values = []; for (var _i = 2; _i < arguments.length; _i++) { values[_i - 2] = arguments[_i]; } var current = map.get(name) || []; current.push.apply(current, __spread(values)); map.set(name, current); } function assembleBoundTextPlaceholders(meta, bindingStartIndex, contextId) { if (bindingStartIndex === void 0) { bindingStartIndex = 0; } if (contextId === void 0) { contextId = 0; } var startIdx = bindingStartIndex; var placeholders = new Map(); var node = meta instanceof Message ? meta.nodes.find(function (node) { return node instanceof Container; }) : meta; if (node) { node .children .filter(function (child) { return child instanceof Placeholder; }) .forEach(function (child, idx) { var content = wrapI18nPlaceholder(startIdx + idx, contextId); updatePlaceholderMap(placeholders, child.name, content); }); } return placeholders; } /** * Format the placeholder names in a map of placeholders to expressions. * * The placeholder names are converted from "internal" format (e.g. `START_TAG_DIV_1`) to "external" * format (e.g. `startTagDiv_1`). * * @param params A map of placeholder names to expressions. * @param useCamelCase whether to camelCase the placeholder name when formatting. * @returns A new map of formatted placeholder names to expressions. */ function i18nFormatPlaceholderNames(params, useCamelCase) { if (params === void 0) { params = {}; } var _params = {}; if (params && Object.keys(params).length) { Object.keys(params).forEach(function (key) { return _params[formatI18nPlaceholderName(key, useCamelCase)] = params[key]; }); } return _params; } /** * Converts internal placeholder names to public-facing format * (for example to use in goog.getMsg call). * Example: `START_TAG_DIV_1` is converted to `startTagDiv_1`. * * @param name The placeholder name that should be formatted * @returns Formatted placeholder name */ function formatI18nPlaceholderName(name, useCamelCase) { if (useCamelCase === void 0) { useCamelCase = true; } var publicName = toPublicName(name); if (!useCamelCase) { return publicName; } var chunks = publicName.split('_'); if (chunks.length === 1) { // if no "_" found - just lowercase the value return name.toLowerCase(); } var postfix; // eject last element if it's a number if (/^\d+$/.test(chunks[chunks.length - 1])) { postfix = chunks.pop(); } var raw = chunks.shift().toLowerCase(); if (chunks.length) { raw += chunks.map(function (c) { return c.charAt(0).toUpperCase() + c.slice(1).toLowerCase(); }).join(''); } return postfix ? raw + "_" + postfix : raw; } /** * Generates a prefix for translation const name. * * @param extra Additional local prefix that should be injected into translation var name * @returns Complete translation const prefix */ function getTranslationConstPrefix(extra) { return ("" + CLOSURE_TRANSLATION_PREFIX + extra).toUpperCase(); } /** * Generate AST to declare a variable. E.g. `var I18N_1;`. * @param variable the name of the variable to declare. */ function declareI18nVariable(variable) { return new DeclareVarStmt(variable.name, undefined, INFERRED_TYPE, null, variable.sourceSpan); } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Checks whether an object key contains potentially unsafe chars, thus the key should be wrapped in * quotes. Note: we do not wrap all keys into quotes, as it may have impact on minification and may * bot work in some cases when object keys are mangled by minifier. * * TODO(FW-1136): this is a temporary solution, we need to come up with a better way of working with * inputs that contain potentially unsafe chars. */ var UNSAFE_OBJECT_KEY_NAME_REGEXP = /[-.]/; /** Name of the temporary to use during data binding */ var TEMPORARY_NAME = '_t'; /** Name of the context parameter passed into a template function */ var CONTEXT_NAME = 'ctx'; /** Name of the RenderFlag passed into a template function */ var RENDER_FLAGS = 'rf'; /** The prefix reference variables */ var REFERENCE_PREFIX = '_r'; /** The name of the implicit context reference */ var IMPLICIT_REFERENCE = '$implicit'; /** Non bindable attribute name **/ var NON_BINDABLE_ATTR = 'ngNonBindable'; /** * Creates an allocator for a temporary variable. * * A variable declaration is added to the statements the first time the allocator is invoked. */ function temporaryAllocator(statements, name) { var temp = null; return function () { if (!temp) { statements.push(new DeclareVarStmt(TEMPORARY_NAME, undefined, DYNAMIC_TYPE)); temp = variable(name); } return temp; }; } function unsupported(feature) { if (this) { throw new Error("Builder " + this.constructor.name + " doesn't support " + feature + " yet"); } throw new Error("Feature " + feature + " is not supported yet"); } function invalid$1(arg) { throw new Error("Invalid state: Visitor " + this.constructor.name + " doesn't handle " + arg.constructor.name); } function asLiteral(value) { if (Array.isArray(value)) { return literalArr(value.map(asLiteral)); } return literal(value, INFERRED_TYPE); } function conditionallyCreateMapObjectLiteral(keys, keepDeclared) { if (Object.getOwnPropertyNames(keys).length > 0) { return mapToExpression(keys, keepDeclared); } return null; } function mapToExpression(map, keepDeclared) { return literalMap(Object.getOwnPropertyNames(map).map(function (key) { var _a, _b; // canonical syntax: `dirProp: publicProp` // if there is no `:`, use dirProp = elProp var value = map[key]; var declaredName; var publicName; var minifiedName; if (Array.isArray(value)) { _a = __read(value, 2), publicName = _a[0], declaredName = _a[1]; } else { _b = __read(splitAtColon(key, [key, value]), 2), declaredName = _b[0], publicName = _b[1]; } minifiedName = declaredName; return { key: minifiedName, // put quotes around keys that contain potentially unsafe characters quoted: UNSAFE_OBJECT_KEY_NAME_REGEXP.test(minifiedName), value: (keepDeclared && publicName !== declaredName) ? literalArr([asLiteral(publicName), asLiteral(declaredName)]) : asLiteral(publicName) }; })); } /** * Remove trailing null nodes as they are implied. */ function trimTrailingNulls(parameters) { while (isNull(parameters[parameters.length - 1])) { parameters.pop(); } return parameters; } function getQueryPredicate(query, constantPool) { if (Array.isArray(query.predicate)) { var predicate_1 = []; query.predicate.forEach(function (selector) { // Each item in predicates array may contain strings with comma-separated refs // (for ex. 'ref, ref1, ..., refN'), thus we extract individual refs and store them // as separate array entities var selectors = selector.split(',').map(function (token) { return literal(token.trim()); }); predicate_1.push.apply(predicate_1, __spread(selectors)); }); return constantPool.getConstLiteral(literalArr(predicate_1), true); } else { return query.predicate; } } function noop() { } var DefinitionMap = /** @class */ (function () { function DefinitionMap() { this.values = []; } DefinitionMap.prototype.set = function (key, value) { if (value) { this.values.push({ key: key, value: value, quoted: false }); } }; DefinitionMap.prototype.toLiteralMap = function () { return literalMap(this.values); }; return DefinitionMap; }()); /** * Extract a map of properties to values for a given element or template node, which can be used * by the directive matching machinery. * * @param elOrTpl the element or template in question * @return an object set up for directive matching. For attributes on the element/template, this * object maps a property name to its (static) value. For any bindings, this map simply maps the * property name to an empty string. */ function getAttrsForDirectiveMatching(elOrTpl) { var attributesMap = {}; if (elOrTpl instanceof Template && elOrTpl.tagName !== 'ng-template') { elOrTpl.templateAttrs.forEach(function (a) { return attributesMap[a.name] = ''; }); } else { elOrTpl.attributes.forEach(function (a) { if (!isI18nAttribute(a.name)) { attributesMap[a.name] = a.value; } }); elOrTpl.inputs.forEach(function (i) { attributesMap[i.name] = ''; }); elOrTpl.outputs.forEach(function (o) { attributesMap[o.name] = ''; }); } return attributesMap; } /** Returns a call expression to a chained instruction, e.g. `property(params[0])(params[1])`. */ function chainedInstruction(reference, calls, span) { var expression = importExpr(reference, null, span); if (calls.length > 0) { for (var i = 0; i < calls.length; i++) { expression = expression.callFn(calls[i], span); } } else { // Add a blank invocation, in case the `calls` array is empty. expression = expression.callFn([], span); } return expression; } /** * Gets the number of arguments expected to be passed to a generated instruction in the case of * interpolation instructions. * @param interpolation An interpolation ast */ function getInterpolationArgsLength(interpolation) { var expressions = interpolation.expressions, strings = interpolation.strings; if (expressions.length === 1 && strings.length === 2 && strings[0] === '' && strings[1] === '') { // If the interpolation has one interpolated value, but the prefix and suffix are both empty // strings, we only pass one argument, to a special instruction like `propertyInterpolate` or // `textInterpolate`. return 1; } else { return expressions.length + strings.length; } } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var R3FactoryDelegateType; (function (R3FactoryDelegateType) { R3FactoryDelegateType[R3FactoryDelegateType["Class"] = 0] = "Class"; R3FactoryDelegateType[R3FactoryDelegateType["Function"] = 1] = "Function"; R3FactoryDelegateType[R3FactoryDelegateType["Factory"] = 2] = "Factory"; })(R3FactoryDelegateType || (R3FactoryDelegateType = {})); var R3FactoryTarget; (function (R3FactoryTarget) { R3FactoryTarget[R3FactoryTarget["Directive"] = 0] = "Directive"; R3FactoryTarget[R3FactoryTarget["Component"] = 1] = "Component"; R3FactoryTarget[R3FactoryTarget["Injectable"] = 2] = "Injectable"; R3FactoryTarget[R3FactoryTarget["Pipe"] = 3] = "Pipe"; R3FactoryTarget[R3FactoryTarget["NgModule"] = 4] = "NgModule"; })(R3FactoryTarget || (R3FactoryTarget = {})); /** * Resolved type of a dependency. * * Occasionally, dependencies will have special significance which is known statically. In that * case the `R3ResolvedDependencyType` informs the factory generator that a particular dependency * should be generated specially (usually by calling a special injection function instead of the * standard one). */ var R3ResolvedDependencyType; (function (R3ResolvedDependencyType) { /** * A normal token dependency. */ R3ResolvedDependencyType[R3ResolvedDependencyType["Token"] = 0] = "Token"; /** * The dependency is for an attribute. * * The token expression is a string representing the attribute name. */ R3ResolvedDependencyType[R3ResolvedDependencyType["Attribute"] = 1] = "Attribute"; /** * Injecting the `ChangeDetectorRef` token. Needs special handling when injected into a pipe. */ R3ResolvedDependencyType[R3ResolvedDependencyType["ChangeDetectorRef"] = 2] = "ChangeDetectorRef"; /** * An invalid dependency (no token could be determined). An error should be thrown at runtime. */ R3ResolvedDependencyType[R3ResolvedDependencyType["Invalid"] = 3] = "Invalid"; })(R3ResolvedDependencyType || (R3ResolvedDependencyType = {})); /** * Construct a factory function expression for the given `R3FactoryMetadata`. */ function compileFactoryFunction(meta) { var t = variable('t'); var statements = []; // The type to instantiate via constructor invocation. If there is no delegated factory, meaning // this type is always created by constructor invocation, then this is the type-to-create // parameter provided by the user (t) if specified, or the current type if not. If there is a // delegated factory (which is used to create the current type) then this is only the type-to- // create parameter (t). var typeForCtor = !isDelegatedMetadata(meta) ? new BinaryOperatorExpr(BinaryOperator.Or, t, meta.internalType) : t; var ctorExpr = null; if (meta.deps !== null) { // There is a constructor (either explicitly or implicitly defined). if (meta.deps !== 'invalid') { ctorExpr = new InstantiateExpr(typeForCtor, injectDependencies(meta.deps, meta.injectFn, meta.target === R3FactoryTarget.Pipe)); } } else { var baseFactory = variable("\u0275" + meta.name + "_BaseFactory"); var getInheritedFactory = importExpr(Identifiers$1.getInheritedFactory); var baseFactoryStmt = baseFactory.set(getInheritedFactory.callFn([meta.internalType])) .toDeclStmt(INFERRED_TYPE, [StmtModifier.Exported, StmtModifier.Final]); statements.push(baseFactoryStmt); // There is no constructor, use the base class' factory to construct typeForCtor. ctorExpr = baseFactory.callFn([typeForCtor]); } var ctorExprFinal = ctorExpr; var body = []; var retExpr = null; function makeConditionalFactory(nonCtorExpr) { var r = variable('r'); body.push(r.set(NULL_EXPR).toDeclStmt()); var ctorStmt = null; if (ctorExprFinal !== null) { ctorStmt = r.set(ctorExprFinal).toStmt(); } else { ctorStmt = importExpr(Identifiers$1.invalidFactory).callFn([]).toStmt(); } body.push(ifStmt(t, [ctorStmt], [r.set(nonCtorExpr).toStmt()])); return r; } if (isDelegatedMetadata(meta) && meta.delegateType === R3FactoryDelegateType.Factory) { var delegateFactory = variable("\u0275" + meta.name + "_BaseFactory"); var getFactoryOf = importExpr(Identifiers$1.getFactoryOf); if (meta.delegate.isEquivalent(meta.internalType)) { throw new Error("Illegal state: compiling factory that delegates to itself"); } var delegateFactoryStmt = delegateFactory.set(getFactoryOf.callFn([meta.delegate])).toDeclStmt(INFERRED_TYPE, [ StmtModifier.Exported, StmtModifier.Final ]); statements.push(delegateFactoryStmt); retExpr = makeConditionalFactory(delegateFactory.callFn([])); } else if (isDelegatedMetadata(meta)) { // This type is created with a delegated factory. If a type parameter is not specified, call // the factory instead. var delegateArgs = injectDependencies(meta.delegateDeps, meta.injectFn, meta.target === R3FactoryTarget.Pipe); // Either call `new delegate(...)` or `delegate(...)` depending on meta.delegateType. var factoryExpr = new (meta.delegateType === R3FactoryDelegateType.Class ? InstantiateExpr : InvokeFunctionExpr)(meta.delegate, delegateArgs); retExpr = makeConditionalFactory(factoryExpr); } else if (isExpressionFactoryMetadata(meta)) { // TODO(alxhub): decide whether to lower the value here or in the caller retExpr = makeConditionalFactory(meta.expression); } else { retExpr = ctorExpr; } if (retExpr !== null) { body.push(new ReturnStatement(retExpr)); } else { body.push(importExpr(Identifiers$1.invalidFactory).callFn([]).toStmt()); } return { factory: fn([new FnParam('t', DYNAMIC_TYPE)], body, INFERRED_TYPE, undefined, meta.name + "_Factory"), statements: statements, type: expressionType(importExpr(Identifiers$1.FactoryDef, [typeWithParameters(meta.type.type, meta.typeArgumentCount)])) }; } function injectDependencies(deps, injectFn, isPipe) { return deps.map(function (dep, index) { return compileInjectDependency(dep, injectFn, isPipe, index); }); } function compileInjectDependency(dep, injectFn, isPipe, index) { // Interpret the dependency according to its resolved type. switch (dep.resolved) { case R3ResolvedDependencyType.Token: case R3ResolvedDependencyType.ChangeDetectorRef: // Build up the injection flags according to the metadata. var flags = 0 /* Default */ | (dep.self ? 2 /* Self */ : 0) | (dep.skipSelf ? 4 /* SkipSelf */ : 0) | (dep.host ? 1 /* Host */ : 0) | (dep.optional ? 8 /* Optional */ : 0); // If this dependency is optional or otherwise has non-default flags, then additional // parameters describing how to inject the dependency must be passed to the inject function // that's being used. var flagsParam = (flags !== 0 /* Default */ || dep.optional) ? literal(flags) : null; // We have a separate instruction for injecting ChangeDetectorRef into a pipe. if (isPipe && dep.resolved === R3ResolvedDependencyType.ChangeDetectorRef) { return importExpr(Identifiers$1.injectPipeChangeDetectorRef).callFn(flagsParam ? [flagsParam] : []); } // Build up the arguments to the injectFn call. var injectArgs = [dep.token]; if (flagsParam) { injectArgs.push(flagsParam); } return importExpr(injectFn).callFn(injectArgs); case R3ResolvedDependencyType.Attribute: // In the case of attributes, the attribute name in question is given as the token. return importExpr(Identifiers$1.injectAttribute).callFn([dep.token]); case R3ResolvedDependencyType.Invalid: return importExpr(Identifiers$1.invalidFactoryDep).callFn([literal(index)]); default: return unsupported("Unknown R3ResolvedDependencyType: " + R3ResolvedDependencyType[dep.resolved]); } } /** * A helper function useful for extracting `R3DependencyMetadata` from a Render2 * `CompileTypeMetadata` instance. */ function dependenciesFromGlobalMetadata(type, outputCtx, reflector) { var e_1, _a; // Use the `CompileReflector` to look up references to some well-known Angular types. These will // be compared with the token to statically determine whether the token has significance to // Angular, and set the correct `R3ResolvedDependencyType` as a result. var injectorRef = reflector.resolveExternalReference(Identifiers.Injector); // Iterate through the type's DI dependencies and produce `R3DependencyMetadata` for each of them. var deps = []; try { for (var _b = __values(type.diDeps), _c = _b.next(); !_c.done; _c = _b.next()) { var dependency = _c.value; if (dependency.token) { var tokenRef = tokenReference(dependency.token); var resolved = dependency.isAttribute ? R3ResolvedDependencyType.Attribute : R3ResolvedDependencyType.Token; // In the case of most dependencies, the token will be a reference to a type. Sometimes, // however, it can be a string, in the case of older Angular code or @Attribute injection. var token = tokenRef instanceof StaticSymbol ? outputCtx.importExpr(tokenRef) : literal(tokenRef); // Construct the dependency. deps.push({ token: token, resolved: resolved, host: !!dependency.isHost, optional: !!dependency.isOptional, self: !!dependency.isSelf, skipSelf: !!dependency.isSkipSelf, }); } else { unsupported('dependency without a token'); } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) _a.call(_b); } finally { if (e_1) throw e_1.error; } } return deps; } function isDelegatedMetadata(meta) { return meta.delegateType !== undefined; } function isExpressionFactoryMetadata(meta) { return meta.expression !== undefined; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ function compileInjectable(meta) { var result = null; var factoryMeta = { name: meta.name, type: meta.type, internalType: meta.internalType, typeArgumentCount: meta.typeArgumentCount, deps: [], injectFn: Identifiers.inject, target: R3FactoryTarget.Injectable, }; if (meta.useClass !== undefined) { // meta.useClass has two modes of operation. Either deps are specified, in which case `new` is // used to instantiate the class with dependencies injected, or deps are not specified and // the factory of the class is used to instantiate it. // // A special case exists for useClass: Type where Type is the injectable type itself and no // deps are specified, in which case 'useClass' is effectively ignored. var useClassOnSelf = meta.useClass.isEquivalent(meta.internalType); var deps = undefined; if (meta.userDeps !== undefined) { deps = meta.userDeps; } if (deps !== undefined) { // factory: () => new meta.useClass(...deps) result = compileFactoryFunction(__assign(__assign({}, factoryMeta), { delegate: meta.useClass, delegateDeps: deps, delegateType: R3FactoryDelegateType.Class })); } else if (useClassOnSelf) { result = compileFactoryFunction(factoryMeta); } else { result = delegateToFactory(meta.type.value, meta.useClass); } } else if (meta.useFactory !== undefined) { if (meta.userDeps !== undefined) { result = compileFactoryFunction(__assign(__assign({}, factoryMeta), { delegate: meta.useFactory, delegateDeps: meta.userDeps || [], delegateType: R3FactoryDelegateType.Function })); } else { result = { statements: [], factory: fn([], [new ReturnStatement(meta.useFactory.callFn([]))]) }; } } else if (meta.useValue !== undefined) { // Note: it's safe to use `meta.useValue` instead of the `USE_VALUE in meta` check used for // client code because meta.useValue is an Expression which will be defined even if the actual // value is undefined. result = compileFactoryFunction(__assign(__assign({}, factoryMeta), { expression: meta.useValue })); } else if (meta.useExisting !== undefined) { // useExisting is an `inject` call on the existing token. result = compileFactoryFunction(__assign(__assign({}, factoryMeta), { expression: importExpr(Identifiers.inject).callFn([meta.useExisting]) })); } else { result = delegateToFactory(meta.type.value, meta.internalType); } var token = meta.internalType; var injectableProps = { token: token, factory: result.factory }; // Only generate providedIn property if it has a non-null value if (meta.providedIn.value !== null) { injectableProps.providedIn = meta.providedIn; } var expression = importExpr(Identifiers.ɵɵdefineInjectable).callFn([mapToMapExpression(injectableProps)]); var type = new ExpressionType(importExpr(Identifiers.InjectableDef, [typeWithParameters(meta.type.type, meta.typeArgumentCount)])); return { expression: expression, type: type, statements: result.statements, }; } function delegateToFactory(type, internalType) { return { statements: [], // If types are the same, we can generate `factory: type.ɵfac` // If types are different, we have to generate a wrapper function to ensure // the internal type has been resolved (`factory: function(t) { return type.ɵfac(t); }`) factory: type.node === internalType.node ? internalType.prop('ɵfac') : fn([new FnParam('t', DYNAMIC_TYPE)], [new ReturnStatement(internalType.callMethod('ɵfac', [variable('t')]))]) }; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ function assertArrayOfStrings(identifier, value) { if (value == null) { return; } if (!Array.isArray(value)) { throw new Error("Expected '" + identifier + "' to be an array of strings."); } for (var i = 0; i < value.length; i += 1) { if (typeof value[i] !== 'string') { throw new Error("Expected '" + identifier + "' to be an array of strings."); } } } var UNUSABLE_INTERPOLATION_REGEXPS = [ /^\s*$/, /[<>]/, /^[{}]$/, /&(#|[a-z])/i, /^\/\//, ]; function assertInterpolationSymbols(identifier, value) { if (value != null && !(Array.isArray(value) && value.length == 2)) { throw new Error("Expected '" + identifier + "' to be an array, [start, end]."); } else if (value != null) { var start_1 = value[0]; var end_1 = value[1]; // Check for unusable interpolation symbols UNUSABLE_INTERPOLATION_REGEXPS.forEach(function (regexp) { if (regexp.test(start_1) || regexp.test(end_1)) { throw new Error("['" + start_1 + "', '" + end_1 + "'] contains unusable interpolation symbol."); } }); } } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var InterpolationConfig = /** @class */ (function () { function InterpolationConfig(start, end) { this.start = start; this.end = end; } InterpolationConfig.fromArray = function (markers) { if (!markers) { return DEFAULT_INTERPOLATION_CONFIG; } assertInterpolationSymbols('interpolation', markers); return new InterpolationConfig(markers[0], markers[1]); }; return InterpolationConfig; }()); var DEFAULT_INTERPOLATION_CONFIG = new InterpolationConfig('{{', '}}'); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit var VERSION = 3; var JS_B64_PREFIX = '# sourceMappingURL=data:application/json;base64,'; var SourceMapGenerator = /** @class */ (function () { function SourceMapGenerator(file) { if (file === void 0) { file = null; } this.file = file; this.sourcesContent = new Map(); this.lines = []; this.lastCol0 = 0; this.hasMappings = false; } // The content is `null` when the content is expected to be loaded using the URL SourceMapGenerator.prototype.addSource = function (url, content) { if (content === void 0) { content = null; } if (!this.sourcesContent.has(url)) { this.sourcesContent.set(url, content); } return this; }; SourceMapGenerator.prototype.addLine = function () { this.lines.push([]); this.lastCol0 = 0; return this; }; SourceMapGenerator.prototype.addMapping = function (col0, sourceUrl, sourceLine0, sourceCol0) { if (!this.currentLine) { throw new Error("A line must be added before mappings can be added"); } if (sourceUrl != null && !this.sourcesContent.has(sourceUrl)) { throw new Error("Unknown source file \"" + sourceUrl + "\""); } if (col0 == null) { throw new Error("The column in the generated code must be provided"); } if (col0 < this.lastCol0) { throw new Error("Mapping should be added in output order"); } if (sourceUrl && (sourceLine0 == null || sourceCol0 == null)) { throw new Error("The source location must be provided when a source url is provided"); } this.hasMappings = true; this.lastCol0 = col0; this.currentLine.push({ col0: col0, sourceUrl: sourceUrl, sourceLine0: sourceLine0, sourceCol0: sourceCol0 }); return this; }; Object.defineProperty(SourceMapGenerator.prototype, "currentLine", { /** * @internal strip this from published d.ts files due to * https://github.com/microsoft/TypeScript/issues/36216 */ get: function () { return this.lines.slice(-1)[0]; }, enumerable: true, configurable: true }); SourceMapGenerator.prototype.toJSON = function () { var _this = this; if (!this.hasMappings) { return null; } var sourcesIndex = new Map(); var sources = []; var sourcesContent = []; Array.from(this.sourcesContent.keys()).forEach(function (url, i) { sourcesIndex.set(url, i); sources.push(url); sourcesContent.push(_this.sourcesContent.get(url) || null); }); var mappings = ''; var lastCol0 = 0; var lastSourceIndex = 0; var lastSourceLine0 = 0; var lastSourceCol0 = 0; this.lines.forEach(function (segments) { lastCol0 = 0; mappings += segments .map(function (segment) { // zero-based starting column of the line in the generated code var segAsStr = toBase64VLQ(segment.col0 - lastCol0); lastCol0 = segment.col0; if (segment.sourceUrl != null) { // zero-based index into the “sources” list segAsStr += toBase64VLQ(sourcesIndex.get(segment.sourceUrl) - lastSourceIndex); lastSourceIndex = sourcesIndex.get(segment.sourceUrl); // the zero-based starting line in the original source segAsStr += toBase64VLQ(segment.sourceLine0 - lastSourceLine0); lastSourceLine0 = segment.sourceLine0; // the zero-based starting column in the original source segAsStr += toBase64VLQ(segment.sourceCol0 - lastSourceCol0); lastSourceCol0 = segment.sourceCol0; } return segAsStr; }) .join(','); mappings += ';'; }); mappings = mappings.slice(0, -1); return { 'file': this.file || '', 'version': VERSION, 'sourceRoot': '', 'sources': sources, 'sourcesContent': sourcesContent, 'mappings': mappings, }; }; SourceMapGenerator.prototype.toJsComment = function () { return this.hasMappings ? '//' + JS_B64_PREFIX + toBase64String(JSON.stringify(this, null, 0)) : ''; }; return SourceMapGenerator; }()); function toBase64String(value) { var b64 = ''; value = utf8Encode(value); for (var i = 0; i < value.length;) { var i1 = value.charCodeAt(i++); var i2 = value.charCodeAt(i++); var i3 = value.charCodeAt(i++); b64 += toBase64Digit(i1 >> 2); b64 += toBase64Digit(((i1 & 3) << 4) | (isNaN(i2) ? 0 : i2 >> 4)); b64 += isNaN(i2) ? '=' : toBase64Digit(((i2 & 15) << 2) | (i3 >> 6)); b64 += isNaN(i2) || isNaN(i3) ? '=' : toBase64Digit(i3 & 63); } return b64; } function toBase64VLQ(value) { value = value < 0 ? ((-value) << 1) + 1 : value << 1; var out = ''; do { var digit = value & 31; value = value >> 5; if (value > 0) { digit = digit | 32; } out += toBase64Digit(digit); } while (value > 0); return out; } var B64_DIGITS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; function toBase64Digit(value) { if (value < 0 || value >= 64) { throw new Error("Can only encode value in the range [0, 63]"); } return B64_DIGITS[value]; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var _SINGLE_QUOTE_ESCAPE_STRING_RE = /'|\\|\n|\r|\$/g; var _LEGAL_IDENTIFIER_RE = /^[$A-Z_][0-9A-Z_$]*$/i; var _INDENT_WITH = ' '; var CATCH_ERROR_VAR$1 = variable('error', null, null); var CATCH_STACK_VAR$1 = variable('stack', null, null); var _EmittedLine = /** @class */ (function () { function _EmittedLine(indent) { this.indent = indent; this.partsLength = 0; this.parts = []; this.srcSpans = []; } return _EmittedLine; }()); var EmitterVisitorContext = /** @class */ (function () { function EmitterVisitorContext(_indent) { this._indent = _indent; this._classes = []; this._preambleLineCount = 0; this._lines = [new _EmittedLine(_indent)]; } EmitterVisitorContext.createRoot = function () { return new EmitterVisitorContext(0); }; Object.defineProperty(EmitterVisitorContext.prototype, "_currentLine", { /** * @internal strip this from published d.ts files due to * https://github.com/microsoft/TypeScript/issues/36216 */ get: function () { return this._lines[this._lines.length - 1]; }, enumerable: true, configurable: true }); EmitterVisitorContext.prototype.println = function (from, lastPart) { if (lastPart === void 0) { lastPart = ''; } this.print(from || null, lastPart, true); }; EmitterVisitorContext.prototype.lineIsEmpty = function () { return this._currentLine.parts.length === 0; }; EmitterVisitorContext.prototype.lineLength = function () { return this._currentLine.indent * _INDENT_WITH.length + this._currentLine.partsLength; }; EmitterVisitorContext.prototype.print = function (from, part, newLine) { if (newLine === void 0) { newLine = false; } if (part.length > 0) { this._currentLine.parts.push(part); this._currentLine.partsLength += part.length; this._currentLine.srcSpans.push(from && from.sourceSpan || null); } if (newLine) { this._lines.push(new _EmittedLine(this._indent)); } }; EmitterVisitorContext.prototype.removeEmptyLastLine = function () { if (this.lineIsEmpty()) { this._lines.pop(); } }; EmitterVisitorContext.prototype.incIndent = function () { this._indent++; if (this.lineIsEmpty()) { this._currentLine.indent = this._indent; } }; EmitterVisitorContext.prototype.decIndent = function () { this._indent--; if (this.lineIsEmpty()) { this._currentLine.indent = this._indent; } }; EmitterVisitorContext.prototype.pushClass = function (clazz) { this._classes.push(clazz); }; EmitterVisitorContext.prototype.popClass = function () { return this._classes.pop(); }; Object.defineProperty(EmitterVisitorContext.prototype, "currentClass", { get: function () { return this._classes.length > 0 ? this._classes[this._classes.length - 1] : null; }, enumerable: true, configurable: true }); EmitterVisitorContext.prototype.toSource = function () { return this.sourceLines .map(function (l) { return l.parts.length > 0 ? _createIndent(l.indent) + l.parts.join('') : ''; }) .join('\n'); }; EmitterVisitorContext.prototype.toSourceMapGenerator = function (genFilePath, startsAtLine) { if (startsAtLine === void 0) { startsAtLine = 0; } var map = new SourceMapGenerator(genFilePath); var firstOffsetMapped = false; var mapFirstOffsetIfNeeded = function () { if (!firstOffsetMapped) { // Add a single space so that tools won't try to load the file from disk. // Note: We are using virtual urls like `ng:///`, so we have to // provide a content here. map.addSource(genFilePath, ' ').addMapping(0, genFilePath, 0, 0); firstOffsetMapped = true; } }; for (var i = 0; i < startsAtLine; i++) { map.addLine(); mapFirstOffsetIfNeeded(); } this.sourceLines.forEach(function (line, lineIdx) { map.addLine(); var spans = line.srcSpans; var parts = line.parts; var col0 = line.indent * _INDENT_WITH.length; var spanIdx = 0; // skip leading parts without source spans while (spanIdx < spans.length && !spans[spanIdx]) { col0 += parts[spanIdx].length; spanIdx++; } if (spanIdx < spans.length && lineIdx === 0 && col0 === 0) { firstOffsetMapped = true; } else { mapFirstOffsetIfNeeded(); } while (spanIdx < spans.length) { var span = spans[spanIdx]; var source = span.start.file; var sourceLine = span.start.line; var sourceCol = span.start.col; map.addSource(source.url, source.content) .addMapping(col0, source.url, sourceLine, sourceCol); col0 += parts[spanIdx].length; spanIdx++; // assign parts without span or the same span to the previous segment while (spanIdx < spans.length && (span === spans[spanIdx] || !spans[spanIdx])) { col0 += parts[spanIdx].length; spanIdx++; } } }); return map; }; EmitterVisitorContext.prototype.setPreambleLineCount = function (count) { return this._preambleLineCount = count; }; EmitterVisitorContext.prototype.spanOf = function (line, column) { var emittedLine = this._lines[line - this._preambleLineCount]; if (emittedLine) { var columnsLeft = column - _createIndent(emittedLine.indent).length; for (var partIndex = 0; partIndex < emittedLine.parts.length; partIndex++) { var part = emittedLine.parts[partIndex]; if (part.length > columnsLeft) { return emittedLine.srcSpans[partIndex]; } columnsLeft -= part.length; } } return null; }; Object.defineProperty(EmitterVisitorContext.prototype, "sourceLines", { /** * @internal strip this from published d.ts files due to * https://github.com/microsoft/TypeScript/issues/36216 */ get: function () { if (this._lines.length && this._lines[this._lines.length - 1].parts.length === 0) { return this._lines.slice(0, -1); } return this._lines; }, enumerable: true, configurable: true }); return EmitterVisitorContext; }()); var AbstractEmitterVisitor = /** @class */ (function () { function AbstractEmitterVisitor(_escapeDollarInStrings) { this._escapeDollarInStrings = _escapeDollarInStrings; } AbstractEmitterVisitor.prototype.visitExpressionStmt = function (stmt, ctx) { stmt.expr.visitExpression(this, ctx); ctx.println(stmt, ';'); return null; }; AbstractEmitterVisitor.prototype.visitReturnStmt = function (stmt, ctx) { ctx.print(stmt, "return "); stmt.value.visitExpression(this, ctx); ctx.println(stmt, ';'); return null; }; AbstractEmitterVisitor.prototype.visitIfStmt = function (stmt, ctx) { ctx.print(stmt, "if ("); stmt.condition.visitExpression(this, ctx); ctx.print(stmt, ") {"); var hasElseCase = stmt.falseCase != null && stmt.falseCase.length > 0; if (stmt.trueCase.length <= 1 && !hasElseCase) { ctx.print(stmt, " "); this.visitAllStatements(stmt.trueCase, ctx); ctx.removeEmptyLastLine(); ctx.print(stmt, " "); } else { ctx.println(); ctx.incIndent(); this.visitAllStatements(stmt.trueCase, ctx); ctx.decIndent(); if (hasElseCase) { ctx.println(stmt, "} else {"); ctx.incIndent(); this.visitAllStatements(stmt.falseCase, ctx); ctx.decIndent(); } } ctx.println(stmt, "}"); return null; }; AbstractEmitterVisitor.prototype.visitThrowStmt = function (stmt, ctx) { ctx.print(stmt, "throw "); stmt.error.visitExpression(this, ctx); ctx.println(stmt, ";"); return null; }; AbstractEmitterVisitor.prototype.visitCommentStmt = function (stmt, ctx) { if (stmt.multiline) { ctx.println(stmt, "/* " + stmt.comment + " */"); } else { stmt.comment.split('\n').forEach(function (line) { ctx.println(stmt, "// " + line); }); } return null; }; AbstractEmitterVisitor.prototype.visitJSDocCommentStmt = function (stmt, ctx) { ctx.println(stmt, "/*" + stmt.toString() + "*/"); return null; }; AbstractEmitterVisitor.prototype.visitWriteVarExpr = function (expr, ctx) { var lineWasEmpty = ctx.lineIsEmpty(); if (!lineWasEmpty) { ctx.print(expr, '('); } ctx.print(expr, expr.name + " = "); expr.value.visitExpression(this, ctx); if (!lineWasEmpty) { ctx.print(expr, ')'); } return null; }; AbstractEmitterVisitor.prototype.visitWriteKeyExpr = function (expr, ctx) { var lineWasEmpty = ctx.lineIsEmpty(); if (!lineWasEmpty) { ctx.print(expr, '('); } expr.receiver.visitExpression(this, ctx); ctx.print(expr, "["); expr.index.visitExpression(this, ctx); ctx.print(expr, "] = "); expr.value.visitExpression(this, ctx); if (!lineWasEmpty) { ctx.print(expr, ')'); } return null; }; AbstractEmitterVisitor.prototype.visitWritePropExpr = function (expr, ctx) { var lineWasEmpty = ctx.lineIsEmpty(); if (!lineWasEmpty) { ctx.print(expr, '('); } expr.receiver.visitExpression(this, ctx); ctx.print(expr, "." + expr.name + " = "); expr.value.visitExpression(this, ctx); if (!lineWasEmpty) { ctx.print(expr, ')'); } return null; }; AbstractEmitterVisitor.prototype.visitInvokeMethodExpr = function (expr, ctx) { expr.receiver.visitExpression(this, ctx); var name = expr.name; if (expr.builtin != null) { name = this.getBuiltinMethodName(expr.builtin); if (name == null) { // some builtins just mean to skip the call. return null; } } ctx.print(expr, "." + name + "("); this.visitAllExpressions(expr.args, ctx, ","); ctx.print(expr, ")"); return null; }; AbstractEmitterVisitor.prototype.visitInvokeFunctionExpr = function (expr, ctx) { expr.fn.visitExpression(this, ctx); ctx.print(expr, "("); this.visitAllExpressions(expr.args, ctx, ','); ctx.print(expr, ")"); return null; }; AbstractEmitterVisitor.prototype.visitWrappedNodeExpr = function (ast, ctx) { throw new Error('Abstract emitter cannot visit WrappedNodeExpr.'); }; AbstractEmitterVisitor.prototype.visitTypeofExpr = function (expr, ctx) { ctx.print(expr, 'typeof '); expr.expr.visitExpression(this, ctx); }; AbstractEmitterVisitor.prototype.visitReadVarExpr = function (ast, ctx) { var varName = ast.name; if (ast.builtin != null) { switch (ast.builtin) { case BuiltinVar.Super: varName = 'super'; break; case BuiltinVar.This: varName = 'this'; break; case BuiltinVar.CatchError: varName = CATCH_ERROR_VAR$1.name; break; case BuiltinVar.CatchStack: varName = CATCH_STACK_VAR$1.name; break; default: throw new Error("Unknown builtin variable " + ast.builtin); } } ctx.print(ast, varName); return null; }; AbstractEmitterVisitor.prototype.visitInstantiateExpr = function (ast, ctx) { ctx.print(ast, "new "); ast.classExpr.visitExpression(this, ctx); ctx.print(ast, "("); this.visitAllExpressions(ast.args, ctx, ','); ctx.print(ast, ")"); return null; }; AbstractEmitterVisitor.prototype.visitLiteralExpr = function (ast, ctx) { var value = ast.value; if (typeof value === 'string') { ctx.print(ast, escapeIdentifier(value, this._escapeDollarInStrings)); } else { ctx.print(ast, "" + value); } return null; }; AbstractEmitterVisitor.prototype.visitLocalizedString = function (ast, ctx) { var head = ast.serializeI18nHead(); ctx.print(ast, '$localize `' + head.raw); for (var i = 1; i < ast.messageParts.length; i++) { ctx.print(ast, '${'); ast.expressions[i - 1].visitExpression(this, ctx); ctx.print(ast, "}" + ast.serializeI18nTemplatePart(i).raw); } ctx.print(ast, '`'); return null; }; AbstractEmitterVisitor.prototype.visitConditionalExpr = function (ast, ctx) { ctx.print(ast, "("); ast.condition.visitExpression(this, ctx); ctx.print(ast, '? '); ast.trueCase.visitExpression(this, ctx); ctx.print(ast, ': '); ast.falseCase.visitExpression(this, ctx); ctx.print(ast, ")"); return null; }; AbstractEmitterVisitor.prototype.visitNotExpr = function (ast, ctx) { ctx.print(ast, '!'); ast.condition.visitExpression(this, ctx); return null; }; AbstractEmitterVisitor.prototype.visitAssertNotNullExpr = function (ast, ctx) { ast.condition.visitExpression(this, ctx); return null; }; AbstractEmitterVisitor.prototype.visitBinaryOperatorExpr = function (ast, ctx) { var opStr; switch (ast.operator) { case BinaryOperator.Equals: opStr = '=='; break; case BinaryOperator.Identical: opStr = '==='; break; case BinaryOperator.NotEquals: opStr = '!='; break; case BinaryOperator.NotIdentical: opStr = '!=='; break; case BinaryOperator.And: opStr = '&&'; break; case BinaryOperator.BitwiseAnd: opStr = '&'; break; case BinaryOperator.Or: opStr = '||'; break; case BinaryOperator.Plus: opStr = '+'; break; case BinaryOperator.Minus: opStr = '-'; break; case BinaryOperator.Divide: opStr = '/'; break; case BinaryOperator.Multiply: opStr = '*'; break; case BinaryOperator.Modulo: opStr = '%'; break; case BinaryOperator.Lower: opStr = '<'; break; case BinaryOperator.LowerEquals: opStr = '<='; break; case BinaryOperator.Bigger: opStr = '>'; break; case BinaryOperator.BiggerEquals: opStr = '>='; break; default: throw new Error("Unknown operator " + ast.operator); } if (ast.parens) ctx.print(ast, "("); ast.lhs.visitExpression(this, ctx); ctx.print(ast, " " + opStr + " "); ast.rhs.visitExpression(this, ctx); if (ast.parens) ctx.print(ast, ")"); return null; }; AbstractEmitterVisitor.prototype.visitReadPropExpr = function (ast, ctx) { ast.receiver.visitExpression(this, ctx); ctx.print(ast, "."); ctx.print(ast, ast.name); return null; }; AbstractEmitterVisitor.prototype.visitReadKeyExpr = function (ast, ctx) { ast.receiver.visitExpression(this, ctx); ctx.print(ast, "["); ast.index.visitExpression(this, ctx); ctx.print(ast, "]"); return null; }; AbstractEmitterVisitor.prototype.visitLiteralArrayExpr = function (ast, ctx) { ctx.print(ast, "["); this.visitAllExpressions(ast.entries, ctx, ','); ctx.print(ast, "]"); return null; }; AbstractEmitterVisitor.prototype.visitLiteralMapExpr = function (ast, ctx) { var _this = this; ctx.print(ast, "{"); this.visitAllObjects(function (entry) { ctx.print(ast, escapeIdentifier(entry.key, _this._escapeDollarInStrings, entry.quoted) + ":"); entry.value.visitExpression(_this, ctx); }, ast.entries, ctx, ','); ctx.print(ast, "}"); return null; }; AbstractEmitterVisitor.prototype.visitCommaExpr = function (ast, ctx) { ctx.print(ast, '('); this.visitAllExpressions(ast.parts, ctx, ','); ctx.print(ast, ')'); return null; }; AbstractEmitterVisitor.prototype.visitAllExpressions = function (expressions, ctx, separator) { var _this = this; this.visitAllObjects(function (expr) { return expr.visitExpression(_this, ctx); }, expressions, ctx, separator); }; AbstractEmitterVisitor.prototype.visitAllObjects = function (handler, expressions, ctx, separator) { var incrementedIndent = false; for (var i = 0; i < expressions.length; i++) { if (i > 0) { if (ctx.lineLength() > 80) { ctx.print(null, separator, true); if (!incrementedIndent) { // continuation are marked with double indent. ctx.incIndent(); ctx.incIndent(); incrementedIndent = true; } } else { ctx.print(null, separator, false); } } handler(expressions[i]); } if (incrementedIndent) { // continuation are marked with double indent. ctx.decIndent(); ctx.decIndent(); } }; AbstractEmitterVisitor.prototype.visitAllStatements = function (statements, ctx) { var _this = this; statements.forEach(function (stmt) { return stmt.visitStatement(_this, ctx); }); }; return AbstractEmitterVisitor; }()); function escapeIdentifier(input, escapeDollar, alwaysQuote) { if (alwaysQuote === void 0) { alwaysQuote = true; } if (input == null) { return null; } var body = input.replace(_SINGLE_QUOTE_ESCAPE_STRING_RE, function () { var match = []; for (var _i = 0; _i < arguments.length; _i++) { match[_i] = arguments[_i]; } if (match[0] == '$') { return escapeDollar ? '\\$' : '$'; } else if (match[0] == '\n') { return '\\n'; } else if (match[0] == '\r') { return '\\r'; } else { return "\\" + match[0]; } }); var requiresQuotes = alwaysQuote || !_LEGAL_IDENTIFIER_RE.test(body); return requiresQuotes ? "'" + body + "'" : body; } function _createIndent(count) { var res = ''; for (var i = 0; i < count; i++) { res += _INDENT_WITH; } return res; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var AbstractJsEmitterVisitor = /** @class */ (function (_super) { __extends(AbstractJsEmitterVisitor, _super); function AbstractJsEmitterVisitor() { return _super.call(this, false) || this; } AbstractJsEmitterVisitor.prototype.visitDeclareClassStmt = function (stmt, ctx) { var _this = this; ctx.pushClass(stmt); this._visitClassConstructor(stmt, ctx); if (stmt.parent != null) { ctx.print(stmt, stmt.name + ".prototype = Object.create("); stmt.parent.visitExpression(this, ctx); ctx.println(stmt, ".prototype);"); } stmt.getters.forEach(function (getter) { return _this._visitClassGetter(stmt, getter, ctx); }); stmt.methods.forEach(function (method) { return _this._visitClassMethod(stmt, method, ctx); }); ctx.popClass(); return null; }; AbstractJsEmitterVisitor.prototype._visitClassConstructor = function (stmt, ctx) { ctx.print(stmt, "function " + stmt.name + "("); if (stmt.constructorMethod != null) { this._visitParams(stmt.constructorMethod.params, ctx); } ctx.println(stmt, ") {"); ctx.incIndent(); if (stmt.constructorMethod != null) { if (stmt.constructorMethod.body.length > 0) { ctx.println(stmt, "var self = this;"); this.visitAllStatements(stmt.constructorMethod.body, ctx); } } ctx.decIndent(); ctx.println(stmt, "}"); }; AbstractJsEmitterVisitor.prototype._visitClassGetter = function (stmt, getter, ctx) { ctx.println(stmt, "Object.defineProperty(" + stmt.name + ".prototype, '" + getter.name + "', { get: function() {"); ctx.incIndent(); if (getter.body.length > 0) { ctx.println(stmt, "var self = this;"); this.visitAllStatements(getter.body, ctx); } ctx.decIndent(); ctx.println(stmt, "}});"); }; AbstractJsEmitterVisitor.prototype._visitClassMethod = function (stmt, method, ctx) { ctx.print(stmt, stmt.name + ".prototype." + method.name + " = function("); this._visitParams(method.params, ctx); ctx.println(stmt, ") {"); ctx.incIndent(); if (method.body.length > 0) { ctx.println(stmt, "var self = this;"); this.visitAllStatements(method.body, ctx); } ctx.decIndent(); ctx.println(stmt, "};"); }; AbstractJsEmitterVisitor.prototype.visitWrappedNodeExpr = function (ast, ctx) { throw new Error('Cannot emit a WrappedNodeExpr in Javascript.'); }; AbstractJsEmitterVisitor.prototype.visitReadVarExpr = function (ast, ctx) { if (ast.builtin === BuiltinVar.This) { ctx.print(ast, 'self'); } else if (ast.builtin === BuiltinVar.Super) { throw new Error("'super' needs to be handled at a parent ast node, not at the variable level!"); } else { _super.prototype.visitReadVarExpr.call(this, ast, ctx); } return null; }; AbstractJsEmitterVisitor.prototype.visitDeclareVarStmt = function (stmt, ctx) { ctx.print(stmt, "var " + stmt.name); if (stmt.value) { ctx.print(stmt, ' = '); stmt.value.visitExpression(this, ctx); } ctx.println(stmt, ";"); return null; }; AbstractJsEmitterVisitor.prototype.visitCastExpr = function (ast, ctx) { ast.value.visitExpression(this, ctx); return null; }; AbstractJsEmitterVisitor.prototype.visitInvokeFunctionExpr = function (expr, ctx) { var fnExpr = expr.fn; if (fnExpr instanceof ReadVarExpr && fnExpr.builtin === BuiltinVar.Super) { ctx.currentClass.parent.visitExpression(this, ctx); ctx.print(expr, ".call(this"); if (expr.args.length > 0) { ctx.print(expr, ", "); this.visitAllExpressions(expr.args, ctx, ','); } ctx.print(expr, ")"); } else { _super.prototype.visitInvokeFunctionExpr.call(this, expr, ctx); } return null; }; AbstractJsEmitterVisitor.prototype.visitFunctionExpr = function (ast, ctx) { ctx.print(ast, "function" + (ast.name ? ' ' + ast.name : '') + "("); this._visitParams(ast.params, ctx); ctx.println(ast, ") {"); ctx.incIndent(); this.visitAllStatements(ast.statements, ctx); ctx.decIndent(); ctx.print(ast, "}"); return null; }; AbstractJsEmitterVisitor.prototype.visitDeclareFunctionStmt = function (stmt, ctx) { ctx.print(stmt, "function " + stmt.name + "("); this._visitParams(stmt.params, ctx); ctx.println(stmt, ") {"); ctx.incIndent(); this.visitAllStatements(stmt.statements, ctx); ctx.decIndent(); ctx.println(stmt, "}"); return null; }; AbstractJsEmitterVisitor.prototype.visitTryCatchStmt = function (stmt, ctx) { ctx.println(stmt, "try {"); ctx.incIndent(); this.visitAllStatements(stmt.bodyStmts, ctx); ctx.decIndent(); ctx.println(stmt, "} catch (" + CATCH_ERROR_VAR$1.name + ") {"); ctx.incIndent(); var catchStmts = [CATCH_STACK_VAR$1.set(CATCH_ERROR_VAR$1.prop('stack')).toDeclStmt(null, [ StmtModifier.Final ])].concat(stmt.catchStmts); this.visitAllStatements(catchStmts, ctx); ctx.decIndent(); ctx.println(stmt, "}"); return null; }; AbstractJsEmitterVisitor.prototype.visitLocalizedString = function (ast, ctx) { var _this = this; // The following convoluted piece of code is effectively the downlevelled equivalent of // ``` // $localize `...` // ``` // which is effectively like: // ``` // $localize(__makeTemplateObject(cooked, raw), expression1, expression2, ...); // ``` // // The `$localize` function expects a "template object", which is an array of "cooked" strings // plus a `raw` property that contains an array of "raw" strings. // // In some environments a helper function called `__makeTemplateObject(cooked, raw)` might be // available, in which case we use that. Otherwise we must create our own helper function // inline. // // In the inline function, if `Object.defineProperty` is available we use that to attach the // `raw` array. ctx.print(ast, '$localize((this&&this.__makeTemplateObject||function(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e})('); var parts = [ast.serializeI18nHead()]; for (var i = 1; i < ast.messageParts.length; i++) { parts.push(ast.serializeI18nTemplatePart(i)); } ctx.print(ast, "[" + parts.map(function (part) { return escapeIdentifier(part.cooked, false); }).join(', ') + "], "); ctx.print(ast, "[" + parts.map(function (part) { return escapeIdentifier(part.raw, false); }).join(', ') + "])"); ast.expressions.forEach(function (expression) { ctx.print(ast, ', '); expression.visitExpression(_this, ctx); }); ctx.print(ast, ')'); return null; }; AbstractJsEmitterVisitor.prototype._visitParams = function (params, ctx) { this.visitAllObjects(function (param) { return ctx.print(null, param.name); }, params, ctx, ','); }; AbstractJsEmitterVisitor.prototype.getBuiltinMethodName = function (method) { var name; switch (method) { case BuiltinMethod.ConcatArray: name = 'concat'; break; case BuiltinMethod.SubscribeObservable: name = 'subscribe'; break; case BuiltinMethod.Bind: name = 'bind'; break; default: throw new Error("Unknown builtin method: " + method); } return name; }; return AbstractJsEmitterVisitor; }(AbstractEmitterVisitor)); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * A helper class to manage the evaluation of JIT generated code. */ var JitEvaluator = /** @class */ (function () { function JitEvaluator() { } /** * * @param sourceUrl The URL of the generated code. * @param statements An array of Angular statement AST nodes to be evaluated. * @param reflector A helper used when converting the statements to executable code. * @param createSourceMaps If true then create a source-map for the generated code and include it * inline as a source-map comment. * @returns A map of all the variables in the generated code. */ JitEvaluator.prototype.evaluateStatements = function (sourceUrl, statements, reflector, createSourceMaps) { var converter = new JitEmitterVisitor(reflector); var ctx = EmitterVisitorContext.createRoot(); // Ensure generated code is in strict mode if (statements.length > 0 && !isUseStrictStatement(statements[0])) { statements = __spread([ literal('use strict').toStmt() ], statements); } converter.visitAllStatements(statements, ctx); converter.createReturnStmt(ctx); return this.evaluateCode(sourceUrl, ctx, converter.getArgs(), createSourceMaps); }; /** * Evaluate a piece of JIT generated code. * @param sourceUrl The URL of this generated code. * @param ctx A context object that contains an AST of the code to be evaluated. * @param vars A map containing the names and values of variables that the evaluated code might * reference. * @param createSourceMap If true then create a source-map for the generated code and include it * inline as a source-map comment. * @returns The result of evaluating the code. */ JitEvaluator.prototype.evaluateCode = function (sourceUrl, ctx, vars, createSourceMap) { var fnBody = "\"use strict\";" + ctx.toSource() + "\n//# sourceURL=" + sourceUrl; var fnArgNames = []; var fnArgValues = []; for (var argName in vars) { fnArgValues.push(vars[argName]); fnArgNames.push(argName); } if (createSourceMap) { // using `new Function(...)` generates a header, 1 line of no arguments, 2 lines otherwise // E.g. ``` // function anonymous(a,b,c // /**/) { ... }``` // We don't want to hard code this fact, so we auto detect it via an empty function first. var emptyFn = new (Function.bind.apply(Function, __spread([void 0], fnArgNames.concat('return null;'))))().toString(); var headerLines = emptyFn.slice(0, emptyFn.indexOf('return null;')).split('\n').length - 1; fnBody += "\n" + ctx.toSourceMapGenerator(sourceUrl, headerLines).toJsComment(); } var fn = new (Function.bind.apply(Function, __spread([void 0], fnArgNames.concat(fnBody))))(); return this.executeFunction(fn, fnArgValues); }; /** * Execute a JIT generated function by calling it. * * This method can be overridden in tests to capture the functions that are generated * by this `JitEvaluator` class. * * @param fn A function to execute. * @param args The arguments to pass to the function being executed. * @returns The return value of the executed function. */ JitEvaluator.prototype.executeFunction = function (fn, args) { return fn.apply(void 0, __spread(args)); }; return JitEvaluator; }()); /** * An Angular AST visitor that converts AST nodes into executable JavaScript code. */ var JitEmitterVisitor = /** @class */ (function (_super) { __extends(JitEmitterVisitor, _super); function JitEmitterVisitor(reflector) { var _this = _super.call(this) || this; _this.reflector = reflector; _this._evalArgNames = []; _this._evalArgValues = []; _this._evalExportedVars = []; return _this; } JitEmitterVisitor.prototype.createReturnStmt = function (ctx) { var stmt = new ReturnStatement(new LiteralMapExpr(this._evalExportedVars.map(function (resultVar) { return new LiteralMapEntry(resultVar, variable(resultVar), false); }))); stmt.visitStatement(this, ctx); }; JitEmitterVisitor.prototype.getArgs = function () { var result = {}; for (var i = 0; i < this._evalArgNames.length; i++) { result[this._evalArgNames[i]] = this._evalArgValues[i]; } return result; }; JitEmitterVisitor.prototype.visitExternalExpr = function (ast, ctx) { this._emitReferenceToExternal(ast, this.reflector.resolveExternalReference(ast.value), ctx); return null; }; JitEmitterVisitor.prototype.visitWrappedNodeExpr = function (ast, ctx) { this._emitReferenceToExternal(ast, ast.node, ctx); return null; }; JitEmitterVisitor.prototype.visitDeclareVarStmt = function (stmt, ctx) { if (stmt.hasModifier(StmtModifier.Exported)) { this._evalExportedVars.push(stmt.name); } return _super.prototype.visitDeclareVarStmt.call(this, stmt, ctx); }; JitEmitterVisitor.prototype.visitDeclareFunctionStmt = function (stmt, ctx) { if (stmt.hasModifier(StmtModifier.Exported)) { this._evalExportedVars.push(stmt.name); } return _super.prototype.visitDeclareFunctionStmt.call(this, stmt, ctx); }; JitEmitterVisitor.prototype.visitDeclareClassStmt = function (stmt, ctx) { if (stmt.hasModifier(StmtModifier.Exported)) { this._evalExportedVars.push(stmt.name); } return _super.prototype.visitDeclareClassStmt.call(this, stmt, ctx); }; JitEmitterVisitor.prototype._emitReferenceToExternal = function (ast, value, ctx) { var id = this._evalArgValues.indexOf(value); if (id === -1) { id = this._evalArgValues.length; this._evalArgValues.push(value); var name_1 = identifierName({ reference: value }) || 'val'; this._evalArgNames.push("jit_" + name_1 + "_" + id); } ctx.print(ast, this._evalArgNames[id]); }; return JitEmitterVisitor; }(AbstractJsEmitterVisitor)); function isUseStrictStatement(statement) { return statement.isEquivalent(literal('use strict').toStmt()); } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Implementation of `CompileReflector` which resolves references to @angular/core * symbols at runtime, according to a consumer-provided mapping. * * Only supports `resolveExternalReference`, all other methods throw. */ var R3JitReflector = /** @class */ (function () { function R3JitReflector(context) { this.context = context; } R3JitReflector.prototype.resolveExternalReference = function (ref) { // This reflector only handles @angular/core imports. if (ref.moduleName !== '@angular/core') { throw new Error("Cannot resolve external reference to " + ref.moduleName + ", only references to @angular/core are supported."); } if (!this.context.hasOwnProperty(ref.name)) { throw new Error("No value provided for @angular/core symbol '" + ref.name + "'."); } return this.context[ref.name]; }; R3JitReflector.prototype.parameters = function (typeOrFunc) { throw new Error('Not implemented.'); }; R3JitReflector.prototype.annotations = function (typeOrFunc) { throw new Error('Not implemented.'); }; R3JitReflector.prototype.shallowAnnotations = function (typeOrFunc) { throw new Error('Not implemented.'); }; R3JitReflector.prototype.tryAnnotations = function (typeOrFunc) { throw new Error('Not implemented.'); }; R3JitReflector.prototype.propMetadata = function (typeOrFunc) { throw new Error('Not implemented.'); }; R3JitReflector.prototype.hasLifecycleHook = function (type, lcProperty) { throw new Error('Not implemented.'); }; R3JitReflector.prototype.guards = function (typeOrFunc) { throw new Error('Not implemented.'); }; R3JitReflector.prototype.componentModuleUrl = function (type, cmpMetadata) { throw new Error('Not implemented.'); }; return R3JitReflector; }()); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ function mapEntry(key, value) { return { key: key, value: value, quoted: false }; } function mapLiteral(obj, quoted) { if (quoted === void 0) { quoted = false; } return literalMap(Object.keys(obj).map(function (key) { return ({ key: key, quoted: quoted, value: obj[key], }); })); } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Construct an `R3NgModuleDef` for the given `R3NgModuleMetadata`. */ function compileNgModule(meta) { var internalType = meta.internalType, 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; var additionalStatements = []; var definitionMap = { type: internalType }; // Only generate the keys in the metadata if the arrays have values. if (bootstrap.length) { definitionMap.bootstrap = refsToArray(bootstrap, containsForwardDecls); } // If requested to emit scope information inline, pass the declarations, imports and exports to // the `ɵɵdefineNgModule` call. The JIT compilation uses this. if (emitInline) { if (declarations.length) { definitionMap.declarations = refsToArray(declarations, containsForwardDecls); } if (imports.length) { definitionMap.imports = refsToArray(imports, containsForwardDecls); } if (exports.length) { definitionMap.exports = refsToArray(exports, containsForwardDecls); } } // If not emitting inline, the scope information is not passed into `ɵɵdefineNgModule` as it would // prevent tree-shaking of the declarations, imports and exports references. else { var setNgModuleScopeCall = generateSetNgModuleScopeCall(meta); if (setNgModuleScopeCall !== null) { additionalStatements.push(setNgModuleScopeCall); } } if (schemas && schemas.length) { definitionMap.schemas = literalArr(schemas.map(function (ref) { return ref.value; })); } if (id) { definitionMap.id = id; } var expression = importExpr(Identifiers$1.defineNgModule).callFn([mapToMapExpression(definitionMap)]); var type = new ExpressionType(importExpr(Identifiers$1.NgModuleDefWithMeta, [ new ExpressionType(moduleType.type), tupleTypeOf(declarations), tupleTypeOf(imports), tupleTypeOf(exports) ])); return { expression: expression, type: type, additionalStatements: additionalStatements }; } /** * Generates a function call to `ɵɵsetNgModuleScope` with all necessary information so that the * transitive module scope can be computed during runtime in JIT mode. This call is marked pure * such that the references to declarations, imports and exports may be elided causing these * symbols to become tree-shakeable. */ function generateSetNgModuleScopeCall(meta) { var moduleType = meta.adjacentType, declarations = meta.declarations, imports = meta.imports, exports = meta.exports, containsForwardDecls = meta.containsForwardDecls; var scopeMap = {}; if (declarations.length) { scopeMap.declarations = refsToArray(declarations, containsForwardDecls); } if (imports.length) { scopeMap.imports = refsToArray(imports, containsForwardDecls); } if (exports.length) { scopeMap.exports = refsToArray(exports, containsForwardDecls); } if (Object.keys(scopeMap).length === 0) { return null; } // setNgModuleScope(...) var fnCall = new InvokeFunctionExpr( /* fn */ importExpr(Identifiers$1.setNgModuleScope), /* args */ [moduleType, mapToMapExpression(scopeMap)]); // (ngJitMode guard) && setNgModuleScope(...) var guardedCall = jitOnlyGuardedExpression(fnCall); // function() { (ngJitMode guard) && setNgModuleScope(...); } var iife = new FunctionExpr( /* params */ [], /* statements */ [guardedCall.toStmt()]); // (function() { (ngJitMode guard) && setNgModuleScope(...); })() var iifeCall = new InvokeFunctionExpr( /* fn */ iife, /* args */ []); return iifeCall.toStmt(); } function compileInjector(meta) { var result = compileFactoryFunction({ name: meta.name, type: meta.type, internalType: meta.internalType, typeArgumentCount: 0, deps: meta.deps, injectFn: Identifiers$1.inject, target: R3FactoryTarget.NgModule, }); var definitionMap = { factory: result.factory, }; if (meta.providers !== null) { definitionMap.providers = meta.providers; } if (meta.imports.length > 0) { definitionMap.imports = literalArr(meta.imports); } var expression = importExpr(Identifiers$1.defineInjector).callFn([mapToMapExpression(definitionMap)]); var type = new ExpressionType(importExpr(Identifiers$1.InjectorDef, [new ExpressionType(meta.type.type)])); return { expression: expression, type: type, statements: result.statements }; } // TODO(alxhub): integrate this with `compileNgModule`. Currently the two are separate operations. function compileNgModuleFromRender2(ctx, ngModule, injectableCompiler) { var className = identifierName(ngModule.type); var rawImports = ngModule.rawImports ? [ngModule.rawImports] : []; var rawExports = ngModule.rawExports ? [ngModule.rawExports] : []; var injectorDefArg = mapLiteral({ 'factory': injectableCompiler.factoryFor({ type: ngModule.type, symbol: ngModule.type.reference }, ctx), 'providers': convertMetaToOutput(ngModule.rawProviders, ctx), 'imports': convertMetaToOutput(__spread(rawImports, rawExports), ctx), }); var injectorDef = importExpr(Identifiers$1.defineInjector).callFn([injectorDefArg]); ctx.statements.push(new ClassStmt( /* name */ className, /* parent */ null, /* fields */ [new ClassField( /* name */ 'ɵinj', /* type */ INFERRED_TYPE, /* modifiers */ [StmtModifier.Static], /* initializer */ injectorDef)], /* getters */ [], /* constructorMethod */ new ClassMethod(null, [], []), /* methods */ [])); } function accessExportScope(module) { var selectorScope = new ReadPropExpr(module, 'ɵmod'); return new ReadPropExpr(selectorScope, 'exported'); } function tupleTypeOf(exp) { var types = exp.map(function (ref) { return typeofExpr(ref.type); }); return exp.length > 0 ? expressionType(literalArr(types)) : NONE_TYPE; } function refsToArray(refs, shouldForwardDeclare) { var values = literalArr(refs.map(function (ref) { return ref.value; })); return shouldForwardDeclare ? fn([], [new ReturnStatement(values)]) : values; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ function compilePipeFromMetadata(metadata) { var definitionMapValues = []; // e.g. `name: 'myPipe'` definitionMapValues.push({ key: 'name', value: literal(metadata.pipeName), quoted: false }); // e.g. `type: MyPipe` definitionMapValues.push({ key: 'type', value: metadata.type.value, quoted: false }); // e.g. `pure: true` definitionMapValues.push({ key: 'pure', value: literal(metadata.pure), quoted: false }); var expression = importExpr(Identifiers$1.definePipe).callFn([literalMap(definitionMapValues)]); var type = new ExpressionType(importExpr(Identifiers$1.PipeDefWithMeta, [ typeWithParameters(metadata.type.type, metadata.typeArgumentCount), new ExpressionType(new LiteralExpr(metadata.pipeName)), ])); return { expression: expression, type: type }; } /** * Write a pipe definition to the output context. */ function compilePipeFromRender2(outputCtx, pipe, reflector) { var name = identifierName(pipe.type); if (!name) { return error("Cannot resolve the name of " + pipe.type); } var type = outputCtx.importExpr(pipe.type.reference); var metadata = { name: name, type: wrapReference(type), internalType: type, pipeName: pipe.name, typeArgumentCount: 0, deps: dependenciesFromGlobalMetadata(pipe.type, outputCtx, reflector), pure: pipe.pure, }; var res = compilePipeFromMetadata(metadata); var factoryRes = compileFactoryFunction(__assign(__assign({}, metadata), { injectFn: Identifiers$1.directiveInject, target: R3FactoryTarget.Pipe })); var definitionField = outputCtx.constantPool.propertyNameOf(3 /* Pipe */); var ngFactoryDefStatement = new ClassStmt( /* name */ name, /* parent */ null, /* fields */ [new ClassField( /* name */ 'ɵfac', /* type */ INFERRED_TYPE, /* modifiers */ [StmtModifier.Static], /* initializer */ factoryRes.factory)], /* getters */ [], /* constructorMethod */ new ClassMethod(null, [], []), /* methods */ []); var pipeDefStatement = new ClassStmt( /* name */ name, /* parent */ null, /* fields */ [new ClassField( /* name */ definitionField, /* type */ INFERRED_TYPE, /* modifiers */ [StmtModifier.Static], /* initializer */ res.expression)], /* getters */ [], /* constructorMethod */ new ClassMethod(null, [], []), /* methods */ []); outputCtx.statements.push(ngFactoryDefStatement, pipeDefStatement); } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var ParserError = /** @class */ (function () { function ParserError(message, input, errLocation, ctxLocation) { this.input = input; this.errLocation = errLocation; this.ctxLocation = ctxLocation; this.message = "Parser Error: " + message + " " + errLocation + " [" + input + "] in " + ctxLocation; } return ParserError; }()); var ParseSpan = /** @class */ (function () { function ParseSpan(start, end) { this.start = start; this.end = end; } ParseSpan.prototype.toAbsolute = function (absoluteOffset) { return new AbsoluteSourceSpan(absoluteOffset + this.start, absoluteOffset + this.end); }; return ParseSpan; }()); var AST = /** @class */ (function () { function AST(span, /** * Absolute location of the expression AST in a source code file. */ sourceSpan) { this.span = span; this.sourceSpan = sourceSpan; } AST.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return null; }; AST.prototype.toString = function () { return 'AST'; }; return AST; }()); /** * Represents a quoted expression of the form: * * quote = prefix `:` uninterpretedExpression * prefix = identifier * uninterpretedExpression = arbitrary string * * A quoted expression is meant to be pre-processed by an AST transformer that * converts it into another AST that no longer contains quoted expressions. * It is meant to allow third-party developers to extend Angular template * expression language. The `uninterpretedExpression` part of the quote is * therefore not interpreted by the Angular's own expression parser. */ var Quote = /** @class */ (function (_super) { __extends(Quote, _super); function Quote(span, sourceSpan, prefix, uninterpretedExpression, location) { var _this = _super.call(this, span, sourceSpan) || this; _this.prefix = prefix; _this.uninterpretedExpression = uninterpretedExpression; _this.location = location; return _this; } Quote.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitQuote(this, context); }; Quote.prototype.toString = function () { return 'Quote'; }; return Quote; }(AST)); var EmptyExpr = /** @class */ (function (_super) { __extends(EmptyExpr, _super); function EmptyExpr() { return _super !== null && _super.apply(this, arguments) || this; } EmptyExpr.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } // do nothing }; return EmptyExpr; }(AST)); var ImplicitReceiver = /** @class */ (function (_super) { __extends(ImplicitReceiver, _super); function ImplicitReceiver() { return _super !== null && _super.apply(this, arguments) || this; } ImplicitReceiver.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitImplicitReceiver(this, context); }; return ImplicitReceiver; }(AST)); /** * Multiple expressions separated by a semicolon. */ var Chain = /** @class */ (function (_super) { __extends(Chain, _super); function Chain(span, sourceSpan, expressions) { var _this = _super.call(this, span, sourceSpan) || this; _this.expressions = expressions; return _this; } Chain.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitChain(this, context); }; return Chain; }(AST)); var Conditional = /** @class */ (function (_super) { __extends(Conditional, _super); function Conditional(span, sourceSpan, condition, trueExp, falseExp) { var _this = _super.call(this, span, sourceSpan) || this; _this.condition = condition; _this.trueExp = trueExp; _this.falseExp = falseExp; return _this; } Conditional.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitConditional(this, context); }; return Conditional; }(AST)); var PropertyRead = /** @class */ (function (_super) { __extends(PropertyRead, _super); function PropertyRead(span, sourceSpan, receiver, name) { var _this = _super.call(this, span, sourceSpan) || this; _this.receiver = receiver; _this.name = name; return _this; } PropertyRead.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitPropertyRead(this, context); }; return PropertyRead; }(AST)); var PropertyWrite = /** @class */ (function (_super) { __extends(PropertyWrite, _super); function PropertyWrite(span, sourceSpan, receiver, name, value) { var _this = _super.call(this, span, sourceSpan) || this; _this.receiver = receiver; _this.name = name; _this.value = value; return _this; } PropertyWrite.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitPropertyWrite(this, context); }; return PropertyWrite; }(AST)); var SafePropertyRead = /** @class */ (function (_super) { __extends(SafePropertyRead, _super); function SafePropertyRead(span, sourceSpan, receiver, name) { var _this = _super.call(this, span, sourceSpan) || this; _this.receiver = receiver; _this.name = name; return _this; } SafePropertyRead.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitSafePropertyRead(this, context); }; return SafePropertyRead; }(AST)); var KeyedRead = /** @class */ (function (_super) { __extends(KeyedRead, _super); function KeyedRead(span, sourceSpan, obj, key) { var _this = _super.call(this, span, sourceSpan) || this; _this.obj = obj; _this.key = key; return _this; } KeyedRead.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitKeyedRead(this, context); }; return KeyedRead; }(AST)); var KeyedWrite = /** @class */ (function (_super) { __extends(KeyedWrite, _super); function KeyedWrite(span, sourceSpan, obj, key, value) { var _this = _super.call(this, span, sourceSpan) || this; _this.obj = obj; _this.key = key; _this.value = value; return _this; } KeyedWrite.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitKeyedWrite(this, context); }; return KeyedWrite; }(AST)); var BindingPipe = /** @class */ (function (_super) { __extends(BindingPipe, _super); function BindingPipe(span, sourceSpan, exp, name, args, nameSpan) { var _this = _super.call(this, span, sourceSpan) || this; _this.exp = exp; _this.name = name; _this.args = args; _this.nameSpan = nameSpan; return _this; } BindingPipe.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitPipe(this, context); }; return BindingPipe; }(AST)); var LiteralPrimitive = /** @class */ (function (_super) { __extends(LiteralPrimitive, _super); function LiteralPrimitive(span, sourceSpan, value) { var _this = _super.call(this, span, sourceSpan) || this; _this.value = value; return _this; } LiteralPrimitive.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitLiteralPrimitive(this, context); }; return LiteralPrimitive; }(AST)); var LiteralArray = /** @class */ (function (_super) { __extends(LiteralArray, _super); function LiteralArray(span, sourceSpan, expressions) { var _this = _super.call(this, span, sourceSpan) || this; _this.expressions = expressions; return _this; } LiteralArray.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitLiteralArray(this, context); }; return LiteralArray; }(AST)); var LiteralMap = /** @class */ (function (_super) { __extends(LiteralMap, _super); function LiteralMap(span, sourceSpan, keys, values) { var _this = _super.call(this, span, sourceSpan) || this; _this.keys = keys; _this.values = values; return _this; } LiteralMap.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitLiteralMap(this, context); }; return LiteralMap; }(AST)); var Interpolation = /** @class */ (function (_super) { __extends(Interpolation, _super); function Interpolation(span, sourceSpan, strings, expressions) { var _this = _super.call(this, span, sourceSpan) || this; _this.strings = strings; _this.expressions = expressions; return _this; } Interpolation.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitInterpolation(this, context); }; return Interpolation; }(AST)); var Binary = /** @class */ (function (_super) { __extends(Binary, _super); function Binary(span, sourceSpan, operation, left, right) { var _this = _super.call(this, span, sourceSpan) || this; _this.operation = operation; _this.left = left; _this.right = right; return _this; } Binary.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitBinary(this, context); }; return Binary; }(AST)); var PrefixNot = /** @class */ (function (_super) { __extends(PrefixNot, _super); function PrefixNot(span, sourceSpan, expression) { var _this = _super.call(this, span, sourceSpan) || this; _this.expression = expression; return _this; } PrefixNot.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitPrefixNot(this, context); }; return PrefixNot; }(AST)); var NonNullAssert = /** @class */ (function (_super) { __extends(NonNullAssert, _super); function NonNullAssert(span, sourceSpan, expression) { var _this = _super.call(this, span, sourceSpan) || this; _this.expression = expression; return _this; } NonNullAssert.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitNonNullAssert(this, context); }; return NonNullAssert; }(AST)); var MethodCall = /** @class */ (function (_super) { __extends(MethodCall, _super); function MethodCall(span, sourceSpan, receiver, name, args) { var _this = _super.call(this, span, sourceSpan) || this; _this.receiver = receiver; _this.name = name; _this.args = args; return _this; } MethodCall.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitMethodCall(this, context); }; return MethodCall; }(AST)); var SafeMethodCall = /** @class */ (function (_super) { __extends(SafeMethodCall, _super); function SafeMethodCall(span, sourceSpan, receiver, name, args) { var _this = _super.call(this, span, sourceSpan) || this; _this.receiver = receiver; _this.name = name; _this.args = args; return _this; } SafeMethodCall.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitSafeMethodCall(this, context); }; return SafeMethodCall; }(AST)); var FunctionCall = /** @class */ (function (_super) { __extends(FunctionCall, _super); function FunctionCall(span, sourceSpan, target, args) { var _this = _super.call(this, span, sourceSpan) || this; _this.target = target; _this.args = args; return _this; } FunctionCall.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitFunctionCall(this, context); }; return FunctionCall; }(AST)); /** * Records the absolute position of a text span in a source file, where `start` and `end` are the * starting and ending byte offsets, respectively, of the text span in a source file. */ var AbsoluteSourceSpan = /** @class */ (function () { function AbsoluteSourceSpan(start, end) { this.start = start; this.end = end; } return AbsoluteSourceSpan; }()); var ASTWithSource = /** @class */ (function (_super) { __extends(ASTWithSource, _super); function ASTWithSource(ast, source, location, absoluteOffset, errors) { var _this = _super.call(this, new ParseSpan(0, source === null ? 0 : source.length), new AbsoluteSourceSpan(absoluteOffset, source === null ? absoluteOffset : absoluteOffset + source.length)) || this; _this.ast = ast; _this.source = source; _this.location = location; _this.errors = errors; return _this; } ASTWithSource.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } if (visitor.visitASTWithSource) { return visitor.visitASTWithSource(this, context); } return this.ast.visit(visitor, context); }; ASTWithSource.prototype.toString = function () { return this.source + " in " + this.location; }; return ASTWithSource; }(AST)); var TemplateBinding = /** @class */ (function () { function TemplateBinding(span, sourceSpan, key, keyIsVar, name, value) { this.span = span; this.key = key; this.keyIsVar = keyIsVar; this.name = name; this.value = value; } return TemplateBinding; }()); var RecursiveAstVisitor$1 = /** @class */ (function () { function RecursiveAstVisitor() { } RecursiveAstVisitor.prototype.visit = function (ast, context) { // The default implementation just visits every node. // Classes that extend RecursiveAstVisitor should override this function // to selectively visit the specified node. ast.visit(this, context); }; RecursiveAstVisitor.prototype.visitBinary = function (ast, context) { this.visit(ast.left, context); this.visit(ast.right, context); }; RecursiveAstVisitor.prototype.visitChain = function (ast, context) { this.visitAll(ast.expressions, context); }; RecursiveAstVisitor.prototype.visitConditional = function (ast, context) { this.visit(ast.condition, context); this.visit(ast.trueExp, context); this.visit(ast.falseExp, context); }; RecursiveAstVisitor.prototype.visitPipe = function (ast, context) { this.visit(ast.exp, context); this.visitAll(ast.args, context); }; RecursiveAstVisitor.prototype.visitFunctionCall = function (ast, context) { if (ast.target) { this.visit(ast.target, context); } this.visitAll(ast.args, context); }; RecursiveAstVisitor.prototype.visitImplicitReceiver = function (ast, context) { }; RecursiveAstVisitor.prototype.visitInterpolation = function (ast, context) { this.visitAll(ast.expressions, context); }; RecursiveAstVisitor.prototype.visitKeyedRead = function (ast, context) { this.visit(ast.obj, context); this.visit(ast.key, context); }; RecursiveAstVisitor.prototype.visitKeyedWrite = function (ast, context) { this.visit(ast.obj, context); this.visit(ast.key, context); this.visit(ast.value, context); }; RecursiveAstVisitor.prototype.visitLiteralArray = function (ast, context) { this.visitAll(ast.expressions, context); }; RecursiveAstVisitor.prototype.visitLiteralMap = function (ast, context) { this.visitAll(ast.values, context); }; RecursiveAstVisitor.prototype.visitLiteralPrimitive = function (ast, context) { }; RecursiveAstVisitor.prototype.visitMethodCall = function (ast, context) { this.visit(ast.receiver, context); this.visitAll(ast.args, context); }; RecursiveAstVisitor.prototype.visitPrefixNot = function (ast, context) { this.visit(ast.expression, context); }; RecursiveAstVisitor.prototype.visitNonNullAssert = function (ast, context) { this.visit(ast.expression, context); }; RecursiveAstVisitor.prototype.visitPropertyRead = function (ast, context) { this.visit(ast.receiver, context); }; RecursiveAstVisitor.prototype.visitPropertyWrite = function (ast, context) { this.visit(ast.receiver, context); this.visit(ast.value, context); }; RecursiveAstVisitor.prototype.visitSafePropertyRead = function (ast, context) { this.visit(ast.receiver, context); }; RecursiveAstVisitor.prototype.visitSafeMethodCall = function (ast, context) { this.visit(ast.receiver, context); this.visitAll(ast.args, context); }; RecursiveAstVisitor.prototype.visitQuote = function (ast, context) { }; // This is not part of the AstVisitor interface, just a helper method RecursiveAstVisitor.prototype.visitAll = function (asts, context) { var e_1, _a; try { for (var asts_1 = __values(asts), asts_1_1 = asts_1.next(); !asts_1_1.done; asts_1_1 = asts_1.next()) { var ast = asts_1_1.value; this.visit(ast, context); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (asts_1_1 && !asts_1_1.done && (_a = asts_1.return)) _a.call(asts_1); } finally { if (e_1) throw e_1.error; } } }; return RecursiveAstVisitor; }()); var AstTransformer$1 = /** @class */ (function () { function AstTransformer() { } AstTransformer.prototype.visitImplicitReceiver = function (ast, context) { return ast; }; AstTransformer.prototype.visitInterpolation = function (ast, context) { return new Interpolation(ast.span, ast.sourceSpan, ast.strings, this.visitAll(ast.expressions)); }; AstTransformer.prototype.visitLiteralPrimitive = function (ast, context) { return new LiteralPrimitive(ast.span, ast.sourceSpan, ast.value); }; AstTransformer.prototype.visitPropertyRead = function (ast, context) { return new PropertyRead(ast.span, ast.sourceSpan, ast.receiver.visit(this), ast.name); }; AstTransformer.prototype.visitPropertyWrite = function (ast, context) { return new PropertyWrite(ast.span, ast.sourceSpan, ast.receiver.visit(this), ast.name, ast.value.visit(this)); }; AstTransformer.prototype.visitSafePropertyRead = function (ast, context) { return new SafePropertyRead(ast.span, ast.sourceSpan, ast.receiver.visit(this), ast.name); }; AstTransformer.prototype.visitMethodCall = function (ast, context) { return new MethodCall(ast.span, ast.sourceSpan, ast.receiver.visit(this), ast.name, this.visitAll(ast.args)); }; AstTransformer.prototype.visitSafeMethodCall = function (ast, context) { return new SafeMethodCall(ast.span, ast.sourceSpan, ast.receiver.visit(this), ast.name, this.visitAll(ast.args)); }; AstTransformer.prototype.visitFunctionCall = function (ast, context) { return new FunctionCall(ast.span, ast.sourceSpan, ast.target.visit(this), this.visitAll(ast.args)); }; AstTransformer.prototype.visitLiteralArray = function (ast, context) { return new LiteralArray(ast.span, ast.sourceSpan, this.visitAll(ast.expressions)); }; AstTransformer.prototype.visitLiteralMap = function (ast, context) { return new LiteralMap(ast.span, ast.sourceSpan, ast.keys, this.visitAll(ast.values)); }; AstTransformer.prototype.visitBinary = function (ast, context) { return new Binary(ast.span, ast.sourceSpan, ast.operation, ast.left.visit(this), ast.right.visit(this)); }; AstTransformer.prototype.visitPrefixNot = function (ast, context) { return new PrefixNot(ast.span, ast.sourceSpan, ast.expression.visit(this)); }; AstTransformer.prototype.visitNonNullAssert = function (ast, context) { return new NonNullAssert(ast.span, ast.sourceSpan, ast.expression.visit(this)); }; AstTransformer.prototype.visitConditional = function (ast, context) { return new Conditional(ast.span, ast.sourceSpan, ast.condition.visit(this), ast.trueExp.visit(this), ast.falseExp.visit(this)); }; AstTransformer.prototype.visitPipe = function (ast, context) { return new BindingPipe(ast.span, ast.sourceSpan, ast.exp.visit(this), ast.name, this.visitAll(ast.args), ast.nameSpan); }; AstTransformer.prototype.visitKeyedRead = function (ast, context) { return new KeyedRead(ast.span, ast.sourceSpan, ast.obj.visit(this), ast.key.visit(this)); }; AstTransformer.prototype.visitKeyedWrite = function (ast, context) { return new KeyedWrite(ast.span, ast.sourceSpan, ast.obj.visit(this), ast.key.visit(this), ast.value.visit(this)); }; AstTransformer.prototype.visitAll = function (asts) { var res = []; for (var i = 0; i < asts.length; ++i) { res[i] = asts[i].visit(this); } return res; }; AstTransformer.prototype.visitChain = function (ast, context) { return new Chain(ast.span, ast.sourceSpan, this.visitAll(ast.expressions)); }; AstTransformer.prototype.visitQuote = function (ast, context) { return new Quote(ast.span, ast.sourceSpan, ast.prefix, ast.uninterpretedExpression, ast.location); }; return AstTransformer; }()); // A transformer that only creates new nodes if the transformer makes a change or // a change is made a child node. var AstMemoryEfficientTransformer = /** @class */ (function () { function AstMemoryEfficientTransformer() { } AstMemoryEfficientTransformer.prototype.visitImplicitReceiver = function (ast, context) { return ast; }; AstMemoryEfficientTransformer.prototype.visitInterpolation = function (ast, context) { var expressions = this.visitAll(ast.expressions); if (expressions !== ast.expressions) return new Interpolation(ast.span, ast.sourceSpan, ast.strings, expressions); return ast; }; AstMemoryEfficientTransformer.prototype.visitLiteralPrimitive = function (ast, context) { return ast; }; AstMemoryEfficientTransformer.prototype.visitPropertyRead = function (ast, context) { var receiver = ast.receiver.visit(this); if (receiver !== ast.receiver) { return new PropertyRead(ast.span, ast.sourceSpan, receiver, ast.name); } return ast; }; AstMemoryEfficientTransformer.prototype.visitPropertyWrite = function (ast, context) { var receiver = ast.receiver.visit(this); var value = ast.value.visit(this); if (receiver !== ast.receiver || value !== ast.value) { return new PropertyWrite(ast.span, ast.sourceSpan, receiver, ast.name, value); } return ast; }; AstMemoryEfficientTransformer.prototype.visitSafePropertyRead = function (ast, context) { var receiver = ast.receiver.visit(this); if (receiver !== ast.receiver) { return new SafePropertyRead(ast.span, ast.sourceSpan, receiver, ast.name); } return ast; }; AstMemoryEfficientTransformer.prototype.visitMethodCall = function (ast, context) { var receiver = ast.receiver.visit(this); var args = this.visitAll(ast.args); if (receiver !== ast.receiver || args !== ast.args) { return new MethodCall(ast.span, ast.sourceSpan, receiver, ast.name, args); } return ast; }; AstMemoryEfficientTransformer.prototype.visitSafeMethodCall = function (ast, context) { var receiver = ast.receiver.visit(this); var args = this.visitAll(ast.args); if (receiver !== ast.receiver || args !== ast.args) { return new SafeMethodCall(ast.span, ast.sourceSpan, receiver, ast.name, args); } return ast; }; AstMemoryEfficientTransformer.prototype.visitFunctionCall = function (ast, context) { var target = ast.target && ast.target.visit(this); var args = this.visitAll(ast.args); if (target !== ast.target || args !== ast.args) { return new FunctionCall(ast.span, ast.sourceSpan, target, args); } return ast; }; AstMemoryEfficientTransformer.prototype.visitLiteralArray = function (ast, context) { var expressions = this.visitAll(ast.expressions); if (expressions !== ast.expressions) { return new LiteralArray(ast.span, ast.sourceSpan, expressions); } return ast; }; AstMemoryEfficientTransformer.prototype.visitLiteralMap = function (ast, context) { var values = this.visitAll(ast.values); if (values !== ast.values) { return new LiteralMap(ast.span, ast.sourceSpan, ast.keys, values); } return ast; }; AstMemoryEfficientTransformer.prototype.visitBinary = function (ast, context) { var left = ast.left.visit(this); var right = ast.right.visit(this); if (left !== ast.left || right !== ast.right) { return new Binary(ast.span, ast.sourceSpan, ast.operation, left, right); } return ast; }; AstMemoryEfficientTransformer.prototype.visitPrefixNot = function (ast, context) { var expression = ast.expression.visit(this); if (expression !== ast.expression) { return new PrefixNot(ast.span, ast.sourceSpan, expression); } return ast; }; AstMemoryEfficientTransformer.prototype.visitNonNullAssert = function (ast, context) { var expression = ast.expression.visit(this); if (expression !== ast.expression) { return new NonNullAssert(ast.span, ast.sourceSpan, expression); } return ast; }; AstMemoryEfficientTransformer.prototype.visitConditional = function (ast, context) { var condition = ast.condition.visit(this); var trueExp = ast.trueExp.visit(this); var falseExp = ast.falseExp.visit(this); if (condition !== ast.condition || trueExp !== ast.trueExp || falseExp !== ast.falseExp) { return new Conditional(ast.span, ast.sourceSpan, condition, trueExp, falseExp); } return ast; }; AstMemoryEfficientTransformer.prototype.visitPipe = function (ast, context) { var exp = ast.exp.visit(this); var args = this.visitAll(ast.args); if (exp !== ast.exp || args !== ast.args) { return new BindingPipe(ast.span, ast.sourceSpan, exp, ast.name, args, ast.nameSpan); } return ast; }; AstMemoryEfficientTransformer.prototype.visitKeyedRead = function (ast, context) { var obj = ast.obj.visit(this); var key = ast.key.visit(this); if (obj !== ast.obj || key !== ast.key) { return new KeyedRead(ast.span, ast.sourceSpan, obj, key); } return ast; }; AstMemoryEfficientTransformer.prototype.visitKeyedWrite = function (ast, context) { var obj = ast.obj.visit(this); var key = ast.key.visit(this); var value = ast.value.visit(this); if (obj !== ast.obj || key !== ast.key || value !== ast.value) { return new KeyedWrite(ast.span, ast.sourceSpan, obj, key, value); } return ast; }; AstMemoryEfficientTransformer.prototype.visitAll = function (asts) { var res = []; var modified = false; for (var i = 0; i < asts.length; ++i) { var original = asts[i]; var value = original.visit(this); res[i] = value; modified = modified || value !== original; } return modified ? res : asts; }; AstMemoryEfficientTransformer.prototype.visitChain = function (ast, context) { var expressions = this.visitAll(ast.expressions); if (expressions !== ast.expressions) { return new Chain(ast.span, ast.sourceSpan, expressions); } return ast; }; AstMemoryEfficientTransformer.prototype.visitQuote = function (ast, context) { return ast; }; return AstMemoryEfficientTransformer; }()); // Bindings var ParsedProperty = /** @class */ (function () { function ParsedProperty(name, expression, type, sourceSpan, valueSpan) { this.name = name; this.expression = expression; this.type = type; this.sourceSpan = sourceSpan; this.valueSpan = valueSpan; this.isLiteral = this.type === ParsedPropertyType.LITERAL_ATTR; this.isAnimation = this.type === ParsedPropertyType.ANIMATION; } return ParsedProperty; }()); var ParsedPropertyType; (function (ParsedPropertyType) { ParsedPropertyType[ParsedPropertyType["DEFAULT"] = 0] = "DEFAULT"; ParsedPropertyType[ParsedPropertyType["LITERAL_ATTR"] = 1] = "LITERAL_ATTR"; ParsedPropertyType[ParsedPropertyType["ANIMATION"] = 2] = "ANIMATION"; })(ParsedPropertyType || (ParsedPropertyType = {})); var ParsedEvent = /** @class */ (function () { // Regular events have a target // Animation events have a phase function ParsedEvent(name, targetOrPhase, type, handler, sourceSpan, handlerSpan) { this.name = name; this.targetOrPhase = targetOrPhase; this.type = type; this.handler = handler; this.sourceSpan = sourceSpan; this.handlerSpan = handlerSpan; } return ParsedEvent; }()); var ParsedVariable = /** @class */ (function () { function ParsedVariable(name, value, sourceSpan) { this.name = name; this.value = value; this.sourceSpan = sourceSpan; } return ParsedVariable; }()); var BoundElementProperty = /** @class */ (function () { function BoundElementProperty(name, type, securityContext, value, unit, sourceSpan, valueSpan) { this.name = name; this.type = type; this.securityContext = securityContext; this.value = value; this.unit = unit; this.sourceSpan = sourceSpan; this.valueSpan = valueSpan; } return BoundElementProperty; }()); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var EventHandlerVars = /** @class */ (function () { function EventHandlerVars() { } EventHandlerVars.event = variable('$event'); return EventHandlerVars; }()); var ConvertActionBindingResult = /** @class */ (function () { function ConvertActionBindingResult( /** * Render2 compatible statements, */ stmts, /** * Variable name used with render2 compatible statements. */ allowDefault) { this.stmts = stmts; this.allowDefault = allowDefault; /** * This is bit of a hack. It converts statements which render2 expects to statements which are * expected by render3. * * Example: `
` will generate: * * Render3: * ``` * const pd_b:any = ((ctx.doSomething($event)) !== false); * return pd_b; * ``` * * but render2 expects: * ``` * return ctx.doSomething($event); * ``` */ // TODO(misko): remove this hack once we no longer support ViewEngine. this.render3Stmts = stmts.map(function (statement) { if (statement instanceof DeclareVarStmt && statement.name == allowDefault.name && statement.value instanceof BinaryOperatorExpr) { var lhs = statement.value.lhs; return new ReturnStatement(lhs.value); } return statement; }); } return ConvertActionBindingResult; }()); /** * Converts the given expression AST into an executable output AST, assuming the expression is * used in an action binding (e.g. an event handler). */ function convertActionBinding(localResolver, implicitReceiver, action, bindingId, interpolationFunction, baseSourceSpan, implicitReceiverAccesses) { if (!localResolver) { localResolver = new DefaultLocalResolver(); } var actionWithoutBuiltins = convertPropertyBindingBuiltins({ createLiteralArrayConverter: function (argCount) { // Note: no caching for literal arrays in actions. return function (args) { return literalArr(args); }; }, createLiteralMapConverter: function (keys) { // Note: no caching for literal maps in actions. return function (values) { var entries = keys.map(function (k, i) { return ({ key: k.key, value: values[i], quoted: k.quoted, }); }); return literalMap(entries); }; }, createPipeConverter: function (name) { throw new Error("Illegal State: Actions are not allowed to contain pipes. Pipe: " + name); } }, action); var visitor = new _AstToIrVisitor(localResolver, implicitReceiver, bindingId, interpolationFunction, baseSourceSpan, implicitReceiverAccesses); var actionStmts = []; flattenStatements(actionWithoutBuiltins.visit(visitor, _Mode.Statement), actionStmts); prependTemporaryDecls(visitor.temporaryCount, bindingId, actionStmts); if (visitor.usesImplicitReceiver) { localResolver.notifyImplicitReceiverUse(); } var lastIndex = actionStmts.length - 1; var preventDefaultVar = null; if (lastIndex >= 0) { var lastStatement = actionStmts[lastIndex]; var returnExpr = convertStmtIntoExpression(lastStatement); if (returnExpr) { // Note: We need to cast the result of the method call to dynamic, // as it might be a void method! preventDefaultVar = createPreventDefaultVar(bindingId); actionStmts[lastIndex] = preventDefaultVar.set(returnExpr.cast(DYNAMIC_TYPE).notIdentical(literal(false))) .toDeclStmt(null, [StmtModifier.Final]); } } return new ConvertActionBindingResult(actionStmts, preventDefaultVar); } function convertPropertyBindingBuiltins(converterFactory, ast) { return convertBuiltins(converterFactory, ast); } var ConvertPropertyBindingResult = /** @class */ (function () { function ConvertPropertyBindingResult(stmts, currValExpr) { this.stmts = stmts; this.currValExpr = currValExpr; } return ConvertPropertyBindingResult; }()); var BindingForm; (function (BindingForm) { // The general form of binding expression, supports all expressions. BindingForm[BindingForm["General"] = 0] = "General"; // Try to generate a simple binding (no temporaries or statements) // otherwise generate a general binding BindingForm[BindingForm["TrySimple"] = 1] = "TrySimple"; })(BindingForm || (BindingForm = {})); /** * Converts the given expression AST into an executable output AST, assuming the expression * is used in property binding. The expression has to be preprocessed via * `convertPropertyBindingBuiltins`. */ function convertPropertyBinding(localResolver, implicitReceiver, expressionWithoutBuiltins, bindingId, form, interpolationFunction) { if (!localResolver) { localResolver = new DefaultLocalResolver(); } var currValExpr = createCurrValueExpr(bindingId); var visitor = new _AstToIrVisitor(localResolver, implicitReceiver, bindingId, interpolationFunction); var outputExpr = expressionWithoutBuiltins.visit(visitor, _Mode.Expression); var stmts = getStatementsFromVisitor(visitor, bindingId); if (visitor.usesImplicitReceiver) { localResolver.notifyImplicitReceiverUse(); } if (visitor.temporaryCount === 0 && form == BindingForm.TrySimple) { return new ConvertPropertyBindingResult([], outputExpr); } stmts.push(currValExpr.set(outputExpr).toDeclStmt(DYNAMIC_TYPE, [StmtModifier.Final])); return new ConvertPropertyBindingResult(stmts, currValExpr); } /** * Given some expression, such as a binding or interpolation expression, and a context expression to * look values up on, visit each facet of the given expression resolving values from the context * expression such that a list of arguments can be derived from the found values that can be used as * arguments to an external update instruction. * * @param localResolver The resolver to use to look up expressions by name appropriately * @param contextVariableExpression The expression representing the context variable used to create * the final argument expressions * @param expressionWithArgumentsToExtract The expression to visit to figure out what values need to * be resolved and what arguments list to build. * @param bindingId A name prefix used to create temporary variable names if they're needed for the * arguments generated * @returns An array of expressions that can be passed as arguments to instruction expressions like * `o.importExpr(R3.propertyInterpolate).callFn(result)` */ function convertUpdateArguments(localResolver, contextVariableExpression, expressionWithArgumentsToExtract, bindingId) { var visitor = new _AstToIrVisitor(localResolver, contextVariableExpression, bindingId, undefined); var outputExpr = expressionWithArgumentsToExtract.visit(visitor, _Mode.Expression); if (visitor.usesImplicitReceiver) { localResolver.notifyImplicitReceiverUse(); } var stmts = getStatementsFromVisitor(visitor, bindingId); // Removing the first argument, because it was a length for ViewEngine, not Ivy. var args = outputExpr.args.slice(1); if (expressionWithArgumentsToExtract instanceof Interpolation) { // If we're dealing with an interpolation of 1 value with an empty prefix and suffix, reduce the // args returned to just the value, because we're going to pass it to a special instruction. var strings = expressionWithArgumentsToExtract.strings; if (args.length === 3 && strings[0] === '' && strings[1] === '') { // Single argument interpolate instructions. args = [args[1]]; } else if (args.length >= 19) { // 19 or more arguments must be passed to the `interpolateV`-style instructions, which accept // an array of arguments args = [literalArr(args)]; } } return { stmts: stmts, args: args }; } function getStatementsFromVisitor(visitor, bindingId) { var stmts = []; for (var i = 0; i < visitor.temporaryCount; i++) { stmts.push(temporaryDeclaration(bindingId, i)); } return stmts; } function convertBuiltins(converterFactory, ast) { var visitor = new _BuiltinAstConverter(converterFactory); return ast.visit(visitor); } function temporaryName(bindingId, temporaryNumber) { return "tmp_" + bindingId + "_" + temporaryNumber; } function temporaryDeclaration(bindingId, temporaryNumber) { return new DeclareVarStmt(temporaryName(bindingId, temporaryNumber), NULL_EXPR); } function prependTemporaryDecls(temporaryCount, bindingId, statements) { for (var i = temporaryCount - 1; i >= 0; i--) { statements.unshift(temporaryDeclaration(bindingId, i)); } } var _Mode; (function (_Mode) { _Mode[_Mode["Statement"] = 0] = "Statement"; _Mode[_Mode["Expression"] = 1] = "Expression"; })(_Mode || (_Mode = {})); function ensureStatementMode(mode, ast) { if (mode !== _Mode.Statement) { throw new Error("Expected a statement, but saw " + ast); } } function ensureExpressionMode(mode, ast) { if (mode !== _Mode.Expression) { throw new Error("Expected an expression, but saw " + ast); } } function convertToStatementIfNeeded(mode, expr) { if (mode === _Mode.Statement) { return expr.toStmt(); } else { return expr; } } var _BuiltinAstConverter = /** @class */ (function (_super) { __extends(_BuiltinAstConverter, _super); function _BuiltinAstConverter(_converterFactory) { var _this = _super.call(this) || this; _this._converterFactory = _converterFactory; return _this; } _BuiltinAstConverter.prototype.visitPipe = function (ast, context) { var _this = this; var args = __spread([ast.exp], ast.args).map(function (ast) { return ast.visit(_this, context); }); return new BuiltinFunctionCall(ast.span, ast.sourceSpan, args, this._converterFactory.createPipeConverter(ast.name, args.length)); }; _BuiltinAstConverter.prototype.visitLiteralArray = function (ast, context) { var _this = this; var args = ast.expressions.map(function (ast) { return ast.visit(_this, context); }); return new BuiltinFunctionCall(ast.span, ast.sourceSpan, args, this._converterFactory.createLiteralArrayConverter(ast.expressions.length)); }; _BuiltinAstConverter.prototype.visitLiteralMap = function (ast, context) { var _this = this; var args = ast.values.map(function (ast) { return ast.visit(_this, context); }); return new BuiltinFunctionCall(ast.span, ast.sourceSpan, args, this._converterFactory.createLiteralMapConverter(ast.keys)); }; return _BuiltinAstConverter; }(AstTransformer$1)); var _AstToIrVisitor = /** @class */ (function () { function _AstToIrVisitor(_localResolver, _implicitReceiver, bindingId, interpolationFunction, baseSourceSpan, implicitReceiverAccesses) { this._localResolver = _localResolver; this._implicitReceiver = _implicitReceiver; this.bindingId = bindingId; this.interpolationFunction = interpolationFunction; this.baseSourceSpan = baseSourceSpan; this.implicitReceiverAccesses = implicitReceiverAccesses; this._nodeMap = new Map(); this._resultMap = new Map(); this._currentTemporary = 0; this.temporaryCount = 0; this.usesImplicitReceiver = false; } _AstToIrVisitor.prototype.visitBinary = function (ast, mode) { var op; switch (ast.operation) { case '+': op = BinaryOperator.Plus; break; case '-': op = BinaryOperator.Minus; break; case '*': op = BinaryOperator.Multiply; break; case '/': op = BinaryOperator.Divide; break; case '%': op = BinaryOperator.Modulo; break; case '&&': op = BinaryOperator.And; break; case '||': op = BinaryOperator.Or; break; case '==': op = BinaryOperator.Equals; break; case '!=': op = BinaryOperator.NotEquals; break; case '===': op = BinaryOperator.Identical; break; case '!==': op = BinaryOperator.NotIdentical; break; case '<': op = BinaryOperator.Lower; break; case '>': op = BinaryOperator.Bigger; break; case '<=': op = BinaryOperator.LowerEquals; break; case '>=': op = BinaryOperator.BiggerEquals; break; default: throw new Error("Unsupported operation " + ast.operation); } return convertToStatementIfNeeded(mode, new BinaryOperatorExpr(op, this._visit(ast.left, _Mode.Expression), this._visit(ast.right, _Mode.Expression), undefined, this.convertSourceSpan(ast.span))); }; _AstToIrVisitor.prototype.visitChain = function (ast, mode) { ensureStatementMode(mode, ast); return this.visitAll(ast.expressions, mode); }; _AstToIrVisitor.prototype.visitConditional = function (ast, mode) { var value = this._visit(ast.condition, _Mode.Expression); return convertToStatementIfNeeded(mode, value.conditional(this._visit(ast.trueExp, _Mode.Expression), this._visit(ast.falseExp, _Mode.Expression), this.convertSourceSpan(ast.span))); }; _AstToIrVisitor.prototype.visitPipe = function (ast, mode) { throw new Error("Illegal state: Pipes should have been converted into functions. Pipe: " + ast.name); }; _AstToIrVisitor.prototype.visitFunctionCall = function (ast, mode) { var convertedArgs = this.visitAll(ast.args, _Mode.Expression); var fnResult; if (ast instanceof BuiltinFunctionCall) { fnResult = ast.converter(convertedArgs); } else { fnResult = this._visit(ast.target, _Mode.Expression) .callFn(convertedArgs, this.convertSourceSpan(ast.span)); } return convertToStatementIfNeeded(mode, fnResult); }; _AstToIrVisitor.prototype.visitImplicitReceiver = function (ast, mode) { ensureExpressionMode(mode, ast); this.usesImplicitReceiver = true; return this._implicitReceiver; }; _AstToIrVisitor.prototype.visitInterpolation = function (ast, mode) { ensureExpressionMode(mode, ast); var args = [literal(ast.expressions.length)]; for (var i = 0; i < ast.strings.length - 1; i++) { args.push(literal(ast.strings[i])); args.push(this._visit(ast.expressions[i], _Mode.Expression)); } args.push(literal(ast.strings[ast.strings.length - 1])); if (this.interpolationFunction) { return this.interpolationFunction(args); } return ast.expressions.length <= 9 ? importExpr(Identifiers.inlineInterpolate).callFn(args) : importExpr(Identifiers.interpolate).callFn([ args[0], literalArr(args.slice(1), undefined, this.convertSourceSpan(ast.span)) ]); }; _AstToIrVisitor.prototype.visitKeyedRead = function (ast, mode) { var leftMostSafe = this.leftMostSafeNode(ast); if (leftMostSafe) { return this.convertSafeAccess(ast, leftMostSafe, mode); } else { return convertToStatementIfNeeded(mode, this._visit(ast.obj, _Mode.Expression).key(this._visit(ast.key, _Mode.Expression))); } }; _AstToIrVisitor.prototype.visitKeyedWrite = function (ast, mode) { var obj = this._visit(ast.obj, _Mode.Expression); var key = this._visit(ast.key, _Mode.Expression); var value = this._visit(ast.value, _Mode.Expression); return convertToStatementIfNeeded(mode, obj.key(key).set(value)); }; _AstToIrVisitor.prototype.visitLiteralArray = function (ast, mode) { throw new Error("Illegal State: literal arrays should have been converted into functions"); }; _AstToIrVisitor.prototype.visitLiteralMap = function (ast, mode) { throw new Error("Illegal State: literal maps should have been converted into functions"); }; _AstToIrVisitor.prototype.visitLiteralPrimitive = function (ast, mode) { // For literal values of null, undefined, true, or false allow type interference // to infer the type. var type = ast.value === null || ast.value === undefined || ast.value === true || ast.value === true ? INFERRED_TYPE : undefined; return convertToStatementIfNeeded(mode, literal(ast.value, type, this.convertSourceSpan(ast.span))); }; _AstToIrVisitor.prototype._getLocal = function (name) { return this._localResolver.getLocal(name); }; _AstToIrVisitor.prototype.visitMethodCall = function (ast, mode) { if (ast.receiver instanceof ImplicitReceiver && ast.name == '$any') { var args = this.visitAll(ast.args, _Mode.Expression); if (args.length != 1) { throw new Error("Invalid call to $any, expected 1 argument but received " + (args.length || 'none')); } return args[0].cast(DYNAMIC_TYPE, this.convertSourceSpan(ast.span)); } var leftMostSafe = this.leftMostSafeNode(ast); if (leftMostSafe) { return this.convertSafeAccess(ast, leftMostSafe, mode); } else { var args = this.visitAll(ast.args, _Mode.Expression); var prevUsesImplicitReceiver = this.usesImplicitReceiver; var result = null; var receiver = this._visit(ast.receiver, _Mode.Expression); if (receiver === this._implicitReceiver) { var varExpr = this._getLocal(ast.name); if (varExpr) { // Restore the previous "usesImplicitReceiver" state since the implicit // receiver has been replaced with a resolved local expression. this.usesImplicitReceiver = prevUsesImplicitReceiver; result = varExpr.callFn(args); } this.addImplicitReceiverAccess(ast.name); } if (result == null) { result = receiver.callMethod(ast.name, args, this.convertSourceSpan(ast.span)); } return convertToStatementIfNeeded(mode, result); } }; _AstToIrVisitor.prototype.visitPrefixNot = function (ast, mode) { return convertToStatementIfNeeded(mode, not(this._visit(ast.expression, _Mode.Expression))); }; _AstToIrVisitor.prototype.visitNonNullAssert = function (ast, mode) { return convertToStatementIfNeeded(mode, assertNotNull(this._visit(ast.expression, _Mode.Expression))); }; _AstToIrVisitor.prototype.visitPropertyRead = function (ast, mode) { var leftMostSafe = this.leftMostSafeNode(ast); if (leftMostSafe) { return this.convertSafeAccess(ast, leftMostSafe, mode); } else { var result = null; var prevUsesImplicitReceiver = this.usesImplicitReceiver; var receiver = this._visit(ast.receiver, _Mode.Expression); if (receiver === this._implicitReceiver) { result = this._getLocal(ast.name); if (result) { // Restore the previous "usesImplicitReceiver" state since the implicit // receiver has been replaced with a resolved local expression. this.usesImplicitReceiver = prevUsesImplicitReceiver; } this.addImplicitReceiverAccess(ast.name); } if (result == null) { result = receiver.prop(ast.name); } return convertToStatementIfNeeded(mode, result); } }; _AstToIrVisitor.prototype.visitPropertyWrite = function (ast, mode) { var receiver = this._visit(ast.receiver, _Mode.Expression); var prevUsesImplicitReceiver = this.usesImplicitReceiver; var varExpr = null; if (receiver === this._implicitReceiver) { var localExpr = this._getLocal(ast.name); if (localExpr) { if (localExpr instanceof ReadPropExpr) { // If the local variable is a property read expression, it's a reference // to a 'context.property' value and will be used as the target of the // write expression. varExpr = localExpr; // Restore the previous "usesImplicitReceiver" state since the implicit // receiver has been replaced with a resolved local expression. this.usesImplicitReceiver = prevUsesImplicitReceiver; this.addImplicitReceiverAccess(ast.name); } else { // Otherwise it's an error. var receiver_1 = ast.name; var value = (ast.value instanceof PropertyRead) ? ast.value.name : undefined; throw new Error("Cannot assign value \"" + value + "\" to template variable \"" + receiver_1 + "\". Template variables are read-only."); } } } // If no local expression could be produced, use the original receiver's // property as the target. if (varExpr === null) { varExpr = receiver.prop(ast.name); } return convertToStatementIfNeeded(mode, varExpr.set(this._visit(ast.value, _Mode.Expression))); }; _AstToIrVisitor.prototype.visitSafePropertyRead = function (ast, mode) { return this.convertSafeAccess(ast, this.leftMostSafeNode(ast), mode); }; _AstToIrVisitor.prototype.visitSafeMethodCall = function (ast, mode) { return this.convertSafeAccess(ast, this.leftMostSafeNode(ast), mode); }; _AstToIrVisitor.prototype.visitAll = function (asts, mode) { var _this = this; return asts.map(function (ast) { return _this._visit(ast, mode); }); }; _AstToIrVisitor.prototype.visitQuote = function (ast, mode) { throw new Error("Quotes are not supported for evaluation!\n Statement: " + ast.uninterpretedExpression + " located at " + ast.location); }; _AstToIrVisitor.prototype._visit = function (ast, mode) { var result = this._resultMap.get(ast); if (result) return result; return (this._nodeMap.get(ast) || ast).visit(this, mode); }; _AstToIrVisitor.prototype.convertSafeAccess = function (ast, leftMostSafe, mode) { // If the expression contains a safe access node on the left it needs to be converted to // an expression that guards the access to the member by checking the receiver for blank. As // execution proceeds from left to right, the left most part of the expression must be guarded // first but, because member access is left associative, the right side of the expression is at // the top of the AST. The desired result requires lifting a copy of the left part of the // expression up to test it for blank before generating the unguarded version. // Consider, for example the following expression: a?.b.c?.d.e // This results in the ast: // . // / \ // ?. e // / \ // . d // / \ // ?. c // / \ // a b // The following tree should be generated: // // /---- ? ----\ // / | \ // a /--- ? ---\ null // / | \ // . . null // / \ / \ // . c . e // / \ / \ // a b . d // / \ // . c // / \ // a b // // Notice that the first guard condition is the left hand of the left most safe access node // which comes in as leftMostSafe to this routine. var guardedExpression = this._visit(leftMostSafe.receiver, _Mode.Expression); var temporary = undefined; if (this.needsTemporary(leftMostSafe.receiver)) { // If the expression has method calls or pipes then we need to save the result into a // temporary variable to avoid calling stateful or impure code more than once. temporary = this.allocateTemporary(); // Preserve the result in the temporary variable guardedExpression = temporary.set(guardedExpression); // Ensure all further references to the guarded expression refer to the temporary instead. this._resultMap.set(leftMostSafe.receiver, temporary); } var condition = guardedExpression.isBlank(); // Convert the ast to an unguarded access to the receiver's member. The map will substitute // leftMostNode with its unguarded version in the call to `this.visit()`. if (leftMostSafe instanceof SafeMethodCall) { this._nodeMap.set(leftMostSafe, new MethodCall(leftMostSafe.span, leftMostSafe.sourceSpan, leftMostSafe.receiver, leftMostSafe.name, leftMostSafe.args)); } else { this._nodeMap.set(leftMostSafe, new PropertyRead(leftMostSafe.span, leftMostSafe.sourceSpan, leftMostSafe.receiver, leftMostSafe.name)); } // Recursively convert the node now without the guarded member access. var access = this._visit(ast, _Mode.Expression); // Remove the mapping. This is not strictly required as the converter only traverses each node // once but is safer if the conversion is changed to traverse the nodes more than once. this._nodeMap.delete(leftMostSafe); // If we allocated a temporary, release it. if (temporary) { this.releaseTemporary(temporary); } // Produce the conditional return convertToStatementIfNeeded(mode, condition.conditional(literal(null), access)); }; // Given an expression of the form a?.b.c?.d.e then the left most safe node is // the (a?.b). The . and ?. are left associative thus can be rewritten as: // ((((a?.c).b).c)?.d).e. This returns the most deeply nested safe read or // safe method call as this needs to be transformed initially to: // a == null ? null : a.c.b.c?.d.e // then to: // a == null ? null : a.b.c == null ? null : a.b.c.d.e _AstToIrVisitor.prototype.leftMostSafeNode = function (ast) { var _this = this; var visit = function (visitor, ast) { return (_this._nodeMap.get(ast) || ast).visit(visitor); }; return ast.visit({ visitBinary: function (ast) { return null; }, visitChain: function (ast) { return null; }, visitConditional: function (ast) { return null; }, visitFunctionCall: function (ast) { return null; }, visitImplicitReceiver: function (ast) { return null; }, visitInterpolation: function (ast) { return null; }, visitKeyedRead: function (ast) { return visit(this, ast.obj); }, visitKeyedWrite: function (ast) { return null; }, visitLiteralArray: function (ast) { return null; }, visitLiteralMap: function (ast) { return null; }, visitLiteralPrimitive: function (ast) { return null; }, visitMethodCall: function (ast) { return visit(this, ast.receiver); }, visitPipe: function (ast) { return null; }, visitPrefixNot: function (ast) { return null; }, visitNonNullAssert: function (ast) { return null; }, visitPropertyRead: function (ast) { return visit(this, ast.receiver); }, visitPropertyWrite: function (ast) { return null; }, visitQuote: function (ast) { return null; }, visitSafeMethodCall: function (ast) { return visit(this, ast.receiver) || ast; }, visitSafePropertyRead: function (ast) { return visit(this, ast.receiver) || ast; } }); }; // Returns true of the AST includes a method or a pipe indicating that, if the // expression is used as the target of a safe property or method access then // the expression should be stored into a temporary variable. _AstToIrVisitor.prototype.needsTemporary = function (ast) { var _this = this; var visit = function (visitor, ast) { return ast && (_this._nodeMap.get(ast) || ast).visit(visitor); }; var visitSome = function (visitor, ast) { return ast.some(function (ast) { return visit(visitor, ast); }); }; return ast.visit({ visitBinary: function (ast) { return visit(this, ast.left) || visit(this, ast.right); }, visitChain: function (ast) { return false; }, visitConditional: function (ast) { return visit(this, ast.condition) || visit(this, ast.trueExp) || visit(this, ast.falseExp); }, visitFunctionCall: function (ast) { return true; }, visitImplicitReceiver: function (ast) { return false; }, visitInterpolation: function (ast) { return visitSome(this, ast.expressions); }, visitKeyedRead: function (ast) { return false; }, visitKeyedWrite: function (ast) { return false; }, visitLiteralArray: function (ast) { return true; }, visitLiteralMap: function (ast) { return true; }, visitLiteralPrimitive: function (ast) { return false; }, visitMethodCall: function (ast) { return true; }, visitPipe: function (ast) { return true; }, visitPrefixNot: function (ast) { return visit(this, ast.expression); }, visitNonNullAssert: function (ast) { return visit(this, ast.expression); }, visitPropertyRead: function (ast) { return false; }, visitPropertyWrite: function (ast) { return false; }, visitQuote: function (ast) { return false; }, visitSafeMethodCall: function (ast) { return true; }, visitSafePropertyRead: function (ast) { return false; } }); }; _AstToIrVisitor.prototype.allocateTemporary = function () { var tempNumber = this._currentTemporary++; this.temporaryCount = Math.max(this._currentTemporary, this.temporaryCount); return new ReadVarExpr(temporaryName(this.bindingId, tempNumber)); }; _AstToIrVisitor.prototype.releaseTemporary = function (temporary) { this._currentTemporary--; if (temporary.name != temporaryName(this.bindingId, this._currentTemporary)) { throw new Error("Temporary " + temporary.name + " released out of order"); } }; /** * Creates an absolute `ParseSourceSpan` from the relative `ParseSpan`. * * `ParseSpan` objects are relative to the start of the expression. * This method converts these to full `ParseSourceSpan` objects that * show where the span is within the overall source file. * * @param span the relative span to convert. * @returns a `ParseSourceSpan` for the given span or null if no * `baseSourceSpan` was provided to this class. */ _AstToIrVisitor.prototype.convertSourceSpan = function (span) { if (this.baseSourceSpan) { var start = this.baseSourceSpan.start.moveBy(span.start); var end = this.baseSourceSpan.start.moveBy(span.end); return new ParseSourceSpan(start, end); } else { return null; } }; /** Adds the name of an AST to the list of implicit receiver accesses. */ _AstToIrVisitor.prototype.addImplicitReceiverAccess = function (name) { if (this.implicitReceiverAccesses) { this.implicitReceiverAccesses.add(name); } }; return _AstToIrVisitor; }()); function flattenStatements(arg, output) { if (Array.isArray(arg)) { arg.forEach(function (entry) { return flattenStatements(entry, output); }); } else { output.push(arg); } } var DefaultLocalResolver = /** @class */ (function () { function DefaultLocalResolver() { } DefaultLocalResolver.prototype.notifyImplicitReceiverUse = function () { }; DefaultLocalResolver.prototype.getLocal = function (name) { if (name === EventHandlerVars.event.name) { return EventHandlerVars.event; } return null; }; return DefaultLocalResolver; }()); function createCurrValueExpr(bindingId) { return variable("currVal_" + bindingId); // fix syntax highlighting: ` } function createPreventDefaultVar(bindingId) { return variable("pd_" + bindingId); } function convertStmtIntoExpression(stmt) { if (stmt instanceof ExpressionStatement) { return stmt.expr; } else if (stmt instanceof ReturnStatement) { return stmt.value; } return null; } var BuiltinFunctionCall = /** @class */ (function (_super) { __extends(BuiltinFunctionCall, _super); function BuiltinFunctionCall(span, sourceSpan, args, converter) { var _this = _super.call(this, span, sourceSpan, null, args) || this; _this.args = args; _this.converter = converter; return _this; } return BuiltinFunctionCall; }(FunctionCall)); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * This file is a port of shadowCSS from webcomponents.js to TypeScript. * * Please make sure to keep to edits in sync with the source file. * * Source: * https://github.com/webcomponents/webcomponentsjs/blob/4efecd7e0e/src/ShadowCSS/ShadowCSS.js * * The original file level comment is reproduced below */ /* This is a limited shim for ShadowDOM css styling. https://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/shadow/index.html#styles The intention here is to support only the styling features which can be relatively simply implemented. The goal is to allow users to avoid the most obvious pitfalls and do so without compromising performance significantly. For ShadowDOM styling that's not covered here, a set of best practices can be provided that should allow users to accomplish more complex styling. The following is a list of specific ShadowDOM styling features and a brief discussion of the approach used to shim. Shimmed features: * :host, :host-context: ShadowDOM allows styling of the shadowRoot's host element using the :host rule. To shim this feature, the :host styles are reformatted and prefixed with a given scope name and promoted to a document level stylesheet. For example, given a scope name of .foo, a rule like this: :host { background: red; } } becomes: .foo { background: red; } * encapsulation: Styles defined within ShadowDOM, apply only to dom inside the ShadowDOM. Polymer uses one of two techniques to implement this feature. By default, rules are prefixed with the host element tag name as a descendant selector. This ensures styling does not leak out of the 'top' of the element's ShadowDOM. For example, div { font-weight: bold; } becomes: x-foo div { font-weight: bold; } becomes: Alternatively, if WebComponents.ShadowCSS.strictStyling is set to true then selectors are scoped by adding an attribute selector suffix to each simple selector that contains the host element tag name. Each element in the element's ShadowDOM template is also given the scope attribute. Thus, these rules match only elements that have the scope attribute. For example, given a scope name of x-foo, a rule like this: div { font-weight: bold; } becomes: div[x-foo] { font-weight: bold; } Note that elements that are dynamically added to a scope must have the scope selector added to them manually. * upper/lower bound encapsulation: Styles which are defined outside a shadowRoot should not cross the ShadowDOM boundary and should not apply inside a shadowRoot. This styling behavior is not emulated. Some possible ways to do this that were rejected due to complexity and/or performance concerns include: (1) reset every possible property for every possible selector for a given scope name; (2) re-implement css in javascript. As an alternative, users should make sure to use selectors specific to the scope in which they are working. * ::distributed: This behavior is not emulated. It's often not necessary to style the contents of a specific insertion point and instead, descendants of the host element can be styled selectively. Users can also create an extra node around an insertion point and style that node's contents via descendent selectors. For example, with a shadowRoot like this: could become:
Note the use of @polyfill in the comment above a ShadowDOM specific style declaration. This is a directive to the styling shim to use the selector in comments in lieu of the next selector when running under polyfill. */ var ShadowCss = /** @class */ (function () { function ShadowCss() { this.strictStyling = true; } /* * Shim some cssText with the given selector. Returns cssText that can * be included in the document via WebComponents.ShadowCSS.addCssToDocument(css). * * When strictStyling is true: * - selector is the attribute added to all elements inside the host, * - hostSelector is the attribute added to the host itself. */ ShadowCss.prototype.shimCssText = function (cssText, selector, hostSelector) { if (hostSelector === void 0) { hostSelector = ''; } var commentsWithHash = extractCommentsWithHash(cssText); cssText = stripComments(cssText); cssText = this._insertDirectives(cssText); var scopedCssText = this._scopeCssText(cssText, selector, hostSelector); return __spread([scopedCssText], commentsWithHash).join('\n'); }; ShadowCss.prototype._insertDirectives = function (cssText) { cssText = this._insertPolyfillDirectivesInCssText(cssText); return this._insertPolyfillRulesInCssText(cssText); }; /* * Process styles to convert native ShadowDOM rules that will trip * up the css parser; we rely on decorating the stylesheet with inert rules. * * For example, we convert this rule: * * polyfill-next-selector { content: ':host menu-item'; } * ::content menu-item { * * to this: * * scopeName menu-item { * **/ ShadowCss.prototype._insertPolyfillDirectivesInCssText = function (cssText) { // Difference with webcomponents.js: does not handle comments return cssText.replace(_cssContentNextSelectorRe, function () { var m = []; for (var _i = 0; _i < arguments.length; _i++) { m[_i] = arguments[_i]; } return m[2] + '{'; }); }; /* * Process styles to add rules which will only apply under the polyfill * * For example, we convert this rule: * * polyfill-rule { * content: ':host menu-item'; * ... * } * * to this: * * scopeName menu-item {...} * **/ ShadowCss.prototype._insertPolyfillRulesInCssText = function (cssText) { // Difference with webcomponents.js: does not handle comments return cssText.replace(_cssContentRuleRe, function () { var m = []; for (var _i = 0; _i < arguments.length; _i++) { m[_i] = arguments[_i]; } var rule = m[0].replace(m[1], '').replace(m[2], ''); return m[4] + rule; }); }; /* Ensure styles are scoped. Pseudo-scoping takes a rule like: * * .foo {... } * * and converts this to * * scopeName .foo { ... } */ ShadowCss.prototype._scopeCssText = function (cssText, scopeSelector, hostSelector) { var unscopedRules = this._extractUnscopedRulesFromCssText(cssText); // replace :host and :host-context -shadowcsshost and -shadowcsshost respectively cssText = this._insertPolyfillHostInCssText(cssText); cssText = this._convertColonHost(cssText); cssText = this._convertColonHostContext(cssText); cssText = this._convertShadowDOMSelectors(cssText); if (scopeSelector) { cssText = this._scopeSelectors(cssText, scopeSelector, hostSelector); } cssText = cssText + '\n' + unscopedRules; return cssText.trim(); }; /* * Process styles to add rules which will only apply under the polyfill * and do not process via CSSOM. (CSSOM is destructive to rules on rare * occasions, e.g. -webkit-calc on Safari.) * For example, we convert this rule: * * @polyfill-unscoped-rule { * content: 'menu-item'; * ... } * * to this: * * menu-item {...} * **/ ShadowCss.prototype._extractUnscopedRulesFromCssText = function (cssText) { // Difference with webcomponents.js: does not handle comments var r = ''; var m; _cssContentUnscopedRuleRe.lastIndex = 0; while ((m = _cssContentUnscopedRuleRe.exec(cssText)) !== null) { var rule = m[0].replace(m[2], '').replace(m[1], m[4]); r += rule + '\n\n'; } return r; }; /* * convert a rule like :host(.foo) > .bar { } * * to * * .foo > .bar */ ShadowCss.prototype._convertColonHost = function (cssText) { return this._convertColonRule(cssText, _cssColonHostRe, this._colonHostPartReplacer); }; /* * convert a rule like :host-context(.foo) > .bar { } * * to * * .foo > .bar, .foo scopeName > .bar { } * * and * * :host-context(.foo:host) .bar { ... } * * to * * .foo .bar { ... } */ ShadowCss.prototype._convertColonHostContext = function (cssText) { return this._convertColonRule(cssText, _cssColonHostContextRe, this._colonHostContextPartReplacer); }; ShadowCss.prototype._convertColonRule = function (cssText, regExp, partReplacer) { // m[1] = :host(-context), m[2] = contents of (), m[3] rest of rule return cssText.replace(regExp, function () { var m = []; for (var _i = 0; _i < arguments.length; _i++) { m[_i] = arguments[_i]; } if (m[2]) { var parts = m[2].split(','); var r = []; for (var i = 0; i < parts.length; i++) { var p = parts[i].trim(); if (!p) break; r.push(partReplacer(_polyfillHostNoCombinator, p, m[3])); } return r.join(','); } else { return _polyfillHostNoCombinator + m[3]; } }); }; ShadowCss.prototype._colonHostContextPartReplacer = function (host, part, suffix) { if (part.indexOf(_polyfillHost) > -1) { return this._colonHostPartReplacer(host, part, suffix); } else { return host + part + suffix + ', ' + part + ' ' + host + suffix; } }; ShadowCss.prototype._colonHostPartReplacer = function (host, part, suffix) { return host + part.replace(_polyfillHost, '') + suffix; }; /* * Convert combinators like ::shadow and pseudo-elements like ::content * by replacing with space. */ ShadowCss.prototype._convertShadowDOMSelectors = function (cssText) { return _shadowDOMSelectorsRe.reduce(function (result, pattern) { return result.replace(pattern, ' '); }, cssText); }; // change a selector like 'div' to 'name div' ShadowCss.prototype._scopeSelectors = function (cssText, scopeSelector, hostSelector) { var _this = this; return processRules(cssText, function (rule) { var selector = rule.selector; var content = rule.content; if (rule.selector[0] != '@') { selector = _this._scopeSelector(rule.selector, scopeSelector, hostSelector, _this.strictStyling); } else if (rule.selector.startsWith('@media') || rule.selector.startsWith('@supports') || rule.selector.startsWith('@page') || rule.selector.startsWith('@document')) { content = _this._scopeSelectors(rule.content, scopeSelector, hostSelector); } return new CssRule(selector, content); }); }; ShadowCss.prototype._scopeSelector = function (selector, scopeSelector, hostSelector, strict) { var _this = this; return selector.split(',') .map(function (part) { return part.trim().split(_shadowDeepSelectors); }) .map(function (deepParts) { var _a = __read(deepParts), shallowPart = _a[0], otherParts = _a.slice(1); var applyScope = function (shallowPart) { if (_this._selectorNeedsScoping(shallowPart, scopeSelector)) { return strict ? _this._applyStrictSelectorScope(shallowPart, scopeSelector, hostSelector) : _this._applySelectorScope(shallowPart, scopeSelector, hostSelector); } else { return shallowPart; } }; return __spread([applyScope(shallowPart)], otherParts).join(' '); }) .join(', '); }; ShadowCss.prototype._selectorNeedsScoping = function (selector, scopeSelector) { var re = this._makeScopeMatcher(scopeSelector); return !re.test(selector); }; ShadowCss.prototype._makeScopeMatcher = function (scopeSelector) { var lre = /\[/g; var rre = /\]/g; scopeSelector = scopeSelector.replace(lre, '\\[').replace(rre, '\\]'); return new RegExp('^(' + scopeSelector + ')' + _selectorReSuffix, 'm'); }; ShadowCss.prototype._applySelectorScope = function (selector, scopeSelector, hostSelector) { // Difference from webcomponents.js: scopeSelector could not be an array return this._applySimpleSelectorScope(selector, scopeSelector, hostSelector); }; // scope via name and [is=name] ShadowCss.prototype._applySimpleSelectorScope = function (selector, scopeSelector, hostSelector) { // In Android browser, the lastIndex is not reset when the regex is used in String.replace() _polyfillHostRe.lastIndex = 0; if (_polyfillHostRe.test(selector)) { var replaceBy_1 = this.strictStyling ? "[" + hostSelector + "]" : scopeSelector; return selector .replace(_polyfillHostNoCombinatorRe, function (hnc, selector) { return selector.replace(/([^:]*)(:*)(.*)/, function (_, before, colon, after) { return before + replaceBy_1 + colon + after; }); }) .replace(_polyfillHostRe, replaceBy_1 + ' '); } return scopeSelector + ' ' + selector; }; // return a selector with [name] suffix on each simple selector // e.g. .foo.bar > .zot becomes .foo[name].bar[name] > .zot[name] /** @internal */ ShadowCss.prototype._applyStrictSelectorScope = function (selector, scopeSelector, hostSelector) { var _this = this; var isRe = /\[is=([^\]]*)\]/g; scopeSelector = scopeSelector.replace(isRe, function (_) { var parts = []; for (var _i = 1; _i < arguments.length; _i++) { parts[_i - 1] = arguments[_i]; } return parts[0]; }); var attrName = '[' + scopeSelector + ']'; var _scopeSelectorPart = function (p) { var scopedP = p.trim(); if (!scopedP) { return ''; } if (p.indexOf(_polyfillHostNoCombinator) > -1) { scopedP = _this._applySimpleSelectorScope(p, scopeSelector, hostSelector); } else { // remove :host since it should be unnecessary var t = p.replace(_polyfillHostRe, ''); if (t.length > 0) { var matches = t.match(/([^:]*)(:*)(.*)/); if (matches) { scopedP = matches[1] + attrName + matches[2] + matches[3]; } } } return scopedP; }; var safeContent = new SafeSelector(selector); selector = safeContent.content(); var scopedSelector = ''; var startIndex = 0; var res; var sep = /( |>|\+|~(?!=))\s*/g; // If a selector appears before :host it should not be shimmed as it // matches on ancestor elements and not on elements in the host's shadow // `:host-context(div)` is transformed to // `-shadowcsshost-no-combinatordiv, div -shadowcsshost-no-combinator` // the `div` is not part of the component in the 2nd selectors and should not be scoped. // Historically `component-tag:host` was matching the component so we also want to preserve // this behavior to avoid breaking legacy apps (it should not match). // The behavior should be: // - `tag:host` -> `tag[h]` (this is to avoid breaking legacy apps, should not match anything) // - `tag :host` -> `tag [h]` (`tag` is not scoped because it's considered part of a // `:host-context(tag)`) var hasHost = selector.indexOf(_polyfillHostNoCombinator) > -1; // Only scope parts after the first `-shadowcsshost-no-combinator` when it is present var shouldScope = !hasHost; while ((res = sep.exec(selector)) !== null) { var separator = res[1]; var part_1 = selector.slice(startIndex, res.index).trim(); shouldScope = shouldScope || part_1.indexOf(_polyfillHostNoCombinator) > -1; var scopedPart = shouldScope ? _scopeSelectorPart(part_1) : part_1; scopedSelector += scopedPart + " " + separator + " "; startIndex = sep.lastIndex; } var part = selector.substring(startIndex); shouldScope = shouldScope || part.indexOf(_polyfillHostNoCombinator) > -1; scopedSelector += shouldScope ? _scopeSelectorPart(part) : part; // replace the placeholders with their original values return safeContent.restore(scopedSelector); }; ShadowCss.prototype._insertPolyfillHostInCssText = function (selector) { return selector.replace(_colonHostContextRe, _polyfillHostContext) .replace(_colonHostRe, _polyfillHost); }; return ShadowCss; }()); var SafeSelector = /** @class */ (function () { function SafeSelector(selector) { var _this = this; this.placeholders = []; this.index = 0; // Replaces attribute selectors with placeholders. // The WS in [attr="va lue"] would otherwise be interpreted as a selector separator. selector = selector.replace(/(\[[^\]]*\])/g, function (_, keep) { var replaceBy = "__ph-" + _this.index + "__"; _this.placeholders.push(keep); _this.index++; return replaceBy; }); // Replaces the expression in `:nth-child(2n + 1)` with a placeholder. // WS and "+" would otherwise be interpreted as selector separators. this._content = selector.replace(/(:nth-[-\w]+)(\([^)]+\))/g, function (_, pseudo, exp) { var replaceBy = "__ph-" + _this.index + "__"; _this.placeholders.push(exp); _this.index++; return pseudo + replaceBy; }); } SafeSelector.prototype.restore = function (content) { var _this = this; return content.replace(/__ph-(\d+)__/g, function (ph, index) { return _this.placeholders[+index]; }); }; SafeSelector.prototype.content = function () { return this._content; }; return SafeSelector; }()); var _cssContentNextSelectorRe = /polyfill-next-selector[^}]*content:[\s]*?(['"])(.*?)\1[;\s]*}([^{]*?){/gim; var _cssContentRuleRe = /(polyfill-rule)[^}]*(content:[\s]*(['"])(.*?)\3)[;\s]*[^}]*}/gim; var _cssContentUnscopedRuleRe = /(polyfill-unscoped-rule)[^}]*(content:[\s]*(['"])(.*?)\3)[;\s]*[^}]*}/gim; var _polyfillHost = '-shadowcsshost'; // note: :host-context pre-processed to -shadowcsshostcontext. var _polyfillHostContext = '-shadowcsscontext'; var _parenSuffix = ')(?:\\((' + '(?:\\([^)(]*\\)|[^)(]*)+?' + ')\\))?([^,{]*)'; var _cssColonHostRe = new RegExp('(' + _polyfillHost + _parenSuffix, 'gim'); var _cssColonHostContextRe = new RegExp('(' + _polyfillHostContext + _parenSuffix, 'gim'); var _polyfillHostNoCombinator = _polyfillHost + '-no-combinator'; var _polyfillHostNoCombinatorRe = /-shadowcsshost-no-combinator([^\s]*)/; var _shadowDOMSelectorsRe = [ /::shadow/g, /::content/g, // Deprecated selectors /\/shadow-deep\//g, /\/shadow\//g, ]; // The deep combinator is deprecated in the CSS spec // Support for `>>>`, `deep`, `::ng-deep` is then also deprecated and will be removed in the future. // see https://github.com/angular/angular/pull/17677 var _shadowDeepSelectors = /(?:>>>)|(?:\/deep\/)|(?:::ng-deep)/g; var _selectorReSuffix = '([>\\s~+\[.,{:][\\s\\S]*)?$'; var _polyfillHostRe = /-shadowcsshost/gim; var _colonHostRe = /:host/gim; var _colonHostContextRe = /:host-context/gim; var _commentRe = /\/\*\s*[\s\S]*?\*\//g; function stripComments(input) { return input.replace(_commentRe, ''); } var _commentWithHashRe = /\/\*\s*#\s*source(Mapping)?URL=[\s\S]+?\*\//g; function extractCommentsWithHash(input) { return input.match(_commentWithHashRe) || []; } var _ruleRe = /(\s*)([^;\{\}]+?)(\s*)((?:{%BLOCK%}?\s*;?)|(?:\s*;))/g; var _curlyRe = /([{}])/g; var OPEN_CURLY = '{'; var CLOSE_CURLY = '}'; var BLOCK_PLACEHOLDER = '%BLOCK%'; var CssRule = /** @class */ (function () { function CssRule(selector, content) { this.selector = selector; this.content = content; } return CssRule; }()); function processRules(input, ruleCallback) { var inputWithEscapedBlocks = escapeBlocks(input); var nextBlockIndex = 0; return inputWithEscapedBlocks.escapedString.replace(_ruleRe, function () { var m = []; for (var _i = 0; _i < arguments.length; _i++) { m[_i] = arguments[_i]; } var selector = m[2]; var content = ''; var suffix = m[4]; var contentPrefix = ''; if (suffix && suffix.startsWith('{' + BLOCK_PLACEHOLDER)) { content = inputWithEscapedBlocks.blocks[nextBlockIndex++]; suffix = suffix.substring(BLOCK_PLACEHOLDER.length + 1); contentPrefix = '{'; } var rule = ruleCallback(new CssRule(selector, content)); return "" + m[1] + rule.selector + m[3] + contentPrefix + rule.content + suffix; }); } var StringWithEscapedBlocks = /** @class */ (function () { function StringWithEscapedBlocks(escapedString, blocks) { this.escapedString = escapedString; this.blocks = blocks; } return StringWithEscapedBlocks; }()); function escapeBlocks(input) { var inputParts = input.split(_curlyRe); var resultParts = []; var escapedBlocks = []; var bracketCount = 0; var currentBlockParts = []; for (var partIndex = 0; partIndex < inputParts.length; partIndex++) { var part = inputParts[partIndex]; if (part == CLOSE_CURLY) { bracketCount--; } if (bracketCount > 0) { currentBlockParts.push(part); } else { if (currentBlockParts.length > 0) { escapedBlocks.push(currentBlockParts.join('')); resultParts.push(BLOCK_PLACEHOLDER); currentBlockParts = []; } resultParts.push(part); } if (part == OPEN_CURLY) { bracketCount++; } } if (currentBlockParts.length > 0) { escapedBlocks.push(currentBlockParts.join('')); resultParts.push(BLOCK_PLACEHOLDER); } return new StringWithEscapedBlocks(resultParts.join(''), escapedBlocks); } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var COMPONENT_VARIABLE = '%COMP%'; var HOST_ATTR = "_nghost-" + COMPONENT_VARIABLE; var CONTENT_ATTR = "_ngcontent-" + COMPONENT_VARIABLE; var StylesCompileDependency = /** @class */ (function () { function StylesCompileDependency(name, moduleUrl, setValue) { this.name = name; this.moduleUrl = moduleUrl; this.setValue = setValue; } return StylesCompileDependency; }()); var CompiledStylesheet = /** @class */ (function () { function CompiledStylesheet(outputCtx, stylesVar, dependencies, isShimmed, meta) { this.outputCtx = outputCtx; this.stylesVar = stylesVar; this.dependencies = dependencies; this.isShimmed = isShimmed; this.meta = meta; } return CompiledStylesheet; }()); var StyleCompiler = /** @class */ (function () { function StyleCompiler(_urlResolver) { this._urlResolver = _urlResolver; this._shadowCss = new ShadowCss(); } StyleCompiler.prototype.compileComponent = function (outputCtx, comp) { var template = comp.template; return this._compileStyles(outputCtx, comp, new CompileStylesheetMetadata({ styles: template.styles, styleUrls: template.styleUrls, moduleUrl: identifierModuleUrl(comp.type) }), this.needsStyleShim(comp), true); }; StyleCompiler.prototype.compileStyles = function (outputCtx, comp, stylesheet, shim) { if (shim === void 0) { shim = this.needsStyleShim(comp); } return this._compileStyles(outputCtx, comp, stylesheet, shim, false); }; StyleCompiler.prototype.needsStyleShim = function (comp) { return comp.template.encapsulation === ViewEncapsulation.Emulated; }; StyleCompiler.prototype._compileStyles = function (outputCtx, comp, stylesheet, shim, isComponentStylesheet) { var _this = this; var styleExpressions = stylesheet.styles.map(function (plainStyle) { return literal(_this._shimIfNeeded(plainStyle, shim)); }); var dependencies = []; stylesheet.styleUrls.forEach(function (styleUrl) { var exprIndex = styleExpressions.length; // Note: This placeholder will be filled later. styleExpressions.push(null); dependencies.push(new StylesCompileDependency(getStylesVarName(null), styleUrl, function (value) { return styleExpressions[exprIndex] = outputCtx.importExpr(value); })); }); // styles variable contains plain strings and arrays of other styles arrays (recursive), // so we set its type to dynamic. var stylesVar = getStylesVarName(isComponentStylesheet ? comp : null); var stmt = variable(stylesVar) .set(literalArr(styleExpressions, new ArrayType(DYNAMIC_TYPE, [TypeModifier.Const]))) .toDeclStmt(null, isComponentStylesheet ? [StmtModifier.Final] : [ StmtModifier.Final, StmtModifier.Exported ]); outputCtx.statements.push(stmt); return new CompiledStylesheet(outputCtx, stylesVar, dependencies, shim, stylesheet); }; StyleCompiler.prototype._shimIfNeeded = function (style, shim) { return shim ? this._shadowCss.shimCssText(style, CONTENT_ATTR, HOST_ATTR) : style; }; return StyleCompiler; }()); function getStylesVarName(component) { var result = "styles"; if (component) { result += "_" + identifierName(component.type); } return result; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * A path is an ordered set of elements. Typically a path is to a * particular offset in a source file. The head of the list is the top * most node. The tail is the node that contains the offset directly. * * For example, the expression `a + b + c` might have an ast that looks * like: * + * / \ * a + * / \ * b c * * The path to the node at offset 9 would be `['+' at 1-10, '+' at 7-10, * 'c' at 9-10]` and the path the node at offset 1 would be * `['+' at 1-10, 'a' at 1-2]`. */ var AstPath = /** @class */ (function () { function AstPath(path, position) { if (position === void 0) { position = -1; } this.path = path; this.position = position; } Object.defineProperty(AstPath.prototype, "empty", { get: function () { return !this.path || !this.path.length; }, enumerable: true, configurable: true }); Object.defineProperty(AstPath.prototype, "head", { get: function () { return this.path[0]; }, enumerable: true, configurable: true }); Object.defineProperty(AstPath.prototype, "tail", { get: function () { return this.path[this.path.length - 1]; }, enumerable: true, configurable: true }); AstPath.prototype.parentOf = function (node) { return node && this.path[this.path.indexOf(node) - 1]; }; AstPath.prototype.childOf = function (node) { return this.path[this.path.indexOf(node) + 1]; }; AstPath.prototype.first = function (ctor) { for (var i = this.path.length - 1; i >= 0; i--) { var item = this.path[i]; if (item instanceof ctor) return item; } }; AstPath.prototype.push = function (node) { this.path.push(node); }; AstPath.prototype.pop = function () { return this.path.pop(); }; return AstPath; }()); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var NodeWithI18n = /** @class */ (function () { function NodeWithI18n(sourceSpan, i18n) { this.sourceSpan = sourceSpan; this.i18n = i18n; } return NodeWithI18n; }()); var Text$3 = /** @class */ (function (_super) { __extends(Text, _super); function Text(value, sourceSpan, i18n) { var _this = _super.call(this, sourceSpan, i18n) || this; _this.value = value; return _this; } Text.prototype.visit = function (visitor, context) { return visitor.visitText(this, context); }; return Text; }(NodeWithI18n)); var Expansion = /** @class */ (function (_super) { __extends(Expansion, _super); function Expansion(switchValue, type, cases, sourceSpan, switchValueSourceSpan, i18n) { var _this = _super.call(this, sourceSpan, i18n) || this; _this.switchValue = switchValue; _this.type = type; _this.cases = cases; _this.switchValueSourceSpan = switchValueSourceSpan; return _this; } Expansion.prototype.visit = function (visitor, context) { return visitor.visitExpansion(this, context); }; return Expansion; }(NodeWithI18n)); var ExpansionCase = /** @class */ (function () { function ExpansionCase(value, expression, sourceSpan, valueSourceSpan, expSourceSpan) { this.value = value; this.expression = expression; this.sourceSpan = sourceSpan; this.valueSourceSpan = valueSourceSpan; this.expSourceSpan = expSourceSpan; } ExpansionCase.prototype.visit = function (visitor, context) { return visitor.visitExpansionCase(this, context); }; return ExpansionCase; }()); var Attribute = /** @class */ (function (_super) { __extends(Attribute, _super); function Attribute(name, value, sourceSpan, valueSpan, i18n) { var _this = _super.call(this, sourceSpan, i18n) || this; _this.name = name; _this.value = value; _this.valueSpan = valueSpan; return _this; } Attribute.prototype.visit = function (visitor, context) { return visitor.visitAttribute(this, context); }; return Attribute; }(NodeWithI18n)); var Element$1 = /** @class */ (function (_super) { __extends(Element, _super); function Element(name, attrs, children, sourceSpan, startSourceSpan, endSourceSpan, i18n) { if (startSourceSpan === void 0) { startSourceSpan = null; } if (endSourceSpan === void 0) { endSourceSpan = null; } var _this = _super.call(this, sourceSpan, i18n) || this; _this.name = name; _this.attrs = attrs; _this.children = children; _this.startSourceSpan = startSourceSpan; _this.endSourceSpan = endSourceSpan; return _this; } Element.prototype.visit = function (visitor, context) { return visitor.visitElement(this, context); }; return Element; }(NodeWithI18n)); var Comment = /** @class */ (function () { function Comment(value, sourceSpan) { this.value = value; this.sourceSpan = sourceSpan; } Comment.prototype.visit = function (visitor, context) { return visitor.visitComment(this, context); }; return Comment; }()); function visitAll$1(visitor, nodes, context) { if (context === void 0) { context = null; } var result = []; var visit = visitor.visit ? function (ast) { return visitor.visit(ast, context) || ast.visit(visitor, context); } : function (ast) { return ast.visit(visitor, context); }; nodes.forEach(function (ast) { var astResult = visit(ast); if (astResult) { result.push(astResult); } }); return result; } var RecursiveVisitor$1 = /** @class */ (function () { function RecursiveVisitor() { } RecursiveVisitor.prototype.visitElement = function (ast, context) { this.visitChildren(context, function (visit) { visit(ast.attrs); visit(ast.children); }); }; RecursiveVisitor.prototype.visitAttribute = function (ast, context) { }; RecursiveVisitor.prototype.visitText = function (ast, context) { }; RecursiveVisitor.prototype.visitComment = function (ast, context) { }; RecursiveVisitor.prototype.visitExpansion = function (ast, context) { return this.visitChildren(context, function (visit) { visit(ast.cases); }); }; RecursiveVisitor.prototype.visitExpansionCase = function (ast, context) { }; RecursiveVisitor.prototype.visitChildren = function (context, cb) { var results = []; var t = this; function visit(children) { if (children) results.push(visitAll$1(t, children, context)); } cb(visit); return Array.prototype.concat.apply([], results); }; return RecursiveVisitor; }()); function spanOf(ast) { var start = ast.sourceSpan.start.offset; var end = ast.sourceSpan.end.offset; if (ast instanceof Element$1) { if (ast.endSourceSpan) { end = ast.endSourceSpan.end.offset; } else if (ast.children && ast.children.length) { end = spanOf(ast.children[ast.children.length - 1]).end; } } return { start: start, end: end }; } function findNode(nodes, position) { var path = []; var visitor = new /** @class */ (function (_super) { __extends(class_1, _super); function class_1() { return _super !== null && _super.apply(this, arguments) || this; } class_1.prototype.visit = function (ast, context) { var span = spanOf(ast); if (span.start <= position && position < span.end) { path.push(ast); } else { // Returning a value here will result in the children being skipped. return true; } }; return class_1; }(RecursiveVisitor$1)); visitAll$1(visitor, nodes); return new AstPath(path, position); } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var TokenType; (function (TokenType) { TokenType[TokenType["TAG_OPEN_START"] = 0] = "TAG_OPEN_START"; TokenType[TokenType["TAG_OPEN_END"] = 1] = "TAG_OPEN_END"; TokenType[TokenType["TAG_OPEN_END_VOID"] = 2] = "TAG_OPEN_END_VOID"; TokenType[TokenType["TAG_CLOSE"] = 3] = "TAG_CLOSE"; TokenType[TokenType["TEXT"] = 4] = "TEXT"; TokenType[TokenType["ESCAPABLE_RAW_TEXT"] = 5] = "ESCAPABLE_RAW_TEXT"; TokenType[TokenType["RAW_TEXT"] = 6] = "RAW_TEXT"; TokenType[TokenType["COMMENT_START"] = 7] = "COMMENT_START"; TokenType[TokenType["COMMENT_END"] = 8] = "COMMENT_END"; TokenType[TokenType["CDATA_START"] = 9] = "CDATA_START"; TokenType[TokenType["CDATA_END"] = 10] = "CDATA_END"; TokenType[TokenType["ATTR_NAME"] = 11] = "ATTR_NAME"; TokenType[TokenType["ATTR_QUOTE"] = 12] = "ATTR_QUOTE"; TokenType[TokenType["ATTR_VALUE"] = 13] = "ATTR_VALUE"; TokenType[TokenType["DOC_TYPE"] = 14] = "DOC_TYPE"; TokenType[TokenType["EXPANSION_FORM_START"] = 15] = "EXPANSION_FORM_START"; TokenType[TokenType["EXPANSION_CASE_VALUE"] = 16] = "EXPANSION_CASE_VALUE"; TokenType[TokenType["EXPANSION_CASE_EXP_START"] = 17] = "EXPANSION_CASE_EXP_START"; TokenType[TokenType["EXPANSION_CASE_EXP_END"] = 18] = "EXPANSION_CASE_EXP_END"; TokenType[TokenType["EXPANSION_FORM_END"] = 19] = "EXPANSION_FORM_END"; TokenType[TokenType["EOF"] = 20] = "EOF"; })(TokenType || (TokenType = {})); var Token = /** @class */ (function () { function Token(type, parts, sourceSpan) { this.type = type; this.parts = parts; this.sourceSpan = sourceSpan; } return Token; }()); var TokenError = /** @class */ (function (_super) { __extends(TokenError, _super); function TokenError(errorMsg, tokenType, span) { var _this = _super.call(this, span, errorMsg) || this; _this.tokenType = tokenType; return _this; } return TokenError; }(ParseError)); var TokenizeResult = /** @class */ (function () { function TokenizeResult(tokens, errors) { this.tokens = tokens; this.errors = errors; } return TokenizeResult; }()); function tokenize(source, url, getTagDefinition, options) { if (options === void 0) { options = {}; } return new _Tokenizer(new ParseSourceFile(source, url), getTagDefinition, options).tokenize(); } var _CR_OR_CRLF_REGEXP = /\r\n?/g; function _unexpectedCharacterErrorMsg(charCode) { var char = charCode === $EOF ? 'EOF' : String.fromCharCode(charCode); return "Unexpected character \"" + char + "\""; } function _unknownEntityErrorMsg(entitySrc) { return "Unknown entity \"" + entitySrc + "\" - use the \"&#;\" or \"&#x;\" syntax"; } var _ControlFlowError = /** @class */ (function () { function _ControlFlowError(error) { this.error = error; } return _ControlFlowError; }()); // See http://www.w3.org/TR/html51/syntax.html#writing var _Tokenizer = /** @class */ (function () { /** * @param _file The html source file being tokenized. * @param _getTagDefinition A function that will retrieve a tag definition for a given tag name. * @param options Configuration of the tokenization. */ function _Tokenizer(_file, _getTagDefinition, options) { this._getTagDefinition = _getTagDefinition; this._currentTokenStart = null; this._currentTokenType = null; this._expansionCaseStack = []; this._inInterpolation = false; this.tokens = []; this.errors = []; this._tokenizeIcu = options.tokenizeExpansionForms || false; this._interpolationConfig = options.interpolationConfig || DEFAULT_INTERPOLATION_CONFIG; this._leadingTriviaCodePoints = options.leadingTriviaChars && options.leadingTriviaChars.map(function (c) { return c.codePointAt(0) || 0; }); var range = options.range || { endPos: _file.content.length, startPos: 0, startLine: 0, startCol: 0 }; this._cursor = options.escapedString ? new EscapedCharacterCursor(_file, range) : new PlainCharacterCursor(_file, range); this._preserveLineEndings = options.preserveLineEndings || false; try { this._cursor.init(); } catch (e) { this.handleError(e); } } _Tokenizer.prototype._processCarriageReturns = function (content) { if (this._preserveLineEndings) { return content; } // http://www.w3.org/TR/html5/syntax.html#preprocessing-the-input-stream // In order to keep the original position in the source, we can not // pre-process it. // Instead CRs are processed right before instantiating the tokens. return content.replace(_CR_OR_CRLF_REGEXP, '\n'); }; _Tokenizer.prototype.tokenize = function () { while (this._cursor.peek() !== $EOF) { var start = this._cursor.clone(); try { if (this._attemptCharCode($LT)) { if (this._attemptCharCode($BANG)) { if (this._attemptCharCode($LBRACKET)) { this._consumeCdata(start); } else if (this._attemptCharCode($MINUS)) { this._consumeComment(start); } else { this._consumeDocType(start); } } else if (this._attemptCharCode($SLASH)) { this._consumeTagClose(start); } else { this._consumeTagOpen(start); } } else if (!(this._tokenizeIcu && this._tokenizeExpansionForm())) { this._consumeText(); } } catch (e) { this.handleError(e); } } this._beginToken(TokenType.EOF); this._endToken([]); return new TokenizeResult(mergeTextTokens(this.tokens), this.errors); }; /** * @returns whether an ICU token has been created * @internal */ _Tokenizer.prototype._tokenizeExpansionForm = function () { if (this.isExpansionFormStart()) { this._consumeExpansionFormStart(); return true; } if (isExpansionCaseStart(this._cursor.peek()) && this._isInExpansionForm()) { this._consumeExpansionCaseStart(); return true; } if (this._cursor.peek() === $RBRACE) { if (this._isInExpansionCase()) { this._consumeExpansionCaseEnd(); return true; } if (this._isInExpansionForm()) { this._consumeExpansionFormEnd(); return true; } } return false; }; _Tokenizer.prototype._beginToken = function (type, start) { if (start === void 0) { start = this._cursor.clone(); } this._currentTokenStart = start; this._currentTokenType = type; }; _Tokenizer.prototype._endToken = function (parts, end) { if (this._currentTokenStart === null) { throw new TokenError('Programming error - attempted to end a token when there was no start to the token', this._currentTokenType, this._cursor.getSpan(end)); } if (this._currentTokenType === null) { throw new TokenError('Programming error - attempted to end a token which has no token type', null, this._cursor.getSpan(this._currentTokenStart)); } var token = new Token(this._currentTokenType, parts, this._cursor.getSpan(this._currentTokenStart, this._leadingTriviaCodePoints)); this.tokens.push(token); this._currentTokenStart = null; this._currentTokenType = null; return token; }; _Tokenizer.prototype._createError = function (msg, span) { if (this._isInExpansionForm()) { msg += " (Do you have an unescaped \"{\" in your template? Use \"{{ '{' }}\") to escape it.)"; } var error = new TokenError(msg, this._currentTokenType, span); this._currentTokenStart = null; this._currentTokenType = null; return new _ControlFlowError(error); }; _Tokenizer.prototype.handleError = function (e) { if (e instanceof CursorError) { e = this._createError(e.msg, this._cursor.getSpan(e.cursor)); } if (e instanceof _ControlFlowError) { this.errors.push(e.error); } else { throw e; } }; _Tokenizer.prototype._attemptCharCode = function (charCode) { if (this._cursor.peek() === charCode) { this._cursor.advance(); return true; } return false; }; _Tokenizer.prototype._attemptCharCodeCaseInsensitive = function (charCode) { if (compareCharCodeCaseInsensitive(this._cursor.peek(), charCode)) { this._cursor.advance(); return true; } return false; }; _Tokenizer.prototype._requireCharCode = function (charCode) { var location = this._cursor.clone(); if (!this._attemptCharCode(charCode)) { throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(location)); } }; _Tokenizer.prototype._attemptStr = function (chars) { var len = chars.length; if (this._cursor.charsLeft() < len) { return false; } var initialPosition = this._cursor.clone(); for (var i = 0; i < len; i++) { if (!this._attemptCharCode(chars.charCodeAt(i))) { // If attempting to parse the string fails, we want to reset the parser // to where it was before the attempt this._cursor = initialPosition; return false; } } return true; }; _Tokenizer.prototype._attemptStrCaseInsensitive = function (chars) { for (var i = 0; i < chars.length; i++) { if (!this._attemptCharCodeCaseInsensitive(chars.charCodeAt(i))) { return false; } } return true; }; _Tokenizer.prototype._requireStr = function (chars) { var location = this._cursor.clone(); if (!this._attemptStr(chars)) { throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(location)); } }; _Tokenizer.prototype._attemptCharCodeUntilFn = function (predicate) { while (!predicate(this._cursor.peek())) { this._cursor.advance(); } }; _Tokenizer.prototype._requireCharCodeUntilFn = function (predicate, len) { var start = this._cursor.clone(); this._attemptCharCodeUntilFn(predicate); if (this._cursor.diff(start) < len) { throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(start)); } }; _Tokenizer.prototype._attemptUntilChar = function (char) { while (this._cursor.peek() !== char) { this._cursor.advance(); } }; _Tokenizer.prototype._readChar = function (decodeEntities) { if (decodeEntities && this._cursor.peek() === $AMPERSAND) { return this._decodeEntity(); } else { // Don't rely upon reading directly from `_input` as the actual char value // may have been generated from an escape sequence. var char = String.fromCodePoint(this._cursor.peek()); this._cursor.advance(); return char; } }; _Tokenizer.prototype._decodeEntity = function () { var start = this._cursor.clone(); this._cursor.advance(); if (this._attemptCharCode($HASH)) { var isHex = this._attemptCharCode($x) || this._attemptCharCode($X); var codeStart = this._cursor.clone(); this._attemptCharCodeUntilFn(isDigitEntityEnd); if (this._cursor.peek() != $SEMICOLON) { throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan()); } var strNum = this._cursor.getChars(codeStart); this._cursor.advance(); try { var charCode = parseInt(strNum, isHex ? 16 : 10); return String.fromCharCode(charCode); } catch (_a) { throw this._createError(_unknownEntityErrorMsg(this._cursor.getChars(start)), this._cursor.getSpan()); } } else { var nameStart = this._cursor.clone(); this._attemptCharCodeUntilFn(isNamedEntityEnd); if (this._cursor.peek() != $SEMICOLON) { this._cursor = nameStart; return '&'; } var name_1 = this._cursor.getChars(nameStart); this._cursor.advance(); var char = NAMED_ENTITIES[name_1]; if (!char) { throw this._createError(_unknownEntityErrorMsg(name_1), this._cursor.getSpan(start)); } return char; } }; _Tokenizer.prototype._consumeRawText = function (decodeEntities, endMarkerPredicate) { this._beginToken(decodeEntities ? TokenType.ESCAPABLE_RAW_TEXT : TokenType.RAW_TEXT); var parts = []; while (true) { var tagCloseStart = this._cursor.clone(); var foundEndMarker = endMarkerPredicate(); this._cursor = tagCloseStart; if (foundEndMarker) { break; } parts.push(this._readChar(decodeEntities)); } return this._endToken([this._processCarriageReturns(parts.join(''))]); }; _Tokenizer.prototype._consumeComment = function (start) { var _this = this; this._beginToken(TokenType.COMMENT_START, start); this._requireCharCode($MINUS); this._endToken([]); this._consumeRawText(false, function () { return _this._attemptStr('-->'); }); this._beginToken(TokenType.COMMENT_END); this._requireStr('-->'); this._endToken([]); }; _Tokenizer.prototype._consumeCdata = function (start) { var _this = this; this._beginToken(TokenType.CDATA_START, start); this._requireStr('CDATA['); this._endToken([]); this._consumeRawText(false, function () { return _this._attemptStr(']]>'); }); this._beginToken(TokenType.CDATA_END); this._requireStr(']]>'); this._endToken([]); }; _Tokenizer.prototype._consumeDocType = function (start) { this._beginToken(TokenType.DOC_TYPE, start); var contentStart = this._cursor.clone(); this._attemptUntilChar($GT); var content = this._cursor.getChars(contentStart); this._cursor.advance(); this._endToken([content]); }; _Tokenizer.prototype._consumePrefixAndName = function () { var nameOrPrefixStart = this._cursor.clone(); var prefix = ''; while (this._cursor.peek() !== $COLON && !isPrefixEnd(this._cursor.peek())) { this._cursor.advance(); } var nameStart; if (this._cursor.peek() === $COLON) { prefix = this._cursor.getChars(nameOrPrefixStart); this._cursor.advance(); nameStart = this._cursor.clone(); } else { nameStart = nameOrPrefixStart; } this._requireCharCodeUntilFn(isNameEnd, prefix === '' ? 0 : 1); var name = this._cursor.getChars(nameStart); return [prefix, name]; }; _Tokenizer.prototype._consumeTagOpen = function (start) { var tagName; var prefix; var openTagToken; var tokensBeforeTagOpen = this.tokens.length; var innerStart = this._cursor.clone(); try { if (!isAsciiLetter(this._cursor.peek())) { throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(start)); } openTagToken = this._consumeTagOpenStart(start); prefix = openTagToken.parts[0]; tagName = openTagToken.parts[1]; this._attemptCharCodeUntilFn(isNotWhitespace); while (this._cursor.peek() !== $SLASH && this._cursor.peek() !== $GT) { this._consumeAttributeName(); this._attemptCharCodeUntilFn(isNotWhitespace); if (this._attemptCharCode($EQ)) { this._attemptCharCodeUntilFn(isNotWhitespace); this._consumeAttributeValue(); } this._attemptCharCodeUntilFn(isNotWhitespace); } this._consumeTagOpenEnd(); } catch (e) { if (e instanceof _ControlFlowError) { // When the start tag is invalid (including invalid "attributes"), assume we want a "<" this._cursor = innerStart; if (openTagToken) { this.tokens.length = tokensBeforeTagOpen; } // Back to back text tokens are merged at the end this._beginToken(TokenType.TEXT, start); this._endToken(['<']); return; } throw e; } var contentTokenType = this._getTagDefinition(tagName).contentType; if (contentTokenType === TagContentType.RAW_TEXT) { this._consumeRawTextWithTagClose(prefix, tagName, false); } else if (contentTokenType === TagContentType.ESCAPABLE_RAW_TEXT) { this._consumeRawTextWithTagClose(prefix, tagName, true); } }; _Tokenizer.prototype._consumeRawTextWithTagClose = function (prefix, tagName, decodeEntities) { var _this = this; var textToken = this._consumeRawText(decodeEntities, function () { if (!_this._attemptCharCode($LT)) return false; if (!_this._attemptCharCode($SLASH)) return false; _this._attemptCharCodeUntilFn(isNotWhitespace); if (!_this._attemptStrCaseInsensitive(tagName)) return false; _this._attemptCharCodeUntilFn(isNotWhitespace); return _this._attemptCharCode($GT); }); this._beginToken(TokenType.TAG_CLOSE); this._requireCharCodeUntilFn(function (code) { return code === $GT; }, 3); this._cursor.advance(); // Consume the `>` this._endToken([prefix, tagName]); }; _Tokenizer.prototype._consumeTagOpenStart = function (start) { this._beginToken(TokenType.TAG_OPEN_START, start); var parts = this._consumePrefixAndName(); return this._endToken(parts); }; _Tokenizer.prototype._consumeAttributeName = function () { var attrNameStart = this._cursor.peek(); if (attrNameStart === $SQ || attrNameStart === $DQ) { throw this._createError(_unexpectedCharacterErrorMsg(attrNameStart), this._cursor.getSpan()); } this._beginToken(TokenType.ATTR_NAME); var prefixAndName = this._consumePrefixAndName(); this._endToken(prefixAndName); }; _Tokenizer.prototype._consumeAttributeValue = function () { var value; if (this._cursor.peek() === $SQ || this._cursor.peek() === $DQ) { this._beginToken(TokenType.ATTR_QUOTE); var quoteChar = this._cursor.peek(); this._cursor.advance(); this._endToken([String.fromCodePoint(quoteChar)]); this._beginToken(TokenType.ATTR_VALUE); var parts = []; while (this._cursor.peek() !== quoteChar) { parts.push(this._readChar(true)); } value = parts.join(''); this._endToken([this._processCarriageReturns(value)]); this._beginToken(TokenType.ATTR_QUOTE); this._cursor.advance(); this._endToken([String.fromCodePoint(quoteChar)]); } else { this._beginToken(TokenType.ATTR_VALUE); var valueStart = this._cursor.clone(); this._requireCharCodeUntilFn(isNameEnd, 1); value = this._cursor.getChars(valueStart); this._endToken([this._processCarriageReturns(value)]); } }; _Tokenizer.prototype._consumeTagOpenEnd = function () { var tokenType = this._attemptCharCode($SLASH) ? TokenType.TAG_OPEN_END_VOID : TokenType.TAG_OPEN_END; this._beginToken(tokenType); this._requireCharCode($GT); this._endToken([]); }; _Tokenizer.prototype._consumeTagClose = function (start) { this._beginToken(TokenType.TAG_CLOSE, start); this._attemptCharCodeUntilFn(isNotWhitespace); var prefixAndName = this._consumePrefixAndName(); this._attemptCharCodeUntilFn(isNotWhitespace); this._requireCharCode($GT); this._endToken(prefixAndName); }; _Tokenizer.prototype._consumeExpansionFormStart = function () { this._beginToken(TokenType.EXPANSION_FORM_START); this._requireCharCode($LBRACE); this._endToken([]); this._expansionCaseStack.push(TokenType.EXPANSION_FORM_START); this._beginToken(TokenType.RAW_TEXT); var condition = this._readUntil($COMMA); this._endToken([condition]); this._requireCharCode($COMMA); this._attemptCharCodeUntilFn(isNotWhitespace); this._beginToken(TokenType.RAW_TEXT); var type = this._readUntil($COMMA); this._endToken([type]); this._requireCharCode($COMMA); this._attemptCharCodeUntilFn(isNotWhitespace); }; _Tokenizer.prototype._consumeExpansionCaseStart = function () { this._beginToken(TokenType.EXPANSION_CASE_VALUE); var value = this._readUntil($LBRACE).trim(); this._endToken([value]); this._attemptCharCodeUntilFn(isNotWhitespace); this._beginToken(TokenType.EXPANSION_CASE_EXP_START); this._requireCharCode($LBRACE); this._endToken([]); this._attemptCharCodeUntilFn(isNotWhitespace); this._expansionCaseStack.push(TokenType.EXPANSION_CASE_EXP_START); }; _Tokenizer.prototype._consumeExpansionCaseEnd = function () { this._beginToken(TokenType.EXPANSION_CASE_EXP_END); this._requireCharCode($RBRACE); this._endToken([]); this._attemptCharCodeUntilFn(isNotWhitespace); this._expansionCaseStack.pop(); }; _Tokenizer.prototype._consumeExpansionFormEnd = function () { this._beginToken(TokenType.EXPANSION_FORM_END); this._requireCharCode($RBRACE); this._endToken([]); this._expansionCaseStack.pop(); }; _Tokenizer.prototype._consumeText = function () { var start = this._cursor.clone(); this._beginToken(TokenType.TEXT, start); var parts = []; do { if (this._interpolationConfig && this._attemptStr(this._interpolationConfig.start)) { parts.push(this._interpolationConfig.start); this._inInterpolation = true; } else if (this._interpolationConfig && this._inInterpolation && this._attemptStr(this._interpolationConfig.end)) { parts.push(this._interpolationConfig.end); this._inInterpolation = false; } else { parts.push(this._readChar(true)); } } while (!this._isTextEnd()); this._endToken([this._processCarriageReturns(parts.join(''))]); }; _Tokenizer.prototype._isTextEnd = function () { if (this._cursor.peek() === $LT || this._cursor.peek() === $EOF) { return true; } if (this._tokenizeIcu && !this._inInterpolation) { if (this.isExpansionFormStart()) { // start of an expansion form return true; } if (this._cursor.peek() === $RBRACE && this._isInExpansionCase()) { // end of and expansion case return true; } } return false; }; _Tokenizer.prototype._readUntil = function (char) { var start = this._cursor.clone(); this._attemptUntilChar(char); return this._cursor.getChars(start); }; _Tokenizer.prototype._isInExpansionCase = function () { return this._expansionCaseStack.length > 0 && this._expansionCaseStack[this._expansionCaseStack.length - 1] === TokenType.EXPANSION_CASE_EXP_START; }; _Tokenizer.prototype._isInExpansionForm = function () { return this._expansionCaseStack.length > 0 && this._expansionCaseStack[this._expansionCaseStack.length - 1] === TokenType.EXPANSION_FORM_START; }; _Tokenizer.prototype.isExpansionFormStart = function () { if (this._cursor.peek() !== $LBRACE) { return false; } if (this._interpolationConfig) { var start = this._cursor.clone(); var isInterpolation = this._attemptStr(this._interpolationConfig.start); this._cursor = start; return !isInterpolation; } return true; }; return _Tokenizer; }()); function isNotWhitespace(code) { return !isWhitespace(code) || code === $EOF; } function isNameEnd(code) { return isWhitespace(code) || code === $GT || code === $SLASH || code === $SQ || code === $DQ || code === $EQ; } function isPrefixEnd(code) { return (code < $a || $z < code) && (code < $A || $Z < code) && (code < $0 || code > $9); } function isDigitEntityEnd(code) { return code == $SEMICOLON || code == $EOF || !isAsciiHexDigit(code); } function isNamedEntityEnd(code) { return code == $SEMICOLON || code == $EOF || !isAsciiLetter(code); } function isExpansionCaseStart(peek) { return peek === $EQ || isAsciiLetter(peek) || isDigit(peek); } function compareCharCodeCaseInsensitive(code1, code2) { return toUpperCaseCharCode(code1) == toUpperCaseCharCode(code2); } function toUpperCaseCharCode(code) { return code >= $a && code <= $z ? code - $a + $A : code; } function mergeTextTokens(srcTokens) { var dstTokens = []; var lastDstToken = undefined; for (var i = 0; i < srcTokens.length; i++) { var token = srcTokens[i]; if (lastDstToken && lastDstToken.type == TokenType.TEXT && token.type == TokenType.TEXT) { lastDstToken.parts[0] += token.parts[0]; lastDstToken.sourceSpan.end = token.sourceSpan.end; } else { lastDstToken = token; dstTokens.push(lastDstToken); } } return dstTokens; } var PlainCharacterCursor = /** @class */ (function () { function PlainCharacterCursor(fileOrCursor, range) { if (fileOrCursor instanceof PlainCharacterCursor) { this.file = fileOrCursor.file; this.input = fileOrCursor.input; this.end = fileOrCursor.end; var state = fileOrCursor.state; // Note: avoid using `{...fileOrCursor.state}` here as that has a severe performance penalty. // In ES5 bundles the object spread operator is translated into the `__assign` helper, which // is not optimized by VMs as efficiently as a raw object literal. Since this constructor is // called in tight loops, this difference matters. this.state = { peek: state.peek, offset: state.offset, line: state.line, column: state.column, }; } else { if (!range) { throw new Error('Programming error: the range argument must be provided with a file argument.'); } this.file = fileOrCursor; this.input = fileOrCursor.content; this.end = range.endPos; this.state = { peek: -1, offset: range.startPos, line: range.startLine, column: range.startCol, }; } } PlainCharacterCursor.prototype.clone = function () { return new PlainCharacterCursor(this); }; PlainCharacterCursor.prototype.peek = function () { return this.state.peek; }; PlainCharacterCursor.prototype.charsLeft = function () { return this.end - this.state.offset; }; PlainCharacterCursor.prototype.diff = function (other) { return this.state.offset - other.state.offset; }; PlainCharacterCursor.prototype.advance = function () { this.advanceState(this.state); }; PlainCharacterCursor.prototype.init = function () { this.updatePeek(this.state); }; PlainCharacterCursor.prototype.getSpan = function (start, leadingTriviaCodePoints) { start = start || this; var cloned = false; if (leadingTriviaCodePoints) { while (this.diff(start) > 0 && leadingTriviaCodePoints.indexOf(start.peek()) !== -1) { if (!cloned) { start = start.clone(); cloned = true; } start.advance(); } } 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)); }; PlainCharacterCursor.prototype.getChars = function (start) { return this.input.substring(start.state.offset, this.state.offset); }; PlainCharacterCursor.prototype.charAt = function (pos) { return this.input.charCodeAt(pos); }; PlainCharacterCursor.prototype.advanceState = function (state) { if (state.offset >= this.end) { this.state = state; throw new CursorError('Unexpected character "EOF"', this); } var currentChar = this.charAt(state.offset); if (currentChar === $LF) { state.line++; state.column = 0; } else if (!isNewLine(currentChar)) { state.column++; } state.offset++; this.updatePeek(state); }; PlainCharacterCursor.prototype.updatePeek = function (state) { state.peek = state.offset >= this.end ? $EOF : this.charAt(state.offset); }; return PlainCharacterCursor; }()); var EscapedCharacterCursor = /** @class */ (function (_super) { __extends(EscapedCharacterCursor, _super); function EscapedCharacterCursor(fileOrCursor, range) { var _this = this; if (fileOrCursor instanceof EscapedCharacterCursor) { _this = _super.call(this, fileOrCursor) || this; _this.internalState = __assign({}, fileOrCursor.internalState); } else { _this = _super.call(this, fileOrCursor, range) || this; _this.internalState = _this.state; } return _this; } EscapedCharacterCursor.prototype.advance = function () { this.state = this.internalState; _super.prototype.advance.call(this); this.processEscapeSequence(); }; EscapedCharacterCursor.prototype.init = function () { _super.prototype.init.call(this); this.processEscapeSequence(); }; EscapedCharacterCursor.prototype.clone = function () { return new EscapedCharacterCursor(this); }; EscapedCharacterCursor.prototype.getChars = function (start) { var cursor = start.clone(); var chars = ''; while (cursor.internalState.offset < this.internalState.offset) { chars += String.fromCodePoint(cursor.peek()); cursor.advance(); } return chars; }; /** * Process the escape sequence that starts at the current position in the text. * * This method is called to ensure that `peek` has the unescaped value of escape sequences. */ EscapedCharacterCursor.prototype.processEscapeSequence = function () { var _this = this; var peek = function () { return _this.internalState.peek; }; if (peek() === $BACKSLASH) { // We have hit an escape sequence so we need the internal state to become independent // of the external state. this.internalState = __assign({}, this.state); // Move past the backslash this.advanceState(this.internalState); // First check for standard control char sequences if (peek() === $n) { this.state.peek = $LF; } else if (peek() === $r) { this.state.peek = $CR; } else if (peek() === $v) { this.state.peek = $VTAB; } else if (peek() === $t) { this.state.peek = $TAB; } else if (peek() === $b) { this.state.peek = $BSPACE; } else if (peek() === $f) { this.state.peek = $FF; } // Now consider more complex sequences else if (peek() === $u) { // Unicode code-point sequence this.advanceState(this.internalState); // advance past the `u` char if (peek() === $LBRACE) { // Variable length Unicode, e.g. `\x{123}` this.advanceState(this.internalState); // advance past the `{` char // Advance past the variable number of hex digits until we hit a `}` char var digitStart = this.clone(); var length_1 = 0; while (peek() !== $RBRACE) { this.advanceState(this.internalState); length_1++; } this.state.peek = this.decodeHexDigits(digitStart, length_1); } else { // Fixed length Unicode, e.g. `\u1234` var digitStart = this.clone(); this.advanceState(this.internalState); this.advanceState(this.internalState); this.advanceState(this.internalState); this.state.peek = this.decodeHexDigits(digitStart, 4); } } else if (peek() === $x) { // Hex char code, e.g. `\x2F` this.advanceState(this.internalState); // advance past the `x` char var digitStart = this.clone(); this.advanceState(this.internalState); this.state.peek = this.decodeHexDigits(digitStart, 2); } else if (isOctalDigit(peek())) { // Octal char code, e.g. `\012`, var octal = ''; var length_2 = 0; var previous = this.clone(); while (isOctalDigit(peek()) && length_2 < 3) { previous = this.clone(); octal += String.fromCodePoint(peek()); this.advanceState(this.internalState); length_2++; } this.state.peek = parseInt(octal, 8); // Backup one char this.internalState = previous.internalState; } else if (isNewLine(this.internalState.peek)) { // Line continuation `\` followed by a new line this.advanceState(this.internalState); // advance over the newline this.state = this.internalState; } else { // If none of the `if` blocks were executed then we just have an escaped normal character. // In that case we just, effectively, skip the backslash from the character. this.state.peek = this.internalState.peek; } } }; EscapedCharacterCursor.prototype.decodeHexDigits = function (start, length) { var hex = this.input.substr(start.internalState.offset, length); var charCode = parseInt(hex, 16); if (!isNaN(charCode)) { return charCode; } else { start.state = start.internalState; throw new CursorError('Invalid hexadecimal escape sequence', start); } }; return EscapedCharacterCursor; }(PlainCharacterCursor)); var CursorError = /** @class */ (function () { function CursorError(msg, cursor) { this.msg = msg; this.cursor = cursor; } return CursorError; }()); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var TreeError = /** @class */ (function (_super) { __extends(TreeError, _super); function TreeError(elementName, span, msg) { var _this = _super.call(this, span, msg) || this; _this.elementName = elementName; return _this; } TreeError.create = function (elementName, span, msg) { return new TreeError(elementName, span, msg); }; return TreeError; }(ParseError)); var ParseTreeResult = /** @class */ (function () { function ParseTreeResult(rootNodes, errors) { this.rootNodes = rootNodes; this.errors = errors; } return ParseTreeResult; }()); var Parser = /** @class */ (function () { function Parser(getTagDefinition) { this.getTagDefinition = getTagDefinition; } Parser.prototype.parse = function (source, url, options) { var tokensAndErrors = tokenize(source, url, this.getTagDefinition, options); var treeAndErrors = new _TreeBuilder(tokensAndErrors.tokens, this.getTagDefinition).build(); return new ParseTreeResult(treeAndErrors.rootNodes, tokensAndErrors.errors.concat(treeAndErrors.errors)); }; return Parser; }()); var _TreeBuilder = /** @class */ (function () { function _TreeBuilder(tokens, getTagDefinition) { this.tokens = tokens; this.getTagDefinition = getTagDefinition; this._index = -1; this._rootNodes = []; this._errors = []; this._elementStack = []; this._advance(); } _TreeBuilder.prototype.build = function () { while (this._peek.type !== TokenType.EOF) { if (this._peek.type === TokenType.TAG_OPEN_START) { this._consumeStartTag(this._advance()); } else if (this._peek.type === TokenType.TAG_CLOSE) { this._consumeEndTag(this._advance()); } else if (this._peek.type === TokenType.CDATA_START) { this._closeVoidElement(); this._consumeCdata(this._advance()); } else if (this._peek.type === TokenType.COMMENT_START) { this._closeVoidElement(); this._consumeComment(this._advance()); } else if (this._peek.type === TokenType.TEXT || this._peek.type === TokenType.RAW_TEXT || this._peek.type === TokenType.ESCAPABLE_RAW_TEXT) { this._closeVoidElement(); this._consumeText(this._advance()); } else if (this._peek.type === TokenType.EXPANSION_FORM_START) { this._consumeExpansion(this._advance()); } else { // Skip all other tokens... this._advance(); } } return new ParseTreeResult(this._rootNodes, this._errors); }; _TreeBuilder.prototype._advance = function () { var prev = this._peek; if (this._index < this.tokens.length - 1) { // Note: there is always an EOF token at the end this._index++; } this._peek = this.tokens[this._index]; return prev; }; _TreeBuilder.prototype._advanceIf = function (type) { if (this._peek.type === type) { return this._advance(); } return null; }; _TreeBuilder.prototype._consumeCdata = function (startToken) { this._consumeText(this._advance()); this._advanceIf(TokenType.CDATA_END); }; _TreeBuilder.prototype._consumeComment = function (token) { var text = this._advanceIf(TokenType.RAW_TEXT); this._advanceIf(TokenType.COMMENT_END); var value = text != null ? text.parts[0].trim() : null; this._addToParent(new Comment(value, token.sourceSpan)); }; _TreeBuilder.prototype._consumeExpansion = function (token) { var switchValue = this._advance(); var type = this._advance(); var cases = []; // read = while (this._peek.type === TokenType.EXPANSION_CASE_VALUE) { var expCase = this._parseExpansionCase(); if (!expCase) return; // error cases.push(expCase); } // read the final } if (this._peek.type !== TokenType.EXPANSION_FORM_END) { this._errors.push(TreeError.create(null, this._peek.sourceSpan, "Invalid ICU message. Missing '}'.")); return; } var sourceSpan = new ParseSourceSpan(token.sourceSpan.start, this._peek.sourceSpan.end); this._addToParent(new Expansion(switchValue.parts[0], type.parts[0], cases, sourceSpan, switchValue.sourceSpan)); this._advance(); }; _TreeBuilder.prototype._parseExpansionCase = function () { var value = this._advance(); // read { if (this._peek.type !== TokenType.EXPANSION_CASE_EXP_START) { this._errors.push(TreeError.create(null, this._peek.sourceSpan, "Invalid ICU message. Missing '{'.")); return null; } // read until } var start = this._advance(); var exp = this._collectExpansionExpTokens(start); if (!exp) return null; var end = this._advance(); exp.push(new Token(TokenType.EOF, [], end.sourceSpan)); // parse everything in between { and } var parsedExp = new _TreeBuilder(exp, this.getTagDefinition).build(); if (parsedExp.errors.length > 0) { this._errors = this._errors.concat(parsedExp.errors); return null; } var sourceSpan = new ParseSourceSpan(value.sourceSpan.start, end.sourceSpan.end); var expSourceSpan = new ParseSourceSpan(start.sourceSpan.start, end.sourceSpan.end); return new ExpansionCase(value.parts[0], parsedExp.rootNodes, sourceSpan, value.sourceSpan, expSourceSpan); }; _TreeBuilder.prototype._collectExpansionExpTokens = function (start) { var exp = []; var expansionFormStack = [TokenType.EXPANSION_CASE_EXP_START]; while (true) { if (this._peek.type === TokenType.EXPANSION_FORM_START || this._peek.type === TokenType.EXPANSION_CASE_EXP_START) { expansionFormStack.push(this._peek.type); } if (this._peek.type === TokenType.EXPANSION_CASE_EXP_END) { if (lastOnStack(expansionFormStack, TokenType.EXPANSION_CASE_EXP_START)) { expansionFormStack.pop(); if (expansionFormStack.length == 0) return exp; } else { this._errors.push(TreeError.create(null, start.sourceSpan, "Invalid ICU message. Missing '}'.")); return null; } } if (this._peek.type === TokenType.EXPANSION_FORM_END) { if (lastOnStack(expansionFormStack, TokenType.EXPANSION_FORM_START)) { expansionFormStack.pop(); } else { this._errors.push(TreeError.create(null, start.sourceSpan, "Invalid ICU message. Missing '}'.")); return null; } } if (this._peek.type === TokenType.EOF) { this._errors.push(TreeError.create(null, start.sourceSpan, "Invalid ICU message. Missing '}'.")); return null; } exp.push(this._advance()); } }; _TreeBuilder.prototype._consumeText = function (token) { var text = token.parts[0]; if (text.length > 0 && text[0] == '\n') { var parent_1 = this._getParentElement(); if (parent_1 != null && parent_1.children.length == 0 && this.getTagDefinition(parent_1.name).ignoreFirstLf) { text = text.substring(1); } } if (text.length > 0) { this._addToParent(new Text$3(text, token.sourceSpan)); } }; _TreeBuilder.prototype._closeVoidElement = function () { var el = this._getParentElement(); if (el && this.getTagDefinition(el.name).isVoid) { this._elementStack.pop(); } }; _TreeBuilder.prototype._consumeStartTag = function (startTagToken) { var prefix = startTagToken.parts[0]; var name = startTagToken.parts[1]; var attrs = []; while (this._peek.type === TokenType.ATTR_NAME) { attrs.push(this._consumeAttr(this._advance())); } var fullName = this._getElementFullName(prefix, name, this._getParentElement()); var selfClosing = false; // Note: There could have been a tokenizer error // so that we don't get a token for the end tag... if (this._peek.type === TokenType.TAG_OPEN_END_VOID) { this._advance(); selfClosing = true; var tagDef = this.getTagDefinition(fullName); if (!(tagDef.canSelfClose || getNsPrefix(fullName) !== null || tagDef.isVoid)) { this._errors.push(TreeError.create(fullName, startTagToken.sourceSpan, "Only void and foreign elements can be self closed \"" + startTagToken.parts[1] + "\"")); } } else if (this._peek.type === TokenType.TAG_OPEN_END) { this._advance(); selfClosing = false; } var end = this._peek.sourceSpan.start; var span = new ParseSourceSpan(startTagToken.sourceSpan.start, end); var el = new Element$1(fullName, attrs, [], span, span, undefined); this._pushElement(el); if (selfClosing) { this._popElement(fullName); el.endSourceSpan = span; } }; _TreeBuilder.prototype._pushElement = function (el) { var parentEl = this._getParentElement(); if (parentEl && this.getTagDefinition(parentEl.name).isClosedByChild(el.name)) { this._elementStack.pop(); } this._addToParent(el); this._elementStack.push(el); }; _TreeBuilder.prototype._consumeEndTag = function (endTagToken) { var fullName = this._getElementFullName(endTagToken.parts[0], endTagToken.parts[1], this._getParentElement()); if (this._getParentElement()) { this._getParentElement().endSourceSpan = endTagToken.sourceSpan; } if (this.getTagDefinition(fullName).isVoid) { this._errors.push(TreeError.create(fullName, endTagToken.sourceSpan, "Void elements do not have end tags \"" + endTagToken.parts[1] + "\"")); } else if (!this._popElement(fullName)) { 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"; this._errors.push(TreeError.create(fullName, endTagToken.sourceSpan, errMsg)); } }; _TreeBuilder.prototype._popElement = function (fullName) { for (var stackIndex = this._elementStack.length - 1; stackIndex >= 0; stackIndex--) { var el = this._elementStack[stackIndex]; if (el.name == fullName) { this._elementStack.splice(stackIndex, this._elementStack.length - stackIndex); return true; } if (!this.getTagDefinition(el.name).closedByParent) { return false; } } return false; }; _TreeBuilder.prototype._consumeAttr = function (attrName) { var fullName = mergeNsAndName(attrName.parts[0], attrName.parts[1]); var end = attrName.sourceSpan.end; var value = ''; var valueSpan = undefined; if (this._peek.type === TokenType.ATTR_QUOTE) { this._advance(); } if (this._peek.type === TokenType.ATTR_VALUE) { var valueToken = this._advance(); value = valueToken.parts[0]; end = valueToken.sourceSpan.end; valueSpan = valueToken.sourceSpan; } if (this._peek.type === TokenType.ATTR_QUOTE) { var quoteToken = this._advance(); end = quoteToken.sourceSpan.end; } return new Attribute(fullName, value, new ParseSourceSpan(attrName.sourceSpan.start, end), valueSpan); }; _TreeBuilder.prototype._getParentElement = function () { return this._elementStack.length > 0 ? this._elementStack[this._elementStack.length - 1] : null; }; /** * Returns the parent in the DOM and the container. * * `` elements are skipped as they are not rendered as DOM element. */ _TreeBuilder.prototype._getParentElementSkippingContainers = function () { var container = null; for (var i = this._elementStack.length - 1; i >= 0; i--) { if (!isNgContainer(this._elementStack[i].name)) { return { parent: this._elementStack[i], container: container }; } container = this._elementStack[i]; } return { parent: null, container: container }; }; _TreeBuilder.prototype._addToParent = function (node) { var parent = this._getParentElement(); if (parent != null) { parent.children.push(node); } else { this._rootNodes.push(node); } }; /** * Insert a node between the parent and the container. * When no container is given, the node is appended as a child of the parent. * Also updates the element stack accordingly. * * @internal */ _TreeBuilder.prototype._insertBeforeContainer = function (parent, container, node) { if (!container) { this._addToParent(node); this._elementStack.push(node); } else { if (parent) { // replace the container with the new node in the children var index = parent.children.indexOf(container); parent.children[index] = node; } else { this._rootNodes.push(node); } node.children.push(container); this._elementStack.splice(this._elementStack.indexOf(container), 0, node); } }; _TreeBuilder.prototype._getElementFullName = function (prefix, localName, parentElement) { if (prefix === '') { prefix = this.getTagDefinition(localName).implicitNamespacePrefix || ''; if (prefix === '' && parentElement != null) { prefix = getNsPrefix(parentElement.name); } } return mergeNsAndName(prefix, localName); }; return _TreeBuilder; }()); function lastOnStack(stack, element) { return stack.length > 0 && stack[stack.length - 1] === element; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var HtmlParser = /** @class */ (function (_super) { __extends(HtmlParser, _super); function HtmlParser() { return _super.call(this, getHtmlTagDefinition) || this; } HtmlParser.prototype.parse = function (source, url, options) { return _super.prototype.parse.call(this, source, url, options); }; return HtmlParser; }(Parser)); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var PRESERVE_WS_ATTR_NAME = 'ngPreserveWhitespaces'; var SKIP_WS_TRIM_TAGS = new Set(['pre', 'template', 'textarea', 'script', 'style']); // Equivalent to \s with \u00a0 (non-breaking space) excluded. // Based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp var WS_CHARS = ' \f\n\r\t\v\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff'; var NO_WS_REGEXP = new RegExp("[^" + WS_CHARS + "]"); var WS_REPLACE_REGEXP = new RegExp("[" + WS_CHARS + "]{2,}", 'g'); function hasPreserveWhitespacesAttr(attrs) { return attrs.some(function (attr) { return attr.name === PRESERVE_WS_ATTR_NAME; }); } /** * Angular Dart introduced &ngsp; as a placeholder for non-removable space, see: * https://github.com/dart-lang/angular/blob/0bb611387d29d65b5af7f9d2515ab571fd3fbee4/_tests/test/compiler/preserve_whitespace_test.dart#L25-L32 * In Angular Dart &ngsp; is converted to the 0xE500 PUA (Private Use Areas) unicode character * and later on replaced by a space. We are re-implementing the same idea here. */ function replaceNgsp(value) { // lexer is replacing the &ngsp; pseudo-entity with NGSP_UNICODE return value.replace(new RegExp(NGSP_UNICODE, 'g'), ' '); } /** * This visitor can walk HTML parse tree and remove / trim text nodes using the following rules: * - consider spaces, tabs and new lines as whitespace characters; * - drop text nodes consisting of whitespace characters only; * - for all other text nodes replace consecutive whitespace characters with one space; * - convert &ngsp; pseudo-entity to a single space; * * Removal and trimming of whitespaces have positive performance impact (less code to generate * while compiling templates, faster view creation). At the same time it can be "destructive" * in some cases (whitespaces can influence layout). Because of the potential of breaking layout * this visitor is not activated by default in Angular 5 and people need to explicitly opt-in for * whitespace removal. The default option for whitespace removal will be revisited in Angular 6 * and might be changed to "on" by default. */ var WhitespaceVisitor = /** @class */ (function () { function WhitespaceVisitor() { } WhitespaceVisitor.prototype.visitElement = function (element, context) { if (SKIP_WS_TRIM_TAGS.has(element.name) || hasPreserveWhitespacesAttr(element.attrs)) { // don't descent into elements where we need to preserve whitespaces // but still visit all attributes to eliminate one used as a market to preserve WS return new Element$1(element.name, visitAll$1(this, element.attrs), element.children, element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n); } return new Element$1(element.name, element.attrs, visitAllWithSiblings(this, element.children), element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n); }; WhitespaceVisitor.prototype.visitAttribute = function (attribute, context) { return attribute.name !== PRESERVE_WS_ATTR_NAME ? attribute : null; }; WhitespaceVisitor.prototype.visitText = function (text, context) { var isNotBlank = text.value.match(NO_WS_REGEXP); var hasExpansionSibling = context && (context.prev instanceof Expansion || context.next instanceof Expansion); if (isNotBlank || hasExpansionSibling) { return new Text$3(replaceNgsp(text.value).replace(WS_REPLACE_REGEXP, ' '), text.sourceSpan, text.i18n); } return null; }; WhitespaceVisitor.prototype.visitComment = function (comment, context) { return comment; }; WhitespaceVisitor.prototype.visitExpansion = function (expansion, context) { return expansion; }; WhitespaceVisitor.prototype.visitExpansionCase = function (expansionCase, context) { return expansionCase; }; return WhitespaceVisitor; }()); function removeWhitespaces(htmlAstWithErrors) { return new ParseTreeResult(visitAll$1(new WhitespaceVisitor(), htmlAstWithErrors.rootNodes), htmlAstWithErrors.errors); } function visitAllWithSiblings(visitor, nodes) { var result = []; nodes.forEach(function (ast, i) { var context = { prev: nodes[i - 1], next: nodes[i + 1] }; var astResult = ast.visit(visitor, context); if (astResult) { result.push(astResult); } }); return result; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // http://cldr.unicode.org/index/cldr-spec/plural-rules var PLURAL_CASES = ['zero', 'one', 'two', 'few', 'many', 'other']; /** * Expands special forms into elements. * * For example, * * ``` * { messages.length, plural, * =0 {zero} * =1 {one} * other {more than one} * } * ``` * * will be expanded into * * ``` * * zero * one * more than one * * ``` */ function expandNodes(nodes) { var expander = new _Expander(); return new ExpansionResult(visitAll$1(expander, nodes), expander.isExpanded, expander.errors); } var ExpansionResult = /** @class */ (function () { function ExpansionResult(nodes, expanded, errors) { this.nodes = nodes; this.expanded = expanded; this.errors = errors; } return ExpansionResult; }()); var ExpansionError = /** @class */ (function (_super) { __extends(ExpansionError, _super); function ExpansionError(span, errorMsg) { return _super.call(this, span, errorMsg) || this; } return ExpansionError; }(ParseError)); /** * Expand expansion forms (plural, select) to directives * * @internal */ var _Expander = /** @class */ (function () { function _Expander() { this.isExpanded = false; this.errors = []; } _Expander.prototype.visitElement = function (element, context) { return new Element$1(element.name, element.attrs, visitAll$1(this, element.children), element.sourceSpan, element.startSourceSpan, element.endSourceSpan); }; _Expander.prototype.visitAttribute = function (attribute, context) { return attribute; }; _Expander.prototype.visitText = function (text, context) { return text; }; _Expander.prototype.visitComment = function (comment, context) { return comment; }; _Expander.prototype.visitExpansion = function (icu, context) { this.isExpanded = true; return icu.type == 'plural' ? _expandPluralForm(icu, this.errors) : _expandDefaultForm(icu, this.errors); }; _Expander.prototype.visitExpansionCase = function (icuCase, context) { throw new Error('Should not be reached'); }; return _Expander; }()); // Plural forms are expanded to `NgPlural` and `NgPluralCase`s function _expandPluralForm(ast, errors) { var children = ast.cases.map(function (c) { if (PLURAL_CASES.indexOf(c.value) == -1 && !c.value.match(/^=\d+$/)) { errors.push(new ExpansionError(c.valueSourceSpan, "Plural cases should be \"=\" or one of " + PLURAL_CASES.join(", "))); } var expansionResult = expandNodes(c.expression); errors.push.apply(errors, __spread(expansionResult.errors)); return new Element$1("ng-template", [new Attribute('ngPluralCase', "" + c.value, c.valueSourceSpan)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan); }); var switchAttr = new Attribute('[ngPlural]', ast.switchValue, ast.switchValueSourceSpan); return new Element$1('ng-container', [switchAttr], children, ast.sourceSpan, ast.sourceSpan, ast.sourceSpan); } // ICU messages (excluding plural form) are expanded to `NgSwitch` and `NgSwitchCase`s function _expandDefaultForm(ast, errors) { var children = ast.cases.map(function (c) { var expansionResult = expandNodes(c.expression); errors.push.apply(errors, __spread(expansionResult.errors)); if (c.value === 'other') { // other is the default case when no values match return new Element$1("ng-template", [new Attribute('ngSwitchDefault', '', c.valueSourceSpan)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan); } return new Element$1("ng-template", [new Attribute('ngSwitchCase', "" + c.value, c.valueSourceSpan)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan); }); var switchAttr = new Attribute('[ngSwitch]', ast.switchValue, ast.switchValueSourceSpan); return new Element$1('ng-container', [switchAttr], children, ast.sourceSpan, ast.sourceSpan, ast.sourceSpan); } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var _a; /** * A segment of text within the template. */ var TextAst = /** @class */ (function () { function TextAst(value, ngContentIndex, sourceSpan) { this.value = value; this.ngContentIndex = ngContentIndex; this.sourceSpan = sourceSpan; } TextAst.prototype.visit = function (visitor, context) { return visitor.visitText(this, context); }; return TextAst; }()); /** * A bound expression within the text of a template. */ var BoundTextAst = /** @class */ (function () { function BoundTextAst(value, ngContentIndex, sourceSpan) { this.value = value; this.ngContentIndex = ngContentIndex; this.sourceSpan = sourceSpan; } BoundTextAst.prototype.visit = function (visitor, context) { return visitor.visitBoundText(this, context); }; return BoundTextAst; }()); /** * A plain attribute on an element. */ var AttrAst = /** @class */ (function () { function AttrAst(name, value, sourceSpan) { this.name = name; this.value = value; this.sourceSpan = sourceSpan; } AttrAst.prototype.visit = function (visitor, context) { return visitor.visitAttr(this, context); }; return AttrAst; }()); var BoundPropertyMapping = (_a = {}, _a[4 /* Animation */] = 4 /* Animation */, _a[1 /* Attribute */] = 1 /* Attribute */, _a[2 /* Class */] = 2 /* Class */, _a[0 /* Property */] = 0 /* Property */, _a[3 /* Style */] = 3 /* Style */, _a); /** * A binding for an element property (e.g. `[property]="expression"`) or an animation trigger (e.g. * `[@trigger]="stateExp"`) */ var BoundElementPropertyAst = /** @class */ (function () { function BoundElementPropertyAst(name, type, securityContext, value, unit, sourceSpan) { this.name = name; this.type = type; this.securityContext = securityContext; this.value = value; this.unit = unit; this.sourceSpan = sourceSpan; this.isAnimation = this.type === 4 /* Animation */; } BoundElementPropertyAst.fromBoundProperty = function (prop) { var type = BoundPropertyMapping[prop.type]; return new BoundElementPropertyAst(prop.name, type, prop.securityContext, prop.value, prop.unit, prop.sourceSpan); }; BoundElementPropertyAst.prototype.visit = function (visitor, context) { return visitor.visitElementProperty(this, context); }; return BoundElementPropertyAst; }()); /** * A binding for an element event (e.g. `(event)="handler()"`) or an animation trigger event (e.g. * `(@trigger.phase)="callback($event)"`). */ var BoundEventAst = /** @class */ (function () { function BoundEventAst(name, target, phase, handler, sourceSpan, handlerSpan) { this.name = name; this.target = target; this.phase = phase; this.handler = handler; this.sourceSpan = sourceSpan; this.handlerSpan = handlerSpan; this.fullName = BoundEventAst.calcFullName(this.name, this.target, this.phase); this.isAnimation = !!this.phase; } BoundEventAst.calcFullName = function (name, target, phase) { if (target) { return target + ":" + name; } if (phase) { return "@" + name + "." + phase; } return name; }; BoundEventAst.fromParsedEvent = function (event) { var target = event.type === 0 /* Regular */ ? event.targetOrPhase : null; var phase = event.type === 1 /* Animation */ ? event.targetOrPhase : null; return new BoundEventAst(event.name, target, phase, event.handler, event.sourceSpan, event.handlerSpan); }; BoundEventAst.prototype.visit = function (visitor, context) { return visitor.visitEvent(this, context); }; return BoundEventAst; }()); /** * A reference declaration on an element (e.g. `let someName="expression"`). */ var ReferenceAst = /** @class */ (function () { function ReferenceAst(name, value, originalValue, sourceSpan) { this.name = name; this.value = value; this.originalValue = originalValue; this.sourceSpan = sourceSpan; } ReferenceAst.prototype.visit = function (visitor, context) { return visitor.visitReference(this, context); }; return ReferenceAst; }()); /** * A variable declaration on a (e.g. `var-someName="someLocalName"`). */ var VariableAst = /** @class */ (function () { function VariableAst(name, value, sourceSpan) { this.name = name; this.value = value; this.sourceSpan = sourceSpan; } VariableAst.fromParsedVariable = function (v) { return new VariableAst(v.name, v.value, v.sourceSpan); }; VariableAst.prototype.visit = function (visitor, context) { return visitor.visitVariable(this, context); }; return VariableAst; }()); /** * An element declaration in a template. */ var ElementAst = /** @class */ (function () { function ElementAst(name, attrs, inputs, outputs, references, directives, providers, hasViewContainer, queryMatches, children, ngContentIndex, sourceSpan, endSourceSpan) { this.name = name; this.attrs = attrs; this.inputs = inputs; this.outputs = outputs; this.references = references; this.directives = directives; this.providers = providers; this.hasViewContainer = hasViewContainer; this.queryMatches = queryMatches; this.children = children; this.ngContentIndex = ngContentIndex; this.sourceSpan = sourceSpan; this.endSourceSpan = endSourceSpan; } ElementAst.prototype.visit = function (visitor, context) { return visitor.visitElement(this, context); }; return ElementAst; }()); /** * A `` element included in an Angular template. */ var EmbeddedTemplateAst = /** @class */ (function () { function EmbeddedTemplateAst(attrs, outputs, references, variables, directives, providers, hasViewContainer, queryMatches, children, ngContentIndex, sourceSpan) { this.attrs = attrs; this.outputs = outputs; this.references = references; this.variables = variables; this.directives = directives; this.providers = providers; this.hasViewContainer = hasViewContainer; this.queryMatches = queryMatches; this.children = children; this.ngContentIndex = ngContentIndex; this.sourceSpan = sourceSpan; } EmbeddedTemplateAst.prototype.visit = function (visitor, context) { return visitor.visitEmbeddedTemplate(this, context); }; return EmbeddedTemplateAst; }()); /** * A directive property with a bound value (e.g. `*ngIf="condition"). */ var BoundDirectivePropertyAst = /** @class */ (function () { function BoundDirectivePropertyAst(directiveName, templateName, value, sourceSpan) { this.directiveName = directiveName; this.templateName = templateName; this.value = value; this.sourceSpan = sourceSpan; } BoundDirectivePropertyAst.prototype.visit = function (visitor, context) { return visitor.visitDirectiveProperty(this, context); }; return BoundDirectivePropertyAst; }()); /** * A directive declared on an element. */ var DirectiveAst = /** @class */ (function () { function DirectiveAst(directive, inputs, hostProperties, hostEvents, contentQueryStartId, sourceSpan) { this.directive = directive; this.inputs = inputs; this.hostProperties = hostProperties; this.hostEvents = hostEvents; this.contentQueryStartId = contentQueryStartId; this.sourceSpan = sourceSpan; } DirectiveAst.prototype.visit = function (visitor, context) { return visitor.visitDirective(this, context); }; return DirectiveAst; }()); /** * A provider declared on an element */ var ProviderAst = /** @class */ (function () { function ProviderAst(token, multiProvider, eager, providers, providerType, lifecycleHooks, sourceSpan, isModule) { this.token = token; this.multiProvider = multiProvider; this.eager = eager; this.providers = providers; this.providerType = providerType; this.lifecycleHooks = lifecycleHooks; this.sourceSpan = sourceSpan; this.isModule = isModule; } ProviderAst.prototype.visit = function (visitor, context) { // No visit method in the visitor for now... return null; }; return ProviderAst; }()); var ProviderAstType; (function (ProviderAstType) { ProviderAstType[ProviderAstType["PublicService"] = 0] = "PublicService"; ProviderAstType[ProviderAstType["PrivateService"] = 1] = "PrivateService"; ProviderAstType[ProviderAstType["Component"] = 2] = "Component"; ProviderAstType[ProviderAstType["Directive"] = 3] = "Directive"; ProviderAstType[ProviderAstType["Builtin"] = 4] = "Builtin"; })(ProviderAstType || (ProviderAstType = {})); /** * Position where content is to be projected (instance of `` in a template). */ var NgContentAst = /** @class */ (function () { function NgContentAst(index, ngContentIndex, sourceSpan) { this.index = index; this.ngContentIndex = ngContentIndex; this.sourceSpan = sourceSpan; } NgContentAst.prototype.visit = function (visitor, context) { return visitor.visitNgContent(this, context); }; return NgContentAst; }()); /** * A visitor that accepts each node but doesn't do anything. It is intended to be used * as the base class for a visitor that is only interested in a subset of the node types. */ var NullTemplateVisitor = /** @class */ (function () { function NullTemplateVisitor() { } NullTemplateVisitor.prototype.visitNgContent = function (ast, context) { }; NullTemplateVisitor.prototype.visitEmbeddedTemplate = function (ast, context) { }; NullTemplateVisitor.prototype.visitElement = function (ast, context) { }; NullTemplateVisitor.prototype.visitReference = function (ast, context) { }; NullTemplateVisitor.prototype.visitVariable = function (ast, context) { }; NullTemplateVisitor.prototype.visitEvent = function (ast, context) { }; NullTemplateVisitor.prototype.visitElementProperty = function (ast, context) { }; NullTemplateVisitor.prototype.visitAttr = function (ast, context) { }; NullTemplateVisitor.prototype.visitBoundText = function (ast, context) { }; NullTemplateVisitor.prototype.visitText = function (ast, context) { }; NullTemplateVisitor.prototype.visitDirective = function (ast, context) { }; NullTemplateVisitor.prototype.visitDirectiveProperty = function (ast, context) { }; return NullTemplateVisitor; }()); /** * Base class that can be used to build a visitor that visits each node * in an template ast recursively. */ var RecursiveTemplateAstVisitor = /** @class */ (function (_super) { __extends(RecursiveTemplateAstVisitor, _super); function RecursiveTemplateAstVisitor() { return _super.call(this) || this; } // Nodes with children RecursiveTemplateAstVisitor.prototype.visitEmbeddedTemplate = function (ast, context) { return this.visitChildren(context, function (visit) { visit(ast.attrs); visit(ast.references); visit(ast.variables); visit(ast.directives); visit(ast.providers); visit(ast.children); }); }; RecursiveTemplateAstVisitor.prototype.visitElement = function (ast, context) { return this.visitChildren(context, function (visit) { visit(ast.attrs); visit(ast.inputs); visit(ast.outputs); visit(ast.references); visit(ast.directives); visit(ast.providers); visit(ast.children); }); }; RecursiveTemplateAstVisitor.prototype.visitDirective = function (ast, context) { return this.visitChildren(context, function (visit) { visit(ast.inputs); visit(ast.hostProperties); visit(ast.hostEvents); }); }; RecursiveTemplateAstVisitor.prototype.visitChildren = function (context, cb) { var results = []; var t = this; function visit(children) { if (children && children.length) results.push(templateVisitAll(t, children, context)); } cb(visit); return Array.prototype.concat.apply([], results); }; return RecursiveTemplateAstVisitor; }(NullTemplateVisitor)); /** * Visit every node in a list of {@link TemplateAst}s with the given {@link TemplateAstVisitor}. */ function templateVisitAll(visitor, asts, context) { if (context === void 0) { context = null; } var result = []; var visit = visitor.visit ? function (ast) { return visitor.visit(ast, context) || ast.visit(visitor, context); } : function (ast) { return ast.visit(visitor, context); }; asts.forEach(function (ast) { var astResult = visit(ast); if (astResult) { result.push(astResult); } }); return result; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var ProviderError = /** @class */ (function (_super) { __extends(ProviderError, _super); function ProviderError(message, span) { return _super.call(this, span, message) || this; } return ProviderError; }(ParseError)); var ProviderViewContext = /** @class */ (function () { function ProviderViewContext(reflector, component) { var _this = this; this.reflector = reflector; this.component = component; this.errors = []; this.viewQueries = _getViewQueries(component); this.viewProviders = new Map(); component.viewProviders.forEach(function (provider) { if (_this.viewProviders.get(tokenReference(provider.token)) == null) { _this.viewProviders.set(tokenReference(provider.token), true); } }); } return ProviderViewContext; }()); var ProviderElementContext = /** @class */ (function () { function ProviderElementContext(viewContext, _parent, _isViewRoot, _directiveAsts, attrs, refs, isTemplate, contentQueryStartId, _sourceSpan) { var _this = this; this.viewContext = viewContext; this._parent = _parent; this._isViewRoot = _isViewRoot; this._directiveAsts = _directiveAsts; this._sourceSpan = _sourceSpan; this._transformedProviders = new Map(); this._seenProviders = new Map(); this._queriedTokens = new Map(); this.transformedHasViewContainer = false; this._attrs = {}; attrs.forEach(function (attrAst) { return _this._attrs[attrAst.name] = attrAst.value; }); var directivesMeta = _directiveAsts.map(function (directiveAst) { return directiveAst.directive; }); this._allProviders = _resolveProvidersFromDirectives(directivesMeta, _sourceSpan, viewContext.errors); this._contentQueries = _getContentQueries(contentQueryStartId, directivesMeta); Array.from(this._allProviders.values()).forEach(function (provider) { _this._addQueryReadsTo(provider.token, provider.token, _this._queriedTokens); }); if (isTemplate) { var templateRefId = createTokenForExternalReference(this.viewContext.reflector, Identifiers.TemplateRef); this._addQueryReadsTo(templateRefId, templateRefId, this._queriedTokens); } refs.forEach(function (refAst) { var defaultQueryValue = refAst.value || createTokenForExternalReference(_this.viewContext.reflector, Identifiers.ElementRef); _this._addQueryReadsTo({ value: refAst.name }, defaultQueryValue, _this._queriedTokens); }); if (this._queriedTokens.get(this.viewContext.reflector.resolveExternalReference(Identifiers.ViewContainerRef))) { this.transformedHasViewContainer = true; } // create the providers that we know are eager first Array.from(this._allProviders.values()).forEach(function (provider) { var eager = provider.eager || _this._queriedTokens.get(tokenReference(provider.token)); if (eager) { _this._getOrCreateLocalProvider(provider.providerType, provider.token, true); } }); } ProviderElementContext.prototype.afterElement = function () { var _this = this; // collect lazy providers Array.from(this._allProviders.values()).forEach(function (provider) { _this._getOrCreateLocalProvider(provider.providerType, provider.token, false); }); }; Object.defineProperty(ProviderElementContext.prototype, "transformProviders", { get: function () { // Note: Maps keep their insertion order. var lazyProviders = []; var eagerProviders = []; this._transformedProviders.forEach(function (provider) { if (provider.eager) { eagerProviders.push(provider); } else { lazyProviders.push(provider); } }); return lazyProviders.concat(eagerProviders); }, enumerable: true, configurable: true }); Object.defineProperty(ProviderElementContext.prototype, "transformedDirectiveAsts", { get: function () { var sortedProviderTypes = this.transformProviders.map(function (provider) { return provider.token.identifier; }); var sortedDirectives = this._directiveAsts.slice(); sortedDirectives.sort(function (dir1, dir2) { return sortedProviderTypes.indexOf(dir1.directive.type) - sortedProviderTypes.indexOf(dir2.directive.type); }); return sortedDirectives; }, enumerable: true, configurable: true }); Object.defineProperty(ProviderElementContext.prototype, "queryMatches", { get: function () { var allMatches = []; this._queriedTokens.forEach(function (matches) { allMatches.push.apply(allMatches, __spread(matches)); }); return allMatches; }, enumerable: true, configurable: true }); ProviderElementContext.prototype._addQueryReadsTo = function (token, defaultValue, queryReadTokens) { this._getQueriesFor(token).forEach(function (query) { var queryValue = query.meta.read || defaultValue; var tokenRef = tokenReference(queryValue); var queryMatches = queryReadTokens.get(tokenRef); if (!queryMatches) { queryMatches = []; queryReadTokens.set(tokenRef, queryMatches); } queryMatches.push({ queryId: query.queryId, value: queryValue }); }); }; ProviderElementContext.prototype._getQueriesFor = function (token) { var result = []; var currentEl = this; var distance = 0; var queries; while (currentEl !== null) { queries = currentEl._contentQueries.get(tokenReference(token)); if (queries) { result.push.apply(result, __spread(queries.filter(function (query) { return query.meta.descendants || distance <= 1; }))); } if (currentEl._directiveAsts.length > 0) { distance++; } currentEl = currentEl._parent; } queries = this.viewContext.viewQueries.get(tokenReference(token)); if (queries) { result.push.apply(result, __spread(queries)); } return result; }; ProviderElementContext.prototype._getOrCreateLocalProvider = function (requestingProviderType, token, eager) { var _this = this; var resolvedProvider = this._allProviders.get(tokenReference(token)); if (!resolvedProvider || ((requestingProviderType === ProviderAstType.Directive || requestingProviderType === ProviderAstType.PublicService) && resolvedProvider.providerType === ProviderAstType.PrivateService) || ((requestingProviderType === ProviderAstType.PrivateService || requestingProviderType === ProviderAstType.PublicService) && resolvedProvider.providerType === ProviderAstType.Builtin)) { return null; } var transformedProviderAst = this._transformedProviders.get(tokenReference(token)); if (transformedProviderAst) { return transformedProviderAst; } if (this._seenProviders.get(tokenReference(token)) != null) { this.viewContext.errors.push(new ProviderError("Cannot instantiate cyclic dependency! " + tokenName(token), this._sourceSpan)); return null; } this._seenProviders.set(tokenReference(token), true); var transformedProviders = resolvedProvider.providers.map(function (provider) { var transformedUseValue = provider.useValue; var transformedUseExisting = provider.useExisting; var transformedDeps = undefined; if (provider.useExisting != null) { var existingDiDep = _this._getDependency(resolvedProvider.providerType, { token: provider.useExisting }, eager); if (existingDiDep.token != null) { transformedUseExisting = existingDiDep.token; } else { transformedUseExisting = null; transformedUseValue = existingDiDep.value; } } else if (provider.useFactory) { var deps = provider.deps || provider.useFactory.diDeps; transformedDeps = deps.map(function (dep) { return _this._getDependency(resolvedProvider.providerType, dep, eager); }); } else if (provider.useClass) { var deps = provider.deps || provider.useClass.diDeps; transformedDeps = deps.map(function (dep) { return _this._getDependency(resolvedProvider.providerType, dep, eager); }); } return _transformProvider(provider, { useExisting: transformedUseExisting, useValue: transformedUseValue, deps: transformedDeps }); }); transformedProviderAst = _transformProviderAst(resolvedProvider, { eager: eager, providers: transformedProviders }); this._transformedProviders.set(tokenReference(token), transformedProviderAst); return transformedProviderAst; }; ProviderElementContext.prototype._getLocalDependency = function (requestingProviderType, dep, eager) { if (eager === void 0) { eager = false; } if (dep.isAttribute) { var attrValue = this._attrs[dep.token.value]; return { isValue: true, value: attrValue == null ? null : attrValue }; } if (dep.token != null) { // access builtints if ((requestingProviderType === ProviderAstType.Directive || requestingProviderType === ProviderAstType.Component)) { if (tokenReference(dep.token) === this.viewContext.reflector.resolveExternalReference(Identifiers.Renderer) || tokenReference(dep.token) === this.viewContext.reflector.resolveExternalReference(Identifiers.ElementRef) || tokenReference(dep.token) === this.viewContext.reflector.resolveExternalReference(Identifiers.ChangeDetectorRef) || tokenReference(dep.token) === this.viewContext.reflector.resolveExternalReference(Identifiers.TemplateRef)) { return dep; } if (tokenReference(dep.token) === this.viewContext.reflector.resolveExternalReference(Identifiers.ViewContainerRef)) { this.transformedHasViewContainer = true; } } // access the injector if (tokenReference(dep.token) === this.viewContext.reflector.resolveExternalReference(Identifiers.Injector)) { return dep; } // access providers if (this._getOrCreateLocalProvider(requestingProviderType, dep.token, eager) != null) { return dep; } } return null; }; ProviderElementContext.prototype._getDependency = function (requestingProviderType, dep, eager) { if (eager === void 0) { eager = false; } var currElement = this; var currEager = eager; var result = null; if (!dep.isSkipSelf) { result = this._getLocalDependency(requestingProviderType, dep, eager); } if (dep.isSelf) { if (!result && dep.isOptional) { result = { isValue: true, value: null }; } } else { // check parent elements while (!result && currElement._parent) { var prevElement = currElement; currElement = currElement._parent; if (prevElement._isViewRoot) { currEager = false; } result = currElement._getLocalDependency(ProviderAstType.PublicService, dep, currEager); } // check @Host restriction if (!result) { if (!dep.isHost || this.viewContext.component.isHost || this.viewContext.component.type.reference === tokenReference(dep.token) || this.viewContext.viewProviders.get(tokenReference(dep.token)) != null) { result = dep; } else { result = dep.isOptional ? { isValue: true, value: null } : null; } } } if (!result) { this.viewContext.errors.push(new ProviderError("No provider for " + tokenName(dep.token), this._sourceSpan)); } return result; }; return ProviderElementContext; }()); var NgModuleProviderAnalyzer = /** @class */ (function () { function NgModuleProviderAnalyzer(reflector, ngModule, extraProviders, sourceSpan) { var _this = this; this.reflector = reflector; this._transformedProviders = new Map(); this._seenProviders = new Map(); this._errors = []; this._allProviders = new Map(); ngModule.transitiveModule.modules.forEach(function (ngModuleType) { var ngModuleProvider = { token: { identifier: ngModuleType }, useClass: ngModuleType }; _resolveProviders([ngModuleProvider], ProviderAstType.PublicService, true, sourceSpan, _this._errors, _this._allProviders, /* isModule */ true); }); _resolveProviders(ngModule.transitiveModule.providers.map(function (entry) { return entry.provider; }).concat(extraProviders), ProviderAstType.PublicService, false, sourceSpan, this._errors, this._allProviders, /* isModule */ false); } NgModuleProviderAnalyzer.prototype.parse = function () { var _this = this; Array.from(this._allProviders.values()).forEach(function (provider) { _this._getOrCreateLocalProvider(provider.token, provider.eager); }); if (this._errors.length > 0) { var errorString = this._errors.join('\n'); throw new Error("Provider parse errors:\n" + errorString); } // Note: Maps keep their insertion order. var lazyProviders = []; var eagerProviders = []; this._transformedProviders.forEach(function (provider) { if (provider.eager) { eagerProviders.push(provider); } else { lazyProviders.push(provider); } }); return lazyProviders.concat(eagerProviders); }; NgModuleProviderAnalyzer.prototype._getOrCreateLocalProvider = function (token, eager) { var _this = this; var resolvedProvider = this._allProviders.get(tokenReference(token)); if (!resolvedProvider) { return null; } var transformedProviderAst = this._transformedProviders.get(tokenReference(token)); if (transformedProviderAst) { return transformedProviderAst; } if (this._seenProviders.get(tokenReference(token)) != null) { this._errors.push(new ProviderError("Cannot instantiate cyclic dependency! " + tokenName(token), resolvedProvider.sourceSpan)); return null; } this._seenProviders.set(tokenReference(token), true); var transformedProviders = resolvedProvider.providers.map(function (provider) { var transformedUseValue = provider.useValue; var transformedUseExisting = provider.useExisting; var transformedDeps = undefined; if (provider.useExisting != null) { var existingDiDep = _this._getDependency({ token: provider.useExisting }, eager, resolvedProvider.sourceSpan); if (existingDiDep.token != null) { transformedUseExisting = existingDiDep.token; } else { transformedUseExisting = null; transformedUseValue = existingDiDep.value; } } else if (provider.useFactory) { var deps = provider.deps || provider.useFactory.diDeps; transformedDeps = deps.map(function (dep) { return _this._getDependency(dep, eager, resolvedProvider.sourceSpan); }); } else if (provider.useClass) { var deps = provider.deps || provider.useClass.diDeps; transformedDeps = deps.map(function (dep) { return _this._getDependency(dep, eager, resolvedProvider.sourceSpan); }); } return _transformProvider(provider, { useExisting: transformedUseExisting, useValue: transformedUseValue, deps: transformedDeps }); }); transformedProviderAst = _transformProviderAst(resolvedProvider, { eager: eager, providers: transformedProviders }); this._transformedProviders.set(tokenReference(token), transformedProviderAst); return transformedProviderAst; }; NgModuleProviderAnalyzer.prototype._getDependency = function (dep, eager, requestorSourceSpan) { if (eager === void 0) { eager = false; } var foundLocal = false; if (!dep.isSkipSelf && dep.token != null) { // access the injector if (tokenReference(dep.token) === this.reflector.resolveExternalReference(Identifiers.Injector) || tokenReference(dep.token) === this.reflector.resolveExternalReference(Identifiers.ComponentFactoryResolver)) { foundLocal = true; // access providers } else if (this._getOrCreateLocalProvider(dep.token, eager) != null) { foundLocal = true; } } return dep; }; return NgModuleProviderAnalyzer; }()); function _transformProvider(provider, _a) { var useExisting = _a.useExisting, useValue = _a.useValue, deps = _a.deps; return { token: provider.token, useClass: provider.useClass, useExisting: useExisting, useFactory: provider.useFactory, useValue: useValue, deps: deps, multi: provider.multi }; } function _transformProviderAst(provider, _a) { var eager = _a.eager, providers = _a.providers; return new ProviderAst(provider.token, provider.multiProvider, provider.eager || eager, providers, provider.providerType, provider.lifecycleHooks, provider.sourceSpan, provider.isModule); } function _resolveProvidersFromDirectives(directives, sourceSpan, targetErrors) { var providersByToken = new Map(); directives.forEach(function (directive) { var dirProvider = { token: { identifier: directive.type }, useClass: directive.type }; _resolveProviders([dirProvider], directive.isComponent ? ProviderAstType.Component : ProviderAstType.Directive, true, sourceSpan, targetErrors, providersByToken, /* isModule */ false); }); // Note: directives need to be able to overwrite providers of a component! var directivesWithComponentFirst = directives.filter(function (dir) { return dir.isComponent; }).concat(directives.filter(function (dir) { return !dir.isComponent; })); directivesWithComponentFirst.forEach(function (directive) { _resolveProviders(directive.providers, ProviderAstType.PublicService, false, sourceSpan, targetErrors, providersByToken, /* isModule */ false); _resolveProviders(directive.viewProviders, ProviderAstType.PrivateService, false, sourceSpan, targetErrors, providersByToken, /* isModule */ false); }); return providersByToken; } function _resolveProviders(providers, providerType, eager, sourceSpan, targetErrors, targetProvidersByToken, isModule) { providers.forEach(function (provider) { var resolvedProvider = targetProvidersByToken.get(tokenReference(provider.token)); if (resolvedProvider != null && !!resolvedProvider.multiProvider !== !!provider.multi) { targetErrors.push(new ProviderError("Mixing multi and non multi provider is not possible for token " + tokenName(resolvedProvider.token), sourceSpan)); } if (!resolvedProvider) { var lifecycleHooks = provider.token.identifier && provider.token.identifier.lifecycleHooks ? provider.token.identifier.lifecycleHooks : []; var isUseValue = !(provider.useClass || provider.useExisting || provider.useFactory); resolvedProvider = new ProviderAst(provider.token, !!provider.multi, eager || isUseValue, [provider], providerType, lifecycleHooks, sourceSpan, isModule); targetProvidersByToken.set(tokenReference(provider.token), resolvedProvider); } else { if (!provider.multi) { resolvedProvider.providers.length = 0; } resolvedProvider.providers.push(provider); } }); } function _getViewQueries(component) { // Note: queries start with id 1 so we can use the number in a Bloom filter! var viewQueryId = 1; var viewQueries = new Map(); if (component.viewQueries) { component.viewQueries.forEach(function (query) { return _addQueryToTokenMap(viewQueries, { meta: query, queryId: viewQueryId++ }); }); } return viewQueries; } function _getContentQueries(contentQueryStartId, directives) { var contentQueryId = contentQueryStartId; var contentQueries = new Map(); directives.forEach(function (directive, directiveIndex) { if (directive.queries) { directive.queries.forEach(function (query) { return _addQueryToTokenMap(contentQueries, { meta: query, queryId: contentQueryId++ }); }); } }); return contentQueries; } function _addQueryToTokenMap(map, query) { query.meta.selectors.forEach(function (token) { var entry = map.get(tokenReference(token)); if (!entry) { entry = []; map.set(tokenReference(token), entry); } entry.push(query); }); } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var StyleWithImports = /** @class */ (function () { function StyleWithImports(style, styleUrls) { this.style = style; this.styleUrls = styleUrls; } return StyleWithImports; }()); function isStyleUrlResolvable(url) { if (url == null || url.length === 0 || url[0] == '/') return false; var schemeMatch = url.match(URL_WITH_SCHEMA_REGEXP); return schemeMatch === null || schemeMatch[1] == 'package' || schemeMatch[1] == 'asset'; } /** * Rewrites stylesheets by resolving and removing the @import urls that * are either relative or don't have a `package:` scheme */ function extractStyleUrls(resolver, baseUrl, cssText) { var foundUrls = []; var modifiedCssText = cssText.replace(CSS_STRIPPABLE_COMMENT_REGEXP, '') .replace(CSS_IMPORT_REGEXP, function () { var m = []; for (var _i = 0; _i < arguments.length; _i++) { m[_i] = arguments[_i]; } var url = m[1] || m[2]; if (!isStyleUrlResolvable(url)) { // Do not attempt to resolve non-package absolute URLs with URI // scheme return m[0]; } foundUrls.push(resolver.resolve(baseUrl, url)); return ''; }); return new StyleWithImports(modifiedCssText, foundUrls); } var CSS_IMPORT_REGEXP = /@import\s+(?:url\()?\s*(?:(?:['"]([^'"]*))|([^;\)\s]*))[^;]*;?/g; var CSS_STRIPPABLE_COMMENT_REGEXP = /\/\*(?!#\s*(?:sourceURL|sourceMappingURL)=)[\s\S]+?\*\//g; var URL_WITH_SCHEMA_REGEXP = /^([^:/?#]+):/; /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var PROPERTY_PARTS_SEPARATOR = '.'; var ATTRIBUTE_PREFIX = 'attr'; var CLASS_PREFIX = 'class'; var STYLE_PREFIX = 'style'; var ANIMATE_PROP_PREFIX = 'animate-'; /** * Parses bindings in templates and in the directive host area. */ var BindingParser = /** @class */ (function () { function BindingParser(_exprParser, _interpolationConfig, _schemaRegistry, pipes, errors) { this._exprParser = _exprParser; this._interpolationConfig = _interpolationConfig; this._schemaRegistry = _schemaRegistry; this.errors = errors; this.pipesByName = null; this._usedPipes = new Map(); // When the `pipes` parameter is `null`, do not check for used pipes // This is used in IVY when we might not know the available pipes at compile time if (pipes) { var pipesByName_1 = new Map(); pipes.forEach(function (pipe) { return pipesByName_1.set(pipe.name, pipe); }); this.pipesByName = pipesByName_1; } } Object.defineProperty(BindingParser.prototype, "interpolationConfig", { get: function () { return this._interpolationConfig; }, enumerable: true, configurable: true }); BindingParser.prototype.getUsedPipes = function () { return Array.from(this._usedPipes.values()); }; BindingParser.prototype.createBoundHostProperties = function (dirMeta, sourceSpan) { var _this = this; if (dirMeta.hostProperties) { var boundProps_1 = []; Object.keys(dirMeta.hostProperties).forEach(function (propName) { var expression = dirMeta.hostProperties[propName]; if (typeof expression === 'string') { _this.parsePropertyBinding(propName, expression, true, sourceSpan, sourceSpan.start.offset, undefined, [], boundProps_1); } else { _this._reportError("Value of the host property binding \"" + propName + "\" needs to be a string representing an expression but got \"" + expression + "\" (" + typeof expression + ")", sourceSpan); } }); return boundProps_1; } return null; }; BindingParser.prototype.createDirectiveHostPropertyAsts = function (dirMeta, elementSelector, sourceSpan) { var _this = this; var boundProps = this.createBoundHostProperties(dirMeta, sourceSpan); return boundProps && boundProps.map(function (prop) { return _this.createBoundElementProperty(elementSelector, prop); }); }; BindingParser.prototype.createDirectiveHostEventAsts = function (dirMeta, sourceSpan) { var _this = this; if (dirMeta.hostListeners) { var targetEvents_1 = []; Object.keys(dirMeta.hostListeners).forEach(function (propName) { var expression = dirMeta.hostListeners[propName]; if (typeof expression === 'string') { // TODO: pass a more accurate handlerSpan for this event. _this.parseEvent(propName, expression, sourceSpan, sourceSpan, [], targetEvents_1); } else { _this._reportError("Value of the host listener \"" + propName + "\" needs to be a string representing an expression but got \"" + expression + "\" (" + typeof expression + ")", sourceSpan); } }); return targetEvents_1; } return null; }; BindingParser.prototype.parseInterpolation = function (value, sourceSpan) { var sourceInfo = sourceSpan.start.toString(); try { var ast = this._exprParser.parseInterpolation(value, sourceInfo, sourceSpan.start.offset, this._interpolationConfig); if (ast) this._reportExpressionParserErrors(ast.errors, sourceSpan); this._checkPipes(ast, sourceSpan); return ast; } catch (e) { this._reportError("" + e, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo, sourceSpan.start.offset); } }; /** * Parses an inline template binding, e.g. * * @param tplKey template binding name * @param tplValue template binding value * @param sourceSpan span of template binding relative to entire the template * @param absoluteValueOffset start of the tplValue relative to the entire template * @param targetMatchableAttrs potential attributes to match in the template * @param targetProps target property bindings in the template * @param targetVars target variables in the template */ BindingParser.prototype.parseInlineTemplateBinding = function (tplKey, tplValue, sourceSpan, absoluteValueOffset, targetMatchableAttrs, targetProps, targetVars) { var bindings = this._parseTemplateBindings(tplKey, tplValue, sourceSpan, absoluteValueOffset); for (var i = 0; i < bindings.length; i++) { var binding = bindings[i]; if (binding.keyIsVar) { targetVars.push(new ParsedVariable(binding.key, binding.name, sourceSpan)); } else if (binding.value) { this._parsePropertyAst(binding.key, binding.value, sourceSpan, undefined, targetMatchableAttrs, targetProps); } else { targetMatchableAttrs.push([binding.key, '']); this.parseLiteralAttr(binding.key, null, sourceSpan, absoluteValueOffset, undefined, targetMatchableAttrs, targetProps); } } }; /** * Parses the bindings in an inline template binding, e.g. * * @param tplKey template binding name * @param tplValue template binding value * @param sourceSpan span of template binding relative to entire the template * @param absoluteValueOffset start of the tplValue relative to the entire template */ BindingParser.prototype._parseTemplateBindings = function (tplKey, tplValue, sourceSpan, absoluteValueOffset) { var _this = this; var sourceInfo = sourceSpan.start.toString(); try { var bindingsResult = this._exprParser.parseTemplateBindings(tplKey, tplValue, sourceInfo, absoluteValueOffset); this._reportExpressionParserErrors(bindingsResult.errors, sourceSpan); bindingsResult.templateBindings.forEach(function (binding) { if (binding.value) { _this._checkPipes(binding.value, sourceSpan); } }); bindingsResult.warnings.forEach(function (warning) { _this._reportError(warning, sourceSpan, ParseErrorLevel.WARNING); }); return bindingsResult.templateBindings; } catch (e) { this._reportError("" + e, sourceSpan); return []; } }; BindingParser.prototype.parseLiteralAttr = function (name, value, sourceSpan, absoluteOffset, valueSpan, targetMatchableAttrs, targetProps) { if (isAnimationLabel(name)) { name = name.substring(1); if (value) { this._reportError("Assigning animation triggers via @prop=\"exp\" attributes with an expression is invalid." + " Use property bindings (e.g. [@prop]=\"exp\") or use an attribute without a value (e.g. @prop) instead.", sourceSpan, ParseErrorLevel.ERROR); } this._parseAnimation(name, value, sourceSpan, absoluteOffset, valueSpan, targetMatchableAttrs, targetProps); } else { targetProps.push(new ParsedProperty(name, this._exprParser.wrapLiteralPrimitive(value, '', absoluteOffset), ParsedPropertyType.LITERAL_ATTR, sourceSpan, valueSpan)); } }; BindingParser.prototype.parsePropertyBinding = function (name, expression, isHost, sourceSpan, absoluteOffset, valueSpan, targetMatchableAttrs, targetProps) { if (name.length === 0) { this._reportError("Property name is missing in binding", sourceSpan); } var isAnimationProp = false; if (name.startsWith(ANIMATE_PROP_PREFIX)) { isAnimationProp = true; name = name.substring(ANIMATE_PROP_PREFIX.length); } else if (isAnimationLabel(name)) { isAnimationProp = true; name = name.substring(1); } if (isAnimationProp) { this._parseAnimation(name, expression, sourceSpan, absoluteOffset, valueSpan, targetMatchableAttrs, targetProps); } else { this._parsePropertyAst(name, this._parseBinding(expression, isHost, valueSpan || sourceSpan, absoluteOffset), sourceSpan, valueSpan, targetMatchableAttrs, targetProps); } }; BindingParser.prototype.parsePropertyInterpolation = function (name, value, sourceSpan, valueSpan, targetMatchableAttrs, targetProps) { var expr = this.parseInterpolation(value, valueSpan || sourceSpan); if (expr) { this._parsePropertyAst(name, expr, sourceSpan, valueSpan, targetMatchableAttrs, targetProps); return true; } return false; }; BindingParser.prototype._parsePropertyAst = function (name, ast, sourceSpan, valueSpan, targetMatchableAttrs, targetProps) { targetMatchableAttrs.push([name, ast.source]); targetProps.push(new ParsedProperty(name, ast, ParsedPropertyType.DEFAULT, sourceSpan, valueSpan)); }; BindingParser.prototype._parseAnimation = function (name, expression, sourceSpan, absoluteOffset, valueSpan, targetMatchableAttrs, targetProps) { if (name.length === 0) { this._reportError('Animation trigger is missing', sourceSpan); } // This will occur when a @trigger is not paired with an expression. // For animations it is valid to not have an expression since */void // states will be applied by angular when the element is attached/detached var ast = this._parseBinding(expression || 'undefined', false, valueSpan || sourceSpan, absoluteOffset); targetMatchableAttrs.push([name, ast.source]); targetProps.push(new ParsedProperty(name, ast, ParsedPropertyType.ANIMATION, sourceSpan, valueSpan)); }; BindingParser.prototype._parseBinding = function (value, isHostBinding, sourceSpan, absoluteOffset) { var sourceInfo = (sourceSpan && sourceSpan.start || '(unknown)').toString(); try { var ast = isHostBinding ? this._exprParser.parseSimpleBinding(value, sourceInfo, absoluteOffset, this._interpolationConfig) : this._exprParser.parseBinding(value, sourceInfo, absoluteOffset, this._interpolationConfig); if (ast) this._reportExpressionParserErrors(ast.errors, sourceSpan); this._checkPipes(ast, sourceSpan); return ast; } catch (e) { this._reportError("" + e, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo, absoluteOffset); } }; BindingParser.prototype.createBoundElementProperty = function (elementSelector, boundProp, skipValidation, mapPropertyName) { if (skipValidation === void 0) { skipValidation = false; } if (mapPropertyName === void 0) { mapPropertyName = true; } if (boundProp.isAnimation) { return new BoundElementProperty(boundProp.name, 4 /* Animation */, SecurityContext.NONE, boundProp.expression, null, boundProp.sourceSpan, boundProp.valueSpan); } var unit = null; var bindingType = undefined; var boundPropertyName = null; var parts = boundProp.name.split(PROPERTY_PARTS_SEPARATOR); var securityContexts = undefined; // Check for special cases (prefix style, attr, class) if (parts.length > 1) { if (parts[0] == ATTRIBUTE_PREFIX) { boundPropertyName = parts.slice(1).join(PROPERTY_PARTS_SEPARATOR); if (!skipValidation) { this._validatePropertyOrAttributeName(boundPropertyName, boundProp.sourceSpan, true); } securityContexts = calcPossibleSecurityContexts(this._schemaRegistry, elementSelector, boundPropertyName, true); var nsSeparatorIdx = boundPropertyName.indexOf(':'); if (nsSeparatorIdx > -1) { var ns = boundPropertyName.substring(0, nsSeparatorIdx); var name_1 = boundPropertyName.substring(nsSeparatorIdx + 1); boundPropertyName = mergeNsAndName(ns, name_1); } bindingType = 1 /* Attribute */; } else if (parts[0] == CLASS_PREFIX) { boundPropertyName = parts[1]; bindingType = 2 /* Class */; securityContexts = [SecurityContext.NONE]; } else if (parts[0] == STYLE_PREFIX) { unit = parts.length > 2 ? parts[2] : null; boundPropertyName = parts[1]; bindingType = 3 /* Style */; securityContexts = [SecurityContext.STYLE]; } } // If not a special case, use the full property name if (boundPropertyName === null) { var mappedPropName = this._schemaRegistry.getMappedPropName(boundProp.name); boundPropertyName = mapPropertyName ? mappedPropName : boundProp.name; securityContexts = calcPossibleSecurityContexts(this._schemaRegistry, elementSelector, mappedPropName, false); bindingType = 0 /* Property */; if (!skipValidation) { this._validatePropertyOrAttributeName(mappedPropName, boundProp.sourceSpan, false); } } return new BoundElementProperty(boundPropertyName, bindingType, securityContexts[0], boundProp.expression, unit, boundProp.sourceSpan, boundProp.valueSpan); }; BindingParser.prototype.parseEvent = function (name, expression, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents) { if (name.length === 0) { this._reportError("Event name is missing in binding", sourceSpan); } if (isAnimationLabel(name)) { name = name.substr(1); this._parseAnimationEvent(name, expression, sourceSpan, handlerSpan, targetEvents); } else { this._parseRegularEvent(name, expression, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents); } }; BindingParser.prototype.calcPossibleSecurityContexts = function (selector, propName, isAttribute) { var prop = this._schemaRegistry.getMappedPropName(propName); return calcPossibleSecurityContexts(this._schemaRegistry, selector, prop, isAttribute); }; BindingParser.prototype._parseAnimationEvent = function (name, expression, sourceSpan, handlerSpan, targetEvents) { var matches = splitAtPeriod(name, [name, '']); var eventName = matches[0]; var phase = matches[1].toLowerCase(); if (phase) { switch (phase) { case 'start': case 'done': var ast = this._parseAction(expression, handlerSpan); targetEvents.push(new ParsedEvent(eventName, phase, 1 /* Animation */, ast, sourceSpan, handlerSpan)); break; default: this._reportError("The provided animation output phase value \"" + phase + "\" for \"@" + eventName + "\" is not supported (use start or done)", sourceSpan); break; } } else { this._reportError("The animation trigger output event (@" + eventName + ") is missing its phase value name (start or done are currently supported)", sourceSpan); } }; BindingParser.prototype._parseRegularEvent = function (name, expression, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents) { // long format: 'target: eventName' var _a = __read(splitAtColon(name, [null, name]), 2), target = _a[0], eventName = _a[1]; var ast = this._parseAction(expression, handlerSpan); targetMatchableAttrs.push([name, ast.source]); targetEvents.push(new ParsedEvent(eventName, target, 0 /* Regular */, ast, sourceSpan, handlerSpan)); // Don't detect directives for event names for now, // so don't add the event name to the matchableAttrs }; BindingParser.prototype._parseAction = function (value, sourceSpan) { var sourceInfo = (sourceSpan && sourceSpan.start || '(unknown').toString(); var absoluteOffset = (sourceSpan && sourceSpan.start) ? sourceSpan.start.offset : 0; try { var ast = this._exprParser.parseAction(value, sourceInfo, absoluteOffset, this._interpolationConfig); if (ast) { this._reportExpressionParserErrors(ast.errors, sourceSpan); } if (!ast || ast.ast instanceof EmptyExpr) { this._reportError("Empty expressions are not allowed", sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo, absoluteOffset); } this._checkPipes(ast, sourceSpan); return ast; } catch (e) { this._reportError("" + e, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo, absoluteOffset); } }; BindingParser.prototype._reportError = function (message, sourceSpan, level) { if (level === void 0) { level = ParseErrorLevel.ERROR; } this.errors.push(new ParseError(sourceSpan, message, level)); }; BindingParser.prototype._reportExpressionParserErrors = function (errors, sourceSpan) { var e_1, _a; try { for (var errors_1 = __values(errors), errors_1_1 = errors_1.next(); !errors_1_1.done; errors_1_1 = errors_1.next()) { var error = errors_1_1.value; this._reportError(error.message, sourceSpan); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (errors_1_1 && !errors_1_1.done && (_a = errors_1.return)) _a.call(errors_1); } finally { if (e_1) throw e_1.error; } } }; // Make sure all the used pipes are known in `this.pipesByName` BindingParser.prototype._checkPipes = function (ast, sourceSpan) { var _this = this; if (ast && this.pipesByName) { var collector = new PipeCollector(); ast.visit(collector); collector.pipes.forEach(function (ast, pipeName) { var pipeMeta = _this.pipesByName.get(pipeName); if (!pipeMeta) { _this._reportError("The pipe '" + pipeName + "' could not be found", new ParseSourceSpan(sourceSpan.start.moveBy(ast.span.start), sourceSpan.start.moveBy(ast.span.end))); } else { _this._usedPipes.set(pipeName, pipeMeta); } }); } }; /** * @param propName the name of the property / attribute * @param sourceSpan * @param isAttr true when binding to an attribute */ BindingParser.prototype._validatePropertyOrAttributeName = function (propName, sourceSpan, isAttr) { var report = isAttr ? this._schemaRegistry.validateAttribute(propName) : this._schemaRegistry.validateProperty(propName); if (report.error) { this._reportError(report.msg, sourceSpan, ParseErrorLevel.ERROR); } }; return BindingParser; }()); var PipeCollector = /** @class */ (function (_super) { __extends(PipeCollector, _super); function PipeCollector() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.pipes = new Map(); return _this; } PipeCollector.prototype.visitPipe = function (ast, context) { this.pipes.set(ast.name, ast); ast.exp.visit(this); this.visitAll(ast.args, context); return null; }; return PipeCollector; }(RecursiveAstVisitor$1)); function isAnimationLabel(name) { return name[0] == '@'; } function calcPossibleSecurityContexts(registry, selector, propName, isAttribute) { var ctxs = []; CssSelector.parse(selector).forEach(function (selector) { var elementNames = selector.element ? [selector.element] : registry.allKnownElementNames(); var notElementNames = new Set(selector.notSelectors.filter(function (selector) { return selector.isElementSelector(); }) .map(function (selector) { return selector.element; })); var possibleElementNames = elementNames.filter(function (elementName) { return !notElementNames.has(elementName); }); ctxs.push.apply(ctxs, __spread(possibleElementNames.map(function (elementName) { return registry.securityContext(elementName, propName, isAttribute); }))); }); return ctxs.length === 0 ? [SecurityContext.NONE] : Array.from(new Set(ctxs)).sort(); } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var NG_CONTENT_SELECT_ATTR = 'select'; var LINK_ELEMENT = 'link'; var LINK_STYLE_REL_ATTR = 'rel'; var LINK_STYLE_HREF_ATTR = 'href'; var LINK_STYLE_REL_VALUE = 'stylesheet'; var STYLE_ELEMENT = 'style'; var SCRIPT_ELEMENT = 'script'; var NG_NON_BINDABLE_ATTR = 'ngNonBindable'; var NG_PROJECT_AS = 'ngProjectAs'; function preparseElement(ast) { var selectAttr = null; var hrefAttr = null; var relAttr = null; var nonBindable = false; var projectAs = ''; ast.attrs.forEach(function (attr) { var lcAttrName = attr.name.toLowerCase(); if (lcAttrName == NG_CONTENT_SELECT_ATTR) { selectAttr = attr.value; } else if (lcAttrName == LINK_STYLE_HREF_ATTR) { hrefAttr = attr.value; } else if (lcAttrName == LINK_STYLE_REL_ATTR) { relAttr = attr.value; } else if (attr.name == NG_NON_BINDABLE_ATTR) { nonBindable = true; } else if (attr.name == NG_PROJECT_AS) { if (attr.value.length > 0) { projectAs = attr.value; } } }); selectAttr = normalizeNgContentSelect(selectAttr); var nodeName = ast.name.toLowerCase(); var type = PreparsedElementType.OTHER; if (isNgContent(nodeName)) { type = PreparsedElementType.NG_CONTENT; } else if (nodeName == STYLE_ELEMENT) { type = PreparsedElementType.STYLE; } else if (nodeName == SCRIPT_ELEMENT) { type = PreparsedElementType.SCRIPT; } else if (nodeName == LINK_ELEMENT && relAttr == LINK_STYLE_REL_VALUE) { type = PreparsedElementType.STYLESHEET; } return new PreparsedElement(type, selectAttr, hrefAttr, nonBindable, projectAs); } var PreparsedElementType; (function (PreparsedElementType) { PreparsedElementType[PreparsedElementType["NG_CONTENT"] = 0] = "NG_CONTENT"; PreparsedElementType[PreparsedElementType["STYLE"] = 1] = "STYLE"; PreparsedElementType[PreparsedElementType["STYLESHEET"] = 2] = "STYLESHEET"; PreparsedElementType[PreparsedElementType["SCRIPT"] = 3] = "SCRIPT"; PreparsedElementType[PreparsedElementType["OTHER"] = 4] = "OTHER"; })(PreparsedElementType || (PreparsedElementType = {})); var PreparsedElement = /** @class */ (function () { function PreparsedElement(type, selectAttr, hrefAttr, nonBindable, projectAs) { this.type = type; this.selectAttr = selectAttr; this.hrefAttr = hrefAttr; this.nonBindable = nonBindable; this.projectAs = projectAs; } return PreparsedElement; }()); function normalizeNgContentSelect(selectAttr) { if (selectAttr === null || selectAttr.length === 0) { return '*'; } return selectAttr; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var BIND_NAME_REGEXP = /^(?:(?:(?:(bind-)|(let-)|(ref-|#)|(on-)|(bindon-)|(@))(.*))|\[\(([^\)]+)\)\]|\[([^\]]+)\]|\(([^\)]+)\))$/; // Group 1 = "bind-" var KW_BIND_IDX = 1; // Group 2 = "let-" var KW_LET_IDX = 2; // Group 3 = "ref-/#" var KW_REF_IDX = 3; // Group 4 = "on-" var KW_ON_IDX = 4; // Group 5 = "bindon-" var KW_BINDON_IDX = 5; // Group 6 = "@" var KW_AT_IDX = 6; // Group 7 = the identifier after "bind-", "let-", "ref-/#", "on-", "bindon-" or "@" var IDENT_KW_IDX = 7; // Group 8 = identifier inside [()] var IDENT_BANANA_BOX_IDX = 8; // Group 9 = identifier inside [] var IDENT_PROPERTY_IDX = 9; // Group 10 = identifier inside () var IDENT_EVENT_IDX = 10; var TEMPLATE_ATTR_PREFIX = '*'; var CLASS_ATTR = 'class'; var _TEXT_CSS_SELECTOR; function TEXT_CSS_SELECTOR() { if (!_TEXT_CSS_SELECTOR) { _TEXT_CSS_SELECTOR = CssSelector.parse('*')[0]; } return _TEXT_CSS_SELECTOR; } var TemplateParseError = /** @class */ (function (_super) { __extends(TemplateParseError, _super); function TemplateParseError(message, span, level) { return _super.call(this, span, message, level) || this; } return TemplateParseError; }(ParseError)); var TemplateParseResult = /** @class */ (function () { function TemplateParseResult(templateAst, usedPipes, errors) { this.templateAst = templateAst; this.usedPipes = usedPipes; this.errors = errors; } return TemplateParseResult; }()); var TemplateParser = /** @class */ (function () { function TemplateParser(_config, _reflector, _exprParser, _schemaRegistry, _htmlParser, _console, transforms) { this._config = _config; this._reflector = _reflector; this._exprParser = _exprParser; this._schemaRegistry = _schemaRegistry; this._htmlParser = _htmlParser; this._console = _console; this.transforms = transforms; } Object.defineProperty(TemplateParser.prototype, "expressionParser", { get: function () { return this._exprParser; }, enumerable: true, configurable: true }); TemplateParser.prototype.parse = function (component, template, directives, pipes, schemas, templateUrl, preserveWhitespaces) { var result = this.tryParse(component, template, directives, pipes, schemas, templateUrl, preserveWhitespaces); var warnings = result.errors.filter(function (error) { return error.level === ParseErrorLevel.WARNING; }); var errors = result.errors.filter(function (error) { return error.level === ParseErrorLevel.ERROR; }); if (warnings.length > 0) { this._console.warn("Template parse warnings:\n" + warnings.join('\n')); } if (errors.length > 0) { var errorString = errors.join('\n'); throw syntaxError("Template parse errors:\n" + errorString, errors); } return { template: result.templateAst, pipes: result.usedPipes }; }; TemplateParser.prototype.tryParse = function (component, template, directives, pipes, schemas, templateUrl, preserveWhitespaces) { var htmlParseResult = typeof template === 'string' ? this._htmlParser.parse(template, templateUrl, { tokenizeExpansionForms: true, interpolationConfig: this.getInterpolationConfig(component) }) : template; if (!preserveWhitespaces) { htmlParseResult = removeWhitespaces(htmlParseResult); } return this.tryParseHtml(this.expandHtml(htmlParseResult), component, directives, pipes, schemas); }; TemplateParser.prototype.tryParseHtml = function (htmlAstWithErrors, component, directives, pipes, schemas) { var result; var errors = htmlAstWithErrors.errors; var usedPipes = []; if (htmlAstWithErrors.rootNodes.length > 0) { var uniqDirectives = removeSummaryDuplicates(directives); var uniqPipes = removeSummaryDuplicates(pipes); var providerViewContext = new ProviderViewContext(this._reflector, component); var interpolationConfig = undefined; if (component.template && component.template.interpolation) { interpolationConfig = { start: component.template.interpolation[0], end: component.template.interpolation[1] }; } var bindingParser = new BindingParser(this._exprParser, interpolationConfig, this._schemaRegistry, uniqPipes, errors); var parseVisitor = new TemplateParseVisitor(this._reflector, this._config, providerViewContext, uniqDirectives, bindingParser, this._schemaRegistry, schemas, errors); result = visitAll$1(parseVisitor, htmlAstWithErrors.rootNodes, EMPTY_ELEMENT_CONTEXT); errors.push.apply(errors, __spread(providerViewContext.errors)); usedPipes.push.apply(usedPipes, __spread(bindingParser.getUsedPipes())); } else { result = []; } this._assertNoReferenceDuplicationOnTemplate(result, errors); if (errors.length > 0) { return new TemplateParseResult(result, usedPipes, errors); } if (this.transforms) { this.transforms.forEach(function (transform) { result = templateVisitAll(transform, result); }); } return new TemplateParseResult(result, usedPipes, errors); }; TemplateParser.prototype.expandHtml = function (htmlAstWithErrors, forced) { if (forced === void 0) { forced = false; } var errors = htmlAstWithErrors.errors; if (errors.length == 0 || forced) { // Transform ICU messages to angular directives var expandedHtmlAst = expandNodes(htmlAstWithErrors.rootNodes); errors.push.apply(errors, __spread(expandedHtmlAst.errors)); htmlAstWithErrors = new ParseTreeResult(expandedHtmlAst.nodes, errors); } return htmlAstWithErrors; }; TemplateParser.prototype.getInterpolationConfig = function (component) { if (component.template) { return InterpolationConfig.fromArray(component.template.interpolation); } return undefined; }; /** @internal */ TemplateParser.prototype._assertNoReferenceDuplicationOnTemplate = function (result, errors) { var existingReferences = []; result.filter(function (element) { return !!element.references; }) .forEach(function (element) { return element.references.forEach(function (reference) { var name = reference.name; if (existingReferences.indexOf(name) < 0) { existingReferences.push(name); } else { var error = new TemplateParseError("Reference \"#" + name + "\" is defined several times", reference.sourceSpan, ParseErrorLevel.ERROR); errors.push(error); } }); }); }; return TemplateParser; }()); var TemplateParseVisitor = /** @class */ (function () { function TemplateParseVisitor(reflector, config, providerViewContext, directives, _bindingParser, _schemaRegistry, _schemas, _targetErrors) { var _this = this; this.reflector = reflector; this.config = config; this.providerViewContext = providerViewContext; this._bindingParser = _bindingParser; this._schemaRegistry = _schemaRegistry; this._schemas = _schemas; this._targetErrors = _targetErrors; this.selectorMatcher = new SelectorMatcher(); this.directivesIndex = new Map(); this.ngContentCount = 0; // Note: queries start with id 1 so we can use the number in a Bloom filter! this.contentQueryStartId = providerViewContext.component.viewQueries.length + 1; directives.forEach(function (directive, index) { var selector = CssSelector.parse(directive.selector); _this.selectorMatcher.addSelectables(selector, directive); _this.directivesIndex.set(directive, index); }); } TemplateParseVisitor.prototype.visitExpansion = function (expansion, context) { return null; }; TemplateParseVisitor.prototype.visitExpansionCase = function (expansionCase, context) { return null; }; TemplateParseVisitor.prototype.visitText = function (text, parent) { var ngContentIndex = parent.findNgContentIndex(TEXT_CSS_SELECTOR()); var valueNoNgsp = replaceNgsp(text.value); var expr = this._bindingParser.parseInterpolation(valueNoNgsp, text.sourceSpan); return expr ? new BoundTextAst(expr, ngContentIndex, text.sourceSpan) : new TextAst(valueNoNgsp, ngContentIndex, text.sourceSpan); }; TemplateParseVisitor.prototype.visitAttribute = function (attribute, context) { return new AttrAst(attribute.name, attribute.value, attribute.sourceSpan); }; TemplateParseVisitor.prototype.visitComment = function (comment, context) { return null; }; TemplateParseVisitor.prototype.visitElement = function (element, parent) { var _this = this; var queryStartIndex = this.contentQueryStartId; var elName = element.name; var preparsedElement = preparseElement(element); if (preparsedElement.type === PreparsedElementType.SCRIPT || preparsedElement.type === PreparsedElementType.STYLE) { // Skipping