package.schematics.ng-generate.standalone-migration.bundle.js Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of core Show documentation
Show all versions of core Show documentation
Angular - the core framework
var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
var __async = (__this, __arguments, generator) => {
return new Promise((resolve5, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve5(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// node_modules/semver/internal/constants.js
var require_constants = __commonJS({
"node_modules/semver/internal/constants.js"(exports, module2) {
var SEMVER_SPEC_VERSION = "2.0.0";
var MAX_LENGTH = 256;
var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
var MAX_SAFE_COMPONENT_LENGTH = 16;
var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6;
var RELEASE_TYPES = [
"major",
"premajor",
"minor",
"preminor",
"patch",
"prepatch",
"prerelease"
];
module2.exports = {
MAX_LENGTH,
MAX_SAFE_COMPONENT_LENGTH,
MAX_SAFE_BUILD_LENGTH,
MAX_SAFE_INTEGER,
RELEASE_TYPES,
SEMVER_SPEC_VERSION,
FLAG_INCLUDE_PRERELEASE: 1,
FLAG_LOOSE: 2
};
}
});
// node_modules/semver/internal/debug.js
var require_debug = __commonJS({
"node_modules/semver/internal/debug.js"(exports, module2) {
var debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => {
};
module2.exports = debug;
}
});
// node_modules/semver/internal/re.js
var require_re = __commonJS({
"node_modules/semver/internal/re.js"(exports, module2) {
var {
MAX_SAFE_COMPONENT_LENGTH,
MAX_SAFE_BUILD_LENGTH,
MAX_LENGTH
} = require_constants();
var debug = require_debug();
exports = module2.exports = {};
var re = exports.re = [];
var safeRe = exports.safeRe = [];
var src = exports.src = [];
var t = exports.t = {};
var R = 0;
var LETTERDASHNUMBER = "[a-zA-Z0-9-]";
var safeRegexReplacements = [
["\\s", 1],
["\\d", MAX_LENGTH],
[LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH]
];
var makeSafeRegex = (value) => {
for (const [token, max] of safeRegexReplacements) {
value = value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`);
}
return value;
};
var createToken = (name, value, isGlobal) => {
const safe = makeSafeRegex(value);
const index = R++;
debug(name, index, value);
t[name] = index;
src[index] = value;
re[index] = new RegExp(value, isGlobal ? "g" : void 0);
safeRe[index] = new RegExp(safe, isGlobal ? "g" : void 0);
};
createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*");
createToken("NUMERICIDENTIFIERLOOSE", "\\d+");
createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`);
createToken("MAINVERSION", `(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})`);
createToken("MAINVERSIONLOOSE", `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})`);
createToken("PRERELEASEIDENTIFIER", `(?:${src[t.NUMERICIDENTIFIER]}|${src[t.NONNUMERICIDENTIFIER]})`);
createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t.NUMERICIDENTIFIERLOOSE]}|${src[t.NONNUMERICIDENTIFIER]})`);
createToken("PRERELEASE", `(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`);
createToken("PRERELEASELOOSE", `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`);
createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`);
createToken("BUILD", `(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`);
createToken("FULLPLAIN", `v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`);
createToken("FULL", `^${src[t.FULLPLAIN]}$`);
createToken("LOOSEPLAIN", `[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`);
createToken("LOOSE", `^${src[t.LOOSEPLAIN]}$`);
createToken("GTLT", "((?:<|>)?=?)");
createToken("XRANGEIDENTIFIERLOOSE", `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
createToken("XRANGEIDENTIFIER", `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`);
createToken("XRANGEPLAIN", `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?)?)?`);
createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?)?)?`);
createToken("XRANGE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`);
createToken("XRANGELOOSE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`);
createToken("COERCEPLAIN", `${"(^|[^\\d])(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`);
createToken("COERCE", `${src[t.COERCEPLAIN]}(?:$|[^\\d])`);
createToken("COERCEFULL", src[t.COERCEPLAIN] + `(?:${src[t.PRERELEASE]})?(?:${src[t.BUILD]})?(?:$|[^\\d])`);
createToken("COERCERTL", src[t.COERCE], true);
createToken("COERCERTLFULL", src[t.COERCEFULL], true);
createToken("LONETILDE", "(?:~>?)");
createToken("TILDETRIM", `(\\s*)${src[t.LONETILDE]}\\s+`, true);
exports.tildeTrimReplace = "$1~";
createToken("TILDE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);
createToken("TILDELOOSE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`);
createToken("LONECARET", "(?:\\^)");
createToken("CARETTRIM", `(\\s*)${src[t.LONECARET]}\\s+`, true);
exports.caretTrimReplace = "$1^";
createToken("CARET", `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);
createToken("CARETLOOSE", `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`);
createToken("COMPARATORLOOSE", `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`);
createToken("COMPARATOR", `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`);
createToken("COMPARATORTRIM", `(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true);
exports.comparatorTrimReplace = "$1$2$3";
createToken("HYPHENRANGE", `^\\s*(${src[t.XRANGEPLAIN]})\\s+-\\s+(${src[t.XRANGEPLAIN]})\\s*$`);
createToken("HYPHENRANGELOOSE", `^\\s*(${src[t.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t.XRANGEPLAINLOOSE]})\\s*$`);
createToken("STAR", "(<|>)?=?\\s*\\*");
createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$");
createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$");
}
});
// node_modules/semver/internal/parse-options.js
var require_parse_options = __commonJS({
"node_modules/semver/internal/parse-options.js"(exports, module2) {
var looseOption = Object.freeze({ loose: true });
var emptyOpts = Object.freeze({});
var parseOptions = (options) => {
if (!options) {
return emptyOpts;
}
if (typeof options !== "object") {
return looseOption;
}
return options;
};
module2.exports = parseOptions;
}
});
// node_modules/semver/internal/identifiers.js
var require_identifiers = __commonJS({
"node_modules/semver/internal/identifiers.js"(exports, module2) {
var numeric = /^[0-9]+$/;
var compareIdentifiers = (a, b) => {
const anum = numeric.test(a);
const bnum = numeric.test(b);
if (anum && bnum) {
a = +a;
b = +b;
}
return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
};
var rcompareIdentifiers = (a, b) => compareIdentifiers(b, a);
module2.exports = {
compareIdentifiers,
rcompareIdentifiers
};
}
});
// node_modules/semver/classes/semver.js
var require_semver = __commonJS({
"node_modules/semver/classes/semver.js"(exports, module2) {
var debug = require_debug();
var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants();
var { safeRe: re, t } = require_re();
var parseOptions = require_parse_options();
var { compareIdentifiers } = require_identifiers();
var SemVer = class {
constructor(version, options) {
options = parseOptions(options);
if (version instanceof SemVer) {
if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) {
return version;
} else {
version = version.version;
}
} else if (typeof version !== "string") {
throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`);
}
if (version.length > MAX_LENGTH) {
throw new TypeError(
`version is longer than ${MAX_LENGTH} characters`
);
}
debug("SemVer", version, options);
this.options = options;
this.loose = !!options.loose;
this.includePrerelease = !!options.includePrerelease;
const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);
if (!m) {
throw new TypeError(`Invalid Version: ${version}`);
}
this.raw = version;
this.major = +m[1];
this.minor = +m[2];
this.patch = +m[3];
if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
throw new TypeError("Invalid major version");
}
if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
throw new TypeError("Invalid minor version");
}
if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
throw new TypeError("Invalid patch version");
}
if (!m[4]) {
this.prerelease = [];
} else {
this.prerelease = m[4].split(".").map((id) => {
if (/^[0-9]+$/.test(id)) {
const num = +id;
if (num >= 0 && num < MAX_SAFE_INTEGER) {
return num;
}
}
return id;
});
}
this.build = m[5] ? m[5].split(".") : [];
this.format();
}
format() {
this.version = `${this.major}.${this.minor}.${this.patch}`;
if (this.prerelease.length) {
this.version += `-${this.prerelease.join(".")}`;
}
return this.version;
}
toString() {
return this.version;
}
compare(other) {
debug("SemVer.compare", this.version, this.options, other);
if (!(other instanceof SemVer)) {
if (typeof other === "string" && other === this.version) {
return 0;
}
other = new SemVer(other, this.options);
}
if (other.version === this.version) {
return 0;
}
return this.compareMain(other) || this.comparePre(other);
}
compareMain(other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options);
}
return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch);
}
comparePre(other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options);
}
if (this.prerelease.length && !other.prerelease.length) {
return -1;
} else if (!this.prerelease.length && other.prerelease.length) {
return 1;
} else if (!this.prerelease.length && !other.prerelease.length) {
return 0;
}
let i = 0;
do {
const a = this.prerelease[i];
const b = other.prerelease[i];
debug("prerelease compare", i, a, b);
if (a === void 0 && b === void 0) {
return 0;
} else if (b === void 0) {
return 1;
} else if (a === void 0) {
return -1;
} else if (a === b) {
continue;
} else {
return compareIdentifiers(a, b);
}
} while (++i);
}
compareBuild(other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options);
}
let i = 0;
do {
const a = this.build[i];
const b = other.build[i];
debug("build compare", i, a, b);
if (a === void 0 && b === void 0) {
return 0;
} else if (b === void 0) {
return 1;
} else if (a === void 0) {
return -1;
} else if (a === b) {
continue;
} else {
return compareIdentifiers(a, b);
}
} while (++i);
}
inc(release, identifier, identifierBase) {
switch (release) {
case "premajor":
this.prerelease.length = 0;
this.patch = 0;
this.minor = 0;
this.major++;
this.inc("pre", identifier, identifierBase);
break;
case "preminor":
this.prerelease.length = 0;
this.patch = 0;
this.minor++;
this.inc("pre", identifier, identifierBase);
break;
case "prepatch":
this.prerelease.length = 0;
this.inc("patch", identifier, identifierBase);
this.inc("pre", identifier, identifierBase);
break;
case "prerelease":
if (this.prerelease.length === 0) {
this.inc("patch", identifier, identifierBase);
}
this.inc("pre", identifier, identifierBase);
break;
case "major":
if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
this.major++;
}
this.minor = 0;
this.patch = 0;
this.prerelease = [];
break;
case "minor":
if (this.patch !== 0 || this.prerelease.length === 0) {
this.minor++;
}
this.patch = 0;
this.prerelease = [];
break;
case "patch":
if (this.prerelease.length === 0) {
this.patch++;
}
this.prerelease = [];
break;
case "pre": {
const base = Number(identifierBase) ? 1 : 0;
if (!identifier && identifierBase === false) {
throw new Error("invalid increment argument: identifier is empty");
}
if (this.prerelease.length === 0) {
this.prerelease = [base];
} else {
let i = this.prerelease.length;
while (--i >= 0) {
if (typeof this.prerelease[i] === "number") {
this.prerelease[i]++;
i = -2;
}
}
if (i === -1) {
if (identifier === this.prerelease.join(".") && identifierBase === false) {
throw new Error("invalid increment argument: identifier already exists");
}
this.prerelease.push(base);
}
}
if (identifier) {
let prerelease = [identifier, base];
if (identifierBase === false) {
prerelease = [identifier];
}
if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
if (isNaN(this.prerelease[1])) {
this.prerelease = prerelease;
}
} else {
this.prerelease = prerelease;
}
}
break;
}
default:
throw new Error(`invalid increment argument: ${release}`);
}
this.raw = this.format();
if (this.build.length) {
this.raw += `+${this.build.join(".")}`;
}
return this;
}
};
module2.exports = SemVer;
}
});
// node_modules/semver/functions/parse.js
var require_parse = __commonJS({
"node_modules/semver/functions/parse.js"(exports, module2) {
var SemVer = require_semver();
var parse2 = (version, options, throwErrors = false) => {
if (version instanceof SemVer) {
return version;
}
try {
return new SemVer(version, options);
} catch (er) {
if (!throwErrors) {
return null;
}
throw er;
}
};
module2.exports = parse2;
}
});
// node_modules/semver/functions/valid.js
var require_valid = __commonJS({
"node_modules/semver/functions/valid.js"(exports, module2) {
var parse2 = require_parse();
var valid = (version, options) => {
const v = parse2(version, options);
return v ? v.version : null;
};
module2.exports = valid;
}
});
// node_modules/semver/functions/clean.js
var require_clean = __commonJS({
"node_modules/semver/functions/clean.js"(exports, module2) {
var parse2 = require_parse();
var clean = (version, options) => {
const s = parse2(version.trim().replace(/^[=v]+/, ""), options);
return s ? s.version : null;
};
module2.exports = clean;
}
});
// node_modules/semver/functions/inc.js
var require_inc = __commonJS({
"node_modules/semver/functions/inc.js"(exports, module2) {
var SemVer = require_semver();
var inc = (version, release, options, identifier, identifierBase) => {
if (typeof options === "string") {
identifierBase = identifier;
identifier = options;
options = void 0;
}
try {
return new SemVer(
version instanceof SemVer ? version.version : version,
options
).inc(release, identifier, identifierBase).version;
} catch (er) {
return null;
}
};
module2.exports = inc;
}
});
// node_modules/semver/functions/diff.js
var require_diff = __commonJS({
"node_modules/semver/functions/diff.js"(exports, module2) {
var parse2 = require_parse();
var diff = (version1, version2) => {
const v1 = parse2(version1, null, true);
const v2 = parse2(version2, null, true);
const comparison = v1.compare(v2);
if (comparison === 0) {
return null;
}
const v1Higher = comparison > 0;
const highVersion = v1Higher ? v1 : v2;
const lowVersion = v1Higher ? v2 : v1;
const highHasPre = !!highVersion.prerelease.length;
const lowHasPre = !!lowVersion.prerelease.length;
if (lowHasPre && !highHasPre) {
if (!lowVersion.patch && !lowVersion.minor) {
return "major";
}
if (highVersion.patch) {
return "patch";
}
if (highVersion.minor) {
return "minor";
}
return "major";
}
const prefix = highHasPre ? "pre" : "";
if (v1.major !== v2.major) {
return prefix + "major";
}
if (v1.minor !== v2.minor) {
return prefix + "minor";
}
if (v1.patch !== v2.patch) {
return prefix + "patch";
}
return "prerelease";
};
module2.exports = diff;
}
});
// node_modules/semver/functions/major.js
var require_major = __commonJS({
"node_modules/semver/functions/major.js"(exports, module2) {
var SemVer = require_semver();
var major = (a, loose) => new SemVer(a, loose).major;
module2.exports = major;
}
});
// node_modules/semver/functions/minor.js
var require_minor = __commonJS({
"node_modules/semver/functions/minor.js"(exports, module2) {
var SemVer = require_semver();
var minor = (a, loose) => new SemVer(a, loose).minor;
module2.exports = minor;
}
});
// node_modules/semver/functions/patch.js
var require_patch = __commonJS({
"node_modules/semver/functions/patch.js"(exports, module2) {
var SemVer = require_semver();
var patch = (a, loose) => new SemVer(a, loose).patch;
module2.exports = patch;
}
});
// node_modules/semver/functions/prerelease.js
var require_prerelease = __commonJS({
"node_modules/semver/functions/prerelease.js"(exports, module2) {
var parse2 = require_parse();
var prerelease = (version, options) => {
const parsed = parse2(version, options);
return parsed && parsed.prerelease.length ? parsed.prerelease : null;
};
module2.exports = prerelease;
}
});
// node_modules/semver/functions/compare.js
var require_compare = __commonJS({
"node_modules/semver/functions/compare.js"(exports, module2) {
var SemVer = require_semver();
var compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose));
module2.exports = compare;
}
});
// node_modules/semver/functions/rcompare.js
var require_rcompare = __commonJS({
"node_modules/semver/functions/rcompare.js"(exports, module2) {
var compare = require_compare();
var rcompare = (a, b, loose) => compare(b, a, loose);
module2.exports = rcompare;
}
});
// node_modules/semver/functions/compare-loose.js
var require_compare_loose = __commonJS({
"node_modules/semver/functions/compare-loose.js"(exports, module2) {
var compare = require_compare();
var compareLoose = (a, b) => compare(a, b, true);
module2.exports = compareLoose;
}
});
// node_modules/semver/functions/compare-build.js
var require_compare_build = __commonJS({
"node_modules/semver/functions/compare-build.js"(exports, module2) {
var SemVer = require_semver();
var compareBuild = (a, b, loose) => {
const versionA = new SemVer(a, loose);
const versionB = new SemVer(b, loose);
return versionA.compare(versionB) || versionA.compareBuild(versionB);
};
module2.exports = compareBuild;
}
});
// node_modules/semver/functions/sort.js
var require_sort = __commonJS({
"node_modules/semver/functions/sort.js"(exports, module2) {
var compareBuild = require_compare_build();
var sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose));
module2.exports = sort;
}
});
// node_modules/semver/functions/rsort.js
var require_rsort = __commonJS({
"node_modules/semver/functions/rsort.js"(exports, module2) {
var compareBuild = require_compare_build();
var rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose));
module2.exports = rsort;
}
});
// node_modules/semver/functions/gt.js
var require_gt = __commonJS({
"node_modules/semver/functions/gt.js"(exports, module2) {
var compare = require_compare();
var gt = (a, b, loose) => compare(a, b, loose) > 0;
module2.exports = gt;
}
});
// node_modules/semver/functions/lt.js
var require_lt = __commonJS({
"node_modules/semver/functions/lt.js"(exports, module2) {
var compare = require_compare();
var lt = (a, b, loose) => compare(a, b, loose) < 0;
module2.exports = lt;
}
});
// node_modules/semver/functions/eq.js
var require_eq = __commonJS({
"node_modules/semver/functions/eq.js"(exports, module2) {
var compare = require_compare();
var eq = (a, b, loose) => compare(a, b, loose) === 0;
module2.exports = eq;
}
});
// node_modules/semver/functions/neq.js
var require_neq = __commonJS({
"node_modules/semver/functions/neq.js"(exports, module2) {
var compare = require_compare();
var neq = (a, b, loose) => compare(a, b, loose) !== 0;
module2.exports = neq;
}
});
// node_modules/semver/functions/gte.js
var require_gte = __commonJS({
"node_modules/semver/functions/gte.js"(exports, module2) {
var compare = require_compare();
var gte = (a, b, loose) => compare(a, b, loose) >= 0;
module2.exports = gte;
}
});
// node_modules/semver/functions/lte.js
var require_lte = __commonJS({
"node_modules/semver/functions/lte.js"(exports, module2) {
var compare = require_compare();
var lte = (a, b, loose) => compare(a, b, loose) <= 0;
module2.exports = lte;
}
});
// node_modules/semver/functions/cmp.js
var require_cmp = __commonJS({
"node_modules/semver/functions/cmp.js"(exports, module2) {
var eq = require_eq();
var neq = require_neq();
var gt = require_gt();
var gte = require_gte();
var lt = require_lt();
var lte = require_lte();
var cmp = (a, op, b, loose) => {
switch (op) {
case "===":
if (typeof a === "object") {
a = a.version;
}
if (typeof b === "object") {
b = b.version;
}
return a === b;
case "!==":
if (typeof a === "object") {
a = a.version;
}
if (typeof b === "object") {
b = b.version;
}
return a !== b;
case "":
case "=":
case "==":
return eq(a, b, loose);
case "!=":
return neq(a, b, loose);
case ">":
return gt(a, b, loose);
case ">=":
return gte(a, b, loose);
case "<":
return lt(a, b, loose);
case "<=":
return lte(a, b, loose);
default:
throw new TypeError(`Invalid operator: ${op}`);
}
};
module2.exports = cmp;
}
});
// node_modules/semver/functions/coerce.js
var require_coerce = __commonJS({
"node_modules/semver/functions/coerce.js"(exports, module2) {
var SemVer = require_semver();
var parse2 = require_parse();
var { safeRe: re, t } = require_re();
var coerce = (version, options) => {
if (version instanceof SemVer) {
return version;
}
if (typeof version === "number") {
version = String(version);
}
if (typeof version !== "string") {
return null;
}
options = options || {};
let match = null;
if (!options.rtl) {
match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]);
} else {
const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL];
let next;
while ((next = coerceRtlRegex.exec(version)) && (!match || match.index + match[0].length !== version.length)) {
if (!match || next.index + next[0].length !== match.index + match[0].length) {
match = next;
}
coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length;
}
coerceRtlRegex.lastIndex = -1;
}
if (match === null) {
return null;
}
const major = match[2];
const minor = match[3] || "0";
const patch = match[4] || "0";
const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : "";
const build = options.includePrerelease && match[6] ? `+${match[6]}` : "";
return parse2(`${major}.${minor}.${patch}${prerelease}${build}`, options);
};
module2.exports = coerce;
}
});
// node_modules/semver/internal/lrucache.js
var require_lrucache = __commonJS({
"node_modules/semver/internal/lrucache.js"(exports, module2) {
var LRUCache = class {
constructor() {
this.max = 1e3;
this.map = /* @__PURE__ */ new Map();
}
get(key) {
const value = this.map.get(key);
if (value === void 0) {
return void 0;
} else {
this.map.delete(key);
this.map.set(key, value);
return value;
}
}
delete(key) {
return this.map.delete(key);
}
set(key, value) {
const deleted = this.delete(key);
if (!deleted && value !== void 0) {
if (this.map.size >= this.max) {
const firstKey = this.map.keys().next().value;
this.delete(firstKey);
}
this.map.set(key, value);
}
return this;
}
};
module2.exports = LRUCache;
}
});
// node_modules/semver/classes/range.js
var require_range = __commonJS({
"node_modules/semver/classes/range.js"(exports, module2) {
var SPACE_CHARACTERS = /\s+/g;
var Range = class {
constructor(range, options) {
options = parseOptions(options);
if (range instanceof Range) {
if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
return range;
} else {
return new Range(range.raw, options);
}
}
if (range instanceof Comparator) {
this.raw = range.value;
this.set = [[range]];
this.formatted = void 0;
return this;
}
this.options = options;
this.loose = !!options.loose;
this.includePrerelease = !!options.includePrerelease;
this.raw = range.trim().replace(SPACE_CHARACTERS, " ");
this.set = this.raw.split("||").map((r) => this.parseRange(r.trim())).filter((c) => c.length);
if (!this.set.length) {
throw new TypeError(`Invalid SemVer Range: ${this.raw}`);
}
if (this.set.length > 1) {
const first = this.set[0];
this.set = this.set.filter((c) => !isNullSet(c[0]));
if (this.set.length === 0) {
this.set = [first];
} else if (this.set.length > 1) {
for (const c of this.set) {
if (c.length === 1 && isAny(c[0])) {
this.set = [c];
break;
}
}
}
}
this.formatted = void 0;
}
get range() {
if (this.formatted === void 0) {
this.formatted = "";
for (let i = 0; i < this.set.length; i++) {
if (i > 0) {
this.formatted += "||";
}
const comps = this.set[i];
for (let k = 0; k < comps.length; k++) {
if (k > 0) {
this.formatted += " ";
}
this.formatted += comps[k].toString().trim();
}
}
}
return this.formatted;
}
format() {
return this.range;
}
toString() {
return this.range;
}
parseRange(range) {
const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE);
const memoKey = memoOpts + ":" + range;
const cached = cache.get(memoKey);
if (cached) {
return cached;
}
const loose = this.options.loose;
const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE];
range = range.replace(hr, hyphenReplace(this.options.includePrerelease));
debug("hyphen replace", range);
range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace);
debug("comparator trim", range);
range = range.replace(re[t.TILDETRIM], tildeTrimReplace);
debug("tilde trim", range);
range = range.replace(re[t.CARETTRIM], caretTrimReplace);
debug("caret trim", range);
let rangeList = range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options));
if (loose) {
rangeList = rangeList.filter((comp) => {
debug("loose invalid filter", comp, this.options);
return !!comp.match(re[t.COMPARATORLOOSE]);
});
}
debug("range list", rangeList);
const rangeMap = /* @__PURE__ */ new Map();
const comparators = rangeList.map((comp) => new Comparator(comp, this.options));
for (const comp of comparators) {
if (isNullSet(comp)) {
return [comp];
}
rangeMap.set(comp.value, comp);
}
if (rangeMap.size > 1 && rangeMap.has("")) {
rangeMap.delete("");
}
const result = [...rangeMap.values()];
cache.set(memoKey, result);
return result;
}
intersects(range, options) {
if (!(range instanceof Range)) {
throw new TypeError("a Range is required");
}
return this.set.some((thisComparators) => {
return isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => {
return isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => {
return rangeComparators.every((rangeComparator) => {
return thisComparator.intersects(rangeComparator, options);
});
});
});
});
}
test(version) {
if (!version) {
return false;
}
if (typeof version === "string") {
try {
version = new SemVer(version, this.options);
} catch (er) {
return false;
}
}
for (let i = 0; i < this.set.length; i++) {
if (testSet(this.set[i], version, this.options)) {
return true;
}
}
return false;
}
};
module2.exports = Range;
var LRU = require_lrucache();
var cache = new LRU();
var parseOptions = require_parse_options();
var Comparator = require_comparator();
var debug = require_debug();
var SemVer = require_semver();
var {
safeRe: re,
t,
comparatorTrimReplace,
tildeTrimReplace,
caretTrimReplace
} = require_re();
var { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants();
var isNullSet = (c) => c.value === "<0.0.0-0";
var isAny = (c) => c.value === "";
var isSatisfiable = (comparators, options) => {
let result = true;
const remainingComparators = comparators.slice();
let testComparator = remainingComparators.pop();
while (result && remainingComparators.length) {
result = remainingComparators.every((otherComparator) => {
return testComparator.intersects(otherComparator, options);
});
testComparator = remainingComparators.pop();
}
return result;
};
var parseComparator = (comp, options) => {
debug("comp", comp, options);
comp = replaceCarets(comp, options);
debug("caret", comp);
comp = replaceTildes(comp, options);
debug("tildes", comp);
comp = replaceXRanges(comp, options);
debug("xrange", comp);
comp = replaceStars(comp, options);
debug("stars", comp);
return comp;
};
var isX = (id) => !id || id.toLowerCase() === "x" || id === "*";
var replaceTildes = (comp, options) => {
return comp.trim().split(/\s+/).map((c) => replaceTilde(c, options)).join(" ");
};
var replaceTilde = (comp, options) => {
const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE];
return comp.replace(r, (_, M, m, p2, pr) => {
debug("tilde", comp, _, M, m, p2, pr);
let ret;
if (isX(M)) {
ret = "";
} else if (isX(m)) {
ret = `>=${M}.0.0 <${+M + 1}.0.0-0`;
} else if (isX(p2)) {
ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`;
} else if (pr) {
debug("replaceTilde pr", pr);
ret = `>=${M}.${m}.${p2}-${pr} <${M}.${+m + 1}.0-0`;
} else {
ret = `>=${M}.${m}.${p2} <${M}.${+m + 1}.0-0`;
}
debug("tilde return", ret);
return ret;
});
};
var replaceCarets = (comp, options) => {
return comp.trim().split(/\s+/).map((c) => replaceCaret(c, options)).join(" ");
};
var replaceCaret = (comp, options) => {
debug("caret", comp, options);
const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET];
const z = options.includePrerelease ? "-0" : "";
return comp.replace(r, (_, M, m, p2, pr) => {
debug("caret", comp, _, M, m, p2, pr);
let ret;
if (isX(M)) {
ret = "";
} else if (isX(m)) {
ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`;
} else if (isX(p2)) {
if (M === "0") {
ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`;
} else {
ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`;
}
} else if (pr) {
debug("replaceCaret pr", pr);
if (M === "0") {
if (m === "0") {
ret = `>=${M}.${m}.${p2}-${pr} <${M}.${m}.${+p2 + 1}-0`;
} else {
ret = `>=${M}.${m}.${p2}-${pr} <${M}.${+m + 1}.0-0`;
}
} else {
ret = `>=${M}.${m}.${p2}-${pr} <${+M + 1}.0.0-0`;
}
} else {
debug("no pr");
if (M === "0") {
if (m === "0") {
ret = `>=${M}.${m}.${p2}${z} <${M}.${m}.${+p2 + 1}-0`;
} else {
ret = `>=${M}.${m}.${p2}${z} <${M}.${+m + 1}.0-0`;
}
} else {
ret = `>=${M}.${m}.${p2} <${+M + 1}.0.0-0`;
}
}
debug("caret return", ret);
return ret;
});
};
var replaceXRanges = (comp, options) => {
debug("replaceXRanges", comp, options);
return comp.split(/\s+/).map((c) => replaceXRange(c, options)).join(" ");
};
var replaceXRange = (comp, options) => {
comp = comp.trim();
const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE];
return comp.replace(r, (ret, gtlt, M, m, p2, pr) => {
debug("xRange", comp, ret, gtlt, M, m, p2, pr);
const xM = isX(M);
const xm = xM || isX(m);
const xp = xm || isX(p2);
const anyX = xp;
if (gtlt === "=" && anyX) {
gtlt = "";
}
pr = options.includePrerelease ? "-0" : "";
if (xM) {
if (gtlt === ">" || gtlt === "<") {
ret = "<0.0.0-0";
} else {
ret = "*";
}
} else if (gtlt && anyX) {
if (xm) {
m = 0;
}
p2 = 0;
if (gtlt === ">") {
gtlt = ">=";
if (xm) {
M = +M + 1;
m = 0;
p2 = 0;
} else {
m = +m + 1;
p2 = 0;
}
} else if (gtlt === "<=") {
gtlt = "<";
if (xm) {
M = +M + 1;
} else {
m = +m + 1;
}
}
if (gtlt === "<") {
pr = "-0";
}
ret = `${gtlt + M}.${m}.${p2}${pr}`;
} else if (xm) {
ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;
} else if (xp) {
ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`;
}
debug("xRange return", ret);
return ret;
});
};
var replaceStars = (comp, options) => {
debug("replaceStars", comp, options);
return comp.trim().replace(re[t.STAR], "");
};
var replaceGTE0 = (comp, options) => {
debug("replaceGTE0", comp, options);
return comp.trim().replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], "");
};
var hyphenReplace = (incPr) => ($02, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => {
if (isX(fM)) {
from = "";
} else if (isX(fm)) {
from = `>=${fM}.0.0${incPr ? "-0" : ""}`;
} else if (isX(fp)) {
from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`;
} else if (fpr) {
from = `>=${from}`;
} else {
from = `>=${from}${incPr ? "-0" : ""}`;
}
if (isX(tM)) {
to = "";
} else if (isX(tm)) {
to = `<${+tM + 1}.0.0-0`;
} else if (isX(tp)) {
to = `<${tM}.${+tm + 1}.0-0`;
} else if (tpr) {
to = `<=${tM}.${tm}.${tp}-${tpr}`;
} else if (incPr) {
to = `<${tM}.${tm}.${+tp + 1}-0`;
} else {
to = `<=${to}`;
}
return `${from} ${to}`.trim();
};
var testSet = (set, version, options) => {
for (let i = 0; i < set.length; i++) {
if (!set[i].test(version)) {
return false;
}
}
if (version.prerelease.length && !options.includePrerelease) {
for (let i = 0; i < set.length; i++) {
debug(set[i].semver);
if (set[i].semver === Comparator.ANY) {
continue;
}
if (set[i].semver.prerelease.length > 0) {
const allowed = set[i].semver;
if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) {
return true;
}
}
}
return false;
}
return true;
};
}
});
// node_modules/semver/classes/comparator.js
var require_comparator = __commonJS({
"node_modules/semver/classes/comparator.js"(exports, module2) {
var ANY = Symbol("SemVer ANY");
var Comparator = class {
static get ANY() {
return ANY;
}
constructor(comp, options) {
options = parseOptions(options);
if (comp instanceof Comparator) {
if (comp.loose === !!options.loose) {
return comp;
} else {
comp = comp.value;
}
}
comp = comp.trim().split(/\s+/).join(" ");
debug("comparator", comp, options);
this.options = options;
this.loose = !!options.loose;
this.parse(comp);
if (this.semver === ANY) {
this.value = "";
} else {
this.value = this.operator + this.semver.version;
}
debug("comp", this);
}
parse(comp) {
const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
const m = comp.match(r);
if (!m) {
throw new TypeError(`Invalid comparator: ${comp}`);
}
this.operator = m[1] !== void 0 ? m[1] : "";
if (this.operator === "=") {
this.operator = "";
}
if (!m[2]) {
this.semver = ANY;
} else {
this.semver = new SemVer(m[2], this.options.loose);
}
}
toString() {
return this.value;
}
test(version) {
debug("Comparator.test", version, this.options.loose);
if (this.semver === ANY || version === ANY) {
return true;
}
if (typeof version === "string") {
try {
version = new SemVer(version, this.options);
} catch (er) {
return false;
}
}
return cmp(version, this.operator, this.semver, this.options);
}
intersects(comp, options) {
if (!(comp instanceof Comparator)) {
throw new TypeError("a Comparator is required");
}
if (this.operator === "") {
if (this.value === "") {
return true;
}
return new Range(comp.value, options).test(this.value);
} else if (comp.operator === "") {
if (comp.value === "") {
return true;
}
return new Range(this.value, options).test(comp.semver);
}
options = parseOptions(options);
if (options.includePrerelease && (this.value === "<0.0.0-0" || comp.value === "<0.0.0-0")) {
return false;
}
if (!options.includePrerelease && (this.value.startsWith("<0.0.0") || comp.value.startsWith("<0.0.0"))) {
return false;
}
if (this.operator.startsWith(">") && comp.operator.startsWith(">")) {
return true;
}
if (this.operator.startsWith("<") && comp.operator.startsWith("<")) {
return true;
}
if (this.semver.version === comp.semver.version && this.operator.includes("=") && comp.operator.includes("=")) {
return true;
}
if (cmp(this.semver, "<", comp.semver, options) && this.operator.startsWith(">") && comp.operator.startsWith("<")) {
return true;
}
if (cmp(this.semver, ">", comp.semver, options) && this.operator.startsWith("<") && comp.operator.startsWith(">")) {
return true;
}
return false;
}
};
module2.exports = Comparator;
var parseOptions = require_parse_options();
var { safeRe: re, t } = require_re();
var cmp = require_cmp();
var debug = require_debug();
var SemVer = require_semver();
var Range = require_range();
}
});
// node_modules/semver/functions/satisfies.js
var require_satisfies = __commonJS({
"node_modules/semver/functions/satisfies.js"(exports, module2) {
var Range = require_range();
var satisfies = (version, range, options) => {
try {
range = new Range(range, options);
} catch (er) {
return false;
}
return range.test(version);
};
module2.exports = satisfies;
}
});
// node_modules/semver/ranges/to-comparators.js
var require_to_comparators = __commonJS({
"node_modules/semver/ranges/to-comparators.js"(exports, module2) {
var Range = require_range();
var toComparators = (range, options) => new Range(range, options).set.map((comp) => comp.map((c) => c.value).join(" ").trim().split(" "));
module2.exports = toComparators;
}
});
// node_modules/semver/ranges/max-satisfying.js
var require_max_satisfying = __commonJS({
"node_modules/semver/ranges/max-satisfying.js"(exports, module2) {
var SemVer = require_semver();
var Range = require_range();
var maxSatisfying = (versions, range, options) => {
let max = null;
let maxSV = null;
let rangeObj = null;
try {
rangeObj = new Range(range, options);
} catch (er) {
return null;
}
versions.forEach((v) => {
if (rangeObj.test(v)) {
if (!max || maxSV.compare(v) === -1) {
max = v;
maxSV = new SemVer(max, options);
}
}
});
return max;
};
module2.exports = maxSatisfying;
}
});
// node_modules/semver/ranges/min-satisfying.js
var require_min_satisfying = __commonJS({
"node_modules/semver/ranges/min-satisfying.js"(exports, module2) {
var SemVer = require_semver();
var Range = require_range();
var minSatisfying = (versions, range, options) => {
let min = null;
let minSV = null;
let rangeObj = null;
try {
rangeObj = new Range(range, options);
} catch (er) {
return null;
}
versions.forEach((v) => {
if (rangeObj.test(v)) {
if (!min || minSV.compare(v) === 1) {
min = v;
minSV = new SemVer(min, options);
}
}
});
return min;
};
module2.exports = minSatisfying;
}
});
// node_modules/semver/ranges/min-version.js
var require_min_version = __commonJS({
"node_modules/semver/ranges/min-version.js"(exports, module2) {
var SemVer = require_semver();
var Range = require_range();
var gt = require_gt();
var minVersion = (range, loose) => {
range = new Range(range, loose);
let minver = new SemVer("0.0.0");
if (range.test(minver)) {
return minver;
}
minver = new SemVer("0.0.0-0");
if (range.test(minver)) {
return minver;
}
minver = null;
for (let i = 0; i < range.set.length; ++i) {
const comparators = range.set[i];
let setMin = null;
comparators.forEach((comparator) => {
const compver = new SemVer(comparator.semver.version);
switch (comparator.operator) {
case ">":
if (compver.prerelease.length === 0) {
compver.patch++;
} else {
compver.prerelease.push(0);
}
compver.raw = compver.format();
case "":
case ">=":
if (!setMin || gt(compver, setMin)) {
setMin = compver;
}
break;
case "<":
case "<=":
break;
default:
throw new Error(`Unexpected operation: ${comparator.operator}`);
}
});
if (setMin && (!minver || gt(minver, setMin))) {
minver = setMin;
}
}
if (minver && range.test(minver)) {
return minver;
}
return null;
};
module2.exports = minVersion;
}
});
// node_modules/semver/ranges/valid.js
var require_valid2 = __commonJS({
"node_modules/semver/ranges/valid.js"(exports, module2) {
var Range = require_range();
var validRange = (range, options) => {
try {
return new Range(range, options).range || "*";
} catch (er) {
return null;
}
};
module2.exports = validRange;
}
});
// node_modules/semver/ranges/outside.js
var require_outside = __commonJS({
"node_modules/semver/ranges/outside.js"(exports, module2) {
var SemVer = require_semver();
var Comparator = require_comparator();
var { ANY } = Comparator;
var Range = require_range();
var satisfies = require_satisfies();
var gt = require_gt();
var lt = require_lt();
var lte = require_lte();
var gte = require_gte();
var outside = (version, range, hilo, options) => {
version = new SemVer(version, options);
range = new Range(range, options);
let gtfn, ltefn, ltfn, comp, ecomp;
switch (hilo) {
case ">":
gtfn = gt;
ltefn = lte;
ltfn = lt;
comp = ">";
ecomp = ">=";
break;
case "<":
gtfn = lt;
ltefn = gte;
ltfn = gt;
comp = "<";
ecomp = "<=";
break;
default:
throw new TypeError('Must provide a hilo val of "<" or ">"');
}
if (satisfies(version, range, options)) {
return false;
}
for (let i = 0; i < range.set.length; ++i) {
const comparators = range.set[i];
let high = null;
let low = null;
comparators.forEach((comparator) => {
if (comparator.semver === ANY) {
comparator = new Comparator(">=0.0.0");
}
high = high || comparator;
low = low || comparator;
if (gtfn(comparator.semver, high.semver, options)) {
high = comparator;
} else if (ltfn(comparator.semver, low.semver, options)) {
low = comparator;
}
});
if (high.operator === comp || high.operator === ecomp) {
return false;
}
if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) {
return false;
} else if (low.operator === ecomp && ltfn(version, low.semver)) {
return false;
}
}
return true;
};
module2.exports = outside;
}
});
// node_modules/semver/ranges/gtr.js
var require_gtr = __commonJS({
"node_modules/semver/ranges/gtr.js"(exports, module2) {
var outside = require_outside();
var gtr = (version, range, options) => outside(version, range, ">", options);
module2.exports = gtr;
}
});
// node_modules/semver/ranges/ltr.js
var require_ltr = __commonJS({
"node_modules/semver/ranges/ltr.js"(exports, module2) {
var outside = require_outside();
var ltr = (version, range, options) => outside(version, range, "<", options);
module2.exports = ltr;
}
});
// node_modules/semver/ranges/intersects.js
var require_intersects = __commonJS({
"node_modules/semver/ranges/intersects.js"(exports, module2) {
var Range = require_range();
var intersects = (r1, r2, options) => {
r1 = new Range(r1, options);
r2 = new Range(r2, options);
return r1.intersects(r2, options);
};
module2.exports = intersects;
}
});
// node_modules/semver/ranges/simplify.js
var require_simplify = __commonJS({
"node_modules/semver/ranges/simplify.js"(exports, module2) {
var satisfies = require_satisfies();
var compare = require_compare();
module2.exports = (versions, range, options) => {
const set = [];
let first = null;
let prev = null;
const v = versions.sort((a, b) => compare(a, b, options));
for (const version of v) {
const included = satisfies(version, range, options);
if (included) {
prev = version;
if (!first) {
first = version;
}
} else {
if (prev) {
set.push([first, prev]);
}
prev = null;
first = null;
}
}
if (first) {
set.push([first, null]);
}
const ranges = [];
for (const [min, max] of set) {
if (min === max) {
ranges.push(min);
} else if (!max && min === v[0]) {
ranges.push("*");
} else if (!max) {
ranges.push(`>=${min}`);
} else if (min === v[0]) {
ranges.push(`<=${max}`);
} else {
ranges.push(`${min} - ${max}`);
}
}
const simplified = ranges.join(" || ");
const original = typeof range.raw === "string" ? range.raw : String(range);
return simplified.length < original.length ? simplified : range;
};
}
});
// node_modules/semver/ranges/subset.js
var require_subset = __commonJS({
"node_modules/semver/ranges/subset.js"(exports, module2) {
var Range = require_range();
var Comparator = require_comparator();
var { ANY } = Comparator;
var satisfies = require_satisfies();
var compare = require_compare();
var subset = (sub, dom, options = {}) => {
if (sub === dom) {
return true;
}
sub = new Range(sub, options);
dom = new Range(dom, options);
let sawNonNull = false;
OUTER:
for (const simpleSub of sub.set) {
for (const simpleDom of dom.set) {
const isSub = simpleSubset(simpleSub, simpleDom, options);
sawNonNull = sawNonNull || isSub !== null;
if (isSub) {
continue OUTER;
}
}
if (sawNonNull) {
return false;
}
}
return true;
};
var minimumVersionWithPreRelease = [new Comparator(">=0.0.0-0")];
var minimumVersion = [new Comparator(">=0.0.0")];
var simpleSubset = (sub, dom, options) => {
if (sub === dom) {
return true;
}
if (sub.length === 1 && sub[0].semver === ANY) {
if (dom.length === 1 && dom[0].semver === ANY) {
return true;
} else if (options.includePrerelease) {
sub = minimumVersionWithPreRelease;
} else {
sub = minimumVersion;
}
}
if (dom.length === 1 && dom[0].semver === ANY) {
if (options.includePrerelease) {
return true;
} else {
dom = minimumVersion;
}
}
const eqSet = /* @__PURE__ */ new Set();
let gt, lt;
for (const c of sub) {
if (c.operator === ">" || c.operator === ">=") {
gt = higherGT(gt, c, options);
} else if (c.operator === "<" || c.operator === "<=") {
lt = lowerLT(lt, c, options);
} else {
eqSet.add(c.semver);
}
}
if (eqSet.size > 1) {
return null;
}
let gtltComp;
if (gt && lt) {
gtltComp = compare(gt.semver, lt.semver, options);
if (gtltComp > 0) {
return null;
} else if (gtltComp === 0 && (gt.operator !== ">=" || lt.operator !== "<=")) {
return null;
}
}
for (const eq of eqSet) {
if (gt && !satisfies(eq, String(gt), options)) {
return null;
}
if (lt && !satisfies(eq, String(lt), options)) {
return null;
}
for (const c of dom) {
if (!satisfies(eq, String(c), options)) {
return false;
}
}
return true;
}
let higher, lower;
let hasDomLT, hasDomGT;
let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false;
let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false;
if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === "<" && needDomLTPre.prerelease[0] === 0) {
needDomLTPre = false;
}
for (const c of dom) {
hasDomGT = hasDomGT || c.operator === ">" || c.operator === ">=";
hasDomLT = hasDomLT || c.operator === "<" || c.operator === "<=";
if (gt) {
if (needDomGTPre) {
if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) {
needDomGTPre = false;
}
}
if (c.operator === ">" || c.operator === ">=") {
higher = higherGT(gt, c, options);
if (higher === c && higher !== gt) {
return false;
}
} else if (gt.operator === ">=" && !satisfies(gt.semver, String(c), options)) {
return false;
}
}
if (lt) {
if (needDomLTPre) {
if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) {
needDomLTPre = false;
}
}
if (c.operator === "<" || c.operator === "<=") {
lower = lowerLT(lt, c, options);
if (lower === c && lower !== lt) {
return false;
}
} else if (lt.operator === "<=" && !satisfies(lt.semver, String(c), options)) {
return false;
}
}
if (!c.operator && (lt || gt) && gtltComp !== 0) {
return false;
}
}
if (gt && hasDomLT && !lt && gtltComp !== 0) {
return false;
}
if (lt && hasDomGT && !gt && gtltComp !== 0) {
return false;
}
if (needDomGTPre || needDomLTPre) {
return false;
}
return true;
};
var higherGT = (a, b, options) => {
if (!a) {
return b;
}
const comp = compare(a.semver, b.semver, options);
return comp > 0 ? a : comp < 0 ? b : b.operator === ">" && a.operator === ">=" ? b : a;
};
var lowerLT = (a, b, options) => {
if (!a) {
return b;
}
const comp = compare(a.semver, b.semver, options);
return comp < 0 ? a : comp > 0 ? b : b.operator === "<" && a.operator === "<=" ? b : a;
};
module2.exports = subset;
}
});
// node_modules/semver/index.js
var require_semver2 = __commonJS({
"node_modules/semver/index.js"(exports, module2) {
var internalRe = require_re();
var constants = require_constants();
var SemVer = require_semver();
var identifiers = require_identifiers();
var parse2 = require_parse();
var valid = require_valid();
var clean = require_clean();
var inc = require_inc();
var diff = require_diff();
var major = require_major();
var minor = require_minor();
var patch = require_patch();
var prerelease = require_prerelease();
var compare = require_compare();
var rcompare = require_rcompare();
var compareLoose = require_compare_loose();
var compareBuild = require_compare_build();
var sort = require_sort();
var rsort = require_rsort();
var gt = require_gt();
var lt = require_lt();
var eq = require_eq();
var neq = require_neq();
var gte = require_gte();
var lte = require_lte();
var cmp = require_cmp();
var coerce = require_coerce();
var Comparator = require_comparator();
var Range = require_range();
var satisfies = require_satisfies();
var toComparators = require_to_comparators();
var maxSatisfying = require_max_satisfying();
var minSatisfying = require_min_satisfying();
var minVersion = require_min_version();
var validRange = require_valid2();
var outside = require_outside();
var gtr = require_gtr();
var ltr = require_ltr();
var intersects = require_intersects();
var simplifyRange = require_simplify();
var subset = require_subset();
module2.exports = {
parse: parse2,
valid,
clean,
inc,
diff,
major,
minor,
patch,
prerelease,
compare,
rcompare,
compareLoose,
compareBuild,
sort,
rsort,
gt,
lt,
eq,
neq,
gte,
lte,
cmp,
coerce,
Comparator,
Range,
satisfies,
toComparators,
maxSatisfying,
minSatisfying,
minVersion,
validRange,
outside,
gtr,
ltr,
intersects,
simplifyRange,
subset,
SemVer,
re: internalRe.re,
src: internalRe.src,
tokens: internalRe.t,
SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,
RELEASE_TYPES: constants.RELEASE_TYPES,
compareIdentifiers: identifiers.compareIdentifiers,
rcompareIdentifiers: identifiers.rcompareIdentifiers
};
}
});
// bazel-out/darwin_arm64-fastbuild/bin/packages/core/schematics/ng-generate/standalone-migration/index.mjs
var standalone_migration_exports = {};
__export(standalone_migration_exports, {
default: () => standalone_migration_default
});
module.exports = __toCommonJS(standalone_migration_exports);
var import_schematics = require("@angular-devkit/schematics");
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/file_system/src/compiler_host.mjs
var import_typescript = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/file_system/src/invalid_file_system.mjs
var InvalidFileSystem = class {
exists(path4) {
throw makeError();
}
readFile(path4) {
throw makeError();
}
readFileBuffer(path4) {
throw makeError();
}
writeFile(path4, data, exclusive) {
throw makeError();
}
removeFile(path4) {
throw makeError();
}
symlink(target, path4) {
throw makeError();
}
readdir(path4) {
throw makeError();
}
lstat(path4) {
throw makeError();
}
stat(path4) {
throw makeError();
}
pwd() {
throw makeError();
}
chdir(path4) {
throw makeError();
}
extname(path4) {
throw makeError();
}
copyFile(from, to) {
throw makeError();
}
moveFile(from, to) {
throw makeError();
}
ensureDir(path4) {
throw makeError();
}
removeDeep(path4) {
throw makeError();
}
isCaseSensitive() {
throw makeError();
}
resolve(...paths) {
throw makeError();
}
dirname(file) {
throw makeError();
}
join(basePath, ...paths) {
throw makeError();
}
isRoot(path4) {
throw makeError();
}
isRooted(path4) {
throw makeError();
}
relative(from, to) {
throw makeError();
}
basename(filePath, extension) {
throw makeError();
}
realpath(filePath) {
throw makeError();
}
getDefaultLibLocation() {
throw makeError();
}
normalize(path4) {
throw makeError();
}
};
function makeError() {
return new Error("FileSystem has not been configured. Please call `setFileSystem()` before calling this method.");
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/file_system/src/util.mjs
var TS_DTS_JS_EXTENSION = /(?:\.d)?\.ts$|\.js$/;
function stripExtension(path4) {
return path4.replace(TS_DTS_JS_EXTENSION, "");
}
function getSourceFileOrError(program, fileName) {
const sf = program.getSourceFile(fileName);
if (sf === void 0) {
throw new Error(`Program does not contain "${fileName}" - available files are ${program.getSourceFiles().map((sf2) => sf2.fileName).join(", ")}`);
}
return sf;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/file_system/src/helpers.mjs
var fs = new InvalidFileSystem();
function getFileSystem() {
return fs;
}
function setFileSystem(fileSystem) {
fs = fileSystem;
}
function absoluteFrom(path4) {
if (!fs.isRooted(path4)) {
throw new Error(`Internal Error: absoluteFrom(${path4}): path is not absolute`);
}
return fs.resolve(path4);
}
var ABSOLUTE_PATH = Symbol("AbsolutePath");
function absoluteFromSourceFile(sf) {
const sfWithPatch = sf;
if (sfWithPatch[ABSOLUTE_PATH] === void 0) {
sfWithPatch[ABSOLUTE_PATH] = fs.resolve(sfWithPatch.fileName);
}
return sfWithPatch[ABSOLUTE_PATH];
}
function dirname(file) {
return fs.dirname(file);
}
function join(basePath, ...paths) {
return fs.join(basePath, ...paths);
}
function resolve(basePath, ...paths) {
return fs.resolve(basePath, ...paths);
}
function isRooted(path4) {
return fs.isRooted(path4);
}
function relative(from, to) {
return fs.relative(from, to);
}
function isLocalRelativePath(relativePath) {
return !isRooted(relativePath) && !relativePath.startsWith("..");
}
function toRelativeImport(relativePath) {
return isLocalRelativePath(relativePath) ? `./${relativePath}` : relativePath;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/file_system/src/logical.mjs
var LogicalProjectPath = {
relativePathBetween: function(from, to) {
const relativePath = relative(dirname(resolve(from)), resolve(to));
return toRelativeImport(relativePath);
}
};
var LogicalFileSystem = class {
constructor(rootDirs, compilerHost) {
this.compilerHost = compilerHost;
this.cache = /* @__PURE__ */ new Map();
this.rootDirs = rootDirs.concat([]).sort((a, b) => b.length - a.length);
this.canonicalRootDirs = this.rootDirs.map((dir) => this.compilerHost.getCanonicalFileName(dir));
}
logicalPathOfSf(sf) {
return this.logicalPathOfFile(absoluteFromSourceFile(sf));
}
logicalPathOfFile(physicalFile) {
if (!this.cache.has(physicalFile)) {
const canonicalFilePath = this.compilerHost.getCanonicalFileName(physicalFile);
let logicalFile = null;
for (let i = 0; i < this.rootDirs.length; i++) {
const rootDir = this.rootDirs[i];
const canonicalRootDir = this.canonicalRootDirs[i];
if (isWithinBasePath(canonicalRootDir, canonicalFilePath)) {
logicalFile = this.createLogicalProjectPath(physicalFile, rootDir);
if (logicalFile.indexOf("/node_modules/") !== -1) {
logicalFile = null;
} else {
break;
}
}
}
this.cache.set(physicalFile, logicalFile);
}
return this.cache.get(physicalFile);
}
createLogicalProjectPath(file, rootDir) {
const logicalPath = stripExtension(file.slice(rootDir.length));
return logicalPath.startsWith("/") ? logicalPath : "/" + logicalPath;
}
};
function isWithinBasePath(base, path4) {
return isLocalRelativePath(relative(base, path4));
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/file_system/src/node_js_file_system.mjs
var import_fs = __toESM(require("fs"), 1);
var import_module = require("module");
var p = __toESM(require("path"), 1);
var import_url = require("url");
var import_meta = {};
var NodeJSPathManipulation = class {
pwd() {
return this.normalize(process.cwd());
}
chdir(dir) {
process.chdir(dir);
}
resolve(...paths) {
return this.normalize(p.resolve(...paths));
}
dirname(file) {
return this.normalize(p.dirname(file));
}
join(basePath, ...paths) {
return this.normalize(p.join(basePath, ...paths));
}
isRoot(path4) {
return this.dirname(path4) === this.normalize(path4);
}
isRooted(path4) {
return p.isAbsolute(path4);
}
relative(from, to) {
return this.normalize(p.relative(from, to));
}
basename(filePath, extension) {
return p.basename(filePath, extension);
}
extname(path4) {
return p.extname(path4);
}
normalize(path4) {
return path4.replace(/\\/g, "/");
}
};
var isCommonJS = typeof __filename !== "undefined";
var currentFileUrl = isCommonJS ? null : import_meta.url;
var currentFileName = isCommonJS ? __filename : (0, import_url.fileURLToPath)(currentFileUrl);
var NodeJSReadonlyFileSystem = class extends NodeJSPathManipulation {
constructor() {
super(...arguments);
this._caseSensitive = void 0;
}
isCaseSensitive() {
if (this._caseSensitive === void 0) {
this._caseSensitive = !import_fs.default.existsSync(this.normalize(toggleCase(currentFileName)));
}
return this._caseSensitive;
}
exists(path4) {
return import_fs.default.existsSync(path4);
}
readFile(path4) {
return import_fs.default.readFileSync(path4, "utf8");
}
readFileBuffer(path4) {
return import_fs.default.readFileSync(path4);
}
readdir(path4) {
return import_fs.default.readdirSync(path4);
}
lstat(path4) {
return import_fs.default.lstatSync(path4);
}
stat(path4) {
return import_fs.default.statSync(path4);
}
realpath(path4) {
return this.resolve(import_fs.default.realpathSync(path4));
}
getDefaultLibLocation() {
const requireFn = isCommonJS ? require : (0, import_module.createRequire)(currentFileUrl);
return this.resolve(requireFn.resolve("typescript"), "..");
}
};
var NodeJSFileSystem = class extends NodeJSReadonlyFileSystem {
writeFile(path4, data, exclusive = false) {
import_fs.default.writeFileSync(path4, data, exclusive ? { flag: "wx" } : void 0);
}
removeFile(path4) {
import_fs.default.unlinkSync(path4);
}
symlink(target, path4) {
import_fs.default.symlinkSync(target, path4);
}
copyFile(from, to) {
import_fs.default.copyFileSync(from, to);
}
moveFile(from, to) {
import_fs.default.renameSync(from, to);
}
ensureDir(path4) {
import_fs.default.mkdirSync(path4, { recursive: true });
}
removeDeep(path4) {
import_fs.default.rmdirSync(path4, { recursive: true });
}
};
function toggleCase(str) {
return str.replace(/\w/g, (ch) => ch.toUpperCase() === ch ? ch.toLowerCase() : ch.toUpperCase());
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/selector.mjs
var _SELECTOR_REGEXP = new RegExp(
`(\\:not\\()|(([\\.\\#]?)[-\\w]+)|(?:\\[([-.\\w*\\\\$]+)(?:=(["']?)([^\\]"']*)\\5)?\\])|(\\))|(\\s*,\\s*)`,
"g"
);
var CssSelector = class {
constructor() {
this.element = null;
this.classNames = [];
this.attrs = [];
this.notSelectors = [];
}
static parse(selector) {
const results = [];
const _addResult = (res, cssSel) => {
if (cssSel.notSelectors.length > 0 && !cssSel.element && cssSel.classNames.length == 0 && cssSel.attrs.length == 0) {
cssSel.element = "*";
}
res.push(cssSel);
};
let cssSelector = new CssSelector();
let match;
let current = cssSelector;
let inNot = false;
_SELECTOR_REGEXP.lastIndex = 0;
while (match = _SELECTOR_REGEXP.exec(selector)) {
if (match[1]) {
if (inNot) {
throw new Error("Nesting :not in a selector is not allowed");
}
inNot = true;
current = new CssSelector();
cssSelector.notSelectors.push(current);
}
const tag = match[2];
if (tag) {
const prefix = match[3];
if (prefix === "#") {
current.addAttribute("id", tag.slice(1));
} else if (prefix === ".") {
current.addClassName(tag.slice(1));
} else {
current.setElement(tag);
}
}
const attribute2 = match[4];
if (attribute2) {
current.addAttribute(current.unescapeAttribute(attribute2), match[6]);
}
if (match[7]) {
inNot = false;
current = cssSelector;
}
if (match[8]) {
if (inNot) {
throw new Error("Multiple selectors in :not are not supported");
}
_addResult(results, cssSelector);
cssSelector = current = new CssSelector();
}
}
_addResult(results, cssSelector);
return results;
}
unescapeAttribute(attr) {
let result = "";
let escaping = false;
for (let i = 0; i < attr.length; i++) {
const char = attr.charAt(i);
if (char === "\\") {
escaping = true;
continue;
}
if (char === "$" && !escaping) {
throw new Error(`Error in attribute selector "${attr}". Unescaped "$" is not supported. Please escape with "\\$".`);
}
escaping = false;
result += char;
}
return result;
}
escapeAttribute(attr) {
return attr.replace(/\\/g, "\\\\").replace(/\$/g, "\\$");
}
isElementSelector() {
return this.hasElementSelector() && this.classNames.length == 0 && this.attrs.length == 0 && this.notSelectors.length === 0;
}
hasElementSelector() {
return !!this.element;
}
setElement(element2 = null) {
this.element = element2;
}
getAttrs() {
const result = [];
if (this.classNames.length > 0) {
result.push("class", this.classNames.join(" "));
}
return result.concat(this.attrs);
}
addAttribute(name, value = "") {
this.attrs.push(name, value && value.toLowerCase() || "");
}
addClassName(name) {
this.classNames.push(name.toLowerCase());
}
toString() {
let res = this.element || "";
if (this.classNames) {
this.classNames.forEach((klass) => res += `.${klass}`);
}
if (this.attrs) {
for (let i = 0; i < this.attrs.length; i += 2) {
const name = this.escapeAttribute(this.attrs[i]);
const value = this.attrs[i + 1];
res += `[${name}${value ? "=" + value : ""}]`;
}
}
this.notSelectors.forEach((notSelector) => res += `:not(${notSelector})`);
return res;
}
};
var SelectorMatcher = class {
constructor() {
this._elementMap = /* @__PURE__ */ new Map();
this._elementPartialMap = /* @__PURE__ */ new Map();
this._classMap = /* @__PURE__ */ new Map();
this._classPartialMap = /* @__PURE__ */ new Map();
this._attrValueMap = /* @__PURE__ */ new Map();
this._attrValuePartialMap = /* @__PURE__ */ new Map();
this._listContexts = [];
}
static createNotMatcher(notSelectors) {
const notMatcher = new SelectorMatcher();
notMatcher.addSelectables(notSelectors, null);
return notMatcher;
}
addSelectables(cssSelectors, callbackCtxt) {
let listContext = null;
if (cssSelectors.length > 1) {
listContext = new SelectorListContext(cssSelectors);
this._listContexts.push(listContext);
}
for (let i = 0; i < cssSelectors.length; i++) {
this._addSelectable(cssSelectors[i], callbackCtxt, listContext);
}
}
_addSelectable(cssSelector, callbackCtxt, listContext) {
let matcher = this;
const element2 = cssSelector.element;
const classNames = cssSelector.classNames;
const attrs = cssSelector.attrs;
const selectable = new SelectorContext(cssSelector, callbackCtxt, listContext);
if (element2) {
const isTerminal = attrs.length === 0 && classNames.length === 0;
if (isTerminal) {
this._addTerminal(matcher._elementMap, element2, selectable);
} else {
matcher = this._addPartial(matcher._elementPartialMap, element2);
}
}
if (classNames) {
for (let i = 0; i < classNames.length; i++) {
const isTerminal = attrs.length === 0 && i === classNames.length - 1;
const className = classNames[i];
if (isTerminal) {
this._addTerminal(matcher._classMap, className, selectable);
} else {
matcher = this._addPartial(matcher._classPartialMap, className);
}
}
}
if (attrs) {
for (let i = 0; i < attrs.length; i += 2) {
const isTerminal = i === attrs.length - 2;
const name = attrs[i];
const value = attrs[i + 1];
if (isTerminal) {
const terminalMap = matcher._attrValueMap;
let terminalValuesMap = terminalMap.get(name);
if (!terminalValuesMap) {
terminalValuesMap = /* @__PURE__ */ new Map();
terminalMap.set(name, terminalValuesMap);
}
this._addTerminal(terminalValuesMap, value, selectable);
} else {
const partialMap = matcher._attrValuePartialMap;
let partialValuesMap = partialMap.get(name);
if (!partialValuesMap) {
partialValuesMap = /* @__PURE__ */ new Map();
partialMap.set(name, partialValuesMap);
}
matcher = this._addPartial(partialValuesMap, value);
}
}
}
}
_addTerminal(map, name, selectable) {
let terminalList = map.get(name);
if (!terminalList) {
terminalList = [];
map.set(name, terminalList);
}
terminalList.push(selectable);
}
_addPartial(map, name) {
let matcher = map.get(name);
if (!matcher) {
matcher = new SelectorMatcher();
map.set(name, matcher);
}
return matcher;
}
match(cssSelector, matchedCallback) {
let result = false;
const element2 = cssSelector.element;
const classNames = cssSelector.classNames;
const attrs = cssSelector.attrs;
for (let i = 0; i < this._listContexts.length; i++) {
this._listContexts[i].alreadyMatched = false;
}
result = this._matchTerminal(this._elementMap, element2, cssSelector, matchedCallback) || result;
result = this._matchPartial(this._elementPartialMap, element2, cssSelector, matchedCallback) || result;
if (classNames) {
for (let i = 0; i < classNames.length; i++) {
const className = classNames[i];
result = this._matchTerminal(this._classMap, className, cssSelector, matchedCallback) || result;
result = this._matchPartial(this._classPartialMap, className, cssSelector, matchedCallback) || result;
}
}
if (attrs) {
for (let i = 0; i < attrs.length; i += 2) {
const name = attrs[i];
const value = attrs[i + 1];
const terminalValuesMap = this._attrValueMap.get(name);
if (value) {
result = this._matchTerminal(terminalValuesMap, "", cssSelector, matchedCallback) || result;
}
result = this._matchTerminal(terminalValuesMap, value, cssSelector, matchedCallback) || result;
const partialValuesMap = this._attrValuePartialMap.get(name);
if (value) {
result = this._matchPartial(partialValuesMap, "", cssSelector, matchedCallback) || result;
}
result = this._matchPartial(partialValuesMap, value, cssSelector, matchedCallback) || result;
}
}
return result;
}
_matchTerminal(map, name, cssSelector, matchedCallback) {
if (!map || typeof name !== "string") {
return false;
}
let selectables = map.get(name) || [];
const starSelectables = map.get("*");
if (starSelectables) {
selectables = selectables.concat(starSelectables);
}
if (selectables.length === 0) {
return false;
}
let selectable;
let result = false;
for (let i = 0; i < selectables.length; i++) {
selectable = selectables[i];
result = selectable.finalize(cssSelector, matchedCallback) || result;
}
return result;
}
_matchPartial(map, name, cssSelector, matchedCallback) {
if (!map || typeof name !== "string") {
return false;
}
const nestedSelector = map.get(name);
if (!nestedSelector) {
return false;
}
return nestedSelector.match(cssSelector, matchedCallback);
}
};
var SelectorListContext = class {
constructor(selectors) {
this.selectors = selectors;
this.alreadyMatched = false;
}
};
var SelectorContext = class {
constructor(selector, cbContext, listContext) {
this.selector = selector;
this.cbContext = cbContext;
this.listContext = listContext;
this.notSelectors = selector.notSelectors;
}
finalize(cssSelector, callback) {
let result = true;
if (this.notSelectors.length > 0 && (!this.listContext || !this.listContext.alreadyMatched)) {
const 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;
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/core.mjs
var emitDistinctChangesOnlyDefaultValue = true;
var ViewEncapsulation;
(function(ViewEncapsulation2) {
ViewEncapsulation2[ViewEncapsulation2["Emulated"] = 0] = "Emulated";
ViewEncapsulation2[ViewEncapsulation2["None"] = 2] = "None";
ViewEncapsulation2[ViewEncapsulation2["ShadowDom"] = 3] = "ShadowDom";
})(ViewEncapsulation || (ViewEncapsulation = {}));
var ChangeDetectionStrategy;
(function(ChangeDetectionStrategy2) {
ChangeDetectionStrategy2[ChangeDetectionStrategy2["OnPush"] = 0] = "OnPush";
ChangeDetectionStrategy2[ChangeDetectionStrategy2["Default"] = 1] = "Default";
})(ChangeDetectionStrategy || (ChangeDetectionStrategy = {}));
var InputFlags;
(function(InputFlags2) {
InputFlags2[InputFlags2["None"] = 0] = "None";
InputFlags2[InputFlags2["SignalBased"] = 1] = "SignalBased";
InputFlags2[InputFlags2["HasDecoratorInputTransform"] = 2] = "HasDecoratorInputTransform";
})(InputFlags || (InputFlags = {}));
var CUSTOM_ELEMENTS_SCHEMA = {
name: "custom-elements"
};
var NO_ERRORS_SCHEMA = {
name: "no-errors-schema"
};
var SecurityContext;
(function(SecurityContext2) {
SecurityContext2[SecurityContext2["NONE"] = 0] = "NONE";
SecurityContext2[SecurityContext2["HTML"] = 1] = "HTML";
SecurityContext2[SecurityContext2["STYLE"] = 2] = "STYLE";
SecurityContext2[SecurityContext2["SCRIPT"] = 3] = "SCRIPT";
SecurityContext2[SecurityContext2["URL"] = 4] = "URL";
SecurityContext2[SecurityContext2["RESOURCE_URL"] = 5] = "RESOURCE_URL";
})(SecurityContext || (SecurityContext = {}));
var MissingTranslationStrategy;
(function(MissingTranslationStrategy2) {
MissingTranslationStrategy2[MissingTranslationStrategy2["Error"] = 0] = "Error";
MissingTranslationStrategy2[MissingTranslationStrategy2["Warning"] = 1] = "Warning";
MissingTranslationStrategy2[MissingTranslationStrategy2["Ignore"] = 2] = "Ignore";
})(MissingTranslationStrategy || (MissingTranslationStrategy = {}));
function parserSelectorToSimpleSelector(selector) {
const classes = selector.classNames && selector.classNames.length ? [8, ...selector.classNames] : [];
const elementName = selector.element && selector.element !== "*" ? selector.element : "";
return [elementName, ...selector.attrs, ...classes];
}
function parserSelectorToNegativeSelector(selector) {
const classes = selector.classNames && selector.classNames.length ? [8, ...selector.classNames] : [];
if (selector.element) {
return [
1 | 4,
selector.element,
...selector.attrs,
...classes
];
} else if (selector.attrs.length) {
return [1 | 2, ...selector.attrs, ...classes];
} else {
return selector.classNames && selector.classNames.length ? [1 | 8, ...selector.classNames] : [];
}
}
function parserSelectorToR3Selector(selector) {
const positive = parserSelectorToSimpleSelector(selector);
const negative = selector.notSelectors && selector.notSelectors.length ? selector.notSelectors.map((notSelector) => parserSelectorToNegativeSelector(notSelector)) : [];
return positive.concat(...negative);
}
function parseSelectorToR3Selector(selector) {
return selector ? CssSelector.parse(selector).map(parserSelectorToR3Selector) : [];
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/output/output_ast.mjs
var output_ast_exports = {};
__export(output_ast_exports, {
ArrayType: () => ArrayType,
ArrowFunctionExpr: () => ArrowFunctionExpr,
BOOL_TYPE: () => BOOL_TYPE,
BinaryOperator: () => BinaryOperator,
BinaryOperatorExpr: () => BinaryOperatorExpr,
BuiltinType: () => BuiltinType,
BuiltinTypeName: () => BuiltinTypeName,
CommaExpr: () => CommaExpr,
ConditionalExpr: () => ConditionalExpr,
DYNAMIC_TYPE: () => DYNAMIC_TYPE,
DeclareFunctionStmt: () => DeclareFunctionStmt,
DeclareVarStmt: () => DeclareVarStmt,
DynamicImportExpr: () => DynamicImportExpr,
Expression: () => Expression,
ExpressionStatement: () => ExpressionStatement,
ExpressionType: () => ExpressionType,
ExternalExpr: () => ExternalExpr,
ExternalReference: () => ExternalReference,
FUNCTION_TYPE: () => FUNCTION_TYPE,
FnParam: () => FnParam,
FunctionExpr: () => FunctionExpr,
INFERRED_TYPE: () => INFERRED_TYPE,
INT_TYPE: () => INT_TYPE,
IfStmt: () => IfStmt,
InstantiateExpr: () => InstantiateExpr,
InvokeFunctionExpr: () => InvokeFunctionExpr,
JSDocComment: () => JSDocComment,
LeadingComment: () => LeadingComment,
LiteralArrayExpr: () => LiteralArrayExpr,
LiteralExpr: () => LiteralExpr,
LiteralMapEntry: () => LiteralMapEntry,
LiteralMapExpr: () => LiteralMapExpr,
LiteralPiece: () => LiteralPiece,
LocalizedString: () => LocalizedString,
MapType: () => MapType,
NONE_TYPE: () => NONE_TYPE,
NULL_EXPR: () => NULL_EXPR,
NUMBER_TYPE: () => NUMBER_TYPE,
NotExpr: () => NotExpr,
PlaceholderPiece: () => PlaceholderPiece,
ReadKeyExpr: () => ReadKeyExpr,
ReadPropExpr: () => ReadPropExpr,
ReadVarExpr: () => ReadVarExpr,
RecursiveAstVisitor: () => RecursiveAstVisitor,
ReturnStatement: () => ReturnStatement,
STRING_TYPE: () => STRING_TYPE,
Statement: () => Statement,
StmtModifier: () => StmtModifier,
TYPED_NULL_EXPR: () => TYPED_NULL_EXPR,
TaggedTemplateExpr: () => TaggedTemplateExpr,
TemplateLiteral: () => TemplateLiteral,
TemplateLiteralElement: () => TemplateLiteralElement,
TransplantedType: () => TransplantedType,
Type: () => Type,
TypeModifier: () => TypeModifier,
TypeofExpr: () => TypeofExpr,
UnaryOperator: () => UnaryOperator,
UnaryOperatorExpr: () => UnaryOperatorExpr,
WrappedNodeExpr: () => WrappedNodeExpr,
WriteKeyExpr: () => WriteKeyExpr,
WritePropExpr: () => WritePropExpr,
WriteVarExpr: () => WriteVarExpr,
areAllEquivalent: () => areAllEquivalent,
arrowFn: () => arrowFn,
expressionType: () => expressionType,
fn: () => fn,
ifStmt: () => ifStmt,
importExpr: () => importExpr,
importType: () => importType,
isNull: () => isNull,
jsDocComment: () => jsDocComment,
leadingComment: () => leadingComment,
literal: () => literal,
literalArr: () => literalArr,
literalMap: () => literalMap,
localizedString: () => localizedString,
not: () => not,
nullSafeIsEquivalent: () => nullSafeIsEquivalent,
taggedTemplate: () => taggedTemplate,
transplantedType: () => transplantedType,
typeofExpr: () => typeofExpr,
unary: () => unary,
variable: () => variable
});
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/i18n/digest.mjs
var textEncoder;
function digest(message) {
return message.id || computeDigest(message);
}
function computeDigest(message) {
return sha1(serializeNodes(message.nodes).join("") + `[${message.meaning}]`);
}
function decimalDigest(message, preservePlaceholders) {
return message.id || computeDecimalDigest(message, preservePlaceholders);
}
function computeDecimalDigest(message, preservePlaceholders) {
const visitor = new _SerializerIgnoreExpVisitor(preservePlaceholders);
const parts = message.nodes.map((a) => a.visit(visitor, null));
return computeMsgId(parts.join(""), message.meaning);
}
var _SerializerVisitor = class {
visitText(text2, context) {
return text2.value;
}
visitContainer(container, context) {
return `[${container.children.map((child) => child.visit(this)).join(", ")}]`;
}
visitIcu(icu, context) {
const strCases = Object.keys(icu.cases).map((k) => `${k} {${icu.cases[k].visit(this)}}`);
return `{${icu.expression}, ${icu.type}, ${strCases.join(", ")}}`;
}
visitTagPlaceholder(ph, context) {
return ph.isVoid ? ` ` : `${ph.children.map((child) => child.visit(this)).join(", ")} `;
}
visitPlaceholder(ph, context) {
return ph.value ? `${ph.value} ` : ` `;
}
visitIcuPlaceholder(ph, context) {
return `${ph.value.visit(this)} `;
}
visitBlockPlaceholder(ph, context) {
return `${ph.children.map((child) => child.visit(this)).join(", ")} `;
}
};
var serializerVisitor = new _SerializerVisitor();
function serializeNodes(nodes) {
return nodes.map((a) => a.visit(serializerVisitor, null));
}
var _SerializerIgnoreExpVisitor = class extends _SerializerVisitor {
constructor(preservePlaceholders) {
super();
this.preservePlaceholders = preservePlaceholders;
}
visitPlaceholder(ph, context) {
return this.preservePlaceholders ? super.visitPlaceholder(ph, context) : ` `;
}
visitIcu(icu) {
let strCases = Object.keys(icu.cases).map((k) => `${k} {${icu.cases[k].visit(this)}}`);
return `{${icu.type}, ${strCases.join(", ")}}`;
}
};
function sha1(str) {
textEncoder != null ? textEncoder : textEncoder = new TextEncoder();
const utf8 = [...textEncoder.encode(str)];
const words32 = bytesToWords32(utf8, Endian.Big);
const len = utf8.length * 8;
const w = new Uint32Array(80);
let a = 1732584193, b = 4023233417, c = 2562383102, d = 271733878, e = 3285377520;
words32[len >> 5] |= 128 << 24 - len % 32;
words32[(len + 64 >> 9 << 4) + 15] = len;
for (let i = 0; i < words32.length; i += 16) {
const h0 = a, h1 = b, h2 = c, h3 = d, h4 = e;
for (let 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);
}
const fkVal = fk(j, b, c, d);
const f = fkVal[0];
const k = fkVal[1];
const 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 toHexU32(a) + toHexU32(b) + toHexU32(c) + toHexU32(d) + toHexU32(e);
}
function toHexU32(value) {
return (value >>> 0).toString(16).padStart(8, "0");
}
function fk(index, b, c, d) {
if (index < 20) {
return [b & c | ~b & d, 1518500249];
}
if (index < 40) {
return [b ^ c ^ d, 1859775393];
}
if (index < 60) {
return [b & c | b & d | c & d, 2400959708];
}
return [b ^ c ^ d, 3395469782];
}
function fingerprint(str) {
textEncoder != null ? textEncoder : textEncoder = new TextEncoder();
const utf8 = textEncoder.encode(str);
const view = new DataView(utf8.buffer, utf8.byteOffset, utf8.byteLength);
let hi = hash32(view, utf8.length, 0);
let lo = hash32(view, utf8.length, 102072);
if (hi == 0 && (lo == 0 || lo == 1)) {
hi = hi ^ 319790063;
lo = lo ^ -1801410264;
}
return BigInt.asUintN(32, BigInt(hi)) << BigInt(32) | BigInt.asUintN(32, BigInt(lo));
}
function computeMsgId(msg, meaning = "") {
let msgFingerprint = fingerprint(msg);
if (meaning) {
msgFingerprint = BigInt.asUintN(64, msgFingerprint << BigInt(1)) | msgFingerprint >> BigInt(63) & BigInt(1);
msgFingerprint += fingerprint(meaning);
}
return BigInt.asUintN(63, msgFingerprint).toString();
}
function hash32(view, length, c) {
let a = 2654435769, b = 2654435769;
let index = 0;
const end = length - 12;
for (; index <= end; index += 12) {
a += view.getUint32(index, true);
b += view.getUint32(index + 4, true);
c += view.getUint32(index + 8, true);
const res = mix(a, b, c);
a = res[0], b = res[1], c = res[2];
}
const remainder = length - index;
c += length;
if (remainder >= 4) {
a += view.getUint32(index, true);
index += 4;
if (remainder >= 8) {
b += view.getUint32(index, true);
index += 4;
if (remainder >= 9) {
c += view.getUint8(index++) << 8;
}
if (remainder >= 10) {
c += view.getUint8(index++) << 16;
}
if (remainder === 11) {
c += view.getUint8(index++) << 24;
}
} else {
if (remainder >= 5) {
b += view.getUint8(index++);
}
if (remainder >= 6) {
b += view.getUint8(index++) << 8;
}
if (remainder === 7) {
b += view.getUint8(index++) << 16;
}
}
} else {
if (remainder >= 1) {
a += view.getUint8(index++);
}
if (remainder >= 2) {
a += view.getUint8(index++) << 8;
}
if (remainder === 3) {
a += view.getUint8(index++) << 16;
}
}
return mix(a, b, c)[2];
}
function mix(a, b, c) {
a -= b;
a -= c;
a ^= c >>> 13;
b -= c;
b -= a;
b ^= a << 8;
c -= a;
c -= b;
c ^= b >>> 13;
a -= b;
a -= c;
a ^= c >>> 12;
b -= c;
b -= a;
b ^= a << 16;
c -= a;
c -= b;
c ^= b >>> 5;
a -= b;
a -= c;
a ^= c >>> 3;
b -= c;
b -= a;
b ^= a << 10;
c -= a;
c -= b;
c ^= b >>> 15;
return [a, b, c];
}
var Endian;
(function(Endian2) {
Endian2[Endian2["Little"] = 0] = "Little";
Endian2[Endian2["Big"] = 1] = "Big";
})(Endian || (Endian = {}));
function add32(a, b) {
return add32to64(a, b)[1];
}
function add32to64(a, b) {
const low = (a & 65535) + (b & 65535);
const high = (a >>> 16) + (b >>> 16) + (low >>> 16);
return [high >>> 16, high << 16 | low & 65535];
}
function rol32(a, count) {
return a << count | a >>> 32 - count;
}
function bytesToWords32(bytes, endian) {
const size = bytes.length + 3 >>> 2;
const words32 = [];
for (let i = 0; i < size; i++) {
words32[i] = wordAt(bytes, i * 4, endian);
}
return words32;
}
function byteAt(bytes, index) {
return index >= bytes.length ? 0 : bytes[index];
}
function wordAt(bytes, index, endian) {
let word = 0;
if (endian === Endian.Big) {
for (let i = 0; i < 4; i++) {
word += byteAt(bytes, index + i) << 24 - 8 * i;
}
} else {
for (let i = 0; i < 4; i++) {
word += byteAt(bytes, index + i) << 8 * i;
}
}
return word;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/output/output_ast.mjs
var TypeModifier;
(function(TypeModifier2) {
TypeModifier2[TypeModifier2["None"] = 0] = "None";
TypeModifier2[TypeModifier2["Const"] = 1] = "Const";
})(TypeModifier || (TypeModifier = {}));
var Type = class {
constructor(modifiers = TypeModifier.None) {
this.modifiers = modifiers;
}
hasModifier(modifier) {
return (this.modifiers & modifier) !== 0;
}
};
var BuiltinTypeName;
(function(BuiltinTypeName2) {
BuiltinTypeName2[BuiltinTypeName2["Dynamic"] = 0] = "Dynamic";
BuiltinTypeName2[BuiltinTypeName2["Bool"] = 1] = "Bool";
BuiltinTypeName2[BuiltinTypeName2["String"] = 2] = "String";
BuiltinTypeName2[BuiltinTypeName2["Int"] = 3] = "Int";
BuiltinTypeName2[BuiltinTypeName2["Number"] = 4] = "Number";
BuiltinTypeName2[BuiltinTypeName2["Function"] = 5] = "Function";
BuiltinTypeName2[BuiltinTypeName2["Inferred"] = 6] = "Inferred";
BuiltinTypeName2[BuiltinTypeName2["None"] = 7] = "None";
})(BuiltinTypeName || (BuiltinTypeName = {}));
var BuiltinType = class extends Type {
constructor(name, modifiers) {
super(modifiers);
this.name = name;
}
visitType(visitor, context) {
return visitor.visitBuiltinType(this, context);
}
};
var ExpressionType = class extends Type {
constructor(value, modifiers, typeParams = null) {
super(modifiers);
this.value = value;
this.typeParams = typeParams;
}
visitType(visitor, context) {
return visitor.visitExpressionType(this, context);
}
};
var ArrayType = class extends Type {
constructor(of, modifiers) {
super(modifiers);
this.of = of;
}
visitType(visitor, context) {
return visitor.visitArrayType(this, context);
}
};
var MapType = class extends Type {
constructor(valueType, modifiers) {
super(modifiers);
this.valueType = valueType || null;
}
visitType(visitor, context) {
return visitor.visitMapType(this, context);
}
};
var TransplantedType = class extends Type {
constructor(type, modifiers) {
super(modifiers);
this.type = type;
}
visitType(visitor, context) {
return visitor.visitTransplantedType(this, context);
}
};
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);
var UnaryOperator;
(function(UnaryOperator2) {
UnaryOperator2[UnaryOperator2["Minus"] = 0] = "Minus";
UnaryOperator2[UnaryOperator2["Plus"] = 1] = "Plus";
})(UnaryOperator || (UnaryOperator = {}));
var BinaryOperator;
(function(BinaryOperator2) {
BinaryOperator2[BinaryOperator2["Equals"] = 0] = "Equals";
BinaryOperator2[BinaryOperator2["NotEquals"] = 1] = "NotEquals";
BinaryOperator2[BinaryOperator2["Identical"] = 2] = "Identical";
BinaryOperator2[BinaryOperator2["NotIdentical"] = 3] = "NotIdentical";
BinaryOperator2[BinaryOperator2["Minus"] = 4] = "Minus";
BinaryOperator2[BinaryOperator2["Plus"] = 5] = "Plus";
BinaryOperator2[BinaryOperator2["Divide"] = 6] = "Divide";
BinaryOperator2[BinaryOperator2["Multiply"] = 7] = "Multiply";
BinaryOperator2[BinaryOperator2["Modulo"] = 8] = "Modulo";
BinaryOperator2[BinaryOperator2["And"] = 9] = "And";
BinaryOperator2[BinaryOperator2["Or"] = 10] = "Or";
BinaryOperator2[BinaryOperator2["BitwiseOr"] = 11] = "BitwiseOr";
BinaryOperator2[BinaryOperator2["BitwiseAnd"] = 12] = "BitwiseAnd";
BinaryOperator2[BinaryOperator2["Lower"] = 13] = "Lower";
BinaryOperator2[BinaryOperator2["LowerEquals"] = 14] = "LowerEquals";
BinaryOperator2[BinaryOperator2["Bigger"] = 15] = "Bigger";
BinaryOperator2[BinaryOperator2["BiggerEquals"] = 16] = "BiggerEquals";
BinaryOperator2[BinaryOperator2["NullishCoalesce"] = 17] = "NullishCoalesce";
})(BinaryOperator || (BinaryOperator = {}));
function nullSafeIsEquivalent(base, other) {
if (base == null || other == null) {
return base == other;
}
return base.isEquivalent(other);
}
function areAllEquivalentPredicate(base, other, equivalentPredicate) {
const len = base.length;
if (len !== other.length) {
return false;
}
for (let i = 0; i < len; i++) {
if (!equivalentPredicate(base[i], other[i])) {
return false;
}
}
return true;
}
function areAllEquivalent(base, other) {
return areAllEquivalentPredicate(base, other, (baseElement, otherElement) => baseElement.isEquivalent(otherElement));
}
var Expression = class {
constructor(type, sourceSpan) {
this.type = type || null;
this.sourceSpan = sourceSpan || null;
}
prop(name, sourceSpan) {
return new ReadPropExpr(this, name, null, sourceSpan);
}
key(index, type, sourceSpan) {
return new ReadKeyExpr(this, index, type, sourceSpan);
}
callFn(params, sourceSpan, pure) {
return new InvokeFunctionExpr(this, params, null, sourceSpan, pure);
}
instantiate(params, type, sourceSpan) {
return new InstantiateExpr(this, params, type, sourceSpan);
}
conditional(trueCase, falseCase = null, sourceSpan) {
return new ConditionalExpr(this, trueCase, falseCase, null, sourceSpan);
}
equals(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Equals, this, rhs, null, sourceSpan);
}
notEquals(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.NotEquals, this, rhs, null, sourceSpan);
}
identical(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Identical, this, rhs, null, sourceSpan);
}
notIdentical(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.NotIdentical, this, rhs, null, sourceSpan);
}
minus(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Minus, this, rhs, null, sourceSpan);
}
plus(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Plus, this, rhs, null, sourceSpan);
}
divide(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Divide, this, rhs, null, sourceSpan);
}
multiply(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Multiply, this, rhs, null, sourceSpan);
}
modulo(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Modulo, this, rhs, null, sourceSpan);
}
and(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.And, this, rhs, null, sourceSpan);
}
bitwiseOr(rhs, sourceSpan, parens = true) {
return new BinaryOperatorExpr(BinaryOperator.BitwiseOr, this, rhs, null, sourceSpan, parens);
}
bitwiseAnd(rhs, sourceSpan, parens = true) {
return new BinaryOperatorExpr(BinaryOperator.BitwiseAnd, this, rhs, null, sourceSpan, parens);
}
or(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Or, this, rhs, null, sourceSpan);
}
lower(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Lower, this, rhs, null, sourceSpan);
}
lowerEquals(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.LowerEquals, this, rhs, null, sourceSpan);
}
bigger(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Bigger, this, rhs, null, sourceSpan);
}
biggerEquals(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.BiggerEquals, this, rhs, null, sourceSpan);
}
isBlank(sourceSpan) {
return this.equals(TYPED_NULL_EXPR, sourceSpan);
}
nullishCoalesce(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.NullishCoalesce, this, rhs, null, sourceSpan);
}
toStmt() {
return new ExpressionStatement(this, null);
}
};
var ReadVarExpr = class extends Expression {
constructor(name, type, sourceSpan) {
super(type, sourceSpan);
this.name = name;
}
isEquivalent(e) {
return e instanceof ReadVarExpr && this.name === e.name;
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitReadVarExpr(this, context);
}
clone() {
return new ReadVarExpr(this.name, this.type, this.sourceSpan);
}
set(value) {
return new WriteVarExpr(this.name, value, null, this.sourceSpan);
}
};
var TypeofExpr = class extends Expression {
constructor(expr, type, sourceSpan) {
super(type, sourceSpan);
this.expr = expr;
}
visitExpression(visitor, context) {
return visitor.visitTypeofExpr(this, context);
}
isEquivalent(e) {
return e instanceof TypeofExpr && e.expr.isEquivalent(this.expr);
}
isConstant() {
return this.expr.isConstant();
}
clone() {
return new TypeofExpr(this.expr.clone());
}
};
var WrappedNodeExpr = class extends Expression {
constructor(node, type, sourceSpan) {
super(type, sourceSpan);
this.node = node;
}
isEquivalent(e) {
return e instanceof WrappedNodeExpr && this.node === e.node;
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitWrappedNodeExpr(this, context);
}
clone() {
return new WrappedNodeExpr(this.node, this.type, this.sourceSpan);
}
};
var WriteVarExpr = class extends Expression {
constructor(name, value, type, sourceSpan) {
super(type || value.type, sourceSpan);
this.name = name;
this.value = value;
}
isEquivalent(e) {
return e instanceof WriteVarExpr && this.name === e.name && this.value.isEquivalent(e.value);
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitWriteVarExpr(this, context);
}
clone() {
return new WriteVarExpr(this.name, this.value.clone(), this.type, this.sourceSpan);
}
toDeclStmt(type, modifiers) {
return new DeclareVarStmt(this.name, this.value, type, modifiers, this.sourceSpan);
}
toConstDecl() {
return this.toDeclStmt(INFERRED_TYPE, StmtModifier.Final);
}
};
var WriteKeyExpr = class extends Expression {
constructor(receiver, index, value, type, sourceSpan) {
super(type || value.type, sourceSpan);
this.receiver = receiver;
this.index = index;
this.value = value;
}
isEquivalent(e) {
return e instanceof WriteKeyExpr && this.receiver.isEquivalent(e.receiver) && this.index.isEquivalent(e.index) && this.value.isEquivalent(e.value);
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitWriteKeyExpr(this, context);
}
clone() {
return new WriteKeyExpr(this.receiver.clone(), this.index.clone(), this.value.clone(), this.type, this.sourceSpan);
}
};
var WritePropExpr = class extends Expression {
constructor(receiver, name, value, type, sourceSpan) {
super(type || value.type, sourceSpan);
this.receiver = receiver;
this.name = name;
this.value = value;
}
isEquivalent(e) {
return e instanceof WritePropExpr && this.receiver.isEquivalent(e.receiver) && this.name === e.name && this.value.isEquivalent(e.value);
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitWritePropExpr(this, context);
}
clone() {
return new WritePropExpr(this.receiver.clone(), this.name, this.value.clone(), this.type, this.sourceSpan);
}
};
var InvokeFunctionExpr = class extends Expression {
constructor(fn2, args, type, sourceSpan, pure = false) {
super(type, sourceSpan);
this.fn = fn2;
this.args = args;
this.pure = pure;
}
get receiver() {
return this.fn;
}
isEquivalent(e) {
return e instanceof InvokeFunctionExpr && this.fn.isEquivalent(e.fn) && areAllEquivalent(this.args, e.args) && this.pure === e.pure;
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitInvokeFunctionExpr(this, context);
}
clone() {
return new InvokeFunctionExpr(this.fn.clone(), this.args.map((arg) => arg.clone()), this.type, this.sourceSpan, this.pure);
}
};
var TaggedTemplateExpr = class extends Expression {
constructor(tag, template2, type, sourceSpan) {
super(type, sourceSpan);
this.tag = tag;
this.template = template2;
}
isEquivalent(e) {
return e instanceof TaggedTemplateExpr && this.tag.isEquivalent(e.tag) && areAllEquivalentPredicate(this.template.elements, e.template.elements, (a, b) => a.text === b.text) && areAllEquivalent(this.template.expressions, e.template.expressions);
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitTaggedTemplateExpr(this, context);
}
clone() {
return new TaggedTemplateExpr(this.tag.clone(), this.template.clone(), this.type, this.sourceSpan);
}
};
var InstantiateExpr = class extends Expression {
constructor(classExpr, args, type, sourceSpan) {
super(type, sourceSpan);
this.classExpr = classExpr;
this.args = args;
}
isEquivalent(e) {
return e instanceof InstantiateExpr && this.classExpr.isEquivalent(e.classExpr) && areAllEquivalent(this.args, e.args);
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitInstantiateExpr(this, context);
}
clone() {
return new InstantiateExpr(this.classExpr.clone(), this.args.map((arg) => arg.clone()), this.type, this.sourceSpan);
}
};
var LiteralExpr = class extends Expression {
constructor(value, type, sourceSpan) {
super(type, sourceSpan);
this.value = value;
}
isEquivalent(e) {
return e instanceof LiteralExpr && this.value === e.value;
}
isConstant() {
return true;
}
visitExpression(visitor, context) {
return visitor.visitLiteralExpr(this, context);
}
clone() {
return new LiteralExpr(this.value, this.type, this.sourceSpan);
}
};
var TemplateLiteral = class {
constructor(elements, expressions) {
this.elements = elements;
this.expressions = expressions;
}
clone() {
return new TemplateLiteral(this.elements.map((el) => el.clone()), this.expressions.map((expr) => expr.clone()));
}
};
var TemplateLiteralElement = class {
constructor(text2, sourceSpan, rawText) {
var _a2;
this.text = text2;
this.sourceSpan = sourceSpan;
this.rawText = (_a2 = rawText != null ? rawText : sourceSpan == null ? void 0 : sourceSpan.toString()) != null ? _a2 : escapeForTemplateLiteral(escapeSlashes(text2));
}
clone() {
return new TemplateLiteralElement(this.text, this.sourceSpan, this.rawText);
}
};
var LiteralPiece = class {
constructor(text2, sourceSpan) {
this.text = text2;
this.sourceSpan = sourceSpan;
}
};
var PlaceholderPiece = class {
constructor(text2, sourceSpan, associatedMessage) {
this.text = text2;
this.sourceSpan = sourceSpan;
this.associatedMessage = associatedMessage;
}
};
var MEANING_SEPARATOR = "|";
var ID_SEPARATOR = "@@";
var LEGACY_ID_INDICATOR = "\u241F";
var LocalizedString = class extends Expression {
constructor(metaBlock, messageParts, placeHolderNames, expressions, sourceSpan) {
super(STRING_TYPE, sourceSpan);
this.metaBlock = metaBlock;
this.messageParts = messageParts;
this.placeHolderNames = placeHolderNames;
this.expressions = expressions;
}
isEquivalent(e) {
return false;
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitLocalizedString(this, context);
}
clone() {
return new LocalizedString(this.metaBlock, this.messageParts, this.placeHolderNames, this.expressions.map((expr) => expr.clone()), this.sourceSpan);
}
serializeI18nHead() {
let 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((legacyId) => {
metaBlock = `${metaBlock}${LEGACY_ID_INDICATOR}${legacyId}`;
});
}
return createCookedRawString(metaBlock, this.messageParts[0].text, this.getMessagePartSourceSpan(0));
}
getMessagePartSourceSpan(i) {
var _a2, _b2;
return (_b2 = (_a2 = this.messageParts[i]) == null ? void 0 : _a2.sourceSpan) != null ? _b2 : this.sourceSpan;
}
getPlaceholderSourceSpan(i) {
var _a2, _b2, _c2, _d2;
return (_d2 = (_c2 = (_a2 = this.placeHolderNames[i]) == null ? void 0 : _a2.sourceSpan) != null ? _c2 : (_b2 = this.expressions[i]) == null ? void 0 : _b2.sourceSpan) != null ? _d2 : this.sourceSpan;
}
serializeI18nTemplatePart(partIndex) {
var _a2;
const placeholder = this.placeHolderNames[partIndex - 1];
const messagePart = this.messageParts[partIndex];
let metaBlock = placeholder.text;
if (((_a2 = placeholder.associatedMessage) == null ? void 0 : _a2.legacyIds.length) === 0) {
metaBlock += `${ID_SEPARATOR}${computeMsgId(placeholder.associatedMessage.messageString, placeholder.associatedMessage.meaning)}`;
}
return createCookedRawString(metaBlock, messagePart.text, this.getMessagePartSourceSpan(partIndex));
}
};
var escapeSlashes = (str) => str.replace(/\\/g, "\\\\");
var escapeStartingColon = (str) => str.replace(/^:/, "\\:");
var escapeColons = (str) => str.replace(/:/g, "\\:");
var escapeForTemplateLiteral = (str) => str.replace(/`/g, "\\`").replace(/\${/g, "$\\{");
function createCookedRawString(metaBlock, messagePart, range) {
if (metaBlock === "") {
return {
cooked: messagePart,
raw: escapeForTemplateLiteral(escapeStartingColon(escapeSlashes(messagePart))),
range
};
} else {
return {
cooked: `:${metaBlock}:${messagePart}`,
raw: escapeForTemplateLiteral(`:${escapeColons(escapeSlashes(metaBlock))}:${escapeSlashes(messagePart)}`),
range
};
}
}
var ExternalExpr = class extends Expression {
constructor(value, type, typeParams = null, sourceSpan) {
super(type, sourceSpan);
this.value = value;
this.typeParams = typeParams;
}
isEquivalent(e) {
return e instanceof ExternalExpr && this.value.name === e.value.name && this.value.moduleName === e.value.moduleName && this.value.runtime === e.value.runtime;
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitExternalExpr(this, context);
}
clone() {
return new ExternalExpr(this.value, this.type, this.typeParams, this.sourceSpan);
}
};
var ExternalReference = class {
constructor(moduleName, name, runtime) {
this.moduleName = moduleName;
this.name = name;
this.runtime = runtime;
}
};
var ConditionalExpr = class extends Expression {
constructor(condition, trueCase, falseCase = null, type, sourceSpan) {
super(type || trueCase.type, sourceSpan);
this.condition = condition;
this.falseCase = falseCase;
this.trueCase = trueCase;
}
isEquivalent(e) {
return e instanceof ConditionalExpr && this.condition.isEquivalent(e.condition) && this.trueCase.isEquivalent(e.trueCase) && nullSafeIsEquivalent(this.falseCase, e.falseCase);
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitConditionalExpr(this, context);
}
clone() {
var _a2;
return new ConditionalExpr(this.condition.clone(), this.trueCase.clone(), (_a2 = this.falseCase) == null ? void 0 : _a2.clone(), this.type, this.sourceSpan);
}
};
var DynamicImportExpr = class extends Expression {
constructor(url, sourceSpan) {
super(null, sourceSpan);
this.url = url;
}
isEquivalent(e) {
return e instanceof DynamicImportExpr && this.url === e.url;
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitDynamicImportExpr(this, context);
}
clone() {
return new DynamicImportExpr(this.url, this.sourceSpan);
}
};
var NotExpr = class extends Expression {
constructor(condition, sourceSpan) {
super(BOOL_TYPE, sourceSpan);
this.condition = condition;
}
isEquivalent(e) {
return e instanceof NotExpr && this.condition.isEquivalent(e.condition);
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitNotExpr(this, context);
}
clone() {
return new NotExpr(this.condition.clone(), this.sourceSpan);
}
};
var FnParam = class {
constructor(name, type = null) {
this.name = name;
this.type = type;
}
isEquivalent(param) {
return this.name === param.name;
}
clone() {
return new FnParam(this.name, this.type);
}
};
var FunctionExpr = class extends Expression {
constructor(params, statements, type, sourceSpan, name) {
super(type, sourceSpan);
this.params = params;
this.statements = statements;
this.name = name;
}
isEquivalent(e) {
return (e instanceof FunctionExpr || e instanceof DeclareFunctionStmt) && areAllEquivalent(this.params, e.params) && areAllEquivalent(this.statements, e.statements);
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitFunctionExpr(this, context);
}
toDeclStmt(name, modifiers) {
return new DeclareFunctionStmt(name, this.params, this.statements, this.type, modifiers, this.sourceSpan);
}
clone() {
return new FunctionExpr(this.params.map((p2) => p2.clone()), this.statements, this.type, this.sourceSpan, this.name);
}
};
var ArrowFunctionExpr = class extends Expression {
constructor(params, body, type, sourceSpan) {
super(type, sourceSpan);
this.params = params;
this.body = body;
}
isEquivalent(e) {
if (!(e instanceof ArrowFunctionExpr) || !areAllEquivalent(this.params, e.params)) {
return false;
}
if (this.body instanceof Expression && e.body instanceof Expression) {
return this.body.isEquivalent(e.body);
}
if (Array.isArray(this.body) && Array.isArray(e.body)) {
return areAllEquivalent(this.body, e.body);
}
return false;
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitArrowFunctionExpr(this, context);
}
clone() {
return new ArrowFunctionExpr(this.params.map((p2) => p2.clone()), Array.isArray(this.body) ? this.body : this.body.clone(), this.type, this.sourceSpan);
}
toDeclStmt(name, modifiers) {
return new DeclareVarStmt(name, this, INFERRED_TYPE, modifiers, this.sourceSpan);
}
};
var UnaryOperatorExpr = class extends Expression {
constructor(operator, expr, type, sourceSpan, parens = true) {
super(type || NUMBER_TYPE, sourceSpan);
this.operator = operator;
this.expr = expr;
this.parens = parens;
}
isEquivalent(e) {
return e instanceof UnaryOperatorExpr && this.operator === e.operator && this.expr.isEquivalent(e.expr);
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitUnaryOperatorExpr(this, context);
}
clone() {
return new UnaryOperatorExpr(this.operator, this.expr.clone(), this.type, this.sourceSpan, this.parens);
}
};
var BinaryOperatorExpr = class extends Expression {
constructor(operator, lhs, rhs, type, sourceSpan, parens = true) {
super(type || lhs.type, sourceSpan);
this.operator = operator;
this.rhs = rhs;
this.parens = parens;
this.lhs = lhs;
}
isEquivalent(e) {
return e instanceof BinaryOperatorExpr && this.operator === e.operator && this.lhs.isEquivalent(e.lhs) && this.rhs.isEquivalent(e.rhs);
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitBinaryOperatorExpr(this, context);
}
clone() {
return new BinaryOperatorExpr(this.operator, this.lhs.clone(), this.rhs.clone(), this.type, this.sourceSpan, this.parens);
}
};
var ReadPropExpr = class extends Expression {
constructor(receiver, name, type, sourceSpan) {
super(type, sourceSpan);
this.receiver = receiver;
this.name = name;
}
get index() {
return this.name;
}
isEquivalent(e) {
return e instanceof ReadPropExpr && this.receiver.isEquivalent(e.receiver) && this.name === e.name;
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitReadPropExpr(this, context);
}
set(value) {
return new WritePropExpr(this.receiver, this.name, value, null, this.sourceSpan);
}
clone() {
return new ReadPropExpr(this.receiver.clone(), this.name, this.type, this.sourceSpan);
}
};
var ReadKeyExpr = class extends Expression {
constructor(receiver, index, type, sourceSpan) {
super(type, sourceSpan);
this.receiver = receiver;
this.index = index;
}
isEquivalent(e) {
return e instanceof ReadKeyExpr && this.receiver.isEquivalent(e.receiver) && this.index.isEquivalent(e.index);
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitReadKeyExpr(this, context);
}
set(value) {
return new WriteKeyExpr(this.receiver, this.index, value, null, this.sourceSpan);
}
clone() {
return new ReadKeyExpr(this.receiver.clone(), this.index.clone(), this.type, this.sourceSpan);
}
};
var LiteralArrayExpr = class extends Expression {
constructor(entries, type, sourceSpan) {
super(type, sourceSpan);
this.entries = entries;
}
isConstant() {
return this.entries.every((e) => e.isConstant());
}
isEquivalent(e) {
return e instanceof LiteralArrayExpr && areAllEquivalent(this.entries, e.entries);
}
visitExpression(visitor, context) {
return visitor.visitLiteralArrayExpr(this, context);
}
clone() {
return new LiteralArrayExpr(this.entries.map((e) => e.clone()), this.type, this.sourceSpan);
}
};
var LiteralMapEntry = class {
constructor(key, value, quoted) {
this.key = key;
this.value = value;
this.quoted = quoted;
}
isEquivalent(e) {
return this.key === e.key && this.value.isEquivalent(e.value);
}
clone() {
return new LiteralMapEntry(this.key, this.value.clone(), this.quoted);
}
};
var LiteralMapExpr = class extends Expression {
constructor(entries, type, sourceSpan) {
super(type, sourceSpan);
this.entries = entries;
this.valueType = null;
if (type) {
this.valueType = type.valueType;
}
}
isEquivalent(e) {
return e instanceof LiteralMapExpr && areAllEquivalent(this.entries, e.entries);
}
isConstant() {
return this.entries.every((e) => e.value.isConstant());
}
visitExpression(visitor, context) {
return visitor.visitLiteralMapExpr(this, context);
}
clone() {
const entriesClone = this.entries.map((entry) => entry.clone());
return new LiteralMapExpr(entriesClone, this.type, this.sourceSpan);
}
};
var CommaExpr = class extends Expression {
constructor(parts, sourceSpan) {
super(parts[parts.length - 1].type, sourceSpan);
this.parts = parts;
}
isEquivalent(e) {
return e instanceof CommaExpr && areAllEquivalent(this.parts, e.parts);
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitCommaExpr(this, context);
}
clone() {
return new CommaExpr(this.parts.map((p2) => p2.clone()));
}
};
var NULL_EXPR = new LiteralExpr(null, null, null);
var TYPED_NULL_EXPR = new LiteralExpr(null, INFERRED_TYPE, null);
var StmtModifier;
(function(StmtModifier2) {
StmtModifier2[StmtModifier2["None"] = 0] = "None";
StmtModifier2[StmtModifier2["Final"] = 1] = "Final";
StmtModifier2[StmtModifier2["Private"] = 2] = "Private";
StmtModifier2[StmtModifier2["Exported"] = 4] = "Exported";
StmtModifier2[StmtModifier2["Static"] = 8] = "Static";
})(StmtModifier || (StmtModifier = {}));
var LeadingComment = class {
constructor(text2, multiline, trailingNewline) {
this.text = text2;
this.multiline = multiline;
this.trailingNewline = trailingNewline;
}
toString() {
return this.multiline ? ` ${this.text} ` : this.text;
}
};
var JSDocComment = class extends LeadingComment {
constructor(tags) {
super("", true, true);
this.tags = tags;
}
toString() {
return serializeTags(this.tags);
}
};
var Statement = class {
constructor(modifiers = StmtModifier.None, sourceSpan = null, leadingComments) {
this.modifiers = modifiers;
this.sourceSpan = sourceSpan;
this.leadingComments = leadingComments;
}
hasModifier(modifier) {
return (this.modifiers & modifier) !== 0;
}
addLeadingComment(leadingComment2) {
var _a2;
this.leadingComments = (_a2 = this.leadingComments) != null ? _a2 : [];
this.leadingComments.push(leadingComment2);
}
};
var DeclareVarStmt = class extends Statement {
constructor(name, value, type, modifiers, sourceSpan, leadingComments) {
super(modifiers, sourceSpan, leadingComments);
this.name = name;
this.value = value;
this.type = type || value && value.type || null;
}
isEquivalent(stmt) {
return stmt instanceof DeclareVarStmt && this.name === stmt.name && (this.value ? !!stmt.value && this.value.isEquivalent(stmt.value) : !stmt.value);
}
visitStatement(visitor, context) {
return visitor.visitDeclareVarStmt(this, context);
}
};
var DeclareFunctionStmt = class extends Statement {
constructor(name, params, statements, type, modifiers, sourceSpan, leadingComments) {
super(modifiers, sourceSpan, leadingComments);
this.name = name;
this.params = params;
this.statements = statements;
this.type = type || null;
}
isEquivalent(stmt) {
return stmt instanceof DeclareFunctionStmt && areAllEquivalent(this.params, stmt.params) && areAllEquivalent(this.statements, stmt.statements);
}
visitStatement(visitor, context) {
return visitor.visitDeclareFunctionStmt(this, context);
}
};
var ExpressionStatement = class extends Statement {
constructor(expr, sourceSpan, leadingComments) {
super(StmtModifier.None, sourceSpan, leadingComments);
this.expr = expr;
}
isEquivalent(stmt) {
return stmt instanceof ExpressionStatement && this.expr.isEquivalent(stmt.expr);
}
visitStatement(visitor, context) {
return visitor.visitExpressionStmt(this, context);
}
};
var ReturnStatement = class extends Statement {
constructor(value, sourceSpan = null, leadingComments) {
super(StmtModifier.None, sourceSpan, leadingComments);
this.value = value;
}
isEquivalent(stmt) {
return stmt instanceof ReturnStatement && this.value.isEquivalent(stmt.value);
}
visitStatement(visitor, context) {
return visitor.visitReturnStmt(this, context);
}
};
var IfStmt = class extends Statement {
constructor(condition, trueCase, falseCase = [], sourceSpan, leadingComments) {
super(StmtModifier.None, sourceSpan, leadingComments);
this.condition = condition;
this.trueCase = trueCase;
this.falseCase = falseCase;
}
isEquivalent(stmt) {
return stmt instanceof IfStmt && this.condition.isEquivalent(stmt.condition) && areAllEquivalent(this.trueCase, stmt.trueCase) && areAllEquivalent(this.falseCase, stmt.falseCase);
}
visitStatement(visitor, context) {
return visitor.visitIfStmt(this, context);
}
};
var RecursiveAstVisitor = class {
visitType(ast, context) {
return ast;
}
visitExpression(ast, context) {
if (ast.type) {
ast.type.visitType(this, context);
}
return ast;
}
visitBuiltinType(type, context) {
return this.visitType(type, context);
}
visitExpressionType(type, context) {
type.value.visitExpression(this, context);
if (type.typeParams !== null) {
type.typeParams.forEach((param) => this.visitType(param, context));
}
return this.visitType(type, context);
}
visitArrayType(type, context) {
return this.visitType(type, context);
}
visitMapType(type, context) {
return this.visitType(type, context);
}
visitTransplantedType(type, context) {
return type;
}
visitWrappedNodeExpr(ast, context) {
return ast;
}
visitTypeofExpr(ast, context) {
return this.visitExpression(ast, context);
}
visitReadVarExpr(ast, context) {
return this.visitExpression(ast, context);
}
visitWriteVarExpr(ast, context) {
ast.value.visitExpression(this, context);
return this.visitExpression(ast, context);
}
visitWriteKeyExpr(ast, context) {
ast.receiver.visitExpression(this, context);
ast.index.visitExpression(this, context);
ast.value.visitExpression(this, context);
return this.visitExpression(ast, context);
}
visitWritePropExpr(ast, context) {
ast.receiver.visitExpression(this, context);
ast.value.visitExpression(this, context);
return this.visitExpression(ast, context);
}
visitDynamicImportExpr(ast, context) {
return this.visitExpression(ast, context);
}
visitInvokeFunctionExpr(ast, context) {
ast.fn.visitExpression(this, context);
this.visitAllExpressions(ast.args, context);
return this.visitExpression(ast, context);
}
visitTaggedTemplateExpr(ast, context) {
ast.tag.visitExpression(this, context);
this.visitAllExpressions(ast.template.expressions, context);
return this.visitExpression(ast, context);
}
visitInstantiateExpr(ast, context) {
ast.classExpr.visitExpression(this, context);
this.visitAllExpressions(ast.args, context);
return this.visitExpression(ast, context);
}
visitLiteralExpr(ast, context) {
return this.visitExpression(ast, context);
}
visitLocalizedString(ast, context) {
return this.visitExpression(ast, context);
}
visitExternalExpr(ast, context) {
if (ast.typeParams) {
ast.typeParams.forEach((type) => type.visitType(this, context));
}
return this.visitExpression(ast, context);
}
visitConditionalExpr(ast, context) {
ast.condition.visitExpression(this, context);
ast.trueCase.visitExpression(this, context);
ast.falseCase.visitExpression(this, context);
return this.visitExpression(ast, context);
}
visitNotExpr(ast, context) {
ast.condition.visitExpression(this, context);
return this.visitExpression(ast, context);
}
visitFunctionExpr(ast, context) {
this.visitAllStatements(ast.statements, context);
return this.visitExpression(ast, context);
}
visitArrowFunctionExpr(ast, context) {
if (Array.isArray(ast.body)) {
this.visitAllStatements(ast.body, context);
} else {
this.visitExpression(ast.body, context);
}
return this.visitExpression(ast, context);
}
visitUnaryOperatorExpr(ast, context) {
ast.expr.visitExpression(this, context);
return this.visitExpression(ast, context);
}
visitBinaryOperatorExpr(ast, context) {
ast.lhs.visitExpression(this, context);
ast.rhs.visitExpression(this, context);
return this.visitExpression(ast, context);
}
visitReadPropExpr(ast, context) {
ast.receiver.visitExpression(this, context);
return this.visitExpression(ast, context);
}
visitReadKeyExpr(ast, context) {
ast.receiver.visitExpression(this, context);
ast.index.visitExpression(this, context);
return this.visitExpression(ast, context);
}
visitLiteralArrayExpr(ast, context) {
this.visitAllExpressions(ast.entries, context);
return this.visitExpression(ast, context);
}
visitLiteralMapExpr(ast, context) {
ast.entries.forEach((entry) => entry.value.visitExpression(this, context));
return this.visitExpression(ast, context);
}
visitCommaExpr(ast, context) {
this.visitAllExpressions(ast.parts, context);
return this.visitExpression(ast, context);
}
visitAllExpressions(exprs, context) {
exprs.forEach((expr) => expr.visitExpression(this, context));
}
visitDeclareVarStmt(stmt, context) {
if (stmt.value) {
stmt.value.visitExpression(this, context);
}
if (stmt.type) {
stmt.type.visitType(this, context);
}
return stmt;
}
visitDeclareFunctionStmt(stmt, context) {
this.visitAllStatements(stmt.statements, context);
if (stmt.type) {
stmt.type.visitType(this, context);
}
return stmt;
}
visitExpressionStmt(stmt, context) {
stmt.expr.visitExpression(this, context);
return stmt;
}
visitReturnStmt(stmt, context) {
stmt.value.visitExpression(this, context);
return stmt;
}
visitIfStmt(stmt, context) {
stmt.condition.visitExpression(this, context);
this.visitAllStatements(stmt.trueCase, context);
this.visitAllStatements(stmt.falseCase, context);
return stmt;
}
visitAllStatements(stmts, context) {
stmts.forEach((stmt) => stmt.visitStatement(this, context));
}
};
function leadingComment(text2, multiline = false, trailingNewline = true) {
return new LeadingComment(text2, multiline, trailingNewline);
}
function jsDocComment(tags = []) {
return new JSDocComment(tags);
}
function variable(name, type, sourceSpan) {
return new ReadVarExpr(name, type, sourceSpan);
}
function importExpr(id, typeParams = null, sourceSpan) {
return new ExternalExpr(id, null, typeParams, sourceSpan);
}
function importType(id, typeParams, typeModifiers) {
return id != null ? expressionType(importExpr(id, typeParams, null), typeModifiers) : null;
}
function expressionType(expr, typeModifiers, typeParams) {
return new ExpressionType(expr, typeModifiers, typeParams);
}
function transplantedType(type, typeModifiers) {
return new TransplantedType(type, typeModifiers);
}
function typeofExpr(expr) {
return new TypeofExpr(expr);
}
function literalArr(values, type, sourceSpan) {
return new LiteralArrayExpr(values, type, sourceSpan);
}
function literalMap(values, type = null) {
return new LiteralMapExpr(values.map((e) => new LiteralMapEntry(e.key, e.value, e.quoted)), type, null);
}
function unary(operator, expr, type, sourceSpan) {
return new UnaryOperatorExpr(operator, expr, type, sourceSpan);
}
function not(expr, sourceSpan) {
return new NotExpr(expr, sourceSpan);
}
function fn(params, body, type, sourceSpan, name) {
return new FunctionExpr(params, body, type, sourceSpan, name);
}
function arrowFn(params, body, type, sourceSpan) {
return new ArrowFunctionExpr(params, body, type, sourceSpan);
}
function ifStmt(condition, thenClause, elseClause, sourceSpan, leadingComments) {
return new IfStmt(condition, thenClause, elseClause, sourceSpan, leadingComments);
}
function taggedTemplate(tag, template2, type, sourceSpan) {
return new TaggedTemplateExpr(tag, template2, type, sourceSpan);
}
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;
}
function tagToString(tag) {
let 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) {
if (tags.length === 0)
return "";
if (tags.length === 1 && tags[0].tagName && !tags[0].text) {
return `*${tagToString(tags[0])} `;
}
let out = "*\n";
for (const tag of tags) {
out += " *";
out += tagToString(tag).replace(/\n/g, "\n * ");
out += "\n";
}
out += " ";
return out;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/constant_pool.mjs
var CONSTANT_PREFIX = "_c";
var UNKNOWN_VALUE_KEY = variable("");
var KEY_CONTEXT = {};
var POOL_INCLUSION_LENGTH_THRESHOLD_FOR_STRINGS = 50;
var FixupExpression = class extends Expression {
constructor(resolved) {
super(resolved.type);
this.resolved = resolved;
this.shared = false;
this.original = resolved;
}
visitExpression(visitor, context) {
if (context === KEY_CONTEXT) {
return this.original.visitExpression(visitor, context);
} else {
return this.resolved.visitExpression(visitor, context);
}
}
isEquivalent(e) {
return e instanceof FixupExpression && this.resolved.isEquivalent(e.resolved);
}
isConstant() {
return true;
}
clone() {
throw new Error(`Not supported.`);
}
fixup(expression) {
this.resolved = expression;
this.shared = true;
}
};
var ConstantPool = class {
constructor(isClosureCompilerEnabled = false) {
this.isClosureCompilerEnabled = isClosureCompilerEnabled;
this.statements = [];
this.literals = /* @__PURE__ */ new Map();
this.literalFactories = /* @__PURE__ */ new Map();
this.sharedConstants = /* @__PURE__ */ new Map();
this._claimedNames = /* @__PURE__ */ new Map();
this.nextNameIndex = 0;
}
getConstLiteral(literal3, forceShared) {
if (literal3 instanceof LiteralExpr && !isLongStringLiteral(literal3) || literal3 instanceof FixupExpression) {
return literal3;
}
const key = GenericKeyFn.INSTANCE.keyOf(literal3);
let fixup = this.literals.get(key);
let newValue = false;
if (!fixup) {
fixup = new FixupExpression(literal3);
this.literals.set(key, fixup);
newValue = true;
}
if (!newValue && !fixup.shared || newValue && forceShared) {
const name = this.freshName();
let definition;
let usage;
if (this.isClosureCompilerEnabled && isLongStringLiteral(literal3)) {
definition = variable(name).set(new FunctionExpr(
[],
[
new ReturnStatement(literal3)
]
));
usage = variable(name).callFn([]);
} else {
definition = variable(name).set(literal3);
usage = variable(name);
}
this.statements.push(definition.toDeclStmt(INFERRED_TYPE, StmtModifier.Final));
fixup.fixup(usage);
}
return fixup;
}
getSharedConstant(def, expr) {
const key = def.keyOf(expr);
if (!this.sharedConstants.has(key)) {
const id = this.freshName();
this.sharedConstants.set(key, variable(id));
this.statements.push(def.toSharedConstantDeclaration(id, expr));
}
return this.sharedConstants.get(key);
}
getLiteralFactory(literal3) {
if (literal3 instanceof LiteralArrayExpr) {
const argumentsForKey = literal3.entries.map((e) => e.isConstant() ? e : UNKNOWN_VALUE_KEY);
const key = GenericKeyFn.INSTANCE.keyOf(literalArr(argumentsForKey));
return this._getLiteralFactory(key, literal3.entries, (entries) => literalArr(entries));
} else {
const expressionForKey = literalMap(literal3.entries.map((e) => ({
key: e.key,
value: e.value.isConstant() ? e.value : UNKNOWN_VALUE_KEY,
quoted: e.quoted
})));
const key = GenericKeyFn.INSTANCE.keyOf(expressionForKey);
return this._getLiteralFactory(key, literal3.entries.map((e) => e.value), (entries) => literalMap(entries.map((value, index) => ({
key: literal3.entries[index].key,
value,
quoted: literal3.entries[index].quoted
}))));
}
}
getSharedFunctionReference(fn2, prefix, useUniqueName = true) {
var _a2;
const isArrow = fn2 instanceof ArrowFunctionExpr;
for (const current of this.statements) {
if (isArrow && current instanceof DeclareVarStmt && ((_a2 = current.value) == null ? void 0 : _a2.isEquivalent(fn2))) {
return variable(current.name);
}
if (!isArrow && current instanceof DeclareFunctionStmt && fn2 instanceof FunctionExpr && fn2.isEquivalent(current)) {
return variable(current.name);
}
}
const name = useUniqueName ? this.uniqueName(prefix) : prefix;
this.statements.push(fn2 instanceof FunctionExpr ? fn2.toDeclStmt(name, StmtModifier.Final) : new DeclareVarStmt(name, fn2, INFERRED_TYPE, StmtModifier.Final, fn2.sourceSpan));
return variable(name);
}
_getLiteralFactory(key, values, resultMap) {
let literalFactory = this.literalFactories.get(key);
const literalFactoryArguments = values.filter((e) => !e.isConstant());
if (!literalFactory) {
const resultExpressions = values.map((e, index) => e.isConstant() ? this.getConstLiteral(e, true) : variable(`a${index}`));
const parameters = resultExpressions.filter(isVariable).map((e) => new FnParam(e.name, DYNAMIC_TYPE));
const pureFunctionDeclaration = arrowFn(parameters, resultMap(resultExpressions), INFERRED_TYPE);
const name = this.freshName();
this.statements.push(variable(name).set(pureFunctionDeclaration).toDeclStmt(INFERRED_TYPE, StmtModifier.Final));
literalFactory = variable(name);
this.literalFactories.set(key, literalFactory);
}
return { literalFactory, literalFactoryArguments };
}
uniqueName(name, alwaysIncludeSuffix = true) {
var _a2;
const count = (_a2 = this._claimedNames.get(name)) != null ? _a2 : 0;
const result = count === 0 && !alwaysIncludeSuffix ? `${name}` : `${name}${count}`;
this._claimedNames.set(name, count + 1);
return result;
}
freshName() {
return this.uniqueName(CONSTANT_PREFIX);
}
};
var _GenericKeyFn = class {
keyOf(expr) {
if (expr instanceof LiteralExpr && typeof expr.value === "string") {
return `"${expr.value}"`;
} else if (expr instanceof LiteralExpr) {
return String(expr.value);
} else if (expr instanceof LiteralArrayExpr) {
const entries = [];
for (const entry of expr.entries) {
entries.push(this.keyOf(entry));
}
return `[${entries.join(",")}]`;
} else if (expr instanceof LiteralMapExpr) {
const entries = [];
for (const entry of expr.entries) {
let key = entry.key;
if (entry.quoted) {
key = `"${key}"`;
}
entries.push(key + ":" + this.keyOf(entry.value));
}
return `{${entries.join(",")}}`;
} else if (expr instanceof ExternalExpr) {
return `import("${expr.value.moduleName}", ${expr.value.name})`;
} else if (expr instanceof ReadVarExpr) {
return `read(${expr.name})`;
} else if (expr instanceof TypeofExpr) {
return `typeof(${this.keyOf(expr.expr)})`;
} else {
throw new Error(`${this.constructor.name} does not handle expressions of type ${expr.constructor.name}`);
}
}
};
var GenericKeyFn = _GenericKeyFn;
(() => {
_GenericKeyFn.INSTANCE = new _GenericKeyFn();
})();
function isVariable(e) {
return e instanceof ReadVarExpr;
}
function isLongStringLiteral(expr) {
return expr instanceof LiteralExpr && typeof expr.value === "string" && expr.value.length >= POOL_INCLUSION_LENGTH_THRESHOLD_FOR_STRINGS;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/r3_identifiers.mjs
var CORE = "@angular/core";
var _Identifiers = class {
};
var Identifiers = _Identifiers;
(() => {
_Identifiers.NEW_METHOD = "factory";
})();
(() => {
_Identifiers.TRANSFORM_METHOD = "transform";
})();
(() => {
_Identifiers.PATCH_DEPS = "patchedDeps";
})();
(() => {
_Identifiers.core = { name: null, moduleName: CORE };
})();
(() => {
_Identifiers.namespaceHTML = { name: "\u0275\u0275namespaceHTML", moduleName: CORE };
})();
(() => {
_Identifiers.namespaceMathML = { name: "\u0275\u0275namespaceMathML", moduleName: CORE };
})();
(() => {
_Identifiers.namespaceSVG = { name: "\u0275\u0275namespaceSVG", moduleName: CORE };
})();
(() => {
_Identifiers.element = { name: "\u0275\u0275element", moduleName: CORE };
})();
(() => {
_Identifiers.elementStart = { name: "\u0275\u0275elementStart", moduleName: CORE };
})();
(() => {
_Identifiers.elementEnd = { name: "\u0275\u0275elementEnd", moduleName: CORE };
})();
(() => {
_Identifiers.advance = { name: "\u0275\u0275advance", moduleName: CORE };
})();
(() => {
_Identifiers.syntheticHostProperty = {
name: "\u0275\u0275syntheticHostProperty",
moduleName: CORE
};
})();
(() => {
_Identifiers.syntheticHostListener = {
name: "\u0275\u0275syntheticHostListener",
moduleName: CORE
};
})();
(() => {
_Identifiers.attribute = { name: "\u0275\u0275attribute", moduleName: CORE };
})();
(() => {
_Identifiers.attributeInterpolate1 = {
name: "\u0275\u0275attributeInterpolate1",
moduleName: CORE
};
})();
(() => {
_Identifiers.attributeInterpolate2 = {
name: "\u0275\u0275attributeInterpolate2",
moduleName: CORE
};
})();
(() => {
_Identifiers.attributeInterpolate3 = {
name: "\u0275\u0275attributeInterpolate3",
moduleName: CORE
};
})();
(() => {
_Identifiers.attributeInterpolate4 = {
name: "\u0275\u0275attributeInterpolate4",
moduleName: CORE
};
})();
(() => {
_Identifiers.attributeInterpolate5 = {
name: "\u0275\u0275attributeInterpolate5",
moduleName: CORE
};
})();
(() => {
_Identifiers.attributeInterpolate6 = {
name: "\u0275\u0275attributeInterpolate6",
moduleName: CORE
};
})();
(() => {
_Identifiers.attributeInterpolate7 = {
name: "\u0275\u0275attributeInterpolate7",
moduleName: CORE
};
})();
(() => {
_Identifiers.attributeInterpolate8 = {
name: "\u0275\u0275attributeInterpolate8",
moduleName: CORE
};
})();
(() => {
_Identifiers.attributeInterpolateV = {
name: "\u0275\u0275attributeInterpolateV",
moduleName: CORE
};
})();
(() => {
_Identifiers.classProp = { name: "\u0275\u0275classProp", moduleName: CORE };
})();
(() => {
_Identifiers.elementContainerStart = {
name: "\u0275\u0275elementContainerStart",
moduleName: CORE
};
})();
(() => {
_Identifiers.elementContainerEnd = {
name: "\u0275\u0275elementContainerEnd",
moduleName: CORE
};
})();
(() => {
_Identifiers.elementContainer = { name: "\u0275\u0275elementContainer", moduleName: CORE };
})();
(() => {
_Identifiers.styleMap = { name: "\u0275\u0275styleMap", moduleName: CORE };
})();
(() => {
_Identifiers.styleMapInterpolate1 = {
name: "\u0275\u0275styleMapInterpolate1",
moduleName: CORE
};
})();
(() => {
_Identifiers.styleMapInterpolate2 = {
name: "\u0275\u0275styleMapInterpolate2",
moduleName: CORE
};
})();
(() => {
_Identifiers.styleMapInterpolate3 = {
name: "\u0275\u0275styleMapInterpolate3",
moduleName: CORE
};
})();
(() => {
_Identifiers.styleMapInterpolate4 = {
name: "\u0275\u0275styleMapInterpolate4",
moduleName: CORE
};
})();
(() => {
_Identifiers.styleMapInterpolate5 = {
name: "\u0275\u0275styleMapInterpolate5",
moduleName: CORE
};
})();
(() => {
_Identifiers.styleMapInterpolate6 = {
name: "\u0275\u0275styleMapInterpolate6",
moduleName: CORE
};
})();
(() => {
_Identifiers.styleMapInterpolate7 = {
name: "\u0275\u0275styleMapInterpolate7",
moduleName: CORE
};
})();
(() => {
_Identifiers.styleMapInterpolate8 = {
name: "\u0275\u0275styleMapInterpolate8",
moduleName: CORE
};
})();
(() => {
_Identifiers.styleMapInterpolateV = {
name: "\u0275\u0275styleMapInterpolateV",
moduleName: CORE
};
})();
(() => {
_Identifiers.classMap = { name: "\u0275\u0275classMap", moduleName: CORE };
})();
(() => {
_Identifiers.classMapInterpolate1 = {
name: "\u0275\u0275classMapInterpolate1",
moduleName: CORE
};
})();
(() => {
_Identifiers.classMapInterpolate2 = {
name: "\u0275\u0275classMapInterpolate2",
moduleName: CORE
};
})();
(() => {
_Identifiers.classMapInterpolate3 = {
name: "\u0275\u0275classMapInterpolate3",
moduleName: CORE
};
})();
(() => {
_Identifiers.classMapInterpolate4 = {
name: "\u0275\u0275classMapInterpolate4",
moduleName: CORE
};
})();
(() => {
_Identifiers.classMapInterpolate5 = {
name: "\u0275\u0275classMapInterpolate5",
moduleName: CORE
};
})();
(() => {
_Identifiers.classMapInterpolate6 = {
name: "\u0275\u0275classMapInterpolate6",
moduleName: CORE
};
})();
(() => {
_Identifiers.classMapInterpolate7 = {
name: "\u0275\u0275classMapInterpolate7",
moduleName: CORE
};
})();
(() => {
_Identifiers.classMapInterpolate8 = {
name: "\u0275\u0275classMapInterpolate8",
moduleName: CORE
};
})();
(() => {
_Identifiers.classMapInterpolateV = {
name: "\u0275\u0275classMapInterpolateV",
moduleName: CORE
};
})();
(() => {
_Identifiers.styleProp = { name: "\u0275\u0275styleProp", moduleName: CORE };
})();
(() => {
_Identifiers.stylePropInterpolate1 = {
name: "\u0275\u0275stylePropInterpolate1",
moduleName: CORE
};
})();
(() => {
_Identifiers.stylePropInterpolate2 = {
name: "\u0275\u0275stylePropInterpolate2",
moduleName: CORE
};
})();
(() => {
_Identifiers.stylePropInterpolate3 = {
name: "\u0275\u0275stylePropInterpolate3",
moduleName: CORE
};
})();
(() => {
_Identifiers.stylePropInterpolate4 = {
name: "\u0275\u0275stylePropInterpolate4",
moduleName: CORE
};
})();
(() => {
_Identifiers.stylePropInterpolate5 = {
name: "\u0275\u0275stylePropInterpolate5",
moduleName: CORE
};
})();
(() => {
_Identifiers.stylePropInterpolate6 = {
name: "\u0275\u0275stylePropInterpolate6",
moduleName: CORE
};
})();
(() => {
_Identifiers.stylePropInterpolate7 = {
name: "\u0275\u0275stylePropInterpolate7",
moduleName: CORE
};
})();
(() => {
_Identifiers.stylePropInterpolate8 = {
name: "\u0275\u0275stylePropInterpolate8",
moduleName: CORE
};
})();
(() => {
_Identifiers.stylePropInterpolateV = {
name: "\u0275\u0275stylePropInterpolateV",
moduleName: CORE
};
})();
(() => {
_Identifiers.nextContext = { name: "\u0275\u0275nextContext", moduleName: CORE };
})();
(() => {
_Identifiers.resetView = { name: "\u0275\u0275resetView", moduleName: CORE };
})();
(() => {
_Identifiers.templateCreate = { name: "\u0275\u0275template", moduleName: CORE };
})();
(() => {
_Identifiers.defer = { name: "\u0275\u0275defer", moduleName: CORE };
})();
(() => {
_Identifiers.deferWhen = { name: "\u0275\u0275deferWhen", moduleName: CORE };
})();
(() => {
_Identifiers.deferOnIdle = { name: "\u0275\u0275deferOnIdle", moduleName: CORE };
})();
(() => {
_Identifiers.deferOnImmediate = { name: "\u0275\u0275deferOnImmediate", moduleName: CORE };
})();
(() => {
_Identifiers.deferOnTimer = { name: "\u0275\u0275deferOnTimer", moduleName: CORE };
})();
(() => {
_Identifiers.deferOnHover = { name: "\u0275\u0275deferOnHover", moduleName: CORE };
})();
(() => {
_Identifiers.deferOnInteraction = { name: "\u0275\u0275deferOnInteraction", moduleName: CORE };
})();
(() => {
_Identifiers.deferOnViewport = { name: "\u0275\u0275deferOnViewport", moduleName: CORE };
})();
(() => {
_Identifiers.deferPrefetchWhen = { name: "\u0275\u0275deferPrefetchWhen", moduleName: CORE };
})();
(() => {
_Identifiers.deferPrefetchOnIdle = {
name: "\u0275\u0275deferPrefetchOnIdle",
moduleName: CORE
};
})();
(() => {
_Identifiers.deferPrefetchOnImmediate = {
name: "\u0275\u0275deferPrefetchOnImmediate",
moduleName: CORE
};
})();
(() => {
_Identifiers.deferPrefetchOnTimer = {
name: "\u0275\u0275deferPrefetchOnTimer",
moduleName: CORE
};
})();
(() => {
_Identifiers.deferPrefetchOnHover = {
name: "\u0275\u0275deferPrefetchOnHover",
moduleName: CORE
};
})();
(() => {
_Identifiers.deferPrefetchOnInteraction = {
name: "\u0275\u0275deferPrefetchOnInteraction",
moduleName: CORE
};
})();
(() => {
_Identifiers.deferPrefetchOnViewport = {
name: "\u0275\u0275deferPrefetchOnViewport",
moduleName: CORE
};
})();
(() => {
_Identifiers.deferEnableTimerScheduling = {
name: "\u0275\u0275deferEnableTimerScheduling",
moduleName: CORE
};
})();
(() => {
_Identifiers.conditional = { name: "\u0275\u0275conditional", moduleName: CORE };
})();
(() => {
_Identifiers.repeater = { name: "\u0275\u0275repeater", moduleName: CORE };
})();
(() => {
_Identifiers.repeaterCreate = { name: "\u0275\u0275repeaterCreate", moduleName: CORE };
})();
(() => {
_Identifiers.repeaterTrackByIndex = {
name: "\u0275\u0275repeaterTrackByIndex",
moduleName: CORE
};
})();
(() => {
_Identifiers.repeaterTrackByIdentity = {
name: "\u0275\u0275repeaterTrackByIdentity",
moduleName: CORE
};
})();
(() => {
_Identifiers.componentInstance = { name: "\u0275\u0275componentInstance", moduleName: CORE };
})();
(() => {
_Identifiers.text = { name: "\u0275\u0275text", moduleName: CORE };
})();
(() => {
_Identifiers.enableBindings = { name: "\u0275\u0275enableBindings", moduleName: CORE };
})();
(() => {
_Identifiers.disableBindings = { name: "\u0275\u0275disableBindings", moduleName: CORE };
})();
(() => {
_Identifiers.getCurrentView = { name: "\u0275\u0275getCurrentView", moduleName: CORE };
})();
(() => {
_Identifiers.textInterpolate = { name: "\u0275\u0275textInterpolate", moduleName: CORE };
})();
(() => {
_Identifiers.textInterpolate1 = { name: "\u0275\u0275textInterpolate1", moduleName: CORE };
})();
(() => {
_Identifiers.textInterpolate2 = { name: "\u0275\u0275textInterpolate2", moduleName: CORE };
})();
(() => {
_Identifiers.textInterpolate3 = { name: "\u0275\u0275textInterpolate3", moduleName: CORE };
})();
(() => {
_Identifiers.textInterpolate4 = { name: "\u0275\u0275textInterpolate4", moduleName: CORE };
})();
(() => {
_Identifiers.textInterpolate5 = { name: "\u0275\u0275textInterpolate5", moduleName: CORE };
})();
(() => {
_Identifiers.textInterpolate6 = { name: "\u0275\u0275textInterpolate6", moduleName: CORE };
})();
(() => {
_Identifiers.textInterpolate7 = { name: "\u0275\u0275textInterpolate7", moduleName: CORE };
})();
(() => {
_Identifiers.textInterpolate8 = { name: "\u0275\u0275textInterpolate8", moduleName: CORE };
})();
(() => {
_Identifiers.textInterpolateV = { name: "\u0275\u0275textInterpolateV", moduleName: CORE };
})();
(() => {
_Identifiers.restoreView = { name: "\u0275\u0275restoreView", moduleName: CORE };
})();
(() => {
_Identifiers.pureFunction0 = { name: "\u0275\u0275pureFunction0", moduleName: CORE };
})();
(() => {
_Identifiers.pureFunction1 = { name: "\u0275\u0275pureFunction1", moduleName: CORE };
})();
(() => {
_Identifiers.pureFunction2 = { name: "\u0275\u0275pureFunction2", moduleName: CORE };
})();
(() => {
_Identifiers.pureFunction3 = { name: "\u0275\u0275pureFunction3", moduleName: CORE };
})();
(() => {
_Identifiers.pureFunction4 = { name: "\u0275\u0275pureFunction4", moduleName: CORE };
})();
(() => {
_Identifiers.pureFunction5 = { name: "\u0275\u0275pureFunction5", moduleName: CORE };
})();
(() => {
_Identifiers.pureFunction6 = { name: "\u0275\u0275pureFunction6", moduleName: CORE };
})();
(() => {
_Identifiers.pureFunction7 = { name: "\u0275\u0275pureFunction7", moduleName: CORE };
})();
(() => {
_Identifiers.pureFunction8 = { name: "\u0275\u0275pureFunction8", moduleName: CORE };
})();
(() => {
_Identifiers.pureFunctionV = { name: "\u0275\u0275pureFunctionV", moduleName: CORE };
})();
(() => {
_Identifiers.pipeBind1 = { name: "\u0275\u0275pipeBind1", moduleName: CORE };
})();
(() => {
_Identifiers.pipeBind2 = { name: "\u0275\u0275pipeBind2", moduleName: CORE };
})();
(() => {
_Identifiers.pipeBind3 = { name: "\u0275\u0275pipeBind3", moduleName: CORE };
})();
(() => {
_Identifiers.pipeBind4 = { name: "\u0275\u0275pipeBind4", moduleName: CORE };
})();
(() => {
_Identifiers.pipeBindV = { name: "\u0275\u0275pipeBindV", moduleName: CORE };
})();
(() => {
_Identifiers.hostProperty = { name: "\u0275\u0275hostProperty", moduleName: CORE };
})();
(() => {
_Identifiers.property = { name: "\u0275\u0275property", moduleName: CORE };
})();
(() => {
_Identifiers.propertyInterpolate = {
name: "\u0275\u0275propertyInterpolate",
moduleName: CORE
};
})();
(() => {
_Identifiers.propertyInterpolate1 = {
name: "\u0275\u0275propertyInterpolate1",
moduleName: CORE
};
})();
(() => {
_Identifiers.propertyInterpolate2 = {
name: "\u0275\u0275propertyInterpolate2",
moduleName: CORE
};
})();
(() => {
_Identifiers.propertyInterpolate3 = {
name: "\u0275\u0275propertyInterpolate3",
moduleName: CORE
};
})();
(() => {
_Identifiers.propertyInterpolate4 = {
name: "\u0275\u0275propertyInterpolate4",
moduleName: CORE
};
})();
(() => {
_Identifiers.propertyInterpolate5 = {
name: "\u0275\u0275propertyInterpolate5",
moduleName: CORE
};
})();
(() => {
_Identifiers.propertyInterpolate6 = {
name: "\u0275\u0275propertyInterpolate6",
moduleName: CORE
};
})();
(() => {
_Identifiers.propertyInterpolate7 = {
name: "\u0275\u0275propertyInterpolate7",
moduleName: CORE
};
})();
(() => {
_Identifiers.propertyInterpolate8 = {
name: "\u0275\u0275propertyInterpolate8",
moduleName: CORE
};
})();
(() => {
_Identifiers.propertyInterpolateV = {
name: "\u0275\u0275propertyInterpolateV",
moduleName: CORE
};
})();
(() => {
_Identifiers.i18n = { name: "\u0275\u0275i18n", moduleName: CORE };
})();
(() => {
_Identifiers.i18nAttributes = { name: "\u0275\u0275i18nAttributes", moduleName: CORE };
})();
(() => {
_Identifiers.i18nExp = { name: "\u0275\u0275i18nExp", moduleName: CORE };
})();
(() => {
_Identifiers.i18nStart = { name: "\u0275\u0275i18nStart", moduleName: CORE };
})();
(() => {
_Identifiers.i18nEnd = { name: "\u0275\u0275i18nEnd", moduleName: CORE };
})();
(() => {
_Identifiers.i18nApply = { name: "\u0275\u0275i18nApply", moduleName: CORE };
})();
(() => {
_Identifiers.i18nPostprocess = { name: "\u0275\u0275i18nPostprocess", moduleName: CORE };
})();
(() => {
_Identifiers.pipe = { name: "\u0275\u0275pipe", moduleName: CORE };
})();
(() => {
_Identifiers.projection = { name: "\u0275\u0275projection", moduleName: CORE };
})();
(() => {
_Identifiers.projectionDef = { name: "\u0275\u0275projectionDef", moduleName: CORE };
})();
(() => {
_Identifiers.reference = { name: "\u0275\u0275reference", moduleName: CORE };
})();
(() => {
_Identifiers.inject = { name: "\u0275\u0275inject", moduleName: CORE };
})();
(() => {
_Identifiers.injectAttribute = { name: "\u0275\u0275injectAttribute", moduleName: CORE };
})();
(() => {
_Identifiers.directiveInject = { name: "\u0275\u0275directiveInject", moduleName: CORE };
})();
(() => {
_Identifiers.invalidFactory = { name: "\u0275\u0275invalidFactory", moduleName: CORE };
})();
(() => {
_Identifiers.invalidFactoryDep = { name: "\u0275\u0275invalidFactoryDep", moduleName: CORE };
})();
(() => {
_Identifiers.templateRefExtractor = {
name: "\u0275\u0275templateRefExtractor",
moduleName: CORE
};
})();
(() => {
_Identifiers.forwardRef = { name: "forwardRef", moduleName: CORE };
})();
(() => {
_Identifiers.resolveForwardRef = { name: "resolveForwardRef", moduleName: CORE };
})();
(() => {
_Identifiers.\u0275\u0275defineInjectable = { name: "\u0275\u0275defineInjectable", moduleName: CORE };
})();
(() => {
_Identifiers.declareInjectable = { name: "\u0275\u0275ngDeclareInjectable", moduleName: CORE };
})();
(() => {
_Identifiers.InjectableDeclaration = {
name: "\u0275\u0275InjectableDeclaration",
moduleName: CORE
};
})();
(() => {
_Identifiers.resolveWindow = { name: "\u0275\u0275resolveWindow", moduleName: CORE };
})();
(() => {
_Identifiers.resolveDocument = { name: "\u0275\u0275resolveDocument", moduleName: CORE };
})();
(() => {
_Identifiers.resolveBody = { name: "\u0275\u0275resolveBody", moduleName: CORE };
})();
(() => {
_Identifiers.getComponentDepsFactory = {
name: "\u0275\u0275getComponentDepsFactory",
moduleName: CORE
};
})();
(() => {
_Identifiers.defineComponent = { name: "\u0275\u0275defineComponent", moduleName: CORE };
})();
(() => {
_Identifiers.declareComponent = { name: "\u0275\u0275ngDeclareComponent", moduleName: CORE };
})();
(() => {
_Identifiers.setComponentScope = { name: "\u0275\u0275setComponentScope", moduleName: CORE };
})();
(() => {
_Identifiers.ChangeDetectionStrategy = {
name: "ChangeDetectionStrategy",
moduleName: CORE
};
})();
(() => {
_Identifiers.ViewEncapsulation = {
name: "ViewEncapsulation",
moduleName: CORE
};
})();
(() => {
_Identifiers.ComponentDeclaration = {
name: "\u0275\u0275ComponentDeclaration",
moduleName: CORE
};
})();
(() => {
_Identifiers.FactoryDeclaration = {
name: "\u0275\u0275FactoryDeclaration",
moduleName: CORE
};
})();
(() => {
_Identifiers.declareFactory = { name: "\u0275\u0275ngDeclareFactory", moduleName: CORE };
})();
(() => {
_Identifiers.FactoryTarget = { name: "\u0275\u0275FactoryTarget", moduleName: CORE };
})();
(() => {
_Identifiers.defineDirective = { name: "\u0275\u0275defineDirective", moduleName: CORE };
})();
(() => {
_Identifiers.declareDirective = { name: "\u0275\u0275ngDeclareDirective", moduleName: CORE };
})();
(() => {
_Identifiers.DirectiveDeclaration = {
name: "\u0275\u0275DirectiveDeclaration",
moduleName: CORE
};
})();
(() => {
_Identifiers.InjectorDef = { name: "\u0275\u0275InjectorDef", moduleName: CORE };
})();
(() => {
_Identifiers.InjectorDeclaration = {
name: "\u0275\u0275InjectorDeclaration",
moduleName: CORE
};
})();
(() => {
_Identifiers.defineInjector = { name: "\u0275\u0275defineInjector", moduleName: CORE };
})();
(() => {
_Identifiers.declareInjector = { name: "\u0275\u0275ngDeclareInjector", moduleName: CORE };
})();
(() => {
_Identifiers.NgModuleDeclaration = {
name: "\u0275\u0275NgModuleDeclaration",
moduleName: CORE
};
})();
(() => {
_Identifiers.ModuleWithProviders = {
name: "ModuleWithProviders",
moduleName: CORE
};
})();
(() => {
_Identifiers.defineNgModule = { name: "\u0275\u0275defineNgModule", moduleName: CORE };
})();
(() => {
_Identifiers.declareNgModule = { name: "\u0275\u0275ngDeclareNgModule", moduleName: CORE };
})();
(() => {
_Identifiers.setNgModuleScope = { name: "\u0275\u0275setNgModuleScope", moduleName: CORE };
})();
(() => {
_Identifiers.registerNgModuleType = {
name: "\u0275\u0275registerNgModuleType",
moduleName: CORE
};
})();
(() => {
_Identifiers.PipeDeclaration = { name: "\u0275\u0275PipeDeclaration", moduleName: CORE };
})();
(() => {
_Identifiers.definePipe = { name: "\u0275\u0275definePipe", moduleName: CORE };
})();
(() => {
_Identifiers.declarePipe = { name: "\u0275\u0275ngDeclarePipe", moduleName: CORE };
})();
(() => {
_Identifiers.declareClassMetadata = {
name: "\u0275\u0275ngDeclareClassMetadata",
moduleName: CORE
};
})();
(() => {
_Identifiers.declareClassMetadataAsync = {
name: "\u0275\u0275ngDeclareClassMetadataAsync",
moduleName: CORE
};
})();
(() => {
_Identifiers.setClassMetadata = { name: "\u0275setClassMetadata", moduleName: CORE };
})();
(() => {
_Identifiers.setClassMetadataAsync = {
name: "\u0275setClassMetadataAsync",
moduleName: CORE
};
})();
(() => {
_Identifiers.setClassDebugInfo = { name: "\u0275setClassDebugInfo", moduleName: CORE };
})();
(() => {
_Identifiers.queryRefresh = { name: "\u0275\u0275queryRefresh", moduleName: CORE };
})();
(() => {
_Identifiers.viewQuery = { name: "\u0275\u0275viewQuery", moduleName: CORE };
})();
(() => {
_Identifiers.loadQuery = { name: "\u0275\u0275loadQuery", moduleName: CORE };
})();
(() => {
_Identifiers.contentQuery = { name: "\u0275\u0275contentQuery", moduleName: CORE };
})();
(() => {
_Identifiers.viewQuerySignal = { name: "\u0275\u0275viewQuerySignal", moduleName: CORE };
})();
(() => {
_Identifiers.contentQuerySignal = { name: "\u0275\u0275contentQuerySignal", moduleName: CORE };
})();
(() => {
_Identifiers.queryAdvance = { name: "\u0275\u0275queryAdvance", moduleName: CORE };
})();
(() => {
_Identifiers.twoWayProperty = { name: "\u0275\u0275twoWayProperty", moduleName: CORE };
})();
(() => {
_Identifiers.twoWayBindingSet = { name: "\u0275\u0275twoWayBindingSet", moduleName: CORE };
})();
(() => {
_Identifiers.twoWayListener = { name: "\u0275\u0275twoWayListener", moduleName: CORE };
})();
(() => {
_Identifiers.declareLet = { name: "\u0275\u0275declareLet", moduleName: CORE };
})();
(() => {
_Identifiers.storeLet = { name: "\u0275\u0275storeLet", moduleName: CORE };
})();
(() => {
_Identifiers.readContextLet = { name: "\u0275\u0275readContextLet", moduleName: CORE };
})();
(() => {
_Identifiers.NgOnChangesFeature = { name: "\u0275\u0275NgOnChangesFeature", moduleName: CORE };
})();
(() => {
_Identifiers.InheritDefinitionFeature = {
name: "\u0275\u0275InheritDefinitionFeature",
moduleName: CORE
};
})();
(() => {
_Identifiers.CopyDefinitionFeature = {
name: "\u0275\u0275CopyDefinitionFeature",
moduleName: CORE
};
})();
(() => {
_Identifiers.StandaloneFeature = { name: "\u0275\u0275StandaloneFeature", moduleName: CORE };
})();
(() => {
_Identifiers.ProvidersFeature = { name: "\u0275\u0275ProvidersFeature", moduleName: CORE };
})();
(() => {
_Identifiers.HostDirectivesFeature = {
name: "\u0275\u0275HostDirectivesFeature",
moduleName: CORE
};
})();
(() => {
_Identifiers.InputTransformsFeatureFeature = {
name: "\u0275\u0275InputTransformsFeature",
moduleName: CORE
};
})();
(() => {
_Identifiers.listener = { name: "\u0275\u0275listener", moduleName: CORE };
})();
(() => {
_Identifiers.getInheritedFactory = {
name: "\u0275\u0275getInheritedFactory",
moduleName: CORE
};
})();
(() => {
_Identifiers.sanitizeHtml = { name: "\u0275\u0275sanitizeHtml", moduleName: CORE };
})();
(() => {
_Identifiers.sanitizeStyle = { name: "\u0275\u0275sanitizeStyle", moduleName: CORE };
})();
(() => {
_Identifiers.sanitizeResourceUrl = {
name: "\u0275\u0275sanitizeResourceUrl",
moduleName: CORE
};
})();
(() => {
_Identifiers.sanitizeScript = { name: "\u0275\u0275sanitizeScript", moduleName: CORE };
})();
(() => {
_Identifiers.sanitizeUrl = { name: "\u0275\u0275sanitizeUrl", moduleName: CORE };
})();
(() => {
_Identifiers.sanitizeUrlOrResourceUrl = {
name: "\u0275\u0275sanitizeUrlOrResourceUrl",
moduleName: CORE
};
})();
(() => {
_Identifiers.trustConstantHtml = { name: "\u0275\u0275trustConstantHtml", moduleName: CORE };
})();
(() => {
_Identifiers.trustConstantResourceUrl = {
name: "\u0275\u0275trustConstantResourceUrl",
moduleName: CORE
};
})();
(() => {
_Identifiers.validateIframeAttribute = {
name: "\u0275\u0275validateIframeAttribute",
moduleName: CORE
};
})();
(() => {
_Identifiers.InputSignalBrandWriteType = { name: "\u0275INPUT_SIGNAL_BRAND_WRITE_TYPE", moduleName: CORE };
})();
(() => {
_Identifiers.UnwrapDirectiveSignalInputs = { name: "\u0275UnwrapDirectiveSignalInputs", moduleName: CORE };
})();
(() => {
_Identifiers.unwrapWritableSignal = { name: "\u0275unwrapWritableSignal", moduleName: CORE };
})();
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/util.mjs
var DASH_CASE_REGEXP = /-+([a-z0-9])/g;
function dashCaseToCamelCase(input) {
return input.replace(DASH_CASE_REGEXP, (...m) => m[1].toUpperCase());
}
function splitAtColon(input, defaultValues) {
return _splitAt(input, ":", defaultValues);
}
function splitAtPeriod(input, defaultValues) {
return _splitAt(input, ".", defaultValues);
}
function _splitAt(input, character, defaultValues) {
const characterIndex = input.indexOf(character);
if (characterIndex == -1)
return defaultValues;
return [input.slice(0, characterIndex).trim(), input.slice(characterIndex + 1).trim()];
}
function utf8Encode(str) {
let encoded = [];
for (let index = 0; index < str.length; index++) {
let codePoint = str.charCodeAt(index);
if (codePoint >= 55296 && codePoint <= 56319 && str.length > index + 1) {
const low = str.charCodeAt(index + 1);
if (low >= 56320 && low <= 57343) {
index++;
codePoint = (codePoint - 55296 << 10) + low - 56320 + 65536;
}
}
if (codePoint <= 127) {
encoded.push(codePoint);
} else if (codePoint <= 2047) {
encoded.push(codePoint >> 6 & 31 | 192, codePoint & 63 | 128);
} else if (codePoint <= 65535) {
encoded.push(codePoint >> 12 | 224, codePoint >> 6 & 63 | 128, codePoint & 63 | 128);
} else if (codePoint <= 2097151) {
encoded.push(codePoint >> 18 & 7 | 240, codePoint >> 12 & 63 | 128, codePoint >> 6 & 63 | 128, codePoint & 63 | 128);
}
}
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";
}
const res = token.toString();
if (res == null) {
return "" + res;
}
const newLineIndex = res.indexOf("\n");
return newLineIndex === -1 ? res : res.substring(0, newLineIndex);
}
var Version = class {
constructor(full) {
this.full = full;
const splits = full.split(".");
this.major = splits[0];
this.minor = splits[1];
this.patch = splits.slice(2).join(".");
}
};
var _global = globalThis;
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/output/source_map.mjs
var VERSION = 3;
var JS_B64_PREFIX = "# sourceMappingURL=data:application/json;base64,";
var SourceMapGenerator = class {
constructor(file = null) {
this.file = file;
this.sourcesContent = /* @__PURE__ */ new Map();
this.lines = [];
this.lastCol0 = 0;
this.hasMappings = false;
}
addSource(url, content = null) {
if (!this.sourcesContent.has(url)) {
this.sourcesContent.set(url, content);
}
return this;
}
addLine() {
this.lines.push([]);
this.lastCol0 = 0;
return this;
}
addMapping(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, sourceUrl, sourceLine0, sourceCol0 });
return this;
}
get currentLine() {
return this.lines.slice(-1)[0];
}
toJSON() {
if (!this.hasMappings) {
return null;
}
const sourcesIndex = /* @__PURE__ */ new Map();
const sources = [];
const sourcesContent = [];
Array.from(this.sourcesContent.keys()).forEach((url, i) => {
sourcesIndex.set(url, i);
sources.push(url);
sourcesContent.push(this.sourcesContent.get(url) || null);
});
let mappings = "";
let lastCol0 = 0;
let lastSourceIndex = 0;
let lastSourceLine0 = 0;
let lastSourceCol0 = 0;
this.lines.forEach((segments) => {
lastCol0 = 0;
mappings += segments.map((segment) => {
let segAsStr = toBase64VLQ(segment.col0 - lastCol0);
lastCol0 = segment.col0;
if (segment.sourceUrl != null) {
segAsStr += toBase64VLQ(sourcesIndex.get(segment.sourceUrl) - lastSourceIndex);
lastSourceIndex = sourcesIndex.get(segment.sourceUrl);
segAsStr += toBase64VLQ(segment.sourceLine0 - lastSourceLine0);
lastSourceLine0 = segment.sourceLine0;
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
};
}
toJsComment() {
return this.hasMappings ? "//" + JS_B64_PREFIX + toBase64String(JSON.stringify(this, null, 0)) : "";
}
};
function toBase64String(value) {
let b64 = "";
const encoded = utf8Encode(value);
for (let i = 0; i < encoded.length; ) {
const i1 = encoded[i++];
const i2 = i < encoded.length ? encoded[i++] : null;
const i3 = i < encoded.length ? encoded[i++] : null;
b64 += toBase64Digit(i1 >> 2);
b64 += toBase64Digit((i1 & 3) << 4 | (i2 === null ? 0 : i2 >> 4));
b64 += i2 === null ? "=" : toBase64Digit((i2 & 15) << 2 | (i3 === null ? 0 : i3 >> 6));
b64 += i2 === null || i3 === null ? "=" : toBase64Digit(i3 & 63);
}
return b64;
}
function toBase64VLQ(value) {
value = value < 0 ? (-value << 1) + 1 : value << 1;
let out = "";
do {
let 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];
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/output/abstract_emitter.mjs
var _SINGLE_QUOTE_ESCAPE_STRING_RE = /'|\\|\n|\r|\$/g;
var _LEGAL_IDENTIFIER_RE = /^[$A-Z_][0-9A-Z_$]*$/i;
var _INDENT_WITH = " ";
var _EmittedLine = class {
constructor(indent) {
this.indent = indent;
this.partsLength = 0;
this.parts = [];
this.srcSpans = [];
}
};
var EmitterVisitorContext = class {
static createRoot() {
return new EmitterVisitorContext(0);
}
constructor(_indent) {
this._indent = _indent;
this._lines = [new _EmittedLine(_indent)];
}
get _currentLine() {
return this._lines[this._lines.length - 1];
}
println(from, lastPart = "") {
this.print(from || null, lastPart, true);
}
lineIsEmpty() {
return this._currentLine.parts.length === 0;
}
lineLength() {
return this._currentLine.indent * _INDENT_WITH.length + this._currentLine.partsLength;
}
print(from, part, 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));
}
}
removeEmptyLastLine() {
if (this.lineIsEmpty()) {
this._lines.pop();
}
}
incIndent() {
this._indent++;
if (this.lineIsEmpty()) {
this._currentLine.indent = this._indent;
}
}
decIndent() {
this._indent--;
if (this.lineIsEmpty()) {
this._currentLine.indent = this._indent;
}
}
toSource() {
return this.sourceLines.map((l) => l.parts.length > 0 ? _createIndent(l.indent) + l.parts.join("") : "").join("\n");
}
toSourceMapGenerator(genFilePath, startsAtLine = 0) {
const map = new SourceMapGenerator(genFilePath);
let firstOffsetMapped = false;
const mapFirstOffsetIfNeeded = () => {
if (!firstOffsetMapped) {
map.addSource(genFilePath, " ").addMapping(0, genFilePath, 0, 0);
firstOffsetMapped = true;
}
};
for (let i = 0; i < startsAtLine; i++) {
map.addLine();
mapFirstOffsetIfNeeded();
}
this.sourceLines.forEach((line, lineIdx) => {
map.addLine();
const spans = line.srcSpans;
const parts = line.parts;
let col0 = line.indent * _INDENT_WITH.length;
let spanIdx = 0;
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) {
const span = spans[spanIdx];
const source = span.start.file;
const sourceLine = span.start.line;
const sourceCol = span.start.col;
map.addSource(source.url, source.content).addMapping(col0, source.url, sourceLine, sourceCol);
col0 += parts[spanIdx].length;
spanIdx++;
while (spanIdx < spans.length && (span === spans[spanIdx] || !spans[spanIdx])) {
col0 += parts[spanIdx].length;
spanIdx++;
}
}
});
return map;
}
spanOf(line, column) {
const emittedLine = this._lines[line];
if (emittedLine) {
let columnsLeft = column - _createIndent(emittedLine.indent).length;
for (let partIndex = 0; partIndex < emittedLine.parts.length; partIndex++) {
const part = emittedLine.parts[partIndex];
if (part.length > columnsLeft) {
return emittedLine.srcSpans[partIndex];
}
columnsLeft -= part.length;
}
}
return null;
}
get sourceLines() {
if (this._lines.length && this._lines[this._lines.length - 1].parts.length === 0) {
return this._lines.slice(0, -1);
}
return this._lines;
}
};
var AbstractEmitterVisitor = class {
constructor(_escapeDollarInStrings) {
this._escapeDollarInStrings = _escapeDollarInStrings;
}
printLeadingComments(stmt, ctx) {
if (stmt.leadingComments === void 0) {
return;
}
for (const comment of stmt.leadingComments) {
if (comment instanceof JSDocComment) {
ctx.print(stmt, `/*${comment.toString()}*/`, comment.trailingNewline);
} else {
if (comment.multiline) {
ctx.print(stmt, `/* ${comment.text} */`, comment.trailingNewline);
} else {
comment.text.split("\n").forEach((line) => {
ctx.println(stmt, `// ${line}`);
});
}
}
}
}
visitExpressionStmt(stmt, ctx) {
this.printLeadingComments(stmt, ctx);
stmt.expr.visitExpression(this, ctx);
ctx.println(stmt, ";");
return null;
}
visitReturnStmt(stmt, ctx) {
this.printLeadingComments(stmt, ctx);
ctx.print(stmt, `return `);
stmt.value.visitExpression(this, ctx);
ctx.println(stmt, ";");
return null;
}
visitIfStmt(stmt, ctx) {
this.printLeadingComments(stmt, ctx);
ctx.print(stmt, `if (`);
stmt.condition.visitExpression(this, ctx);
ctx.print(stmt, `) {`);
const 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;
}
visitWriteVarExpr(expr, ctx) {
const 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;
}
visitWriteKeyExpr(expr, ctx) {
const 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;
}
visitWritePropExpr(expr, ctx) {
const 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;
}
visitInvokeFunctionExpr(expr, ctx) {
const shouldParenthesize = expr.fn instanceof ArrowFunctionExpr;
if (shouldParenthesize) {
ctx.print(expr.fn, "(");
}
expr.fn.visitExpression(this, ctx);
if (shouldParenthesize) {
ctx.print(expr.fn, ")");
}
ctx.print(expr, `(`);
this.visitAllExpressions(expr.args, ctx, ",");
ctx.print(expr, `)`);
return null;
}
visitTaggedTemplateExpr(expr, ctx) {
expr.tag.visitExpression(this, ctx);
ctx.print(expr, "`" + expr.template.elements[0].rawText);
for (let i = 1; i < expr.template.elements.length; i++) {
ctx.print(expr, "${");
expr.template.expressions[i - 1].visitExpression(this, ctx);
ctx.print(expr, `}${expr.template.elements[i].rawText}`);
}
ctx.print(expr, "`");
return null;
}
visitWrappedNodeExpr(ast, ctx) {
throw new Error("Abstract emitter cannot visit WrappedNodeExpr.");
}
visitTypeofExpr(expr, ctx) {
ctx.print(expr, "typeof ");
expr.expr.visitExpression(this, ctx);
}
visitReadVarExpr(ast, ctx) {
ctx.print(ast, ast.name);
return null;
}
visitInstantiateExpr(ast, ctx) {
ctx.print(ast, `new `);
ast.classExpr.visitExpression(this, ctx);
ctx.print(ast, `(`);
this.visitAllExpressions(ast.args, ctx, ",");
ctx.print(ast, `)`);
return null;
}
visitLiteralExpr(ast, ctx) {
const value = ast.value;
if (typeof value === "string") {
ctx.print(ast, escapeIdentifier(value, this._escapeDollarInStrings));
} else {
ctx.print(ast, `${value}`);
}
return null;
}
visitLocalizedString(ast, ctx) {
const head = ast.serializeI18nHead();
ctx.print(ast, "$localize `" + head.raw);
for (let 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;
}
visitConditionalExpr(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;
}
visitDynamicImportExpr(ast, ctx) {
ctx.print(ast, `import(${ast.url})`);
}
visitNotExpr(ast, ctx) {
ctx.print(ast, "!");
ast.condition.visitExpression(this, ctx);
return null;
}
visitUnaryOperatorExpr(ast, ctx) {
let opStr;
switch (ast.operator) {
case UnaryOperator.Plus:
opStr = "+";
break;
case UnaryOperator.Minus:
opStr = "-";
break;
default:
throw new Error(`Unknown operator ${ast.operator}`);
}
if (ast.parens)
ctx.print(ast, `(`);
ctx.print(ast, opStr);
ast.expr.visitExpression(this, ctx);
if (ast.parens)
ctx.print(ast, `)`);
return null;
}
visitBinaryOperatorExpr(ast, ctx) {
let 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.BitwiseOr:
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;
case BinaryOperator.NullishCoalesce:
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;
}
visitReadPropExpr(ast, ctx) {
ast.receiver.visitExpression(this, ctx);
ctx.print(ast, `.`);
ctx.print(ast, ast.name);
return null;
}
visitReadKeyExpr(ast, ctx) {
ast.receiver.visitExpression(this, ctx);
ctx.print(ast, `[`);
ast.index.visitExpression(this, ctx);
ctx.print(ast, `]`);
return null;
}
visitLiteralArrayExpr(ast, ctx) {
ctx.print(ast, `[`);
this.visitAllExpressions(ast.entries, ctx, ",");
ctx.print(ast, `]`);
return null;
}
visitLiteralMapExpr(ast, ctx) {
ctx.print(ast, `{`);
this.visitAllObjects((entry) => {
ctx.print(ast, `${escapeIdentifier(entry.key, this._escapeDollarInStrings, entry.quoted)}:`);
entry.value.visitExpression(this, ctx);
}, ast.entries, ctx, ",");
ctx.print(ast, `}`);
return null;
}
visitCommaExpr(ast, ctx) {
ctx.print(ast, "(");
this.visitAllExpressions(ast.parts, ctx, ",");
ctx.print(ast, ")");
return null;
}
visitAllExpressions(expressions, ctx, separator) {
this.visitAllObjects((expr) => expr.visitExpression(this, ctx), expressions, ctx, separator);
}
visitAllObjects(handler, expressions, ctx, separator) {
let incrementedIndent = false;
for (let i = 0; i < expressions.length; i++) {
if (i > 0) {
if (ctx.lineLength() > 80) {
ctx.print(null, separator, true);
if (!incrementedIndent) {
ctx.incIndent();
ctx.incIndent();
incrementedIndent = true;
}
} else {
ctx.print(null, separator, false);
}
}
handler(expressions[i]);
}
if (incrementedIndent) {
ctx.decIndent();
ctx.decIndent();
}
}
visitAllStatements(statements, ctx) {
statements.forEach((stmt) => stmt.visitStatement(this, ctx));
}
};
function escapeIdentifier(input, escapeDollar, alwaysQuote = true) {
if (input == null) {
return null;
}
const body = input.replace(_SINGLE_QUOTE_ESCAPE_STRING_RE, (...match) => {
if (match[0] == "$") {
return escapeDollar ? "\\$" : "$";
} else if (match[0] == "\n") {
return "\\n";
} else if (match[0] == "\r") {
return "\\r";
} else {
return `\\${match[0]}`;
}
});
const requiresQuotes = alwaysQuote || !_LEGAL_IDENTIFIER_RE.test(body);
return requiresQuotes ? `'${body}'` : body;
}
function _createIndent(count) {
let res = "";
for (let i = 0; i < count; i++) {
res += _INDENT_WITH;
}
return res;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/util.mjs
function typeWithParameters(type, numParams) {
if (numParams === 0) {
return expressionType(type);
}
const params = [];
for (let i = 0; i < numParams; i++) {
params.push(DYNAMIC_TYPE);
}
return expressionType(type, void 0, params);
}
function getSafePropertyAccessString(accessor, name) {
const escapedName = escapeIdentifier(name, false, false);
return escapedName !== name ? `${accessor}[${escapedName}]` : `${accessor}.${name}`;
}
function jitOnlyGuardedExpression(expr) {
return guardedExpression("ngJitMode", expr);
}
function devOnlyGuardedExpression(expr) {
return guardedExpression("ngDevMode", expr);
}
function guardedExpression(guard, expr) {
const guardExpr = new ExternalExpr({ name: guard, moduleName: null });
const guardNotDefined = new BinaryOperatorExpr(BinaryOperator.Identical, new TypeofExpr(guardExpr), literal("undefined"));
const guardUndefinedOrTrue = new BinaryOperatorExpr(
BinaryOperator.Or,
guardNotDefined,
guardExpr,
void 0,
void 0,
true
);
return new BinaryOperatorExpr(BinaryOperator.And, guardUndefinedOrTrue, expr);
}
function wrapReference(value) {
const wrapped = new WrappedNodeExpr(value);
return { value: wrapped, type: wrapped };
}
function refsToArray(refs, shouldForwardDeclare) {
const values = literalArr(refs.map((ref) => ref.value));
return shouldForwardDeclare ? arrowFn([], values) : values;
}
function createMayBeForwardRefExpression(expression, forwardRef) {
return { expression, forwardRef };
}
function convertFromMaybeForwardRefExpression({ expression, forwardRef }) {
switch (forwardRef) {
case 0:
case 1:
return expression;
case 2:
return generateForwardRef(expression);
}
}
function generateForwardRef(expr) {
return importExpr(Identifiers.forwardRef).callFn([arrowFn([], expr)]);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/r3_factory.mjs
var R3FactoryDelegateType;
(function(R3FactoryDelegateType2) {
R3FactoryDelegateType2[R3FactoryDelegateType2["Class"] = 0] = "Class";
R3FactoryDelegateType2[R3FactoryDelegateType2["Function"] = 1] = "Function";
})(R3FactoryDelegateType || (R3FactoryDelegateType = {}));
var FactoryTarget;
(function(FactoryTarget3) {
FactoryTarget3[FactoryTarget3["Directive"] = 0] = "Directive";
FactoryTarget3[FactoryTarget3["Component"] = 1] = "Component";
FactoryTarget3[FactoryTarget3["Injectable"] = 2] = "Injectable";
FactoryTarget3[FactoryTarget3["Pipe"] = 3] = "Pipe";
FactoryTarget3[FactoryTarget3["NgModule"] = 4] = "NgModule";
})(FactoryTarget || (FactoryTarget = {}));
function compileFactoryFunction(meta) {
const t = variable("__ngFactoryType__");
let baseFactoryVar = null;
const typeForCtor = !isDelegatedFactoryMetadata(meta) ? new BinaryOperatorExpr(BinaryOperator.Or, t, meta.type.value) : t;
let ctorExpr = null;
if (meta.deps !== null) {
if (meta.deps !== "invalid") {
ctorExpr = new InstantiateExpr(typeForCtor, injectDependencies(meta.deps, meta.target));
}
} else {
baseFactoryVar = variable(`\u0275${meta.name}_BaseFactory`);
ctorExpr = baseFactoryVar.callFn([typeForCtor]);
}
const body = [];
let retExpr = null;
function makeConditionalFactory(nonCtorExpr) {
const r = variable("__ngConditionalFactory__");
body.push(r.set(NULL_EXPR).toDeclStmt());
const ctorStmt = ctorExpr !== null ? r.set(ctorExpr).toStmt() : importExpr(Identifiers.invalidFactory).callFn([]).toStmt();
body.push(ifStmt(t, [ctorStmt], [r.set(nonCtorExpr).toStmt()]));
return r;
}
if (isDelegatedFactoryMetadata(meta)) {
const delegateArgs = injectDependencies(meta.delegateDeps, meta.target);
const factoryExpr = new (meta.delegateType === R3FactoryDelegateType.Class ? InstantiateExpr : InvokeFunctionExpr)(meta.delegate, delegateArgs);
retExpr = makeConditionalFactory(factoryExpr);
} else if (isExpressionFactoryMetadata(meta)) {
retExpr = makeConditionalFactory(meta.expression);
} else {
retExpr = ctorExpr;
}
if (retExpr === null) {
body.push(importExpr(Identifiers.invalidFactory).callFn([]).toStmt());
} else if (baseFactoryVar !== null) {
const getInheritedFactoryCall = importExpr(Identifiers.getInheritedFactory).callFn([meta.type.value]);
const baseFactory = new BinaryOperatorExpr(BinaryOperator.Or, baseFactoryVar, baseFactoryVar.set(getInheritedFactoryCall));
body.push(new ReturnStatement(baseFactory.callFn([typeForCtor])));
} else {
body.push(new ReturnStatement(retExpr));
}
let factoryFn = fn([new FnParam(t.name, DYNAMIC_TYPE)], body, INFERRED_TYPE, void 0, `${meta.name}_Factory`);
if (baseFactoryVar !== null) {
factoryFn = arrowFn([], [new DeclareVarStmt(baseFactoryVar.name), new ReturnStatement(factoryFn)]).callFn([], void 0, true);
}
return {
expression: factoryFn,
statements: [],
type: createFactoryType(meta)
};
}
function createFactoryType(meta) {
const ctorDepsType = meta.deps !== null && meta.deps !== "invalid" ? createCtorDepsType(meta.deps) : NONE_TYPE;
return expressionType(importExpr(Identifiers.FactoryDeclaration, [
typeWithParameters(meta.type.type, meta.typeArgumentCount),
ctorDepsType
]));
}
function injectDependencies(deps, target) {
return deps.map((dep, index) => compileInjectDependency(dep, target, index));
}
function compileInjectDependency(dep, target, index) {
if (dep.token === null) {
return importExpr(Identifiers.invalidFactoryDep).callFn([literal(index)]);
} else if (dep.attributeNameType === null) {
const flags = 0 | (dep.self ? 2 : 0) | (dep.skipSelf ? 4 : 0) | (dep.host ? 1 : 0) | (dep.optional ? 8 : 0) | (target === FactoryTarget.Pipe ? 16 : 0);
let flagsParam = flags !== 0 || dep.optional ? literal(flags) : null;
const injectArgs = [dep.token];
if (flagsParam) {
injectArgs.push(flagsParam);
}
const injectFn = getInjectFn(target);
return importExpr(injectFn).callFn(injectArgs);
} else {
return importExpr(Identifiers.injectAttribute).callFn([dep.token]);
}
}
function createCtorDepsType(deps) {
let hasTypes = false;
const attributeTypes = deps.map((dep) => {
const type = createCtorDepType(dep);
if (type !== null) {
hasTypes = true;
return type;
} else {
return literal(null);
}
});
if (hasTypes) {
return expressionType(literalArr(attributeTypes));
} else {
return NONE_TYPE;
}
}
function createCtorDepType(dep) {
const entries = [];
if (dep.attributeNameType !== null) {
entries.push({ key: "attribute", value: dep.attributeNameType, quoted: false });
}
if (dep.optional) {
entries.push({ key: "optional", value: literal(true), quoted: false });
}
if (dep.host) {
entries.push({ key: "host", value: literal(true), quoted: false });
}
if (dep.self) {
entries.push({ key: "self", value: literal(true), quoted: false });
}
if (dep.skipSelf) {
entries.push({ key: "skipSelf", value: literal(true), quoted: false });
}
return entries.length > 0 ? literalMap(entries) : null;
}
function isDelegatedFactoryMetadata(meta) {
return meta.delegateType !== void 0;
}
function isExpressionFactoryMetadata(meta) {
return meta.expression !== void 0;
}
function getInjectFn(target) {
switch (target) {
case FactoryTarget.Component:
case FactoryTarget.Directive:
case FactoryTarget.Pipe:
return Identifiers.directiveInject;
case FactoryTarget.NgModule:
case FactoryTarget.Injectable:
default:
return Identifiers.inject;
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/expression_parser/ast.mjs
var ParserError = class {
constructor(message, input, errLocation, ctxLocation) {
this.input = input;
this.errLocation = errLocation;
this.ctxLocation = ctxLocation;
this.message = `Parser Error: ${message} ${errLocation} [${input}] in ${ctxLocation}`;
}
};
var ParseSpan = class {
constructor(start, end) {
this.start = start;
this.end = end;
}
toAbsolute(absoluteOffset) {
return new AbsoluteSourceSpan(absoluteOffset + this.start, absoluteOffset + this.end);
}
};
var AST = class {
constructor(span, sourceSpan) {
this.span = span;
this.sourceSpan = sourceSpan;
}
toString() {
return "AST";
}
};
var ASTWithName = class extends AST {
constructor(span, sourceSpan, nameSpan) {
super(span, sourceSpan);
this.nameSpan = nameSpan;
}
};
var EmptyExpr = class extends AST {
visit(visitor, context = null) {
}
};
var ImplicitReceiver = class extends AST {
visit(visitor, context = null) {
return visitor.visitImplicitReceiver(this, context);
}
};
var ThisReceiver = class extends ImplicitReceiver {
visit(visitor, context = null) {
var _a2;
return (_a2 = visitor.visitThisReceiver) == null ? void 0 : _a2.call(visitor, this, context);
}
};
var Chain = class extends AST {
constructor(span, sourceSpan, expressions) {
super(span, sourceSpan);
this.expressions = expressions;
}
visit(visitor, context = null) {
return visitor.visitChain(this, context);
}
};
var Conditional = class extends AST {
constructor(span, sourceSpan, condition, trueExp, falseExp) {
super(span, sourceSpan);
this.condition = condition;
this.trueExp = trueExp;
this.falseExp = falseExp;
}
visit(visitor, context = null) {
return visitor.visitConditional(this, context);
}
};
var PropertyRead = class extends ASTWithName {
constructor(span, sourceSpan, nameSpan, receiver, name) {
super(span, sourceSpan, nameSpan);
this.receiver = receiver;
this.name = name;
}
visit(visitor, context = null) {
return visitor.visitPropertyRead(this, context);
}
};
var PropertyWrite = class extends ASTWithName {
constructor(span, sourceSpan, nameSpan, receiver, name, value) {
super(span, sourceSpan, nameSpan);
this.receiver = receiver;
this.name = name;
this.value = value;
}
visit(visitor, context = null) {
return visitor.visitPropertyWrite(this, context);
}
};
var SafePropertyRead = class extends ASTWithName {
constructor(span, sourceSpan, nameSpan, receiver, name) {
super(span, sourceSpan, nameSpan);
this.receiver = receiver;
this.name = name;
}
visit(visitor, context = null) {
return visitor.visitSafePropertyRead(this, context);
}
};
var KeyedRead = class extends AST {
constructor(span, sourceSpan, receiver, key) {
super(span, sourceSpan);
this.receiver = receiver;
this.key = key;
}
visit(visitor, context = null) {
return visitor.visitKeyedRead(this, context);
}
};
var SafeKeyedRead = class extends AST {
constructor(span, sourceSpan, receiver, key) {
super(span, sourceSpan);
this.receiver = receiver;
this.key = key;
}
visit(visitor, context = null) {
return visitor.visitSafeKeyedRead(this, context);
}
};
var KeyedWrite = class extends AST {
constructor(span, sourceSpan, receiver, key, value) {
super(span, sourceSpan);
this.receiver = receiver;
this.key = key;
this.value = value;
}
visit(visitor, context = null) {
return visitor.visitKeyedWrite(this, context);
}
};
var BindingPipe = class extends ASTWithName {
constructor(span, sourceSpan, exp, name, args, nameSpan) {
super(span, sourceSpan, nameSpan);
this.exp = exp;
this.name = name;
this.args = args;
}
visit(visitor, context = null) {
return visitor.visitPipe(this, context);
}
};
var LiteralPrimitive = class extends AST {
constructor(span, sourceSpan, value) {
super(span, sourceSpan);
this.value = value;
}
visit(visitor, context = null) {
return visitor.visitLiteralPrimitive(this, context);
}
};
var LiteralArray = class extends AST {
constructor(span, sourceSpan, expressions) {
super(span, sourceSpan);
this.expressions = expressions;
}
visit(visitor, context = null) {
return visitor.visitLiteralArray(this, context);
}
};
var LiteralMap = class extends AST {
constructor(span, sourceSpan, keys, values) {
super(span, sourceSpan);
this.keys = keys;
this.values = values;
}
visit(visitor, context = null) {
return visitor.visitLiteralMap(this, context);
}
};
var Interpolation = class extends AST {
constructor(span, sourceSpan, strings, expressions) {
super(span, sourceSpan);
this.strings = strings;
this.expressions = expressions;
}
visit(visitor, context = null) {
return visitor.visitInterpolation(this, context);
}
};
var Binary = class extends AST {
constructor(span, sourceSpan, operation, left, right) {
super(span, sourceSpan);
this.operation = operation;
this.left = left;
this.right = right;
}
visit(visitor, context = null) {
return visitor.visitBinary(this, context);
}
};
var Unary = class extends Binary {
static createMinus(span, sourceSpan, expr) {
return new Unary(span, sourceSpan, "-", expr, "-", new LiteralPrimitive(span, sourceSpan, 0), expr);
}
static createPlus(span, sourceSpan, expr) {
return new Unary(span, sourceSpan, "+", expr, "-", expr, new LiteralPrimitive(span, sourceSpan, 0));
}
constructor(span, sourceSpan, operator, expr, binaryOp, binaryLeft, binaryRight) {
super(span, sourceSpan, binaryOp, binaryLeft, binaryRight);
this.operator = operator;
this.expr = expr;
this.left = null;
this.right = null;
this.operation = null;
}
visit(visitor, context = null) {
if (visitor.visitUnary !== void 0) {
return visitor.visitUnary(this, context);
}
return visitor.visitBinary(this, context);
}
};
var PrefixNot = class extends AST {
constructor(span, sourceSpan, expression) {
super(span, sourceSpan);
this.expression = expression;
}
visit(visitor, context = null) {
return visitor.visitPrefixNot(this, context);
}
};
var NonNullAssert = class extends AST {
constructor(span, sourceSpan, expression) {
super(span, sourceSpan);
this.expression = expression;
}
visit(visitor, context = null) {
return visitor.visitNonNullAssert(this, context);
}
};
var Call = class extends AST {
constructor(span, sourceSpan, receiver, args, argumentSpan) {
super(span, sourceSpan);
this.receiver = receiver;
this.args = args;
this.argumentSpan = argumentSpan;
}
visit(visitor, context = null) {
return visitor.visitCall(this, context);
}
};
var SafeCall = class extends AST {
constructor(span, sourceSpan, receiver, args, argumentSpan) {
super(span, sourceSpan);
this.receiver = receiver;
this.args = args;
this.argumentSpan = argumentSpan;
}
visit(visitor, context = null) {
return visitor.visitSafeCall(this, context);
}
};
var AbsoluteSourceSpan = class {
constructor(start, end) {
this.start = start;
this.end = end;
}
};
var ASTWithSource = class extends AST {
constructor(ast, source, location, absoluteOffset, errors) {
super(new ParseSpan(0, source === null ? 0 : source.length), new AbsoluteSourceSpan(absoluteOffset, source === null ? absoluteOffset : absoluteOffset + source.length));
this.ast = ast;
this.source = source;
this.location = location;
this.errors = errors;
}
visit(visitor, context = null) {
if (visitor.visitASTWithSource) {
return visitor.visitASTWithSource(this, context);
}
return this.ast.visit(visitor, context);
}
toString() {
return `${this.source} in ${this.location}`;
}
};
var VariableBinding = class {
constructor(sourceSpan, key, value) {
this.sourceSpan = sourceSpan;
this.key = key;
this.value = value;
}
};
var ExpressionBinding = class {
constructor(sourceSpan, key, value) {
this.sourceSpan = sourceSpan;
this.key = key;
this.value = value;
}
};
var RecursiveAstVisitor2 = class {
visit(ast, context) {
ast.visit(this, context);
}
visitUnary(ast, context) {
this.visit(ast.expr, context);
}
visitBinary(ast, context) {
this.visit(ast.left, context);
this.visit(ast.right, context);
}
visitChain(ast, context) {
this.visitAll(ast.expressions, context);
}
visitConditional(ast, context) {
this.visit(ast.condition, context);
this.visit(ast.trueExp, context);
this.visit(ast.falseExp, context);
}
visitPipe(ast, context) {
this.visit(ast.exp, context);
this.visitAll(ast.args, context);
}
visitImplicitReceiver(ast, context) {
}
visitThisReceiver(ast, context) {
}
visitInterpolation(ast, context) {
this.visitAll(ast.expressions, context);
}
visitKeyedRead(ast, context) {
this.visit(ast.receiver, context);
this.visit(ast.key, context);
}
visitKeyedWrite(ast, context) {
this.visit(ast.receiver, context);
this.visit(ast.key, context);
this.visit(ast.value, context);
}
visitLiteralArray(ast, context) {
this.visitAll(ast.expressions, context);
}
visitLiteralMap(ast, context) {
this.visitAll(ast.values, context);
}
visitLiteralPrimitive(ast, context) {
}
visitPrefixNot(ast, context) {
this.visit(ast.expression, context);
}
visitNonNullAssert(ast, context) {
this.visit(ast.expression, context);
}
visitPropertyRead(ast, context) {
this.visit(ast.receiver, context);
}
visitPropertyWrite(ast, context) {
this.visit(ast.receiver, context);
this.visit(ast.value, context);
}
visitSafePropertyRead(ast, context) {
this.visit(ast.receiver, context);
}
visitSafeKeyedRead(ast, context) {
this.visit(ast.receiver, context);
this.visit(ast.key, context);
}
visitCall(ast, context) {
this.visit(ast.receiver, context);
this.visitAll(ast.args, context);
}
visitSafeCall(ast, context) {
this.visit(ast.receiver, context);
this.visitAll(ast.args, context);
}
visitAll(asts, context) {
for (const ast of asts) {
this.visit(ast, context);
}
}
};
var ParsedProperty = class {
constructor(name, expression, type, sourceSpan, keySpan, valueSpan) {
this.name = name;
this.expression = expression;
this.type = type;
this.sourceSpan = sourceSpan;
this.keySpan = keySpan;
this.valueSpan = valueSpan;
this.isLiteral = this.type === ParsedPropertyType.LITERAL_ATTR;
this.isAnimation = this.type === ParsedPropertyType.ANIMATION;
}
};
var ParsedPropertyType;
(function(ParsedPropertyType2) {
ParsedPropertyType2[ParsedPropertyType2["DEFAULT"] = 0] = "DEFAULT";
ParsedPropertyType2[ParsedPropertyType2["LITERAL_ATTR"] = 1] = "LITERAL_ATTR";
ParsedPropertyType2[ParsedPropertyType2["ANIMATION"] = 2] = "ANIMATION";
ParsedPropertyType2[ParsedPropertyType2["TWO_WAY"] = 3] = "TWO_WAY";
})(ParsedPropertyType || (ParsedPropertyType = {}));
var ParsedEventType;
(function(ParsedEventType2) {
ParsedEventType2[ParsedEventType2["Regular"] = 0] = "Regular";
ParsedEventType2[ParsedEventType2["Animation"] = 1] = "Animation";
ParsedEventType2[ParsedEventType2["TwoWay"] = 2] = "TwoWay";
})(ParsedEventType || (ParsedEventType = {}));
var ParsedEvent = class {
constructor(name, targetOrPhase, type, handler, sourceSpan, handlerSpan, keySpan) {
this.name = name;
this.targetOrPhase = targetOrPhase;
this.type = type;
this.handler = handler;
this.sourceSpan = sourceSpan;
this.handlerSpan = handlerSpan;
this.keySpan = keySpan;
}
};
var ParsedVariable = class {
constructor(name, value, sourceSpan, keySpan, valueSpan) {
this.name = name;
this.value = value;
this.sourceSpan = sourceSpan;
this.keySpan = keySpan;
this.valueSpan = valueSpan;
}
};
var BindingType;
(function(BindingType2) {
BindingType2[BindingType2["Property"] = 0] = "Property";
BindingType2[BindingType2["Attribute"] = 1] = "Attribute";
BindingType2[BindingType2["Class"] = 2] = "Class";
BindingType2[BindingType2["Style"] = 3] = "Style";
BindingType2[BindingType2["Animation"] = 4] = "Animation";
BindingType2[BindingType2["TwoWay"] = 5] = "TwoWay";
})(BindingType || (BindingType = {}));
var BoundElementProperty = class {
constructor(name, type, securityContext, value, unit, sourceSpan, keySpan, valueSpan) {
this.name = name;
this.type = type;
this.securityContext = securityContext;
this.value = value;
this.unit = unit;
this.sourceSpan = sourceSpan;
this.keySpan = keySpan;
this.valueSpan = valueSpan;
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/ml_parser/tags.mjs
var TagContentType;
(function(TagContentType2) {
TagContentType2[TagContentType2["RAW_TEXT"] = 0] = "RAW_TEXT";
TagContentType2[TagContentType2["ESCAPABLE_RAW_TEXT"] = 1] = "ESCAPABLE_RAW_TEXT";
TagContentType2[TagContentType2["PARSABLE_DATA"] = 2] = "PARSABLE_DATA";
})(TagContentType || (TagContentType = {}));
function splitNsName(elementName, fatal = true) {
if (elementName[0] != ":") {
return [null, elementName];
}
const colonIndex = elementName.indexOf(":", 1);
if (colonIndex === -1) {
if (fatal) {
throw new Error(`Unsupported format "${elementName}" expecting ":namespace:name"`);
} else {
return [null, elementName];
}
}
return [elementName.slice(1, colonIndex), elementName.slice(colonIndex + 1)];
}
function isNgContainer(tagName) {
return splitNsName(tagName)[1] === "ng-container";
}
function isNgContent(tagName) {
return splitNsName(tagName)[1] === "ng-content";
}
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;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/r3_ast.mjs
var Comment = class {
constructor(value, sourceSpan) {
this.value = value;
this.sourceSpan = sourceSpan;
}
visit(_visitor2) {
throw new Error("visit() not implemented for Comment");
}
};
var Text = class {
constructor(value, sourceSpan) {
this.value = value;
this.sourceSpan = sourceSpan;
}
visit(visitor) {
return visitor.visitText(this);
}
};
var BoundText = class {
constructor(value, sourceSpan, i18n2) {
this.value = value;
this.sourceSpan = sourceSpan;
this.i18n = i18n2;
}
visit(visitor) {
return visitor.visitBoundText(this);
}
};
var TextAttribute = class {
constructor(name, value, sourceSpan, keySpan, valueSpan, i18n2) {
this.name = name;
this.value = value;
this.sourceSpan = sourceSpan;
this.keySpan = keySpan;
this.valueSpan = valueSpan;
this.i18n = i18n2;
}
visit(visitor) {
return visitor.visitTextAttribute(this);
}
};
var BoundAttribute = class {
constructor(name, type, securityContext, value, unit, sourceSpan, keySpan, valueSpan, i18n2) {
this.name = name;
this.type = type;
this.securityContext = securityContext;
this.value = value;
this.unit = unit;
this.sourceSpan = sourceSpan;
this.keySpan = keySpan;
this.valueSpan = valueSpan;
this.i18n = i18n2;
}
static fromBoundElementProperty(prop, i18n2) {
if (prop.keySpan === void 0) {
throw new Error(`Unexpected state: keySpan must be defined for bound attributes but was not for ${prop.name}: ${prop.sourceSpan}`);
}
return new BoundAttribute(prop.name, prop.type, prop.securityContext, prop.value, prop.unit, prop.sourceSpan, prop.keySpan, prop.valueSpan, i18n2);
}
visit(visitor) {
return visitor.visitBoundAttribute(this);
}
};
var BoundEvent = class {
constructor(name, type, handler, target, phase, sourceSpan, handlerSpan, keySpan) {
this.name = name;
this.type = type;
this.handler = handler;
this.target = target;
this.phase = phase;
this.sourceSpan = sourceSpan;
this.handlerSpan = handlerSpan;
this.keySpan = keySpan;
}
static fromParsedEvent(event) {
const target = event.type === ParsedEventType.Regular ? event.targetOrPhase : null;
const phase = event.type === ParsedEventType.Animation ? event.targetOrPhase : null;
if (event.keySpan === void 0) {
throw new Error(`Unexpected state: keySpan must be defined for bound event but was not for ${event.name}: ${event.sourceSpan}`);
}
return new BoundEvent(event.name, event.type, event.handler, target, phase, event.sourceSpan, event.handlerSpan, event.keySpan);
}
visit(visitor) {
return visitor.visitBoundEvent(this);
}
};
var Element = class {
constructor(name, attributes, inputs, outputs, children, references, sourceSpan, startSourceSpan, endSourceSpan, i18n2) {
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 = i18n2;
}
visit(visitor) {
return visitor.visitElement(this);
}
};
var DeferredTrigger = class {
constructor(nameSpan, sourceSpan, prefetchSpan, whenOrOnSourceSpan) {
this.nameSpan = nameSpan;
this.sourceSpan = sourceSpan;
this.prefetchSpan = prefetchSpan;
this.whenOrOnSourceSpan = whenOrOnSourceSpan;
}
visit(visitor) {
return visitor.visitDeferredTrigger(this);
}
};
var BoundDeferredTrigger = class extends DeferredTrigger {
constructor(value, sourceSpan, prefetchSpan, whenSourceSpan) {
super(null, sourceSpan, prefetchSpan, whenSourceSpan);
this.value = value;
}
};
var IdleDeferredTrigger = class extends DeferredTrigger {
};
var ImmediateDeferredTrigger = class extends DeferredTrigger {
};
var HoverDeferredTrigger = class extends DeferredTrigger {
constructor(reference2, nameSpan, sourceSpan, prefetchSpan, onSourceSpan) {
super(nameSpan, sourceSpan, prefetchSpan, onSourceSpan);
this.reference = reference2;
}
};
var TimerDeferredTrigger = class extends DeferredTrigger {
constructor(delay, nameSpan, sourceSpan, prefetchSpan, onSourceSpan) {
super(nameSpan, sourceSpan, prefetchSpan, onSourceSpan);
this.delay = delay;
}
};
var InteractionDeferredTrigger = class extends DeferredTrigger {
constructor(reference2, nameSpan, sourceSpan, prefetchSpan, onSourceSpan) {
super(nameSpan, sourceSpan, prefetchSpan, onSourceSpan);
this.reference = reference2;
}
};
var ViewportDeferredTrigger = class extends DeferredTrigger {
constructor(reference2, nameSpan, sourceSpan, prefetchSpan, onSourceSpan) {
super(nameSpan, sourceSpan, prefetchSpan, onSourceSpan);
this.reference = reference2;
}
};
var BlockNode = class {
constructor(nameSpan, sourceSpan, startSourceSpan, endSourceSpan) {
this.nameSpan = nameSpan;
this.sourceSpan = sourceSpan;
this.startSourceSpan = startSourceSpan;
this.endSourceSpan = endSourceSpan;
}
};
var DeferredBlockPlaceholder = class extends BlockNode {
constructor(children, minimumTime, nameSpan, sourceSpan, startSourceSpan, endSourceSpan, i18n2) {
super(nameSpan, sourceSpan, startSourceSpan, endSourceSpan);
this.children = children;
this.minimumTime = minimumTime;
this.i18n = i18n2;
}
visit(visitor) {
return visitor.visitDeferredBlockPlaceholder(this);
}
};
var DeferredBlockLoading = class extends BlockNode {
constructor(children, afterTime, minimumTime, nameSpan, sourceSpan, startSourceSpan, endSourceSpan, i18n2) {
super(nameSpan, sourceSpan, startSourceSpan, endSourceSpan);
this.children = children;
this.afterTime = afterTime;
this.minimumTime = minimumTime;
this.i18n = i18n2;
}
visit(visitor) {
return visitor.visitDeferredBlockLoading(this);
}
};
var DeferredBlockError = class extends BlockNode {
constructor(children, nameSpan, sourceSpan, startSourceSpan, endSourceSpan, i18n2) {
super(nameSpan, sourceSpan, startSourceSpan, endSourceSpan);
this.children = children;
this.i18n = i18n2;
}
visit(visitor) {
return visitor.visitDeferredBlockError(this);
}
};
var DeferredBlock = class extends BlockNode {
constructor(children, triggers, prefetchTriggers, placeholder, loading, error, nameSpan, sourceSpan, mainBlockSpan, startSourceSpan, endSourceSpan, i18n2) {
super(nameSpan, sourceSpan, startSourceSpan, endSourceSpan);
this.children = children;
this.placeholder = placeholder;
this.loading = loading;
this.error = error;
this.mainBlockSpan = mainBlockSpan;
this.i18n = i18n2;
this.triggers = triggers;
this.prefetchTriggers = prefetchTriggers;
this.definedTriggers = Object.keys(triggers);
this.definedPrefetchTriggers = Object.keys(prefetchTriggers);
}
visit(visitor) {
return visitor.visitDeferredBlock(this);
}
visitAll(visitor) {
this.visitTriggers(this.definedTriggers, this.triggers, visitor);
this.visitTriggers(this.definedPrefetchTriggers, this.prefetchTriggers, visitor);
visitAll(visitor, this.children);
const remainingBlocks = [this.placeholder, this.loading, this.error].filter((x) => x !== null);
visitAll(visitor, remainingBlocks);
}
visitTriggers(keys, triggers, visitor) {
visitAll(visitor, keys.map((k) => triggers[k]));
}
};
var SwitchBlock = class extends BlockNode {
constructor(expression, cases, unknownBlocks, sourceSpan, startSourceSpan, endSourceSpan, nameSpan) {
super(nameSpan, sourceSpan, startSourceSpan, endSourceSpan);
this.expression = expression;
this.cases = cases;
this.unknownBlocks = unknownBlocks;
}
visit(visitor) {
return visitor.visitSwitchBlock(this);
}
};
var SwitchBlockCase = class extends BlockNode {
constructor(expression, children, sourceSpan, startSourceSpan, endSourceSpan, nameSpan, i18n2) {
super(nameSpan, sourceSpan, startSourceSpan, endSourceSpan);
this.expression = expression;
this.children = children;
this.i18n = i18n2;
}
visit(visitor) {
return visitor.visitSwitchBlockCase(this);
}
};
var ForLoopBlock = class extends BlockNode {
constructor(item, expression, trackBy, trackKeywordSpan, contextVariables, children, empty, sourceSpan, mainBlockSpan, startSourceSpan, endSourceSpan, nameSpan, i18n2) {
super(nameSpan, sourceSpan, startSourceSpan, endSourceSpan);
this.item = item;
this.expression = expression;
this.trackBy = trackBy;
this.trackKeywordSpan = trackKeywordSpan;
this.contextVariables = contextVariables;
this.children = children;
this.empty = empty;
this.mainBlockSpan = mainBlockSpan;
this.i18n = i18n2;
}
visit(visitor) {
return visitor.visitForLoopBlock(this);
}
};
var ForLoopBlockEmpty = class extends BlockNode {
constructor(children, sourceSpan, startSourceSpan, endSourceSpan, nameSpan, i18n2) {
super(nameSpan, sourceSpan, startSourceSpan, endSourceSpan);
this.children = children;
this.i18n = i18n2;
}
visit(visitor) {
return visitor.visitForLoopBlockEmpty(this);
}
};
var IfBlock = class extends BlockNode {
constructor(branches, sourceSpan, startSourceSpan, endSourceSpan, nameSpan) {
super(nameSpan, sourceSpan, startSourceSpan, endSourceSpan);
this.branches = branches;
}
visit(visitor) {
return visitor.visitIfBlock(this);
}
};
var IfBlockBranch = class extends BlockNode {
constructor(expression, children, expressionAlias, sourceSpan, startSourceSpan, endSourceSpan, nameSpan, i18n2) {
super(nameSpan, sourceSpan, startSourceSpan, endSourceSpan);
this.expression = expression;
this.children = children;
this.expressionAlias = expressionAlias;
this.i18n = i18n2;
}
visit(visitor) {
return visitor.visitIfBlockBranch(this);
}
};
var UnknownBlock = class {
constructor(name, sourceSpan, nameSpan) {
this.name = name;
this.sourceSpan = sourceSpan;
this.nameSpan = nameSpan;
}
visit(visitor) {
return visitor.visitUnknownBlock(this);
}
};
var LetDeclaration = class {
constructor(name, value, sourceSpan, nameSpan, valueSpan) {
this.name = name;
this.value = value;
this.sourceSpan = sourceSpan;
this.nameSpan = nameSpan;
this.valueSpan = valueSpan;
}
visit(visitor) {
return visitor.visitLetDeclaration(this);
}
};
var Template = class {
constructor(tagName, attributes, inputs, outputs, templateAttrs, children, references, variables, sourceSpan, startSourceSpan, endSourceSpan, i18n2) {
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 = i18n2;
}
visit(visitor) {
return visitor.visitTemplate(this);
}
};
var Content = class {
constructor(selector, attributes, children, sourceSpan, i18n2) {
this.selector = selector;
this.attributes = attributes;
this.children = children;
this.sourceSpan = sourceSpan;
this.i18n = i18n2;
this.name = "ng-content";
}
visit(visitor) {
return visitor.visitContent(this);
}
};
var Variable = class {
constructor(name, value, sourceSpan, keySpan, valueSpan) {
this.name = name;
this.value = value;
this.sourceSpan = sourceSpan;
this.keySpan = keySpan;
this.valueSpan = valueSpan;
}
visit(visitor) {
return visitor.visitVariable(this);
}
};
var Reference = class {
constructor(name, value, sourceSpan, keySpan, valueSpan) {
this.name = name;
this.value = value;
this.sourceSpan = sourceSpan;
this.keySpan = keySpan;
this.valueSpan = valueSpan;
}
visit(visitor) {
return visitor.visitReference(this);
}
};
var Icu = class {
constructor(vars, placeholders, sourceSpan, i18n2) {
this.vars = vars;
this.placeholders = placeholders;
this.sourceSpan = sourceSpan;
this.i18n = i18n2;
}
visit(visitor) {
return visitor.visitIcu(this);
}
};
var RecursiveVisitor = class {
visitElement(element2) {
visitAll(this, element2.attributes);
visitAll(this, element2.inputs);
visitAll(this, element2.outputs);
visitAll(this, element2.children);
visitAll(this, element2.references);
}
visitTemplate(template2) {
visitAll(this, template2.attributes);
visitAll(this, template2.inputs);
visitAll(this, template2.outputs);
visitAll(this, template2.children);
visitAll(this, template2.references);
visitAll(this, template2.variables);
}
visitDeferredBlock(deferred) {
deferred.visitAll(this);
}
visitDeferredBlockPlaceholder(block) {
visitAll(this, block.children);
}
visitDeferredBlockError(block) {
visitAll(this, block.children);
}
visitDeferredBlockLoading(block) {
visitAll(this, block.children);
}
visitSwitchBlock(block) {
visitAll(this, block.cases);
}
visitSwitchBlockCase(block) {
visitAll(this, block.children);
}
visitForLoopBlock(block) {
const blockItems = [block.item, ...block.contextVariables, ...block.children];
block.empty && blockItems.push(block.empty);
visitAll(this, blockItems);
}
visitForLoopBlockEmpty(block) {
visitAll(this, block.children);
}
visitIfBlock(block) {
visitAll(this, block.branches);
}
visitIfBlockBranch(block) {
const blockItems = block.children;
block.expressionAlias && blockItems.push(block.expressionAlias);
visitAll(this, blockItems);
}
visitContent(content) {
visitAll(this, content.children);
}
visitVariable(variable2) {
}
visitReference(reference2) {
}
visitTextAttribute(attribute2) {
}
visitBoundAttribute(attribute2) {
}
visitBoundEvent(attribute2) {
}
visitText(text2) {
}
visitBoundText(text2) {
}
visitIcu(icu) {
}
visitDeferredTrigger(trigger) {
}
visitUnknownBlock(block) {
}
visitLetDeclaration(decl) {
}
};
function visitAll(visitor, nodes) {
const result = [];
if (visitor.visit) {
for (const node of nodes) {
visitor.visit(node) || node.visit(visitor);
}
} else {
for (const node of nodes) {
const newNode = node.visit(visitor);
if (newNode) {
result.push(newNode);
}
}
}
return result;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/i18n/i18n_ast.mjs
var Message = class {
constructor(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.legacyIds = [];
this.id = this.customId;
this.messageString = serializeMessage(this.nodes);
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 = [];
}
}
};
var Text2 = class {
constructor(value, sourceSpan) {
this.value = value;
this.sourceSpan = sourceSpan;
}
visit(visitor, context) {
return visitor.visitText(this, context);
}
};
var Container = class {
constructor(children, sourceSpan) {
this.children = children;
this.sourceSpan = sourceSpan;
}
visit(visitor, context) {
return visitor.visitContainer(this, context);
}
};
var Icu2 = class {
constructor(expression, type, cases, sourceSpan, expressionPlaceholder) {
this.expression = expression;
this.type = type;
this.cases = cases;
this.sourceSpan = sourceSpan;
this.expressionPlaceholder = expressionPlaceholder;
}
visit(visitor, context) {
return visitor.visitIcu(this, context);
}
};
var TagPlaceholder = class {
constructor(tag, attrs, startName, closeName, children, isVoid, sourceSpan, startSourceSpan, endSourceSpan) {
this.tag = tag;
this.attrs = attrs;
this.startName = startName;
this.closeName = closeName;
this.children = children;
this.isVoid = isVoid;
this.sourceSpan = sourceSpan;
this.startSourceSpan = startSourceSpan;
this.endSourceSpan = endSourceSpan;
}
visit(visitor, context) {
return visitor.visitTagPlaceholder(this, context);
}
};
var Placeholder = class {
constructor(value, name, sourceSpan) {
this.value = value;
this.name = name;
this.sourceSpan = sourceSpan;
}
visit(visitor, context) {
return visitor.visitPlaceholder(this, context);
}
};
var IcuPlaceholder = class {
constructor(value, name, sourceSpan) {
this.value = value;
this.name = name;
this.sourceSpan = sourceSpan;
}
visit(visitor, context) {
return visitor.visitIcuPlaceholder(this, context);
}
};
var BlockPlaceholder = class {
constructor(name, parameters, startName, closeName, children, sourceSpan, startSourceSpan, endSourceSpan) {
this.name = name;
this.parameters = parameters;
this.startName = startName;
this.closeName = closeName;
this.children = children;
this.sourceSpan = sourceSpan;
this.startSourceSpan = startSourceSpan;
this.endSourceSpan = endSourceSpan;
}
visit(visitor, context) {
return visitor.visitBlockPlaceholder(this, context);
}
};
var CloneVisitor = class {
visitText(text2, context) {
return new Text2(text2.value, text2.sourceSpan);
}
visitContainer(container, context) {
const children = container.children.map((n2) => n2.visit(this, context));
return new Container(children, container.sourceSpan);
}
visitIcu(icu, context) {
const cases = {};
Object.keys(icu.cases).forEach((key) => cases[key] = icu.cases[key].visit(this, context));
const msg = new Icu2(icu.expression, icu.type, cases, icu.sourceSpan, icu.expressionPlaceholder);
return msg;
}
visitTagPlaceholder(ph, context) {
const children = ph.children.map((n2) => n2.visit(this, context));
return new TagPlaceholder(ph.tag, ph.attrs, ph.startName, ph.closeName, children, ph.isVoid, ph.sourceSpan, ph.startSourceSpan, ph.endSourceSpan);
}
visitPlaceholder(ph, context) {
return new Placeholder(ph.value, ph.name, ph.sourceSpan);
}
visitIcuPlaceholder(ph, context) {
return new IcuPlaceholder(ph.value, ph.name, ph.sourceSpan);
}
visitBlockPlaceholder(ph, context) {
const children = ph.children.map((n2) => n2.visit(this, context));
return new BlockPlaceholder(ph.name, ph.parameters, ph.startName, ph.closeName, children, ph.sourceSpan, ph.startSourceSpan, ph.endSourceSpan);
}
};
var RecurseVisitor = class {
visitText(text2, context) {
}
visitContainer(container, context) {
container.children.forEach((child) => child.visit(this));
}
visitIcu(icu, context) {
Object.keys(icu.cases).forEach((k) => {
icu.cases[k].visit(this);
});
}
visitTagPlaceholder(ph, context) {
ph.children.forEach((child) => child.visit(this));
}
visitPlaceholder(ph, context) {
}
visitIcuPlaceholder(ph, context) {
}
visitBlockPlaceholder(ph, context) {
ph.children.forEach((child) => child.visit(this));
}
};
function serializeMessage(messageNodes) {
const visitor = new LocalizeMessageStringVisitor();
const str = messageNodes.map((n2) => n2.visit(visitor)).join("");
return str;
}
var LocalizeMessageStringVisitor = class {
visitText(text2) {
return text2.value;
}
visitContainer(container) {
return container.children.map((child) => child.visit(this)).join("");
}
visitIcu(icu) {
const strCases = Object.keys(icu.cases).map((k) => `${k} {${icu.cases[k].visit(this)}}`);
return `{${icu.expressionPlaceholder}, ${icu.type}, ${strCases.join(" ")}}`;
}
visitTagPlaceholder(ph) {
const children = ph.children.map((child) => child.visit(this)).join("");
return `{$${ph.startName}}${children}{$${ph.closeName}}`;
}
visitPlaceholder(ph) {
return `{$${ph.name}}`;
}
visitIcuPlaceholder(ph) {
return `{$${ph.name}}`;
}
visitBlockPlaceholder(ph) {
const children = ph.children.map((child) => child.visit(this)).join("");
return `{$${ph.startName}}${children}{$${ph.closeName}}`;
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/i18n/serializers/serializer.mjs
var Serializer = class {
createNameMapper(message) {
return null;
}
};
var SimplePlaceholderMapper = class extends RecurseVisitor {
constructor(message, mapName) {
super();
this.mapName = mapName;
this.internalToPublic = {};
this.publicToNextId = {};
this.publicToInternal = {};
message.nodes.forEach((node) => node.visit(this));
}
toPublicName(internalName) {
return this.internalToPublic.hasOwnProperty(internalName) ? this.internalToPublic[internalName] : null;
}
toInternalName(publicName) {
return this.publicToInternal.hasOwnProperty(publicName) ? this.publicToInternal[publicName] : null;
}
visitText(text2, context) {
return null;
}
visitTagPlaceholder(ph, context) {
this.visitPlaceholderName(ph.startName);
super.visitTagPlaceholder(ph, context);
this.visitPlaceholderName(ph.closeName);
}
visitPlaceholder(ph, context) {
this.visitPlaceholderName(ph.name);
}
visitBlockPlaceholder(ph, context) {
this.visitPlaceholderName(ph.startName);
super.visitBlockPlaceholder(ph, context);
this.visitPlaceholderName(ph.closeName);
}
visitIcuPlaceholder(ph, context) {
this.visitPlaceholderName(ph.name);
}
visitPlaceholderName(internalName) {
if (!internalName || this.internalToPublic.hasOwnProperty(internalName)) {
return;
}
let publicName = this.mapName(internalName);
if (this.publicToInternal.hasOwnProperty(publicName)) {
const 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;
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/i18n/serializers/xml_helper.mjs
var _Visitor = class {
visitTag(tag) {
const strAttrs = this._serializeAttributes(tag.attrs);
if (tag.children.length == 0) {
return `<${tag.name}${strAttrs}/>`;
}
const strChildren = tag.children.map((node) => node.visit(this));
return `<${tag.name}${strAttrs}>${strChildren.join("")}${tag.name}>`;
}
visitText(text2) {
return text2.value;
}
visitDeclaration(decl) {
return ``;
}
_serializeAttributes(attrs) {
const strAttrs = Object.keys(attrs).map((name) => `${name}="${attrs[name]}"`).join(" ");
return strAttrs.length > 0 ? " " + strAttrs : "";
}
visitDoctype(doctype) {
return ``;
}
};
var _visitor = new _Visitor();
function serialize(nodes) {
return nodes.map((node) => node.visit(_visitor)).join("");
}
var Declaration = class {
constructor(unescapedAttrs) {
this.attrs = {};
Object.keys(unescapedAttrs).forEach((k) => {
this.attrs[k] = escapeXml(unescapedAttrs[k]);
});
}
visit(visitor) {
return visitor.visitDeclaration(this);
}
};
var Doctype = class {
constructor(rootTag, dtd) {
this.rootTag = rootTag;
this.dtd = dtd;
}
visit(visitor) {
return visitor.visitDoctype(this);
}
};
var Tag = class {
constructor(name, unescapedAttrs = {}, children = []) {
this.name = name;
this.children = children;
this.attrs = {};
Object.keys(unescapedAttrs).forEach((k) => {
this.attrs[k] = escapeXml(unescapedAttrs[k]);
});
}
visit(visitor) {
return visitor.visitTag(this);
}
};
var Text3 = class {
constructor(unescapedValue) {
this.value = escapeXml(unescapedValue);
}
visit(visitor) {
return visitor.visitText(this);
}
};
var CR = class extends Text3 {
constructor(ws = 0) {
super(`
${new Array(ws + 1).join(" ")}`);
}
};
var _ESCAPED_CHARS = [
[/&/g, "&"],
[/"/g, """],
[/'/g, "'"],
[//g, ">"]
];
function escapeXml(text2) {
return _ESCAPED_CHARS.reduce((text3, entry) => text3.replace(entry[0], entry[1]), text2);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/i18n/serializers/xmb.mjs
var _XMB_HANDLER = "angular";
var _MESSAGES_TAG = "messagebundle";
var _MESSAGE_TAG = "msg";
var _PLACEHOLDER_TAG = "ph";
var _EXAMPLE_TAG = "ex";
var _SOURCE_TAG = "source";
var _DOCTYPE = `
`;
var Xmb = class extends Serializer {
constructor(preservePlaceholders = true) {
super();
this.preservePlaceholders = preservePlaceholders;
}
write(messages, locale) {
const exampleVisitor = new ExampleVisitor();
const visitor = new _Visitor2();
const rootNode = new Tag(_MESSAGES_TAG);
rootNode.attrs["handler"] = _XMB_HANDLER;
messages.forEach((message) => {
const attrs = { id: message.id };
if (message.description) {
attrs["desc"] = message.description;
}
if (message.meaning) {
attrs["meaning"] = message.meaning;
}
let sourceTags = [];
message.sources.forEach((source) => {
sourceTags.push(new Tag(_SOURCE_TAG, {}, [
new Text3(`${source.filePath}:${source.startLine}${source.endLine !== source.startLine ? "," + source.endLine : ""}`)
]));
});
rootNode.children.push(new CR(2), new Tag(_MESSAGE_TAG, attrs, [...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()
]);
}
load(content, url) {
throw new Error("Unsupported");
}
digest(message) {
return digest2(message, this.preservePlaceholders);
}
createNameMapper(message) {
return new SimplePlaceholderMapper(message, toPublicName);
}
};
var _Visitor2 = class {
visitText(text2, context) {
return [new Text3(text2.value)];
}
visitContainer(container, context) {
const nodes = [];
container.children.forEach((node) => nodes.push(...node.visit(this)));
return nodes;
}
visitIcu(icu, context) {
const nodes = [new Text3(`{${icu.expressionPlaceholder}, ${icu.type}, `)];
Object.keys(icu.cases).forEach((c) => {
nodes.push(new Text3(`${c} {`), ...icu.cases[c].visit(this), new Text3(`} `));
});
nodes.push(new Text3(`}`));
return nodes;
}
visitTagPlaceholder(ph, context) {
const startTagAsText = new Text3(`<${ph.tag}>`);
const startEx = new Tag(_EXAMPLE_TAG, {}, [startTagAsText]);
const startTagPh = new Tag(_PLACEHOLDER_TAG, { name: ph.startName }, [
startEx,
startTagAsText
]);
if (ph.isVoid) {
return [startTagPh];
}
const closeTagAsText = new Text3(`${ph.tag}>`);
const closeEx = new Tag(_EXAMPLE_TAG, {}, [closeTagAsText]);
const closeTagPh = new Tag(_PLACEHOLDER_TAG, { name: ph.closeName }, [
closeEx,
closeTagAsText
]);
return [startTagPh, ...this.serialize(ph.children), closeTagPh];
}
visitPlaceholder(ph, context) {
const interpolationAsText = new Text3(`{{${ph.value}}}`);
const exTag = new Tag(_EXAMPLE_TAG, {}, [interpolationAsText]);
return [
new Tag(_PLACEHOLDER_TAG, { name: ph.name }, [exTag, interpolationAsText])
];
}
visitBlockPlaceholder(ph, context) {
const startAsText = new Text3(`@${ph.name}`);
const startEx = new Tag(_EXAMPLE_TAG, {}, [startAsText]);
const startTagPh = new Tag(_PLACEHOLDER_TAG, { name: ph.startName }, [startEx, startAsText]);
const closeAsText = new Text3(`}`);
const closeEx = new Tag(_EXAMPLE_TAG, {}, [closeAsText]);
const closeTagPh = new Tag(_PLACEHOLDER_TAG, { name: ph.closeName }, [closeEx, closeAsText]);
return [startTagPh, ...this.serialize(ph.children), closeTagPh];
}
visitIcuPlaceholder(ph, context) {
const icuExpression = ph.value.expression;
const icuType = ph.value.type;
const icuCases = Object.keys(ph.value.cases).map((value) => value + " {...}").join(" ");
const icuAsText = new Text3(`{${icuExpression}, ${icuType}, ${icuCases}}`);
const exTag = new Tag(_EXAMPLE_TAG, {}, [icuAsText]);
return [
new Tag(_PLACEHOLDER_TAG, { name: ph.name }, [exTag, icuAsText])
];
}
serialize(nodes) {
return [].concat(...nodes.map((node) => node.visit(this)));
}
};
function digest2(message, preservePlaceholders) {
return decimalDigest(message, preservePlaceholders);
}
var ExampleVisitor = class {
addDefaultExamples(node) {
node.visit(this);
return node;
}
visitTag(tag) {
if (tag.name === _PLACEHOLDER_TAG) {
if (!tag.children || tag.children.length == 0) {
const exText = new Text3(tag.attrs["name"] || "...");
tag.children = [new Tag(_EXAMPLE_TAG, {}, [exText])];
}
} else if (tag.children) {
tag.children.forEach((node) => node.visit(this));
}
}
visitText(text2) {
}
visitDeclaration(decl) {
}
visitDoctype(doctype) {
}
};
function toPublicName(internalName) {
return internalName.toUpperCase().replace(/[^A-Z0-9_]/g, "_");
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/view/i18n/util.mjs
var I18N_ATTR = "i18n";
var I18N_ATTR_PREFIX = "i18n-";
var I18N_ICU_VAR_PREFIX = "VAR_";
function isI18nAttribute(name) {
return name === I18N_ATTR || name.startsWith(I18N_ATTR_PREFIX);
}
function hasI18nAttrs(element2) {
return element2.attrs.some((attr) => isI18nAttribute(attr.name));
}
function icuFromI18nMessage(message) {
return message.nodes[0];
}
function formatI18nPlaceholderNamesInMap(params = {}, useCamelCase) {
const _params = {};
if (params && Object.keys(params).length) {
Object.keys(params).forEach((key) => _params[formatI18nPlaceholderName(key, useCamelCase)] = params[key]);
}
return _params;
}
function formatI18nPlaceholderName(name, useCamelCase = true) {
const publicName = toPublicName(name);
if (!useCamelCase) {
return publicName;
}
const chunks = publicName.split("_");
if (chunks.length === 1) {
return name.toLowerCase();
}
let postfix;
if (/^\d+$/.test(chunks[chunks.length - 1])) {
postfix = chunks.pop();
}
let raw = chunks.shift().toLowerCase();
if (chunks.length) {
raw += chunks.map((c) => c.charAt(0).toUpperCase() + c.slice(1).toLowerCase()).join("");
}
return postfix ? `${raw}_${postfix}` : raw;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/view/util.mjs
var UNSAFE_OBJECT_KEY_NAME_REGEXP = /[-.]/;
var TEMPORARY_NAME = "_t";
var CONTEXT_NAME = "ctx";
var RENDER_FLAGS = "rf";
function temporaryAllocator(pushStatement, name) {
let temp = null;
return () => {
if (!temp) {
pushStatement(new DeclareVarStmt(TEMPORARY_NAME, void 0, DYNAMIC_TYPE));
temp = variable(name);
}
return temp;
};
}
function asLiteral(value) {
if (Array.isArray(value)) {
return literalArr(value.map(asLiteral));
}
return literal(value, INFERRED_TYPE);
}
function conditionallyCreateDirectiveBindingLiteral(map, forInputs) {
const keys = Object.getOwnPropertyNames(map);
if (keys.length === 0) {
return null;
}
return literalMap(keys.map((key) => {
const value = map[key];
let declaredName;
let publicName;
let minifiedName;
let expressionValue;
if (typeof value === "string") {
declaredName = key;
minifiedName = key;
publicName = value;
expressionValue = asLiteral(publicName);
} else {
minifiedName = key;
declaredName = value.classPropertyName;
publicName = value.bindingPropertyName;
const differentDeclaringName = publicName !== declaredName;
const hasDecoratorInputTransform = value.transformFunction !== null;
let flags = InputFlags.None;
if (value.isSignal) {
flags |= InputFlags.SignalBased;
}
if (hasDecoratorInputTransform) {
flags |= InputFlags.HasDecoratorInputTransform;
}
if (forInputs && (differentDeclaringName || hasDecoratorInputTransform || flags !== InputFlags.None)) {
const result = [literal(flags), asLiteral(publicName)];
if (differentDeclaringName || hasDecoratorInputTransform) {
result.push(asLiteral(declaredName));
if (hasDecoratorInputTransform) {
result.push(value.transformFunction);
}
}
expressionValue = literalArr(result);
} else {
expressionValue = asLiteral(publicName);
}
}
return {
key: minifiedName,
quoted: UNSAFE_OBJECT_KEY_NAME_REGEXP.test(minifiedName),
value: expressionValue
};
}));
}
var DefinitionMap = class {
constructor() {
this.values = [];
}
set(key, value) {
if (value) {
const existing = this.values.find((value2) => value2.key === key);
if (existing) {
existing.value = value;
} else {
this.values.push({ key, value, quoted: false });
}
}
}
toLiteralMap() {
return literalMap(this.values);
}
};
function createCssSelectorFromNode(node) {
const elementName = node instanceof Element ? node.name : "ng-template";
const attributes = getAttrsForDirectiveMatching(node);
const cssSelector = new CssSelector();
const elementNameNoNs = splitNsName(elementName)[1];
cssSelector.setElement(elementNameNoNs);
Object.getOwnPropertyNames(attributes).forEach((name) => {
const nameNoNs = splitNsName(name)[1];
const value = attributes[name];
cssSelector.addAttribute(nameNoNs, value);
if (name.toLowerCase() === "class") {
const classes = value.trim().split(/\s+/);
classes.forEach((className) => cssSelector.addClassName(className));
}
});
return cssSelector;
}
function getAttrsForDirectiveMatching(elOrTpl) {
const attributesMap = {};
if (elOrTpl instanceof Template && elOrTpl.tagName !== "ng-template") {
elOrTpl.templateAttrs.forEach((a) => attributesMap[a.name] = "");
} else {
elOrTpl.attributes.forEach((a) => {
if (!isI18nAttribute(a.name)) {
attributesMap[a.name] = a.value;
}
});
elOrTpl.inputs.forEach((i) => {
if (i.type === BindingType.Property || i.type === BindingType.TwoWay) {
attributesMap[i.name] = "";
}
});
elOrTpl.outputs.forEach((o) => {
attributesMap[o.name] = "";
});
}
return attributesMap;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/injectable_compiler_2.mjs
function compileInjectable(meta, resolveForwardRefs) {
let result = null;
const factoryMeta = {
name: meta.name,
type: meta.type,
typeArgumentCount: meta.typeArgumentCount,
deps: [],
target: FactoryTarget.Injectable
};
if (meta.useClass !== void 0) {
const useClassOnSelf = meta.useClass.expression.isEquivalent(meta.type.value);
let deps = void 0;
if (meta.deps !== void 0) {
deps = meta.deps;
}
if (deps !== void 0) {
result = compileFactoryFunction(__spreadProps(__spreadValues({}, factoryMeta), {
delegate: meta.useClass.expression,
delegateDeps: deps,
delegateType: R3FactoryDelegateType.Class
}));
} else if (useClassOnSelf) {
result = compileFactoryFunction(factoryMeta);
} else {
result = {
statements: [],
expression: delegateToFactory(meta.type.value, meta.useClass.expression, resolveForwardRefs)
};
}
} else if (meta.useFactory !== void 0) {
if (meta.deps !== void 0) {
result = compileFactoryFunction(__spreadProps(__spreadValues({}, factoryMeta), {
delegate: meta.useFactory,
delegateDeps: meta.deps || [],
delegateType: R3FactoryDelegateType.Function
}));
} else {
result = { statements: [], expression: arrowFn([], meta.useFactory.callFn([])) };
}
} else if (meta.useValue !== void 0) {
result = compileFactoryFunction(__spreadProps(__spreadValues({}, factoryMeta), {
expression: meta.useValue.expression
}));
} else if (meta.useExisting !== void 0) {
result = compileFactoryFunction(__spreadProps(__spreadValues({}, factoryMeta), {
expression: importExpr(Identifiers.inject).callFn([meta.useExisting.expression])
}));
} else {
result = {
statements: [],
expression: delegateToFactory(meta.type.value, meta.type.value, resolveForwardRefs)
};
}
const token = meta.type.value;
const injectableProps = new DefinitionMap();
injectableProps.set("token", token);
injectableProps.set("factory", result.expression);
if (meta.providedIn.expression.value !== null) {
injectableProps.set("providedIn", convertFromMaybeForwardRefExpression(meta.providedIn));
}
const expression = importExpr(Identifiers.\u0275\u0275defineInjectable).callFn([injectableProps.toLiteralMap()], void 0, true);
return {
expression,
type: createInjectableType(meta),
statements: result.statements
};
}
function createInjectableType(meta) {
return new ExpressionType(importExpr(Identifiers.InjectableDeclaration, [
typeWithParameters(meta.type.type, meta.typeArgumentCount)
]));
}
function delegateToFactory(type, useType, unwrapForwardRefs) {
if (type.node === useType.node) {
return useType.prop("\u0275fac");
}
if (!unwrapForwardRefs) {
return createFactoryFunction(useType);
}
const unwrappedType = importExpr(Identifiers.resolveForwardRef).callFn([useType]);
return createFactoryFunction(unwrappedType);
}
function createFactoryFunction(type) {
const t = new FnParam("__ngFactoryType__", DYNAMIC_TYPE);
return arrowFn([t], type.prop("\u0275fac").callFn([variable(t.name)]));
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/assertions.mjs
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) {
const start = value[0];
const end = value[1];
UNUSABLE_INTERPOLATION_REGEXPS.forEach((regexp) => {
if (regexp.test(start) || regexp.test(end)) {
throw new Error(`['${start}', '${end}'] contains unusable interpolation symbol.`);
}
});
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/ml_parser/defaults.mjs
var InterpolationConfig = class {
static fromArray(markers) {
if (!markers) {
return DEFAULT_INTERPOLATION_CONFIG;
}
assertInterpolationSymbols("interpolation", markers);
return new InterpolationConfig(markers[0], markers[1]);
}
constructor(start, end) {
this.start = start;
this.end = end;
}
};
var DEFAULT_INTERPOLATION_CONFIG = new InterpolationConfig("{{", "}}");
var DEFAULT_CONTAINER_BLOCKS = /* @__PURE__ */ new Set(["switch"]);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/chars.mjs
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 $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;
}
function isQuote(code) {
return code === $SQ || code === $DQ || code === $BT;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/parse_util.mjs
var ParseLocation = class {
constructor(file, offset, line, col) {
this.file = file;
this.offset = offset;
this.line = line;
this.col = col;
}
toString() {
return this.offset != null ? `${this.file.url}@${this.line}:${this.col}` : this.file.url;
}
moveBy(delta) {
const source = this.file.content;
const len = source.length;
let offset = this.offset;
let line = this.line;
let col = this.col;
while (offset > 0 && delta < 0) {
offset--;
delta++;
const ch = source.charCodeAt(offset);
if (ch == $LF) {
line--;
const priorLine = source.substring(0, offset - 1).lastIndexOf(String.fromCharCode($LF));
col = priorLine > 0 ? offset - priorLine : offset;
} else {
col--;
}
}
while (offset < len && delta > 0) {
const ch = source.charCodeAt(offset);
offset++;
delta--;
if (ch == $LF) {
line++;
col = 0;
} else {
col++;
}
}
return new ParseLocation(this.file, offset, line, col);
}
getContext(maxChars, maxLines) {
const content = this.file.content;
let startOffset = this.offset;
if (startOffset != null) {
if (startOffset > content.length - 1) {
startOffset = content.length - 1;
}
let endOffset = startOffset;
let ctxChars = 0;
let 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;
}
};
var ParseSourceFile = class {
constructor(content, url) {
this.content = content;
this.url = url;
}
};
var ParseSourceSpan = class {
constructor(start, end, fullStart = start, details = null) {
this.start = start;
this.end = end;
this.fullStart = fullStart;
this.details = details;
}
toString() {
return this.start.file.content.substring(this.start.offset, this.end.offset);
}
};
var ParseErrorLevel;
(function(ParseErrorLevel2) {
ParseErrorLevel2[ParseErrorLevel2["WARNING"] = 0] = "WARNING";
ParseErrorLevel2[ParseErrorLevel2["ERROR"] = 1] = "ERROR";
})(ParseErrorLevel || (ParseErrorLevel = {}));
var ParseError = class {
constructor(span, msg, level = ParseErrorLevel.ERROR) {
this.span = span;
this.msg = msg;
this.level = level;
}
contextualMessage() {
const ctx = this.span.start.getContext(100, 3);
return ctx ? `${this.msg} ("${ctx.before}[${ParseErrorLevel[this.level]} ->]${ctx.after}")` : this.msg;
}
toString() {
const details = this.span.details ? `, ${this.span.details}` : "";
return `${this.contextualMessage()}: ${this.span.start}${details}`;
}
};
function r3JitTypeSourceSpan(kind, typeName, sourceUrl) {
const sourceFileName = `in ${kind} ${typeName} in ${sourceUrl}`;
const sourceFile = new ParseSourceFile("", sourceFileName);
return new ParseSourceSpan(new ParseLocation(sourceFile, -1, -1, -1), new ParseLocation(sourceFile, -1, -1, -1));
}
var _anonymousTypeIndex = 0;
function identifierName(compileIdentifier) {
if (!compileIdentifier || !compileIdentifier.reference) {
return null;
}
const ref = compileIdentifier.reference;
if (ref["__anonymousType"]) {
return ref["__anonymousType"];
}
if (ref["__forward_ref__"]) {
return "__forward_ref__";
}
let identifier = stringify(ref);
if (identifier.indexOf("(") >= 0) {
identifier = `anonymous_${_anonymousTypeIndex++}`;
ref["__anonymousType"] = identifier;
} else {
identifier = sanitizeIdentifier(identifier);
}
return identifier;
}
function sanitizeIdentifier(name) {
return name.replace(/\W/g, "_");
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/output/abstract_js_emitter.mjs
var makeTemplateObjectPolyfill = '(this&&this.__makeTemplateObject||function(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e})';
var AbstractJsEmitterVisitor = class extends AbstractEmitterVisitor {
constructor() {
super(false);
}
visitWrappedNodeExpr(ast, ctx) {
throw new Error("Cannot emit a WrappedNodeExpr in Javascript.");
}
visitDeclareVarStmt(stmt, ctx) {
ctx.print(stmt, `var ${stmt.name}`);
if (stmt.value) {
ctx.print(stmt, " = ");
stmt.value.visitExpression(this, ctx);
}
ctx.println(stmt, `;`);
return null;
}
visitTaggedTemplateExpr(ast, ctx) {
const elements = ast.template.elements;
ast.tag.visitExpression(this, ctx);
ctx.print(ast, `(${makeTemplateObjectPolyfill}(`);
ctx.print(ast, `[${elements.map((part) => escapeIdentifier(part.text, false)).join(", ")}], `);
ctx.print(ast, `[${elements.map((part) => escapeIdentifier(part.rawText, false)).join(", ")}])`);
ast.template.expressions.forEach((expression) => {
ctx.print(ast, ", ");
expression.visitExpression(this, ctx);
});
ctx.print(ast, ")");
return null;
}
visitFunctionExpr(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;
}
visitArrowFunctionExpr(ast, ctx) {
ctx.print(ast, "(");
this._visitParams(ast.params, ctx);
ctx.print(ast, ") =>");
if (Array.isArray(ast.body)) {
ctx.println(ast, `{`);
ctx.incIndent();
this.visitAllStatements(ast.body, ctx);
ctx.decIndent();
ctx.print(ast, `}`);
} else {
const isObjectLiteral = ast.body instanceof LiteralMapExpr;
if (isObjectLiteral) {
ctx.print(ast, "(");
}
ast.body.visitExpression(this, ctx);
if (isObjectLiteral) {
ctx.print(ast, ")");
}
}
return null;
}
visitDeclareFunctionStmt(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;
}
visitLocalizedString(ast, ctx) {
ctx.print(ast, `$localize(${makeTemplateObjectPolyfill}(`);
const parts = [ast.serializeI18nHead()];
for (let i = 1; i < ast.messageParts.length; i++) {
parts.push(ast.serializeI18nTemplatePart(i));
}
ctx.print(ast, `[${parts.map((part) => escapeIdentifier(part.cooked, false)).join(", ")}], `);
ctx.print(ast, `[${parts.map((part) => escapeIdentifier(part.raw, false)).join(", ")}])`);
ast.expressions.forEach((expression) => {
ctx.print(ast, ", ");
expression.visitExpression(this, ctx);
});
ctx.print(ast, ")");
return null;
}
_visitParams(params, ctx) {
this.visitAllObjects((param) => ctx.print(null, param.name), params, ctx, ",");
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/output/output_jit_trusted_types.mjs
var policy;
function getPolicy() {
if (policy === void 0) {
const trustedTypes = _global["trustedTypes"];
policy = null;
if (trustedTypes) {
try {
policy = trustedTypes.createPolicy("angular#unsafe-jit", {
createScript: (s) => s
});
} catch (e) {
}
}
}
return policy;
}
function trustedScriptFromString(script) {
var _a2;
return ((_a2 = getPolicy()) == null ? void 0 : _a2.createScript(script)) || script;
}
function newTrustedFunctionForJIT(...args) {
if (!_global["trustedTypes"]) {
return new Function(...args);
}
const fnArgs = args.slice(0, -1).join(",");
const fnBody = args[args.length - 1];
const body = `(function anonymous(${fnArgs}
) { ${fnBody}
})`;
const fn2 = _global["eval"](trustedScriptFromString(body));
if (fn2.bind === void 0) {
return new Function(...args);
}
fn2.toString = () => body;
return fn2.bind(_global);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/output/output_jit.mjs
var JitEvaluator = class {
evaluateStatements(sourceUrl, statements, refResolver, createSourceMaps) {
const converter = new JitEmitterVisitor(refResolver);
const ctx = EmitterVisitorContext.createRoot();
if (statements.length > 0 && !isUseStrictStatement(statements[0])) {
statements = [literal("use strict").toStmt(), ...statements];
}
converter.visitAllStatements(statements, ctx);
converter.createReturnStmt(ctx);
return this.evaluateCode(sourceUrl, ctx, converter.getArgs(), createSourceMaps);
}
evaluateCode(sourceUrl, ctx, vars, createSourceMap) {
let fnBody = `"use strict";${ctx.toSource()}
//# sourceURL=${sourceUrl}`;
const fnArgNames = [];
const fnArgValues = [];
for (const argName in vars) {
fnArgValues.push(vars[argName]);
fnArgNames.push(argName);
}
if (createSourceMap) {
const emptyFn = newTrustedFunctionForJIT(...fnArgNames.concat("return null;")).toString();
const headerLines = emptyFn.slice(0, emptyFn.indexOf("return null;")).split("\n").length - 1;
fnBody += `
${ctx.toSourceMapGenerator(sourceUrl, headerLines).toJsComment()}`;
}
const fn2 = newTrustedFunctionForJIT(...fnArgNames.concat(fnBody));
return this.executeFunction(fn2, fnArgValues);
}
executeFunction(fn2, args) {
return fn2(...args);
}
};
var JitEmitterVisitor = class extends AbstractJsEmitterVisitor {
constructor(refResolver) {
super();
this.refResolver = refResolver;
this._evalArgNames = [];
this._evalArgValues = [];
this._evalExportedVars = [];
}
createReturnStmt(ctx) {
const stmt = new ReturnStatement(new LiteralMapExpr(this._evalExportedVars.map((resultVar) => new LiteralMapEntry(resultVar, variable(resultVar), false))));
stmt.visitStatement(this, ctx);
}
getArgs() {
const result = {};
for (let i = 0; i < this._evalArgNames.length; i++) {
result[this._evalArgNames[i]] = this._evalArgValues[i];
}
return result;
}
visitExternalExpr(ast, ctx) {
this._emitReferenceToExternal(ast, this.refResolver.resolveExternalReference(ast.value), ctx);
return null;
}
visitWrappedNodeExpr(ast, ctx) {
this._emitReferenceToExternal(ast, ast.node, ctx);
return null;
}
visitDeclareVarStmt(stmt, ctx) {
if (stmt.hasModifier(StmtModifier.Exported)) {
this._evalExportedVars.push(stmt.name);
}
return super.visitDeclareVarStmt(stmt, ctx);
}
visitDeclareFunctionStmt(stmt, ctx) {
if (stmt.hasModifier(StmtModifier.Exported)) {
this._evalExportedVars.push(stmt.name);
}
return super.visitDeclareFunctionStmt(stmt, ctx);
}
_emitReferenceToExternal(ast, value, ctx) {
let id = this._evalArgValues.indexOf(value);
if (id === -1) {
id = this._evalArgValues.length;
this._evalArgValues.push(value);
const name = identifierName({ reference: value }) || "val";
this._evalArgNames.push(`jit_${name}_${id}`);
}
ctx.print(ast, this._evalArgNames[id]);
}
};
function isUseStrictStatement(statement) {
return statement.isEquivalent(literal("use strict").toStmt());
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/r3_injector_compiler.mjs
function compileInjector(meta) {
const definitionMap = new DefinitionMap();
if (meta.providers !== null) {
definitionMap.set("providers", meta.providers);
}
if (meta.imports.length > 0) {
definitionMap.set("imports", literalArr(meta.imports));
}
const expression = importExpr(Identifiers.defineInjector).callFn([definitionMap.toLiteralMap()], void 0, true);
const type = createInjectorType(meta);
return { expression, type, statements: [] };
}
function createInjectorType(meta) {
return new ExpressionType(importExpr(Identifiers.InjectorDeclaration, [new ExpressionType(meta.type.type)]));
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/r3_jit.mjs
var R3JitReflector = class {
constructor(context) {
this.context = context;
}
resolveExternalReference(ref) {
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];
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/r3_module_compiler.mjs
var R3SelectorScopeMode;
(function(R3SelectorScopeMode2) {
R3SelectorScopeMode2[R3SelectorScopeMode2["Inline"] = 0] = "Inline";
R3SelectorScopeMode2[R3SelectorScopeMode2["SideEffect"] = 1] = "SideEffect";
R3SelectorScopeMode2[R3SelectorScopeMode2["Omit"] = 2] = "Omit";
})(R3SelectorScopeMode || (R3SelectorScopeMode = {}));
var R3NgModuleMetadataKind;
(function(R3NgModuleMetadataKind2) {
R3NgModuleMetadataKind2[R3NgModuleMetadataKind2["Global"] = 0] = "Global";
R3NgModuleMetadataKind2[R3NgModuleMetadataKind2["Local"] = 1] = "Local";
})(R3NgModuleMetadataKind || (R3NgModuleMetadataKind = {}));
function compileNgModule(meta) {
const statements = [];
const definitionMap = new DefinitionMap();
definitionMap.set("type", meta.type.value);
if (meta.kind === R3NgModuleMetadataKind.Global && meta.bootstrap.length > 0) {
definitionMap.set("bootstrap", refsToArray(meta.bootstrap, meta.containsForwardDecls));
}
if (meta.selectorScopeMode === R3SelectorScopeMode.Inline) {
if (meta.declarations.length > 0) {
definitionMap.set("declarations", refsToArray(meta.declarations, meta.containsForwardDecls));
}
if (meta.imports.length > 0) {
definitionMap.set("imports", refsToArray(meta.imports, meta.containsForwardDecls));
}
if (meta.exports.length > 0) {
definitionMap.set("exports", refsToArray(meta.exports, meta.containsForwardDecls));
}
} else if (meta.selectorScopeMode === R3SelectorScopeMode.SideEffect) {
const setNgModuleScopeCall = generateSetNgModuleScopeCall(meta);
if (setNgModuleScopeCall !== null) {
statements.push(setNgModuleScopeCall);
}
} else {
}
if (meta.schemas !== null && meta.schemas.length > 0) {
definitionMap.set("schemas", literalArr(meta.schemas.map((ref) => ref.value)));
}
if (meta.id !== null) {
definitionMap.set("id", meta.id);
statements.push(importExpr(Identifiers.registerNgModuleType).callFn([meta.type.value, meta.id]).toStmt());
}
const expression = importExpr(Identifiers.defineNgModule).callFn([definitionMap.toLiteralMap()], void 0, true);
const type = createNgModuleType(meta);
return { expression, type, statements };
}
function compileNgModuleDeclarationExpression(meta) {
const definitionMap = new DefinitionMap();
definitionMap.set("type", new WrappedNodeExpr(meta.type));
if (meta.bootstrap !== void 0) {
definitionMap.set("bootstrap", new WrappedNodeExpr(meta.bootstrap));
}
if (meta.declarations !== void 0) {
definitionMap.set("declarations", new WrappedNodeExpr(meta.declarations));
}
if (meta.imports !== void 0) {
definitionMap.set("imports", new WrappedNodeExpr(meta.imports));
}
if (meta.exports !== void 0) {
definitionMap.set("exports", new WrappedNodeExpr(meta.exports));
}
if (meta.schemas !== void 0) {
definitionMap.set("schemas", new WrappedNodeExpr(meta.schemas));
}
if (meta.id !== void 0) {
definitionMap.set("id", new WrappedNodeExpr(meta.id));
}
return importExpr(Identifiers.defineNgModule).callFn([definitionMap.toLiteralMap()]);
}
function createNgModuleType(meta) {
if (meta.kind === R3NgModuleMetadataKind.Local) {
return new ExpressionType(meta.type.value);
}
const { type: moduleType, declarations, exports, imports, includeImportTypes, publicDeclarationTypes } = meta;
return new ExpressionType(importExpr(Identifiers.NgModuleDeclaration, [
new ExpressionType(moduleType.type),
publicDeclarationTypes === null ? tupleTypeOf(declarations) : tupleOfTypes(publicDeclarationTypes),
includeImportTypes ? tupleTypeOf(imports) : NONE_TYPE,
tupleTypeOf(exports)
]));
}
function generateSetNgModuleScopeCall(meta) {
const scopeMap = new DefinitionMap();
if (meta.kind === R3NgModuleMetadataKind.Global) {
if (meta.declarations.length > 0) {
scopeMap.set("declarations", refsToArray(meta.declarations, meta.containsForwardDecls));
}
} else {
if (meta.declarationsExpression) {
scopeMap.set("declarations", meta.declarationsExpression);
}
}
if (meta.kind === R3NgModuleMetadataKind.Global) {
if (meta.imports.length > 0) {
scopeMap.set("imports", refsToArray(meta.imports, meta.containsForwardDecls));
}
} else {
if (meta.importsExpression) {
scopeMap.set("imports", meta.importsExpression);
}
}
if (meta.kind === R3NgModuleMetadataKind.Global) {
if (meta.exports.length > 0) {
scopeMap.set("exports", refsToArray(meta.exports, meta.containsForwardDecls));
}
} else {
if (meta.exportsExpression) {
scopeMap.set("exports", meta.exportsExpression);
}
}
if (meta.kind === R3NgModuleMetadataKind.Local && meta.bootstrapExpression) {
scopeMap.set("bootstrap", meta.bootstrapExpression);
}
if (Object.keys(scopeMap.values).length === 0) {
return null;
}
const fnCall = new InvokeFunctionExpr(
importExpr(Identifiers.setNgModuleScope),
[meta.type.value, scopeMap.toLiteralMap()]
);
const guardedCall = jitOnlyGuardedExpression(fnCall);
const iife = new FunctionExpr([], [guardedCall.toStmt()]);
const iifeCall = new InvokeFunctionExpr(iife, []);
return iifeCall.toStmt();
}
function tupleTypeOf(exp) {
const types = exp.map((ref) => typeofExpr(ref.type));
return exp.length > 0 ? expressionType(literalArr(types)) : NONE_TYPE;
}
function tupleOfTypes(types) {
const typeofTypes = types.map((type) => typeofExpr(type));
return types.length > 0 ? expressionType(literalArr(typeofTypes)) : NONE_TYPE;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/r3_pipe_compiler.mjs
function compilePipeFromMetadata(metadata) {
const definitionMapValues = [];
definitionMapValues.push({ key: "name", value: literal(metadata.pipeName), quoted: false });
definitionMapValues.push({ key: "type", value: metadata.type.value, quoted: false });
definitionMapValues.push({ key: "pure", value: literal(metadata.pure), quoted: false });
if (metadata.isStandalone) {
definitionMapValues.push({ key: "standalone", value: literal(true), quoted: false });
}
const expression = importExpr(Identifiers.definePipe).callFn([literalMap(definitionMapValues)], void 0, true);
const type = createPipeType(metadata);
return { expression, type, statements: [] };
}
function createPipeType(metadata) {
return new ExpressionType(importExpr(Identifiers.PipeDeclaration, [
typeWithParameters(metadata.type.type, metadata.typeArgumentCount),
new ExpressionType(new LiteralExpr(metadata.pipeName)),
new ExpressionType(new LiteralExpr(metadata.isStandalone))
]));
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/view/api.mjs
var R3TemplateDependencyKind;
(function(R3TemplateDependencyKind2) {
R3TemplateDependencyKind2[R3TemplateDependencyKind2["Directive"] = 0] = "Directive";
R3TemplateDependencyKind2[R3TemplateDependencyKind2["Pipe"] = 1] = "Pipe";
R3TemplateDependencyKind2[R3TemplateDependencyKind2["NgModule"] = 2] = "NgModule";
})(R3TemplateDependencyKind || (R3TemplateDependencyKind = {}));
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/shadow_css.mjs
var animationKeywords = /* @__PURE__ */ new Set([
"inherit",
"initial",
"revert",
"unset",
"alternate",
"alternate-reverse",
"normal",
"reverse",
"backwards",
"both",
"forwards",
"none",
"paused",
"running",
"ease",
"ease-in",
"ease-in-out",
"ease-out",
"linear",
"step-start",
"step-end",
"end",
"jump-both",
"jump-end",
"jump-none",
"jump-start",
"start"
]);
var scopedAtRuleIdentifiers = [
"@media",
"@supports",
"@document",
"@layer",
"@container",
"@scope",
"@starting-style"
];
var ShadowCss = class {
constructor() {
this._animationDeclarationKeyframesRe = /(^|\s+|,)(?:(?:(['"])((?:\\\\|\\\2|(?!\2).)+)\2)|(-?[A-Za-z][\w\-]*))(?=[,\s]|$)/g;
}
shimCssText(cssText, selector, hostSelector = "") {
const comments = [];
cssText = cssText.replace(_commentRe, (m) => {
var _a2;
if (m.match(_commentWithHashRe)) {
comments.push(m);
} else {
const newLinesMatches = m.match(_newLinesRe);
comments.push(((_a2 = newLinesMatches == null ? void 0 : newLinesMatches.join("")) != null ? _a2 : "") + "\n");
}
return COMMENT_PLACEHOLDER;
});
cssText = this._insertDirectives(cssText);
const scopedCssText = this._scopeCssText(cssText, selector, hostSelector);
let commentIdx = 0;
return scopedCssText.replace(_commentWithHashPlaceHolderRe, () => comments[commentIdx++]);
}
_insertDirectives(cssText) {
cssText = this._insertPolyfillDirectivesInCssText(cssText);
return this._insertPolyfillRulesInCssText(cssText);
}
_scopeKeyframesRelatedCss(cssText, scopeSelector) {
const unscopedKeyframesSet = /* @__PURE__ */ new Set();
const scopedKeyframesCssText = processRules(cssText, (rule) => this._scopeLocalKeyframeDeclarations(rule, scopeSelector, unscopedKeyframesSet));
return processRules(scopedKeyframesCssText, (rule) => this._scopeAnimationRule(rule, scopeSelector, unscopedKeyframesSet));
}
_scopeLocalKeyframeDeclarations(rule, scopeSelector, unscopedKeyframesSet) {
return __spreadProps(__spreadValues({}, rule), {
selector: rule.selector.replace(/(^@(?:-webkit-)?keyframes(?:\s+))(['"]?)(.+)\2(\s*)$/, (_, start, quote, keyframeName, endSpaces) => {
unscopedKeyframesSet.add(unescapeQuotes(keyframeName, quote));
return `${start}${quote}${scopeSelector}_${keyframeName}${quote}${endSpaces}`;
})
});
}
_scopeAnimationKeyframe(keyframe, scopeSelector, unscopedKeyframesSet) {
return keyframe.replace(/^(\s*)(['"]?)(.+?)\2(\s*)$/, (_, spaces1, quote, name, spaces2) => {
name = `${unscopedKeyframesSet.has(unescapeQuotes(name, quote)) ? scopeSelector + "_" : ""}${name}`;
return `${spaces1}${quote}${name}${quote}${spaces2}`;
});
}
_scopeAnimationRule(rule, scopeSelector, unscopedKeyframesSet) {
let content = rule.content.replace(/((?:^|\s+|;)(?:-webkit-)?animation\s*:\s*),*([^;]+)/g, (_, start, animationDeclarations) => start + animationDeclarations.replace(this._animationDeclarationKeyframesRe, (original, leadingSpaces, quote = "", quotedName, nonQuotedName) => {
if (quotedName) {
return `${leadingSpaces}${this._scopeAnimationKeyframe(`${quote}${quotedName}${quote}`, scopeSelector, unscopedKeyframesSet)}`;
} else {
return animationKeywords.has(nonQuotedName) ? original : `${leadingSpaces}${this._scopeAnimationKeyframe(nonQuotedName, scopeSelector, unscopedKeyframesSet)}`;
}
}));
content = content.replace(/((?:^|\s+|;)(?:-webkit-)?animation-name(?:\s*):(?:\s*))([^;]+)/g, (_match, start, commaSeparatedKeyframes) => `${start}${commaSeparatedKeyframes.split(",").map((keyframe) => this._scopeAnimationKeyframe(keyframe, scopeSelector, unscopedKeyframesSet)).join(",")}`);
return __spreadProps(__spreadValues({}, rule), { content });
}
_insertPolyfillDirectivesInCssText(cssText) {
return cssText.replace(_cssContentNextSelectorRe, function(...m) {
return m[2] + "{";
});
}
_insertPolyfillRulesInCssText(cssText) {
return cssText.replace(_cssContentRuleRe, (...m) => {
const rule = m[0].replace(m[1], "").replace(m[2], "");
return m[4] + rule;
});
}
_scopeCssText(cssText, scopeSelector, hostSelector) {
const unscopedRules = this._extractUnscopedRulesFromCssText(cssText);
cssText = this._insertPolyfillHostInCssText(cssText);
cssText = this._convertColonHost(cssText);
cssText = this._convertColonHostContext(cssText);
cssText = this._convertShadowDOMSelectors(cssText);
if (scopeSelector) {
cssText = this._scopeKeyframesRelatedCss(cssText, scopeSelector);
cssText = this._scopeSelectors(cssText, scopeSelector, hostSelector);
}
cssText = cssText + "\n" + unscopedRules;
return cssText.trim();
}
_extractUnscopedRulesFromCssText(cssText) {
let r = "";
let m;
_cssContentUnscopedRuleRe.lastIndex = 0;
while ((m = _cssContentUnscopedRuleRe.exec(cssText)) !== null) {
const rule = m[0].replace(m[2], "").replace(m[1], m[4]);
r += rule + "\n\n";
}
return r;
}
_convertColonHost(cssText) {
return cssText.replace(_cssColonHostRe, (_, hostSelectors, otherSelectors) => {
if (hostSelectors) {
const convertedSelectors = [];
const hostSelectorArray = hostSelectors.split(",").map((p2) => p2.trim());
for (const hostSelector of hostSelectorArray) {
if (!hostSelector)
break;
const convertedSelector = _polyfillHostNoCombinator + hostSelector.replace(_polyfillHost, "") + otherSelectors;
convertedSelectors.push(convertedSelector);
}
return convertedSelectors.join(",");
} else {
return _polyfillHostNoCombinator + otherSelectors;
}
});
}
_convertColonHostContext(cssText) {
return cssText.replace(_cssColonHostContextReGlobal, (selectorText) => {
var _a2;
const contextSelectorGroups = [[]];
let match;
while (match = _cssColonHostContextRe.exec(selectorText)) {
const newContextSelectors = ((_a2 = match[1]) != null ? _a2 : "").trim().split(",").map((m) => m.trim()).filter((m) => m !== "");
const contextSelectorGroupsLength = contextSelectorGroups.length;
repeatGroups(contextSelectorGroups, newContextSelectors.length);
for (let i = 0; i < newContextSelectors.length; i++) {
for (let j = 0; j < contextSelectorGroupsLength; j++) {
contextSelectorGroups[j + i * contextSelectorGroupsLength].push(newContextSelectors[i]);
}
}
selectorText = match[2];
}
return contextSelectorGroups.map((contextSelectors) => combineHostContextSelectors(contextSelectors, selectorText)).join(", ");
});
}
_convertShadowDOMSelectors(cssText) {
return _shadowDOMSelectorsRe.reduce((result, pattern) => result.replace(pattern, " "), cssText);
}
_scopeSelectors(cssText, scopeSelector, hostSelector) {
return processRules(cssText, (rule) => {
let selector = rule.selector;
let content = rule.content;
if (rule.selector[0] !== "@") {
selector = this._scopeSelector(rule.selector, scopeSelector, hostSelector);
} else if (scopedAtRuleIdentifiers.some((atRule) => rule.selector.startsWith(atRule))) {
content = this._scopeSelectors(rule.content, scopeSelector, hostSelector);
} else if (rule.selector.startsWith("@font-face") || rule.selector.startsWith("@page")) {
content = this._stripScopingSelectors(rule.content);
}
return new CssRule(selector, content);
});
}
_stripScopingSelectors(cssText) {
return processRules(cssText, (rule) => {
const selector = rule.selector.replace(_shadowDeepSelectors, " ").replace(_polyfillHostNoCombinatorRe, " ");
return new CssRule(selector, rule.content);
});
}
_scopeSelector(selector, scopeSelector, hostSelector) {
return selector.split(/ ?, ?/).map((part) => part.split(_shadowDeepSelectors)).map((deepParts) => {
const [shallowPart, ...otherParts] = deepParts;
const applyScope = (shallowPart2) => {
if (this._selectorNeedsScoping(shallowPart2, scopeSelector)) {
return this._applySelectorScope(shallowPart2, scopeSelector, hostSelector);
} else {
return shallowPart2;
}
};
return [applyScope(shallowPart), ...otherParts].join(" ");
}).join(", ");
}
_selectorNeedsScoping(selector, scopeSelector) {
const re = this._makeScopeMatcher(scopeSelector);
return !re.test(selector);
}
_makeScopeMatcher(scopeSelector) {
const lre = /\[/g;
const rre = /\]/g;
scopeSelector = scopeSelector.replace(lre, "\\[").replace(rre, "\\]");
return new RegExp("^(" + scopeSelector + ")" + _selectorReSuffix, "m");
}
_applySimpleSelectorScope(selector, scopeSelector, hostSelector) {
_polyfillHostRe.lastIndex = 0;
if (_polyfillHostRe.test(selector)) {
const replaceBy = `[${hostSelector}]`;
return selector.replace(_polyfillHostNoCombinatorRe, (hnc, selector2) => {
return selector2.replace(/([^:]*)(:*)(.*)/, (_, before, colon, after) => {
return before + replaceBy + colon + after;
});
}).replace(_polyfillHostRe, replaceBy + " ");
}
return scopeSelector + " " + selector;
}
_applySelectorScope(selector, scopeSelector, hostSelector) {
var _a2;
const isRe = /\[is=([^\]]*)\]/g;
scopeSelector = scopeSelector.replace(isRe, (_, ...parts) => parts[0]);
const attrName = "[" + scopeSelector + "]";
const _scopeSelectorPart = (p2) => {
let scopedP = p2.trim();
if (!scopedP) {
return p2;
}
if (p2.includes(_polyfillHostNoCombinator)) {
scopedP = this._applySimpleSelectorScope(p2, scopeSelector, hostSelector);
} else {
const t = p2.replace(_polyfillHostRe, "");
if (t.length > 0) {
const matches = t.match(/([^:]*)(:*)(.*)/);
if (matches) {
scopedP = matches[1] + attrName + matches[2] + matches[3];
}
}
}
return scopedP;
};
const safeContent = new SafeSelector(selector);
selector = safeContent.content();
let scopedSelector = "";
let startIndex = 0;
let res;
const sep2 = /( |>|\+|~(?!=))\s*/g;
const hasHost = selector.includes(_polyfillHostNoCombinator);
let shouldScope = !hasHost;
while ((res = sep2.exec(selector)) !== null) {
const separator = res[1];
const part2 = selector.slice(startIndex, res.index);
if (part2.match(/__esc-ph-(\d+)__/) && ((_a2 = selector[res.index + 1]) == null ? void 0 : _a2.match(/[a-fA-F\d]/))) {
continue;
}
shouldScope = shouldScope || part2.includes(_polyfillHostNoCombinator);
const scopedPart = shouldScope ? _scopeSelectorPart(part2) : part2;
scopedSelector += `${scopedPart} ${separator} `;
startIndex = sep2.lastIndex;
}
const part = selector.substring(startIndex);
shouldScope = shouldScope || part.includes(_polyfillHostNoCombinator);
scopedSelector += shouldScope ? _scopeSelectorPart(part) : part;
return safeContent.restore(scopedSelector);
}
_insertPolyfillHostInCssText(selector) {
return selector.replace(_colonHostContextRe, _polyfillHostContext).replace(_colonHostRe, _polyfillHost);
}
};
var SafeSelector = class {
constructor(selector) {
this.placeholders = [];
this.index = 0;
selector = this._escapeRegexMatches(selector, /(\[[^\]]*\])/g);
selector = selector.replace(/(\\.)/g, (_, keep) => {
const replaceBy = `__esc-ph-${this.index}__`;
this.placeholders.push(keep);
this.index++;
return replaceBy;
});
this._content = selector.replace(/(:nth-[-\w]+)(\([^)]+\))/g, (_, pseudo, exp) => {
const replaceBy = `__ph-${this.index}__`;
this.placeholders.push(exp);
this.index++;
return pseudo + replaceBy;
});
}
restore(content) {
return content.replace(/__(?:ph|esc-ph)-(\d+)__/g, (_ph, index) => this.placeholders[+index]);
}
content() {
return this._content;
}
_escapeRegexMatches(content, pattern) {
return content.replace(pattern, (_, keep) => {
const replaceBy = `__ph-${this.index}__`;
this.placeholders.push(keep);
this.index++;
return replaceBy;
});
}
};
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";
var _polyfillHostContext = "-shadowcsscontext";
var _parenSuffix = "(?:\\(((?:\\([^)(]*\\)|[^)(]*)+?)\\))?([^,{]*)";
var _cssColonHostRe = new RegExp(_polyfillHost + _parenSuffix, "gim");
var _cssColonHostContextReGlobal = new RegExp(_polyfillHostContext + _parenSuffix, "gim");
var _cssColonHostContextRe = new RegExp(_polyfillHostContext + _parenSuffix, "im");
var _polyfillHostNoCombinator = _polyfillHost + "-no-combinator";
var _polyfillHostNoCombinatorRe = /-shadowcsshost-no-combinator([^\s]*)/;
var _shadowDOMSelectorsRe = [
/::shadow/g,
/::content/g,
/\/shadow-deep\//g,
/\/shadow\//g
];
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 _newLinesRe = /\r?\n/g;
var _commentRe = /\/\*[\s\S]*?\*\//g;
var _commentWithHashRe = /\/\*\s*#\s*source(Mapping)?URL=/g;
var COMMENT_PLACEHOLDER = "%COMMENT%";
var _commentWithHashPlaceHolderRe = new RegExp(COMMENT_PLACEHOLDER, "g");
var BLOCK_PLACEHOLDER = "%BLOCK%";
var _ruleRe = new RegExp(`(\\s*(?:${COMMENT_PLACEHOLDER}\\s*)*)([^;\\{\\}]+?)(\\s*)((?:{%BLOCK%}?\\s*;?)|(?:\\s*;))`, "g");
var CONTENT_PAIRS = /* @__PURE__ */ new Map([["{", "}"]]);
var COMMA_IN_PLACEHOLDER = "%COMMA_IN_PLACEHOLDER%";
var SEMI_IN_PLACEHOLDER = "%SEMI_IN_PLACEHOLDER%";
var COLON_IN_PLACEHOLDER = "%COLON_IN_PLACEHOLDER%";
var _cssCommaInPlaceholderReGlobal = new RegExp(COMMA_IN_PLACEHOLDER, "g");
var _cssSemiInPlaceholderReGlobal = new RegExp(SEMI_IN_PLACEHOLDER, "g");
var _cssColonInPlaceholderReGlobal = new RegExp(COLON_IN_PLACEHOLDER, "g");
var CssRule = class {
constructor(selector, content) {
this.selector = selector;
this.content = content;
}
};
function processRules(input, ruleCallback) {
const escaped = escapeInStrings(input);
const inputWithEscapedBlocks = escapeBlocks(escaped, CONTENT_PAIRS, BLOCK_PLACEHOLDER);
let nextBlockIndex = 0;
const escapedResult = inputWithEscapedBlocks.escapedString.replace(_ruleRe, (...m) => {
const selector = m[2];
let content = "";
let suffix = m[4];
let contentPrefix = "";
if (suffix && suffix.startsWith("{" + BLOCK_PLACEHOLDER)) {
content = inputWithEscapedBlocks.blocks[nextBlockIndex++];
suffix = suffix.substring(BLOCK_PLACEHOLDER.length + 1);
contentPrefix = "{";
}
const rule = ruleCallback(new CssRule(selector, content));
return `${m[1]}${rule.selector}${m[3]}${contentPrefix}${rule.content}${suffix}`;
});
return unescapeInStrings(escapedResult);
}
var StringWithEscapedBlocks = class {
constructor(escapedString, blocks) {
this.escapedString = escapedString;
this.blocks = blocks;
}
};
function escapeBlocks(input, charPairs, placeholder) {
const resultParts = [];
const escapedBlocks = [];
let openCharCount = 0;
let nonBlockStartIndex = 0;
let blockStartIndex = -1;
let openChar;
let closeChar;
for (let i = 0; i < input.length; i++) {
const char = input[i];
if (char === "\\") {
i++;
} else if (char === closeChar) {
openCharCount--;
if (openCharCount === 0) {
escapedBlocks.push(input.substring(blockStartIndex, i));
resultParts.push(placeholder);
nonBlockStartIndex = i;
blockStartIndex = -1;
openChar = closeChar = void 0;
}
} else if (char === openChar) {
openCharCount++;
} else if (openCharCount === 0 && charPairs.has(char)) {
openChar = char;
closeChar = charPairs.get(char);
openCharCount = 1;
blockStartIndex = i + 1;
resultParts.push(input.substring(nonBlockStartIndex, blockStartIndex));
}
}
if (blockStartIndex !== -1) {
escapedBlocks.push(input.substring(blockStartIndex));
resultParts.push(placeholder);
} else {
resultParts.push(input.substring(nonBlockStartIndex));
}
return new StringWithEscapedBlocks(resultParts.join(""), escapedBlocks);
}
var ESCAPE_IN_STRING_MAP = {
";": SEMI_IN_PLACEHOLDER,
",": COMMA_IN_PLACEHOLDER,
":": COLON_IN_PLACEHOLDER
};
function escapeInStrings(input) {
let result = input;
let currentQuoteChar = null;
for (let i = 0; i < result.length; i++) {
const char = result[i];
if (char === "\\") {
i++;
} else {
if (currentQuoteChar !== null) {
if (char === currentQuoteChar) {
currentQuoteChar = null;
} else {
const placeholder = ESCAPE_IN_STRING_MAP[char];
if (placeholder) {
result = `${result.substr(0, i)}${placeholder}${result.substr(i + 1)}`;
i += placeholder.length - 1;
}
}
} else if (char === "'" || char === '"') {
currentQuoteChar = char;
}
}
}
return result;
}
function unescapeInStrings(input) {
let result = input.replace(_cssCommaInPlaceholderReGlobal, ",");
result = result.replace(_cssSemiInPlaceholderReGlobal, ";");
result = result.replace(_cssColonInPlaceholderReGlobal, ":");
return result;
}
function unescapeQuotes(str, isQuoted) {
return !isQuoted ? str : str.replace(/((?:^|[^\\])(?:\\\\)*)\\(?=['"])/g, "$1");
}
function combineHostContextSelectors(contextSelectors, otherSelectors) {
const hostMarker = _polyfillHostNoCombinator;
_polyfillHostRe.lastIndex = 0;
const otherSelectorsHasHost = _polyfillHostRe.test(otherSelectors);
if (contextSelectors.length === 0) {
return hostMarker + otherSelectors;
}
const combined = [contextSelectors.pop() || ""];
while (contextSelectors.length > 0) {
const length = combined.length;
const contextSelector = contextSelectors.pop();
for (let i = 0; i < length; i++) {
const previousSelectors = combined[i];
combined[length * 2 + i] = previousSelectors + " " + contextSelector;
combined[length + i] = contextSelector + " " + previousSelectors;
combined[i] = contextSelector + previousSelectors;
}
}
return combined.map((s) => otherSelectorsHasHost ? `${s}${otherSelectors}` : `${s}${hostMarker}${otherSelectors}, ${s} ${hostMarker}${otherSelectors}`).join(",");
}
function repeatGroups(groups, multiples) {
const length = groups.length;
for (let i = 1; i < multiples; i++) {
for (let j = 0; j < length; j++) {
groups[j + i * length] = groups[j].slice(0);
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/ir/src/enums.mjs
var OpKind;
(function(OpKind2) {
OpKind2[OpKind2["ListEnd"] = 0] = "ListEnd";
OpKind2[OpKind2["Statement"] = 1] = "Statement";
OpKind2[OpKind2["Variable"] = 2] = "Variable";
OpKind2[OpKind2["ElementStart"] = 3] = "ElementStart";
OpKind2[OpKind2["Element"] = 4] = "Element";
OpKind2[OpKind2["Template"] = 5] = "Template";
OpKind2[OpKind2["ElementEnd"] = 6] = "ElementEnd";
OpKind2[OpKind2["ContainerStart"] = 7] = "ContainerStart";
OpKind2[OpKind2["Container"] = 8] = "Container";
OpKind2[OpKind2["ContainerEnd"] = 9] = "ContainerEnd";
OpKind2[OpKind2["DisableBindings"] = 10] = "DisableBindings";
OpKind2[OpKind2["Conditional"] = 11] = "Conditional";
OpKind2[OpKind2["EnableBindings"] = 12] = "EnableBindings";
OpKind2[OpKind2["Text"] = 13] = "Text";
OpKind2[OpKind2["Listener"] = 14] = "Listener";
OpKind2[OpKind2["InterpolateText"] = 15] = "InterpolateText";
OpKind2[OpKind2["Binding"] = 16] = "Binding";
OpKind2[OpKind2["Property"] = 17] = "Property";
OpKind2[OpKind2["StyleProp"] = 18] = "StyleProp";
OpKind2[OpKind2["ClassProp"] = 19] = "ClassProp";
OpKind2[OpKind2["StyleMap"] = 20] = "StyleMap";
OpKind2[OpKind2["ClassMap"] = 21] = "ClassMap";
OpKind2[OpKind2["Advance"] = 22] = "Advance";
OpKind2[OpKind2["Pipe"] = 23] = "Pipe";
OpKind2[OpKind2["Attribute"] = 24] = "Attribute";
OpKind2[OpKind2["ExtractedAttribute"] = 25] = "ExtractedAttribute";
OpKind2[OpKind2["Defer"] = 26] = "Defer";
OpKind2[OpKind2["DeferOn"] = 27] = "DeferOn";
OpKind2[OpKind2["DeferWhen"] = 28] = "DeferWhen";
OpKind2[OpKind2["I18nMessage"] = 29] = "I18nMessage";
OpKind2[OpKind2["HostProperty"] = 30] = "HostProperty";
OpKind2[OpKind2["Namespace"] = 31] = "Namespace";
OpKind2[OpKind2["ProjectionDef"] = 32] = "ProjectionDef";
OpKind2[OpKind2["Projection"] = 33] = "Projection";
OpKind2[OpKind2["RepeaterCreate"] = 34] = "RepeaterCreate";
OpKind2[OpKind2["Repeater"] = 35] = "Repeater";
OpKind2[OpKind2["TwoWayProperty"] = 36] = "TwoWayProperty";
OpKind2[OpKind2["TwoWayListener"] = 37] = "TwoWayListener";
OpKind2[OpKind2["DeclareLet"] = 38] = "DeclareLet";
OpKind2[OpKind2["StoreLet"] = 39] = "StoreLet";
OpKind2[OpKind2["I18nStart"] = 40] = "I18nStart";
OpKind2[OpKind2["I18n"] = 41] = "I18n";
OpKind2[OpKind2["I18nEnd"] = 42] = "I18nEnd";
OpKind2[OpKind2["I18nExpression"] = 43] = "I18nExpression";
OpKind2[OpKind2["I18nApply"] = 44] = "I18nApply";
OpKind2[OpKind2["IcuStart"] = 45] = "IcuStart";
OpKind2[OpKind2["IcuEnd"] = 46] = "IcuEnd";
OpKind2[OpKind2["IcuPlaceholder"] = 47] = "IcuPlaceholder";
OpKind2[OpKind2["I18nContext"] = 48] = "I18nContext";
OpKind2[OpKind2["I18nAttributes"] = 49] = "I18nAttributes";
})(OpKind || (OpKind = {}));
var ExpressionKind;
(function(ExpressionKind2) {
ExpressionKind2[ExpressionKind2["LexicalRead"] = 0] = "LexicalRead";
ExpressionKind2[ExpressionKind2["Context"] = 1] = "Context";
ExpressionKind2[ExpressionKind2["TrackContext"] = 2] = "TrackContext";
ExpressionKind2[ExpressionKind2["ReadVariable"] = 3] = "ReadVariable";
ExpressionKind2[ExpressionKind2["NextContext"] = 4] = "NextContext";
ExpressionKind2[ExpressionKind2["Reference"] = 5] = "Reference";
ExpressionKind2[ExpressionKind2["StoreLet"] = 6] = "StoreLet";
ExpressionKind2[ExpressionKind2["ContextLetReference"] = 7] = "ContextLetReference";
ExpressionKind2[ExpressionKind2["GetCurrentView"] = 8] = "GetCurrentView";
ExpressionKind2[ExpressionKind2["RestoreView"] = 9] = "RestoreView";
ExpressionKind2[ExpressionKind2["ResetView"] = 10] = "ResetView";
ExpressionKind2[ExpressionKind2["PureFunctionExpr"] = 11] = "PureFunctionExpr";
ExpressionKind2[ExpressionKind2["PureFunctionParameterExpr"] = 12] = "PureFunctionParameterExpr";
ExpressionKind2[ExpressionKind2["PipeBinding"] = 13] = "PipeBinding";
ExpressionKind2[ExpressionKind2["PipeBindingVariadic"] = 14] = "PipeBindingVariadic";
ExpressionKind2[ExpressionKind2["SafePropertyRead"] = 15] = "SafePropertyRead";
ExpressionKind2[ExpressionKind2["SafeKeyedRead"] = 16] = "SafeKeyedRead";
ExpressionKind2[ExpressionKind2["SafeInvokeFunction"] = 17] = "SafeInvokeFunction";
ExpressionKind2[ExpressionKind2["SafeTernaryExpr"] = 18] = "SafeTernaryExpr";
ExpressionKind2[ExpressionKind2["EmptyExpr"] = 19] = "EmptyExpr";
ExpressionKind2[ExpressionKind2["AssignTemporaryExpr"] = 20] = "AssignTemporaryExpr";
ExpressionKind2[ExpressionKind2["ReadTemporaryExpr"] = 21] = "ReadTemporaryExpr";
ExpressionKind2[ExpressionKind2["SlotLiteralExpr"] = 22] = "SlotLiteralExpr";
ExpressionKind2[ExpressionKind2["ConditionalCase"] = 23] = "ConditionalCase";
ExpressionKind2[ExpressionKind2["ConstCollected"] = 24] = "ConstCollected";
ExpressionKind2[ExpressionKind2["TwoWayBindingSet"] = 25] = "TwoWayBindingSet";
})(ExpressionKind || (ExpressionKind = {}));
var VariableFlags;
(function(VariableFlags2) {
VariableFlags2[VariableFlags2["None"] = 0] = "None";
VariableFlags2[VariableFlags2["AlwaysInline"] = 1] = "AlwaysInline";
})(VariableFlags || (VariableFlags = {}));
var SemanticVariableKind;
(function(SemanticVariableKind2) {
SemanticVariableKind2[SemanticVariableKind2["Context"] = 0] = "Context";
SemanticVariableKind2[SemanticVariableKind2["Identifier"] = 1] = "Identifier";
SemanticVariableKind2[SemanticVariableKind2["SavedView"] = 2] = "SavedView";
SemanticVariableKind2[SemanticVariableKind2["Alias"] = 3] = "Alias";
})(SemanticVariableKind || (SemanticVariableKind = {}));
var CompatibilityMode;
(function(CompatibilityMode2) {
CompatibilityMode2[CompatibilityMode2["Normal"] = 0] = "Normal";
CompatibilityMode2[CompatibilityMode2["TemplateDefinitionBuilder"] = 1] = "TemplateDefinitionBuilder";
})(CompatibilityMode || (CompatibilityMode = {}));
var BindingKind;
(function(BindingKind2) {
BindingKind2[BindingKind2["Attribute"] = 0] = "Attribute";
BindingKind2[BindingKind2["ClassName"] = 1] = "ClassName";
BindingKind2[BindingKind2["StyleProperty"] = 2] = "StyleProperty";
BindingKind2[BindingKind2["Property"] = 3] = "Property";
BindingKind2[BindingKind2["Template"] = 4] = "Template";
BindingKind2[BindingKind2["I18n"] = 5] = "I18n";
BindingKind2[BindingKind2["Animation"] = 6] = "Animation";
BindingKind2[BindingKind2["TwoWayProperty"] = 7] = "TwoWayProperty";
})(BindingKind || (BindingKind = {}));
var I18nParamResolutionTime;
(function(I18nParamResolutionTime2) {
I18nParamResolutionTime2[I18nParamResolutionTime2["Creation"] = 0] = "Creation";
I18nParamResolutionTime2[I18nParamResolutionTime2["Postproccessing"] = 1] = "Postproccessing";
})(I18nParamResolutionTime || (I18nParamResolutionTime = {}));
var I18nExpressionFor;
(function(I18nExpressionFor2) {
I18nExpressionFor2[I18nExpressionFor2["I18nText"] = 0] = "I18nText";
I18nExpressionFor2[I18nExpressionFor2["I18nAttribute"] = 1] = "I18nAttribute";
})(I18nExpressionFor || (I18nExpressionFor = {}));
var I18nParamValueFlags;
(function(I18nParamValueFlags2) {
I18nParamValueFlags2[I18nParamValueFlags2["None"] = 0] = "None";
I18nParamValueFlags2[I18nParamValueFlags2["ElementTag"] = 1] = "ElementTag";
I18nParamValueFlags2[I18nParamValueFlags2["TemplateTag"] = 2] = "TemplateTag";
I18nParamValueFlags2[I18nParamValueFlags2["OpenTag"] = 4] = "OpenTag";
I18nParamValueFlags2[I18nParamValueFlags2["CloseTag"] = 8] = "CloseTag";
I18nParamValueFlags2[I18nParamValueFlags2["ExpressionIndex"] = 16] = "ExpressionIndex";
})(I18nParamValueFlags || (I18nParamValueFlags = {}));
var Namespace;
(function(Namespace2) {
Namespace2[Namespace2["HTML"] = 0] = "HTML";
Namespace2[Namespace2["SVG"] = 1] = "SVG";
Namespace2[Namespace2["Math"] = 2] = "Math";
})(Namespace || (Namespace = {}));
var DeferTriggerKind;
(function(DeferTriggerKind2) {
DeferTriggerKind2[DeferTriggerKind2["Idle"] = 0] = "Idle";
DeferTriggerKind2[DeferTriggerKind2["Immediate"] = 1] = "Immediate";
DeferTriggerKind2[DeferTriggerKind2["Timer"] = 2] = "Timer";
DeferTriggerKind2[DeferTriggerKind2["Hover"] = 3] = "Hover";
DeferTriggerKind2[DeferTriggerKind2["Interaction"] = 4] = "Interaction";
DeferTriggerKind2[DeferTriggerKind2["Viewport"] = 5] = "Viewport";
})(DeferTriggerKind || (DeferTriggerKind = {}));
var I18nContextKind;
(function(I18nContextKind2) {
I18nContextKind2[I18nContextKind2["RootI18n"] = 0] = "RootI18n";
I18nContextKind2[I18nContextKind2["Icu"] = 1] = "Icu";
I18nContextKind2[I18nContextKind2["Attr"] = 2] = "Attr";
})(I18nContextKind || (I18nContextKind = {}));
var TemplateKind;
(function(TemplateKind2) {
TemplateKind2[TemplateKind2["NgTemplate"] = 0] = "NgTemplate";
TemplateKind2[TemplateKind2["Structural"] = 1] = "Structural";
TemplateKind2[TemplateKind2["Block"] = 2] = "Block";
})(TemplateKind || (TemplateKind = {}));
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/ir/src/traits.mjs
var ConsumesSlot = Symbol("ConsumesSlot");
var DependsOnSlotContext = Symbol("DependsOnSlotContext");
var ConsumesVarsTrait = Symbol("ConsumesVars");
var UsesVarOffset = Symbol("UsesVarOffset");
var TRAIT_CONSUMES_SLOT = {
[ConsumesSlot]: true,
numSlotsUsed: 1
};
var TRAIT_DEPENDS_ON_SLOT_CONTEXT = {
[DependsOnSlotContext]: true
};
var TRAIT_CONSUMES_VARS = {
[ConsumesVarsTrait]: true
};
function hasConsumesSlotTrait(op) {
return op[ConsumesSlot] === true;
}
function hasDependsOnSlotContextTrait(value) {
return value[DependsOnSlotContext] === true;
}
function hasConsumesVarsTrait(value) {
return value[ConsumesVarsTrait] === true;
}
function hasUsesVarOffsetTrait(expr) {
return expr[UsesVarOffset] === true;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/ir/src/ops/shared.mjs
function createStatementOp(statement) {
return __spreadValues({
kind: OpKind.Statement,
statement
}, NEW_OP);
}
function createVariableOp(xref, variable2, initializer, flags) {
return __spreadValues({
kind: OpKind.Variable,
xref,
variable: variable2,
initializer,
flags
}, NEW_OP);
}
var NEW_OP = {
debugListId: null,
prev: null,
next: null
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/ir/src/ops/update.mjs
function createInterpolateTextOp(xref, interpolation, sourceSpan) {
return __spreadValues(__spreadValues(__spreadValues({
kind: OpKind.InterpolateText,
target: xref,
interpolation,
sourceSpan
}, TRAIT_DEPENDS_ON_SLOT_CONTEXT), TRAIT_CONSUMES_VARS), NEW_OP);
}
var Interpolation2 = class {
constructor(strings, expressions, i18nPlaceholders) {
this.strings = strings;
this.expressions = expressions;
this.i18nPlaceholders = i18nPlaceholders;
if (i18nPlaceholders.length !== 0 && i18nPlaceholders.length !== expressions.length) {
throw new Error(`Expected ${expressions.length} placeholders to match interpolation expression count, but got ${i18nPlaceholders.length}`);
}
}
};
function createBindingOp(target, kind, name, expression, unit, securityContext, isTextAttribute, isStructuralTemplateAttribute, templateKind, i18nMessage, sourceSpan) {
return __spreadValues({
kind: OpKind.Binding,
bindingKind: kind,
target,
name,
expression,
unit,
securityContext,
isTextAttribute,
isStructuralTemplateAttribute,
templateKind,
i18nContext: null,
i18nMessage,
sourceSpan
}, NEW_OP);
}
function createPropertyOp(target, name, expression, isAnimationTrigger, securityContext, isStructuralTemplateAttribute, templateKind, i18nContext, i18nMessage, sourceSpan) {
return __spreadValues(__spreadValues(__spreadValues({
kind: OpKind.Property,
target,
name,
expression,
isAnimationTrigger,
securityContext,
sanitizer: null,
isStructuralTemplateAttribute,
templateKind,
i18nContext,
i18nMessage,
sourceSpan
}, TRAIT_DEPENDS_ON_SLOT_CONTEXT), TRAIT_CONSUMES_VARS), NEW_OP);
}
function createTwoWayPropertyOp(target, name, expression, securityContext, isStructuralTemplateAttribute, templateKind, i18nContext, i18nMessage, sourceSpan) {
return __spreadValues(__spreadValues(__spreadValues({
kind: OpKind.TwoWayProperty,
target,
name,
expression,
securityContext,
sanitizer: null,
isStructuralTemplateAttribute,
templateKind,
i18nContext,
i18nMessage,
sourceSpan
}, TRAIT_DEPENDS_ON_SLOT_CONTEXT), TRAIT_CONSUMES_VARS), NEW_OP);
}
function createStylePropOp(xref, name, expression, unit, sourceSpan) {
return __spreadValues(__spreadValues(__spreadValues({
kind: OpKind.StyleProp,
target: xref,
name,
expression,
unit,
sourceSpan
}, TRAIT_DEPENDS_ON_SLOT_CONTEXT), TRAIT_CONSUMES_VARS), NEW_OP);
}
function createClassPropOp(xref, name, expression, sourceSpan) {
return __spreadValues(__spreadValues(__spreadValues({
kind: OpKind.ClassProp,
target: xref,
name,
expression,
sourceSpan
}, TRAIT_DEPENDS_ON_SLOT_CONTEXT), TRAIT_CONSUMES_VARS), NEW_OP);
}
function createStyleMapOp(xref, expression, sourceSpan) {
return __spreadValues(__spreadValues(__spreadValues({
kind: OpKind.StyleMap,
target: xref,
expression,
sourceSpan
}, TRAIT_DEPENDS_ON_SLOT_CONTEXT), TRAIT_CONSUMES_VARS), NEW_OP);
}
function createClassMapOp(xref, expression, sourceSpan) {
return __spreadValues(__spreadValues(__spreadValues({
kind: OpKind.ClassMap,
target: xref,
expression,
sourceSpan
}, TRAIT_DEPENDS_ON_SLOT_CONTEXT), TRAIT_CONSUMES_VARS), NEW_OP);
}
function createAttributeOp(target, namespace, name, expression, securityContext, isTextAttribute, isStructuralTemplateAttribute, templateKind, i18nMessage, sourceSpan) {
return __spreadValues(__spreadValues(__spreadValues({
kind: OpKind.Attribute,
target,
namespace,
name,
expression,
securityContext,
sanitizer: null,
isTextAttribute,
isStructuralTemplateAttribute,
templateKind,
i18nContext: null,
i18nMessage,
sourceSpan
}, TRAIT_DEPENDS_ON_SLOT_CONTEXT), TRAIT_CONSUMES_VARS), NEW_OP);
}
function createAdvanceOp(delta, sourceSpan) {
return __spreadValues({
kind: OpKind.Advance,
delta,
sourceSpan
}, NEW_OP);
}
function createConditionalOp(target, test, conditions, sourceSpan) {
return __spreadValues(__spreadValues(__spreadValues({
kind: OpKind.Conditional,
target,
test,
conditions,
processed: null,
sourceSpan,
contextValue: null
}, NEW_OP), TRAIT_DEPENDS_ON_SLOT_CONTEXT), TRAIT_CONSUMES_VARS);
}
function createRepeaterOp(repeaterCreate2, targetSlot, collection, sourceSpan) {
return __spreadValues(__spreadValues({
kind: OpKind.Repeater,
target: repeaterCreate2,
targetSlot,
collection,
sourceSpan
}, NEW_OP), TRAIT_DEPENDS_ON_SLOT_CONTEXT);
}
function createDeferWhenOp(target, expr, prefetch, sourceSpan) {
return __spreadValues(__spreadValues(__spreadValues({
kind: OpKind.DeferWhen,
target,
expr,
prefetch,
sourceSpan
}, NEW_OP), TRAIT_DEPENDS_ON_SLOT_CONTEXT), TRAIT_CONSUMES_VARS);
}
function createI18nExpressionOp(context, target, i18nOwner, handle, expression, icuPlaceholder, i18nPlaceholder, resolutionTime, usage, name, sourceSpan) {
return __spreadValues(__spreadValues(__spreadValues({
kind: OpKind.I18nExpression,
context,
target,
i18nOwner,
handle,
expression,
icuPlaceholder,
i18nPlaceholder,
resolutionTime,
usage,
name,
sourceSpan
}, NEW_OP), TRAIT_CONSUMES_VARS), TRAIT_DEPENDS_ON_SLOT_CONTEXT);
}
function createI18nApplyOp(owner, handle, sourceSpan) {
return __spreadValues({
kind: OpKind.I18nApply,
owner,
handle,
sourceSpan
}, NEW_OP);
}
function createStoreLetOp(target, declaredName, value, sourceSpan) {
return __spreadValues(__spreadValues(__spreadValues({
kind: OpKind.StoreLet,
target,
declaredName,
value,
sourceSpan
}, TRAIT_DEPENDS_ON_SLOT_CONTEXT), TRAIT_CONSUMES_VARS), NEW_OP);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/ir/src/expression.mjs
var _a;
var _b;
var _c;
var _d;
var _e;
var _f;
var _g;
var _h;
function isIrExpression(expr) {
return expr instanceof ExpressionBase;
}
var ExpressionBase = class extends Expression {
constructor(sourceSpan = null) {
super(null, sourceSpan);
}
};
var LexicalReadExpr = class extends ExpressionBase {
constructor(name) {
super();
this.name = name;
this.kind = ExpressionKind.LexicalRead;
}
visitExpression(visitor, context) {
}
isEquivalent(other) {
return this.name === other.name;
}
isConstant() {
return false;
}
transformInternalExpressions() {
}
clone() {
return new LexicalReadExpr(this.name);
}
};
var ReferenceExpr = class extends ExpressionBase {
constructor(target, targetSlot, offset) {
super();
this.target = target;
this.targetSlot = targetSlot;
this.offset = offset;
this.kind = ExpressionKind.Reference;
}
visitExpression() {
}
isEquivalent(e) {
return e instanceof ReferenceExpr && e.target === this.target;
}
isConstant() {
return false;
}
transformInternalExpressions() {
}
clone() {
return new ReferenceExpr(this.target, this.targetSlot, this.offset);
}
};
var _StoreLetExpr = class extends ExpressionBase {
constructor(target, value, sourceSpan) {
super();
this.target = target;
this.value = value;
this.sourceSpan = sourceSpan;
this.kind = ExpressionKind.StoreLet;
this[_a] = true;
this[_b] = true;
}
visitExpression() {
}
isEquivalent(e) {
return e instanceof _StoreLetExpr && e.target === this.target && e.value.isEquivalent(this.value);
}
isConstant() {
return false;
}
transformInternalExpressions(transform2, flags) {
this.value = transformExpressionsInExpression(this.value, transform2, flags);
}
clone() {
return new _StoreLetExpr(this.target, this.value, this.sourceSpan);
}
};
var StoreLetExpr = _StoreLetExpr;
(() => {
_a = ConsumesVarsTrait, _b = DependsOnSlotContext;
})();
var ContextLetReferenceExpr = class extends ExpressionBase {
constructor(target, targetSlot) {
super();
this.target = target;
this.targetSlot = targetSlot;
this.kind = ExpressionKind.ContextLetReference;
}
visitExpression() {
}
isEquivalent(e) {
return e instanceof ContextLetReferenceExpr && e.target === this.target;
}
isConstant() {
return false;
}
transformInternalExpressions() {
}
clone() {
return new ContextLetReferenceExpr(this.target, this.targetSlot);
}
};
var ContextExpr = class extends ExpressionBase {
constructor(view) {
super();
this.view = view;
this.kind = ExpressionKind.Context;
}
visitExpression() {
}
isEquivalent(e) {
return e instanceof ContextExpr && e.view === this.view;
}
isConstant() {
return false;
}
transformInternalExpressions() {
}
clone() {
return new ContextExpr(this.view);
}
};
var TrackContextExpr = class extends ExpressionBase {
constructor(view) {
super();
this.view = view;
this.kind = ExpressionKind.TrackContext;
}
visitExpression() {
}
isEquivalent(e) {
return e instanceof TrackContextExpr && e.view === this.view;
}
isConstant() {
return false;
}
transformInternalExpressions() {
}
clone() {
return new TrackContextExpr(this.view);
}
};
var NextContextExpr = class extends ExpressionBase {
constructor() {
super();
this.kind = ExpressionKind.NextContext;
this.steps = 1;
}
visitExpression() {
}
isEquivalent(e) {
return e instanceof NextContextExpr && e.steps === this.steps;
}
isConstant() {
return false;
}
transformInternalExpressions() {
}
clone() {
const expr = new NextContextExpr();
expr.steps = this.steps;
return expr;
}
};
var GetCurrentViewExpr = class extends ExpressionBase {
constructor() {
super();
this.kind = ExpressionKind.GetCurrentView;
}
visitExpression() {
}
isEquivalent(e) {
return e instanceof GetCurrentViewExpr;
}
isConstant() {
return false;
}
transformInternalExpressions() {
}
clone() {
return new GetCurrentViewExpr();
}
};
var RestoreViewExpr = class extends ExpressionBase {
constructor(view) {
super();
this.view = view;
this.kind = ExpressionKind.RestoreView;
}
visitExpression(visitor, context) {
if (typeof this.view !== "number") {
this.view.visitExpression(visitor, context);
}
}
isEquivalent(e) {
if (!(e instanceof RestoreViewExpr) || typeof e.view !== typeof this.view) {
return false;
}
if (typeof this.view === "number") {
return this.view === e.view;
} else {
return this.view.isEquivalent(e.view);
}
}
isConstant() {
return false;
}
transformInternalExpressions(transform2, flags) {
if (typeof this.view !== "number") {
this.view = transformExpressionsInExpression(this.view, transform2, flags);
}
}
clone() {
return new RestoreViewExpr(this.view instanceof Expression ? this.view.clone() : this.view);
}
};
var ResetViewExpr = class extends ExpressionBase {
constructor(expr) {
super();
this.expr = expr;
this.kind = ExpressionKind.ResetView;
}
visitExpression(visitor, context) {
this.expr.visitExpression(visitor, context);
}
isEquivalent(e) {
return e instanceof ResetViewExpr && this.expr.isEquivalent(e.expr);
}
isConstant() {
return false;
}
transformInternalExpressions(transform2, flags) {
this.expr = transformExpressionsInExpression(this.expr, transform2, flags);
}
clone() {
return new ResetViewExpr(this.expr.clone());
}
};
var TwoWayBindingSetExpr = class extends ExpressionBase {
constructor(target, value) {
super();
this.target = target;
this.value = value;
this.kind = ExpressionKind.TwoWayBindingSet;
}
visitExpression(visitor, context) {
this.target.visitExpression(visitor, context);
this.value.visitExpression(visitor, context);
}
isEquivalent(other) {
return this.target.isEquivalent(other.target) && this.value.isEquivalent(other.value);
}
isConstant() {
return false;
}
transformInternalExpressions(transform2, flags) {
this.target = transformExpressionsInExpression(this.target, transform2, flags);
this.value = transformExpressionsInExpression(this.value, transform2, flags);
}
clone() {
return new TwoWayBindingSetExpr(this.target, this.value);
}
};
var ReadVariableExpr = class extends ExpressionBase {
constructor(xref) {
super();
this.xref = xref;
this.kind = ExpressionKind.ReadVariable;
this.name = null;
}
visitExpression() {
}
isEquivalent(other) {
return other instanceof ReadVariableExpr && other.xref === this.xref;
}
isConstant() {
return false;
}
transformInternalExpressions() {
}
clone() {
const expr = new ReadVariableExpr(this.xref);
expr.name = this.name;
return expr;
}
};
var _PureFunctionExpr = class extends ExpressionBase {
constructor(expression, args) {
super();
this.kind = ExpressionKind.PureFunctionExpr;
this[_c] = true;
this[_d] = true;
this.varOffset = null;
this.fn = null;
this.body = expression;
this.args = args;
}
visitExpression(visitor, context) {
var _a2;
(_a2 = this.body) == null ? void 0 : _a2.visitExpression(visitor, context);
for (const arg of this.args) {
arg.visitExpression(visitor, context);
}
}
isEquivalent(other) {
if (!(other instanceof _PureFunctionExpr) || other.args.length !== this.args.length) {
return false;
}
return other.body !== null && this.body !== null && other.body.isEquivalent(this.body) && other.args.every((arg, idx) => arg.isEquivalent(this.args[idx]));
}
isConstant() {
return false;
}
transformInternalExpressions(transform2, flags) {
if (this.body !== null) {
this.body = transformExpressionsInExpression(this.body, transform2, flags | VisitorContextFlag.InChildOperation);
} else if (this.fn !== null) {
this.fn = transformExpressionsInExpression(this.fn, transform2, flags);
}
for (let i = 0; i < this.args.length; i++) {
this.args[i] = transformExpressionsInExpression(this.args[i], transform2, flags);
}
}
clone() {
var _a2, _b2, _c2, _d2;
const expr = new _PureFunctionExpr((_b2 = (_a2 = this.body) == null ? void 0 : _a2.clone()) != null ? _b2 : null, this.args.map((arg) => arg.clone()));
expr.fn = (_d2 = (_c2 = this.fn) == null ? void 0 : _c2.clone()) != null ? _d2 : null;
expr.varOffset = this.varOffset;
return expr;
}
};
var PureFunctionExpr = _PureFunctionExpr;
(() => {
_c = ConsumesVarsTrait, _d = UsesVarOffset;
})();
var PureFunctionParameterExpr = class extends ExpressionBase {
constructor(index) {
super();
this.index = index;
this.kind = ExpressionKind.PureFunctionParameterExpr;
}
visitExpression() {
}
isEquivalent(other) {
return other instanceof PureFunctionParameterExpr && other.index === this.index;
}
isConstant() {
return true;
}
transformInternalExpressions() {
}
clone() {
return new PureFunctionParameterExpr(this.index);
}
};
var _PipeBindingExpr = class extends ExpressionBase {
constructor(target, targetSlot, name, args) {
super();
this.target = target;
this.targetSlot = targetSlot;
this.name = name;
this.args = args;
this.kind = ExpressionKind.PipeBinding;
this[_e] = true;
this[_f] = true;
this.varOffset = null;
}
visitExpression(visitor, context) {
for (const arg of this.args) {
arg.visitExpression(visitor, context);
}
}
isEquivalent() {
return false;
}
isConstant() {
return false;
}
transformInternalExpressions(transform2, flags) {
for (let idx = 0; idx < this.args.length; idx++) {
this.args[idx] = transformExpressionsInExpression(this.args[idx], transform2, flags);
}
}
clone() {
const r = new _PipeBindingExpr(this.target, this.targetSlot, this.name, this.args.map((a) => a.clone()));
r.varOffset = this.varOffset;
return r;
}
};
var PipeBindingExpr = _PipeBindingExpr;
(() => {
_e = ConsumesVarsTrait, _f = UsesVarOffset;
})();
var _PipeBindingVariadicExpr = class extends ExpressionBase {
constructor(target, targetSlot, name, args, numArgs) {
super();
this.target = target;
this.targetSlot = targetSlot;
this.name = name;
this.args = args;
this.numArgs = numArgs;
this.kind = ExpressionKind.PipeBindingVariadic;
this[_g] = true;
this[_h] = true;
this.varOffset = null;
}
visitExpression(visitor, context) {
this.args.visitExpression(visitor, context);
}
isEquivalent() {
return false;
}
isConstant() {
return false;
}
transformInternalExpressions(transform2, flags) {
this.args = transformExpressionsInExpression(this.args, transform2, flags);
}
clone() {
const r = new _PipeBindingVariadicExpr(this.target, this.targetSlot, this.name, this.args.clone(), this.numArgs);
r.varOffset = this.varOffset;
return r;
}
};
var PipeBindingVariadicExpr = _PipeBindingVariadicExpr;
(() => {
_g = ConsumesVarsTrait, _h = UsesVarOffset;
})();
var SafePropertyReadExpr = class extends ExpressionBase {
constructor(receiver, name) {
super();
this.receiver = receiver;
this.name = name;
this.kind = ExpressionKind.SafePropertyRead;
}
get index() {
return this.name;
}
visitExpression(visitor, context) {
this.receiver.visitExpression(visitor, context);
}
isEquivalent() {
return false;
}
isConstant() {
return false;
}
transformInternalExpressions(transform2, flags) {
this.receiver = transformExpressionsInExpression(this.receiver, transform2, flags);
}
clone() {
return new SafePropertyReadExpr(this.receiver.clone(), this.name);
}
};
var SafeKeyedReadExpr = class extends ExpressionBase {
constructor(receiver, index, sourceSpan) {
super(sourceSpan);
this.receiver = receiver;
this.index = index;
this.kind = ExpressionKind.SafeKeyedRead;
}
visitExpression(visitor, context) {
this.receiver.visitExpression(visitor, context);
this.index.visitExpression(visitor, context);
}
isEquivalent() {
return false;
}
isConstant() {
return false;
}
transformInternalExpressions(transform2, flags) {
this.receiver = transformExpressionsInExpression(this.receiver, transform2, flags);
this.index = transformExpressionsInExpression(this.index, transform2, flags);
}
clone() {
return new SafeKeyedReadExpr(this.receiver.clone(), this.index.clone(), this.sourceSpan);
}
};
var SafeInvokeFunctionExpr = class extends ExpressionBase {
constructor(receiver, args) {
super();
this.receiver = receiver;
this.args = args;
this.kind = ExpressionKind.SafeInvokeFunction;
}
visitExpression(visitor, context) {
this.receiver.visitExpression(visitor, context);
for (const a of this.args) {
a.visitExpression(visitor, context);
}
}
isEquivalent() {
return false;
}
isConstant() {
return false;
}
transformInternalExpressions(transform2, flags) {
this.receiver = transformExpressionsInExpression(this.receiver, transform2, flags);
for (let i = 0; i < this.args.length; i++) {
this.args[i] = transformExpressionsInExpression(this.args[i], transform2, flags);
}
}
clone() {
return new SafeInvokeFunctionExpr(this.receiver.clone(), this.args.map((a) => a.clone()));
}
};
var SafeTernaryExpr = class extends ExpressionBase {
constructor(guard, expr) {
super();
this.guard = guard;
this.expr = expr;
this.kind = ExpressionKind.SafeTernaryExpr;
}
visitExpression(visitor, context) {
this.guard.visitExpression(visitor, context);
this.expr.visitExpression(visitor, context);
}
isEquivalent() {
return false;
}
isConstant() {
return false;
}
transformInternalExpressions(transform2, flags) {
this.guard = transformExpressionsInExpression(this.guard, transform2, flags);
this.expr = transformExpressionsInExpression(this.expr, transform2, flags);
}
clone() {
return new SafeTernaryExpr(this.guard.clone(), this.expr.clone());
}
};
var EmptyExpr2 = class extends ExpressionBase {
constructor() {
super(...arguments);
this.kind = ExpressionKind.EmptyExpr;
}
visitExpression(visitor, context) {
}
isEquivalent(e) {
return e instanceof EmptyExpr2;
}
isConstant() {
return true;
}
clone() {
return new EmptyExpr2();
}
transformInternalExpressions() {
}
};
var AssignTemporaryExpr = class extends ExpressionBase {
constructor(expr, xref) {
super();
this.expr = expr;
this.xref = xref;
this.kind = ExpressionKind.AssignTemporaryExpr;
this.name = null;
}
visitExpression(visitor, context) {
this.expr.visitExpression(visitor, context);
}
isEquivalent() {
return false;
}
isConstant() {
return false;
}
transformInternalExpressions(transform2, flags) {
this.expr = transformExpressionsInExpression(this.expr, transform2, flags);
}
clone() {
const a = new AssignTemporaryExpr(this.expr.clone(), this.xref);
a.name = this.name;
return a;
}
};
var ReadTemporaryExpr = class extends ExpressionBase {
constructor(xref) {
super();
this.xref = xref;
this.kind = ExpressionKind.ReadTemporaryExpr;
this.name = null;
}
visitExpression(visitor, context) {
}
isEquivalent() {
return this.xref === this.xref;
}
isConstant() {
return false;
}
transformInternalExpressions(transform2, flags) {
}
clone() {
const r = new ReadTemporaryExpr(this.xref);
r.name = this.name;
return r;
}
};
var SlotLiteralExpr = class extends ExpressionBase {
constructor(slot) {
super();
this.slot = slot;
this.kind = ExpressionKind.SlotLiteralExpr;
}
visitExpression(visitor, context) {
}
isEquivalent(e) {
return e instanceof SlotLiteralExpr && e.slot === this.slot;
}
isConstant() {
return true;
}
clone() {
return new SlotLiteralExpr(this.slot);
}
transformInternalExpressions() {
}
};
var ConditionalCaseExpr = class extends ExpressionBase {
constructor(expr, target, targetSlot, alias = null) {
super();
this.expr = expr;
this.target = target;
this.targetSlot = targetSlot;
this.alias = alias;
this.kind = ExpressionKind.ConditionalCase;
}
visitExpression(visitor, context) {
if (this.expr !== null) {
this.expr.visitExpression(visitor, context);
}
}
isEquivalent(e) {
return e instanceof ConditionalCaseExpr && e.expr === this.expr;
}
isConstant() {
return true;
}
clone() {
return new ConditionalCaseExpr(this.expr, this.target, this.targetSlot);
}
transformInternalExpressions(transform2, flags) {
if (this.expr !== null) {
this.expr = transformExpressionsInExpression(this.expr, transform2, flags);
}
}
};
var ConstCollectedExpr = class extends ExpressionBase {
constructor(expr) {
super();
this.expr = expr;
this.kind = ExpressionKind.ConstCollected;
}
transformInternalExpressions(transform2, flags) {
this.expr = transform2(this.expr, flags);
}
visitExpression(visitor, context) {
this.expr.visitExpression(visitor, context);
}
isEquivalent(e) {
if (!(e instanceof ConstCollectedExpr)) {
return false;
}
return this.expr.isEquivalent(e.expr);
}
isConstant() {
return this.expr.isConstant();
}
clone() {
return new ConstCollectedExpr(this.expr);
}
};
function visitExpressionsInOp(op, visitor) {
transformExpressionsInOp(op, (expr, flags) => {
visitor(expr, flags);
return expr;
}, VisitorContextFlag.None);
}
var VisitorContextFlag;
(function(VisitorContextFlag2) {
VisitorContextFlag2[VisitorContextFlag2["None"] = 0] = "None";
VisitorContextFlag2[VisitorContextFlag2["InChildOperation"] = 1] = "InChildOperation";
})(VisitorContextFlag || (VisitorContextFlag = {}));
function transformExpressionsInInterpolation(interpolation, transform2, flags) {
for (let i = 0; i < interpolation.expressions.length; i++) {
interpolation.expressions[i] = transformExpressionsInExpression(interpolation.expressions[i], transform2, flags);
}
}
function transformExpressionsInOp(op, transform2, flags) {
switch (op.kind) {
case OpKind.StyleProp:
case OpKind.StyleMap:
case OpKind.ClassProp:
case OpKind.ClassMap:
case OpKind.Binding:
if (op.expression instanceof Interpolation2) {
transformExpressionsInInterpolation(op.expression, transform2, flags);
} else {
op.expression = transformExpressionsInExpression(op.expression, transform2, flags);
}
break;
case OpKind.Property:
case OpKind.HostProperty:
case OpKind.Attribute:
if (op.expression instanceof Interpolation2) {
transformExpressionsInInterpolation(op.expression, transform2, flags);
} else {
op.expression = transformExpressionsInExpression(op.expression, transform2, flags);
}
op.sanitizer = op.sanitizer && transformExpressionsInExpression(op.sanitizer, transform2, flags);
break;
case OpKind.TwoWayProperty:
op.expression = transformExpressionsInExpression(op.expression, transform2, flags);
op.sanitizer = op.sanitizer && transformExpressionsInExpression(op.sanitizer, transform2, flags);
break;
case OpKind.I18nExpression:
op.expression = transformExpressionsInExpression(op.expression, transform2, flags);
break;
case OpKind.InterpolateText:
transformExpressionsInInterpolation(op.interpolation, transform2, flags);
break;
case OpKind.Statement:
transformExpressionsInStatement(op.statement, transform2, flags);
break;
case OpKind.Variable:
op.initializer = transformExpressionsInExpression(op.initializer, transform2, flags);
break;
case OpKind.Conditional:
for (const condition of op.conditions) {
if (condition.expr === null) {
continue;
}
condition.expr = transformExpressionsInExpression(condition.expr, transform2, flags);
}
if (op.processed !== null) {
op.processed = transformExpressionsInExpression(op.processed, transform2, flags);
}
if (op.contextValue !== null) {
op.contextValue = transformExpressionsInExpression(op.contextValue, transform2, flags);
}
break;
case OpKind.Listener:
case OpKind.TwoWayListener:
for (const innerOp of op.handlerOps) {
transformExpressionsInOp(innerOp, transform2, flags | VisitorContextFlag.InChildOperation);
}
break;
case OpKind.ExtractedAttribute:
op.expression = op.expression && transformExpressionsInExpression(op.expression, transform2, flags);
op.trustedValueFn = op.trustedValueFn && transformExpressionsInExpression(op.trustedValueFn, transform2, flags);
break;
case OpKind.RepeaterCreate:
op.track = transformExpressionsInExpression(op.track, transform2, flags);
if (op.trackByFn !== null) {
op.trackByFn = transformExpressionsInExpression(op.trackByFn, transform2, flags);
}
break;
case OpKind.Repeater:
op.collection = transformExpressionsInExpression(op.collection, transform2, flags);
break;
case OpKind.Defer:
if (op.loadingConfig !== null) {
op.loadingConfig = transformExpressionsInExpression(op.loadingConfig, transform2, flags);
}
if (op.placeholderConfig !== null) {
op.placeholderConfig = transformExpressionsInExpression(op.placeholderConfig, transform2, flags);
}
if (op.resolverFn !== null) {
op.resolverFn = transformExpressionsInExpression(op.resolverFn, transform2, flags);
}
break;
case OpKind.I18nMessage:
for (const [placeholder, expr] of op.params) {
op.params.set(placeholder, transformExpressionsInExpression(expr, transform2, flags));
}
for (const [placeholder, expr] of op.postprocessingParams) {
op.postprocessingParams.set(placeholder, transformExpressionsInExpression(expr, transform2, flags));
}
break;
case OpKind.DeferWhen:
op.expr = transformExpressionsInExpression(op.expr, transform2, flags);
break;
case OpKind.StoreLet:
op.value = transformExpressionsInExpression(op.value, transform2, flags);
break;
case OpKind.Advance:
case OpKind.Container:
case OpKind.ContainerEnd:
case OpKind.ContainerStart:
case OpKind.DeferOn:
case OpKind.DisableBindings:
case OpKind.Element:
case OpKind.ElementEnd:
case OpKind.ElementStart:
case OpKind.EnableBindings:
case OpKind.I18n:
case OpKind.I18nApply:
case OpKind.I18nContext:
case OpKind.I18nEnd:
case OpKind.I18nStart:
case OpKind.IcuEnd:
case OpKind.IcuStart:
case OpKind.Namespace:
case OpKind.Pipe:
case OpKind.Projection:
case OpKind.ProjectionDef:
case OpKind.Template:
case OpKind.Text:
case OpKind.I18nAttributes:
case OpKind.IcuPlaceholder:
case OpKind.DeclareLet:
break;
default:
throw new Error(`AssertionError: transformExpressionsInOp doesn't handle ${OpKind[op.kind]}`);
}
}
function transformExpressionsInExpression(expr, transform2, flags) {
if (expr instanceof ExpressionBase) {
expr.transformInternalExpressions(transform2, flags);
} else if (expr instanceof BinaryOperatorExpr) {
expr.lhs = transformExpressionsInExpression(expr.lhs, transform2, flags);
expr.rhs = transformExpressionsInExpression(expr.rhs, transform2, flags);
} else if (expr instanceof UnaryOperatorExpr) {
expr.expr = transformExpressionsInExpression(expr.expr, transform2, flags);
} else if (expr instanceof ReadPropExpr) {
expr.receiver = transformExpressionsInExpression(expr.receiver, transform2, flags);
} else if (expr instanceof ReadKeyExpr) {
expr.receiver = transformExpressionsInExpression(expr.receiver, transform2, flags);
expr.index = transformExpressionsInExpression(expr.index, transform2, flags);
} else if (expr instanceof WritePropExpr) {
expr.receiver = transformExpressionsInExpression(expr.receiver, transform2, flags);
expr.value = transformExpressionsInExpression(expr.value, transform2, flags);
} else if (expr instanceof WriteKeyExpr) {
expr.receiver = transformExpressionsInExpression(expr.receiver, transform2, flags);
expr.index = transformExpressionsInExpression(expr.index, transform2, flags);
expr.value = transformExpressionsInExpression(expr.value, transform2, flags);
} else if (expr instanceof InvokeFunctionExpr) {
expr.fn = transformExpressionsInExpression(expr.fn, transform2, flags);
for (let i = 0; i < expr.args.length; i++) {
expr.args[i] = transformExpressionsInExpression(expr.args[i], transform2, flags);
}
} else if (expr instanceof LiteralArrayExpr) {
for (let i = 0; i < expr.entries.length; i++) {
expr.entries[i] = transformExpressionsInExpression(expr.entries[i], transform2, flags);
}
} else if (expr instanceof LiteralMapExpr) {
for (let i = 0; i < expr.entries.length; i++) {
expr.entries[i].value = transformExpressionsInExpression(expr.entries[i].value, transform2, flags);
}
} else if (expr instanceof ConditionalExpr) {
expr.condition = transformExpressionsInExpression(expr.condition, transform2, flags);
expr.trueCase = transformExpressionsInExpression(expr.trueCase, transform2, flags);
if (expr.falseCase !== null) {
expr.falseCase = transformExpressionsInExpression(expr.falseCase, transform2, flags);
}
} else if (expr instanceof TypeofExpr) {
expr.expr = transformExpressionsInExpression(expr.expr, transform2, flags);
} else if (expr instanceof WriteVarExpr) {
expr.value = transformExpressionsInExpression(expr.value, transform2, flags);
} else if (expr instanceof LocalizedString) {
for (let i = 0; i < expr.expressions.length; i++) {
expr.expressions[i] = transformExpressionsInExpression(expr.expressions[i], transform2, flags);
}
} else if (expr instanceof NotExpr) {
expr.condition = transformExpressionsInExpression(expr.condition, transform2, flags);
} else if (expr instanceof TaggedTemplateExpr) {
expr.tag = transformExpressionsInExpression(expr.tag, transform2, flags);
expr.template.expressions = expr.template.expressions.map((e) => transformExpressionsInExpression(e, transform2, flags));
} else if (expr instanceof ArrowFunctionExpr) {
if (Array.isArray(expr.body)) {
for (let i = 0; i < expr.body.length; i++) {
transformExpressionsInStatement(expr.body[i], transform2, flags);
}
} else {
expr.body = transformExpressionsInExpression(expr.body, transform2, flags);
}
} else if (expr instanceof WrappedNodeExpr) {
} else if (expr instanceof ReadVarExpr || expr instanceof ExternalExpr || expr instanceof LiteralExpr) {
} else {
throw new Error(`Unhandled expression kind: ${expr.constructor.name}`);
}
return transform2(expr, flags);
}
function transformExpressionsInStatement(stmt, transform2, flags) {
if (stmt instanceof ExpressionStatement) {
stmt.expr = transformExpressionsInExpression(stmt.expr, transform2, flags);
} else if (stmt instanceof ReturnStatement) {
stmt.value = transformExpressionsInExpression(stmt.value, transform2, flags);
} else if (stmt instanceof DeclareVarStmt) {
if (stmt.value !== void 0) {
stmt.value = transformExpressionsInExpression(stmt.value, transform2, flags);
}
} else if (stmt instanceof IfStmt) {
stmt.condition = transformExpressionsInExpression(stmt.condition, transform2, flags);
for (const caseStatement of stmt.trueCase) {
transformExpressionsInStatement(caseStatement, transform2, flags);
}
for (const caseStatement of stmt.falseCase) {
transformExpressionsInStatement(caseStatement, transform2, flags);
}
} else {
throw new Error(`Unhandled statement kind: ${stmt.constructor.name}`);
}
}
function isStringLiteral(expr) {
return expr instanceof LiteralExpr && typeof expr.value === "string";
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/ir/src/operations.mjs
var _OpList = class {
constructor() {
this.debugListId = _OpList.nextListId++;
this.head = {
kind: OpKind.ListEnd,
next: null,
prev: null,
debugListId: this.debugListId
};
this.tail = {
kind: OpKind.ListEnd,
next: null,
prev: null,
debugListId: this.debugListId
};
this.head.next = this.tail;
this.tail.prev = this.head;
}
push(op) {
if (Array.isArray(op)) {
for (const o of op) {
this.push(o);
}
return;
}
_OpList.assertIsNotEnd(op);
_OpList.assertIsUnowned(op);
op.debugListId = this.debugListId;
const oldLast = this.tail.prev;
op.prev = oldLast;
oldLast.next = op;
op.next = this.tail;
this.tail.prev = op;
}
prepend(ops) {
if (ops.length === 0) {
return;
}
for (const op of ops) {
_OpList.assertIsNotEnd(op);
_OpList.assertIsUnowned(op);
op.debugListId = this.debugListId;
}
const first = this.head.next;
let prev = this.head;
for (const op of ops) {
prev.next = op;
op.prev = prev;
prev = op;
}
prev.next = first;
first.prev = prev;
}
*[Symbol.iterator]() {
let current = this.head.next;
while (current !== this.tail) {
_OpList.assertIsOwned(current, this.debugListId);
const next = current.next;
yield current;
current = next;
}
}
*reversed() {
let current = this.tail.prev;
while (current !== this.head) {
_OpList.assertIsOwned(current, this.debugListId);
const prev = current.prev;
yield current;
current = prev;
}
}
static replace(oldOp, newOp) {
_OpList.assertIsNotEnd(oldOp);
_OpList.assertIsNotEnd(newOp);
_OpList.assertIsOwned(oldOp);
_OpList.assertIsUnowned(newOp);
newOp.debugListId = oldOp.debugListId;
if (oldOp.prev !== null) {
oldOp.prev.next = newOp;
newOp.prev = oldOp.prev;
}
if (oldOp.next !== null) {
oldOp.next.prev = newOp;
newOp.next = oldOp.next;
}
oldOp.debugListId = null;
oldOp.prev = null;
oldOp.next = null;
}
static replaceWithMany(oldOp, newOps) {
if (newOps.length === 0) {
_OpList.remove(oldOp);
return;
}
_OpList.assertIsNotEnd(oldOp);
_OpList.assertIsOwned(oldOp);
const listId = oldOp.debugListId;
oldOp.debugListId = null;
for (const newOp of newOps) {
_OpList.assertIsNotEnd(newOp);
_OpList.assertIsUnowned(newOp);
}
const { prev: oldPrev, next: oldNext } = oldOp;
oldOp.prev = null;
oldOp.next = null;
let prev = oldPrev;
for (const newOp of newOps) {
this.assertIsUnowned(newOp);
newOp.debugListId = listId;
prev.next = newOp;
newOp.prev = prev;
newOp.next = null;
prev = newOp;
}
const first = newOps[0];
const last = prev;
if (oldPrev !== null) {
oldPrev.next = first;
first.prev = oldPrev;
}
if (oldNext !== null) {
oldNext.prev = last;
last.next = oldNext;
}
}
static remove(op) {
_OpList.assertIsNotEnd(op);
_OpList.assertIsOwned(op);
op.prev.next = op.next;
op.next.prev = op.prev;
op.debugListId = null;
op.prev = null;
op.next = null;
}
static insertBefore(op, target) {
if (Array.isArray(op)) {
for (const o of op) {
this.insertBefore(o, target);
}
return;
}
_OpList.assertIsOwned(target);
if (target.prev === null) {
throw new Error(`AssertionError: illegal operation on list start`);
}
_OpList.assertIsNotEnd(op);
_OpList.assertIsUnowned(op);
op.debugListId = target.debugListId;
op.prev = null;
target.prev.next = op;
op.prev = target.prev;
op.next = target;
target.prev = op;
}
static insertAfter(op, target) {
_OpList.assertIsOwned(target);
if (target.next === null) {
throw new Error(`AssertionError: illegal operation on list end`);
}
_OpList.assertIsNotEnd(op);
_OpList.assertIsUnowned(op);
op.debugListId = target.debugListId;
target.next.prev = op;
op.next = target.next;
op.prev = target;
target.next = op;
}
static assertIsUnowned(op) {
if (op.debugListId !== null) {
throw new Error(`AssertionError: illegal operation on owned node: ${OpKind[op.kind]}`);
}
}
static assertIsOwned(op, byList) {
if (op.debugListId === null) {
throw new Error(`AssertionError: illegal operation on unowned node: ${OpKind[op.kind]}`);
} else if (byList !== void 0 && op.debugListId !== byList) {
throw new Error(`AssertionError: node belongs to the wrong list (expected ${byList}, actual ${op.debugListId})`);
}
}
static assertIsNotEnd(op) {
if (op.kind === OpKind.ListEnd) {
throw new Error(`AssertionError: illegal operation on list head or tail`);
}
}
};
var OpList = _OpList;
(() => {
_OpList.nextListId = 0;
})();
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/ir/src/handle.mjs
var SlotHandle = class {
constructor() {
this.slot = null;
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/ir/src/ops/create.mjs
var elementContainerOpKinds = /* @__PURE__ */ new Set([
OpKind.Element,
OpKind.ElementStart,
OpKind.Container,
OpKind.ContainerStart,
OpKind.Template,
OpKind.RepeaterCreate
]);
function isElementOrContainerOp(op) {
return elementContainerOpKinds.has(op.kind);
}
function createElementStartOp(tag, xref, namespace, i18nPlaceholder, startSourceSpan, wholeSourceSpan) {
return __spreadValues(__spreadValues({
kind: OpKind.ElementStart,
xref,
tag,
handle: new SlotHandle(),
attributes: null,
localRefs: [],
nonBindable: false,
namespace,
i18nPlaceholder,
startSourceSpan,
wholeSourceSpan
}, TRAIT_CONSUMES_SLOT), NEW_OP);
}
function createTemplateOp(xref, templateKind, tag, functionNameSuffix, namespace, i18nPlaceholder, startSourceSpan, wholeSourceSpan) {
return __spreadValues(__spreadValues({
kind: OpKind.Template,
xref,
templateKind,
attributes: null,
tag,
handle: new SlotHandle(),
functionNameSuffix,
decls: null,
vars: null,
localRefs: [],
nonBindable: false,
namespace,
i18nPlaceholder,
startSourceSpan,
wholeSourceSpan
}, TRAIT_CONSUMES_SLOT), NEW_OP);
}
function createRepeaterCreateOp(primaryView, emptyView, tag, track, varNames, emptyTag, i18nPlaceholder, emptyI18nPlaceholder, startSourceSpan, wholeSourceSpan) {
return __spreadProps(__spreadValues(__spreadValues(__spreadValues({
kind: OpKind.RepeaterCreate,
attributes: null,
xref: primaryView,
handle: new SlotHandle(),
emptyView,
track,
trackByFn: null,
tag,
emptyTag,
emptyAttributes: null,
functionNameSuffix: "For",
namespace: Namespace.HTML,
nonBindable: false,
localRefs: [],
decls: null,
vars: null,
varNames,
usesComponentInstance: false,
i18nPlaceholder,
emptyI18nPlaceholder,
startSourceSpan,
wholeSourceSpan
}, TRAIT_CONSUMES_SLOT), NEW_OP), TRAIT_CONSUMES_VARS), {
numSlotsUsed: emptyView === null ? 2 : 3
});
}
function createElementEndOp(xref, sourceSpan) {
return __spreadValues({
kind: OpKind.ElementEnd,
xref,
sourceSpan
}, NEW_OP);
}
function createDisableBindingsOp(xref) {
return __spreadValues({
kind: OpKind.DisableBindings,
xref
}, NEW_OP);
}
function createEnableBindingsOp(xref) {
return __spreadValues({
kind: OpKind.EnableBindings,
xref
}, NEW_OP);
}
function createTextOp(xref, initialValue, icuPlaceholder, sourceSpan) {
return __spreadValues(__spreadValues({
kind: OpKind.Text,
xref,
handle: new SlotHandle(),
initialValue,
icuPlaceholder,
sourceSpan
}, TRAIT_CONSUMES_SLOT), NEW_OP);
}
function createListenerOp(target, targetSlot, name, tag, handlerOps, animationPhase, eventTarget, hostListener, sourceSpan) {
const handlerList = new OpList();
handlerList.push(handlerOps);
return __spreadValues({
kind: OpKind.Listener,
target,
targetSlot,
tag,
hostListener,
name,
handlerOps: handlerList,
handlerFnName: null,
consumesDollarEvent: false,
isAnimationListener: animationPhase !== null,
animationPhase,
eventTarget,
sourceSpan
}, NEW_OP);
}
function createTwoWayListenerOp(target, targetSlot, name, tag, handlerOps, sourceSpan) {
const handlerList = new OpList();
handlerList.push(handlerOps);
return __spreadValues({
kind: OpKind.TwoWayListener,
target,
targetSlot,
tag,
name,
handlerOps: handlerList,
handlerFnName: null,
sourceSpan
}, NEW_OP);
}
function createPipeOp(xref, slot, name) {
return __spreadValues(__spreadValues({
kind: OpKind.Pipe,
xref,
handle: slot,
name
}, NEW_OP), TRAIT_CONSUMES_SLOT);
}
function createNamespaceOp(namespace) {
return __spreadValues({
kind: OpKind.Namespace,
active: namespace
}, NEW_OP);
}
function createProjectionDefOp(def) {
return __spreadValues({
kind: OpKind.ProjectionDef,
def
}, NEW_OP);
}
function createProjectionOp(xref, selector, i18nPlaceholder, fallbackView, sourceSpan) {
return __spreadProps(__spreadValues(__spreadValues({
kind: OpKind.Projection,
xref,
handle: new SlotHandle(),
selector,
i18nPlaceholder,
fallbackView,
projectionSlotIndex: 0,
attributes: null,
localRefs: [],
sourceSpan
}, NEW_OP), TRAIT_CONSUMES_SLOT), {
numSlotsUsed: fallbackView === null ? 1 : 2
});
}
function createExtractedAttributeOp(target, bindingKind, namespace, name, expression, i18nContext, i18nMessage, securityContext) {
return __spreadValues({
kind: OpKind.ExtractedAttribute,
target,
bindingKind,
namespace,
name,
expression,
i18nContext,
i18nMessage,
securityContext,
trustedValueFn: null
}, NEW_OP);
}
function createDeferOp(xref, main, mainSlot, ownResolverFn, resolverFn, sourceSpan) {
return __spreadProps(__spreadValues(__spreadValues({
kind: OpKind.Defer,
xref,
handle: new SlotHandle(),
mainView: main,
mainSlot,
loadingView: null,
loadingSlot: null,
loadingConfig: null,
loadingMinimumTime: null,
loadingAfterTime: null,
placeholderView: null,
placeholderSlot: null,
placeholderConfig: null,
placeholderMinimumTime: null,
errorView: null,
errorSlot: null,
ownResolverFn,
resolverFn,
sourceSpan
}, NEW_OP), TRAIT_CONSUMES_SLOT), {
numSlotsUsed: 2
});
}
function createDeferOnOp(defer2, trigger, prefetch, sourceSpan) {
return __spreadValues({
kind: OpKind.DeferOn,
defer: defer2,
trigger,
prefetch,
sourceSpan
}, NEW_OP);
}
function createDeclareLetOp(xref, declaredName, sourceSpan) {
return __spreadValues(__spreadValues({
kind: OpKind.DeclareLet,
xref,
declaredName,
sourceSpan,
handle: new SlotHandle()
}, TRAIT_CONSUMES_SLOT), NEW_OP);
}
function createI18nMessageOp(xref, i18nContext, i18nBlock, message, messagePlaceholder, params, postprocessingParams, needsPostprocessing) {
return __spreadValues({
kind: OpKind.I18nMessage,
xref,
i18nContext,
i18nBlock,
message,
messagePlaceholder,
params,
postprocessingParams,
needsPostprocessing,
subMessages: []
}, NEW_OP);
}
function createI18nStartOp(xref, message, root, sourceSpan) {
return __spreadValues(__spreadValues({
kind: OpKind.I18nStart,
xref,
handle: new SlotHandle(),
root: root != null ? root : xref,
message,
messageIndex: null,
subTemplateIndex: null,
context: null,
sourceSpan
}, NEW_OP), TRAIT_CONSUMES_SLOT);
}
function createI18nEndOp(xref, sourceSpan) {
return __spreadValues({
kind: OpKind.I18nEnd,
xref,
sourceSpan
}, NEW_OP);
}
function createIcuStartOp(xref, message, messagePlaceholder, sourceSpan) {
return __spreadValues({
kind: OpKind.IcuStart,
xref,
message,
messagePlaceholder,
context: null,
sourceSpan
}, NEW_OP);
}
function createIcuEndOp(xref) {
return __spreadValues({
kind: OpKind.IcuEnd,
xref
}, NEW_OP);
}
function createIcuPlaceholderOp(xref, name, strings) {
return __spreadValues({
kind: OpKind.IcuPlaceholder,
xref,
name,
strings,
expressionPlaceholders: []
}, NEW_OP);
}
function createI18nContextOp(contextKind, xref, i18nBlock, message, sourceSpan) {
if (i18nBlock === null && contextKind !== I18nContextKind.Attr) {
throw new Error("AssertionError: i18nBlock must be provided for non-attribute contexts.");
}
return __spreadValues({
kind: OpKind.I18nContext,
contextKind,
xref,
i18nBlock,
message,
sourceSpan,
params: /* @__PURE__ */ new Map(),
postprocessingParams: /* @__PURE__ */ new Map()
}, NEW_OP);
}
function createI18nAttributesOp(xref, handle, target) {
return __spreadValues(__spreadValues({
kind: OpKind.I18nAttributes,
xref,
handle,
target,
i18nAttributesConfig: null
}, NEW_OP), TRAIT_CONSUMES_SLOT);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/ir/src/ops/host.mjs
function createHostPropertyOp(name, expression, isAnimationTrigger, i18nContext, securityContext, sourceSpan) {
return __spreadValues(__spreadValues({
kind: OpKind.HostProperty,
name,
expression,
isAnimationTrigger,
i18nContext,
securityContext,
sanitizer: null,
sourceSpan
}, TRAIT_CONSUMES_VARS), NEW_OP);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/ir/src/variable.mjs
var CTX_REF = "CTX_REF_MARKER";
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/compilation.mjs
var CompilationJobKind;
(function(CompilationJobKind2) {
CompilationJobKind2[CompilationJobKind2["Tmpl"] = 0] = "Tmpl";
CompilationJobKind2[CompilationJobKind2["Host"] = 1] = "Host";
CompilationJobKind2[CompilationJobKind2["Both"] = 2] = "Both";
})(CompilationJobKind || (CompilationJobKind = {}));
var CompilationJob = class {
constructor(componentName, pool, compatibility) {
this.componentName = componentName;
this.pool = pool;
this.compatibility = compatibility;
this.kind = CompilationJobKind.Both;
this.nextXrefId = 0;
}
allocateXrefId() {
return this.nextXrefId++;
}
};
var ComponentCompilationJob = class extends CompilationJob {
constructor(componentName, pool, compatibility, relativeContextFilePath, i18nUseExternalIds, deferMeta, allDeferrableDepsFn) {
super(componentName, pool, compatibility);
this.relativeContextFilePath = relativeContextFilePath;
this.i18nUseExternalIds = i18nUseExternalIds;
this.deferMeta = deferMeta;
this.allDeferrableDepsFn = allDeferrableDepsFn;
this.kind = CompilationJobKind.Tmpl;
this.fnSuffix = "Template";
this.views = /* @__PURE__ */ new Map();
this.contentSelectors = null;
this.consts = [];
this.constsInitializers = [];
this.root = new ViewCompilationUnit(this, this.allocateXrefId(), null);
this.views.set(this.root.xref, this.root);
}
allocateView(parent) {
const view = new ViewCompilationUnit(this, this.allocateXrefId(), parent);
this.views.set(view.xref, view);
return view;
}
get units() {
return this.views.values();
}
addConst(newConst, initializers) {
for (let idx2 = 0; idx2 < this.consts.length; idx2++) {
if (this.consts[idx2].isEquivalent(newConst)) {
return idx2;
}
}
const idx = this.consts.length;
this.consts.push(newConst);
if (initializers) {
this.constsInitializers.push(...initializers);
}
return idx;
}
};
var CompilationUnit = class {
constructor(xref) {
this.xref = xref;
this.create = new OpList();
this.update = new OpList();
this.fnName = null;
this.vars = null;
}
*ops() {
for (const op of this.create) {
yield op;
if (op.kind === OpKind.Listener || op.kind === OpKind.TwoWayListener) {
for (const listenerOp of op.handlerOps) {
yield listenerOp;
}
}
}
for (const op of this.update) {
yield op;
}
}
};
var ViewCompilationUnit = class extends CompilationUnit {
constructor(job, xref, parent) {
super(xref);
this.job = job;
this.parent = parent;
this.contextVariables = /* @__PURE__ */ new Map();
this.aliases = /* @__PURE__ */ new Set();
this.decls = null;
}
};
var HostBindingCompilationJob = class extends CompilationJob {
constructor(componentName, pool, compatibility) {
super(componentName, pool, compatibility);
this.kind = CompilationJobKind.Host;
this.fnSuffix = "HostBindings";
this.root = new HostBindingCompilationUnit(this);
}
get units() {
return [this.root];
}
};
var HostBindingCompilationUnit = class extends CompilationUnit {
constructor(job) {
super(0);
this.job = job;
this.attributes = null;
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/any_cast.mjs
function deleteAnyCasts(job) {
for (const unit of job.units) {
for (const op of unit.ops()) {
transformExpressionsInOp(op, removeAnys, VisitorContextFlag.None);
}
}
}
function removeAnys(e) {
if (e instanceof InvokeFunctionExpr && e.fn instanceof LexicalReadExpr && e.fn.name === "$any") {
if (e.args.length !== 1) {
throw new Error("The $any builtin function expects exactly one argument.");
}
return e.args[0];
}
return e;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/apply_i18n_expressions.mjs
function applyI18nExpressions(job) {
const i18nContexts = /* @__PURE__ */ new Map();
for (const unit of job.units) {
for (const op of unit.create) {
if (op.kind === OpKind.I18nContext) {
i18nContexts.set(op.xref, op);
}
}
}
for (const unit of job.units) {
for (const op of unit.update) {
if (op.kind === OpKind.I18nExpression && needsApplication(i18nContexts, op)) {
OpList.insertAfter(createI18nApplyOp(op.i18nOwner, op.handle, null), op);
}
}
}
}
function needsApplication(i18nContexts, op) {
var _a2;
if (((_a2 = op.next) == null ? void 0 : _a2.kind) !== OpKind.I18nExpression) {
return true;
}
const context = i18nContexts.get(op.context);
const nextContext2 = i18nContexts.get(op.next.context);
if (context === void 0) {
throw new Error("AssertionError: expected an I18nContextOp to exist for the I18nExpressionOp's context");
}
if (nextContext2 === void 0) {
throw new Error("AssertionError: expected an I18nContextOp to exist for the next I18nExpressionOp's context");
}
if (context.i18nBlock !== null) {
if (context.i18nBlock !== nextContext2.i18nBlock) {
return true;
}
return false;
}
if (op.i18nOwner !== op.next.i18nOwner) {
return true;
}
return false;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/assign_i18n_slot_dependencies.mjs
function assignI18nSlotDependencies(job) {
for (const unit of job.units) {
let updateOp = unit.update.head;
let i18nExpressionsInProgress = [];
let state = null;
for (const createOp of unit.create) {
if (createOp.kind === OpKind.I18nStart) {
state = {
blockXref: createOp.xref,
lastSlotConsumer: createOp.xref
};
} else if (createOp.kind === OpKind.I18nEnd) {
for (const op of i18nExpressionsInProgress) {
op.target = state.lastSlotConsumer;
OpList.insertBefore(op, updateOp);
}
i18nExpressionsInProgress.length = 0;
state = null;
}
if (hasConsumesSlotTrait(createOp)) {
if (state !== null) {
state.lastSlotConsumer = createOp.xref;
}
while (true) {
if (updateOp.next === null) {
break;
}
if (state !== null && updateOp.kind === OpKind.I18nExpression && updateOp.usage === I18nExpressionFor.I18nText && updateOp.i18nOwner === state.blockXref) {
const opToRemove = updateOp;
updateOp = updateOp.next;
OpList.remove(opToRemove);
i18nExpressionsInProgress.push(opToRemove);
continue;
}
if (hasDependsOnSlotContextTrait(updateOp) && updateOp.target !== createOp.xref) {
break;
}
updateOp = updateOp.next;
}
}
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/util/elements.mjs
function createOpXrefMap(unit) {
const map = /* @__PURE__ */ new Map();
for (const op of unit.create) {
if (!hasConsumesSlotTrait(op)) {
continue;
}
map.set(op.xref, op);
if (op.kind === OpKind.RepeaterCreate && op.emptyView !== null) {
map.set(op.emptyView, op);
}
}
return map;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/attribute_extraction.mjs
function extractAttributes(job) {
for (const unit of job.units) {
const elements = createOpXrefMap(unit);
for (const op of unit.ops()) {
switch (op.kind) {
case OpKind.Attribute:
extractAttributeOp(unit, op, elements);
break;
case OpKind.Property:
if (!op.isAnimationTrigger) {
let bindingKind;
if (op.i18nMessage !== null && op.templateKind === null) {
bindingKind = BindingKind.I18n;
} else if (op.isStructuralTemplateAttribute) {
bindingKind = BindingKind.Template;
} else {
bindingKind = BindingKind.Property;
}
OpList.insertBefore(
createExtractedAttributeOp(
op.target,
bindingKind,
null,
op.name,
null,
null,
null,
op.securityContext
),
lookupElement(elements, op.target)
);
}
break;
case OpKind.TwoWayProperty:
OpList.insertBefore(createExtractedAttributeOp(
op.target,
BindingKind.TwoWayProperty,
null,
op.name,
null,
null,
null,
op.securityContext
), lookupElement(elements, op.target));
break;
case OpKind.StyleProp:
case OpKind.ClassProp:
if (unit.job.compatibility === CompatibilityMode.TemplateDefinitionBuilder && op.expression instanceof EmptyExpr2) {
OpList.insertBefore(createExtractedAttributeOp(
op.target,
BindingKind.Property,
null,
op.name,
null,
null,
null,
SecurityContext.STYLE
), lookupElement(elements, op.target));
}
break;
case OpKind.Listener:
if (!op.isAnimationListener) {
const extractedAttributeOp = createExtractedAttributeOp(
op.target,
BindingKind.Property,
null,
op.name,
null,
null,
null,
SecurityContext.NONE
);
if (job.kind === CompilationJobKind.Host) {
if (job.compatibility) {
break;
}
unit.create.push(extractedAttributeOp);
} else {
OpList.insertBefore(extractedAttributeOp, lookupElement(elements, op.target));
}
}
break;
case OpKind.TwoWayListener:
if (job.kind !== CompilationJobKind.Host) {
const extractedAttributeOp = createExtractedAttributeOp(
op.target,
BindingKind.Property,
null,
op.name,
null,
null,
null,
SecurityContext.NONE
);
OpList.insertBefore(extractedAttributeOp, lookupElement(elements, op.target));
}
break;
}
}
}
}
function lookupElement(elements, xref) {
const el = elements.get(xref);
if (el === void 0) {
throw new Error("All attributes should have an element-like target.");
}
return el;
}
function extractAttributeOp(unit, op, elements) {
if (op.expression instanceof Interpolation2) {
return;
}
let extractable = op.isTextAttribute || op.expression.isConstant();
if (unit.job.compatibility === CompatibilityMode.TemplateDefinitionBuilder) {
extractable && (extractable = op.isTextAttribute);
}
if (extractable) {
const extractedAttributeOp = createExtractedAttributeOp(op.target, op.isStructuralTemplateAttribute ? BindingKind.Template : BindingKind.Attribute, op.namespace, op.name, op.expression, op.i18nContext, op.i18nMessage, op.securityContext);
if (unit.job.kind === CompilationJobKind.Host) {
unit.create.push(extractedAttributeOp);
} else {
const ownerOp = lookupElement(elements, op.target);
OpList.insertBefore(extractedAttributeOp, ownerOp);
}
OpList.remove(op);
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/binding_specialization.mjs
function lookupElement2(elements, xref) {
const el = elements.get(xref);
if (el === void 0) {
throw new Error("All attributes should have an element-like target.");
}
return el;
}
function specializeBindings(job) {
const elements = /* @__PURE__ */ new Map();
for (const unit of job.units) {
for (const op of unit.create) {
if (!isElementOrContainerOp(op)) {
continue;
}
elements.set(op.xref, op);
}
}
for (const unit of job.units) {
for (const op of unit.ops()) {
if (op.kind !== OpKind.Binding) {
continue;
}
switch (op.bindingKind) {
case BindingKind.Attribute:
if (op.name === "ngNonBindable") {
OpList.remove(op);
const target = lookupElement2(elements, op.target);
target.nonBindable = true;
} else {
const [namespace, name] = splitNsName(op.name);
OpList.replace(op, createAttributeOp(op.target, namespace, name, op.expression, op.securityContext, op.isTextAttribute, op.isStructuralTemplateAttribute, op.templateKind, op.i18nMessage, op.sourceSpan));
}
break;
case BindingKind.Property:
case BindingKind.Animation:
if (job.kind === CompilationJobKind.Host) {
OpList.replace(op, createHostPropertyOp(op.name, op.expression, op.bindingKind === BindingKind.Animation, op.i18nContext, op.securityContext, op.sourceSpan));
} else {
OpList.replace(op, createPropertyOp(op.target, op.name, op.expression, op.bindingKind === BindingKind.Animation, op.securityContext, op.isStructuralTemplateAttribute, op.templateKind, op.i18nContext, op.i18nMessage, op.sourceSpan));
}
break;
case BindingKind.TwoWayProperty:
if (!(op.expression instanceof Expression)) {
throw new Error(`Expected value of two-way property binding "${op.name}" to be an expression`);
}
OpList.replace(op, createTwoWayPropertyOp(op.target, op.name, op.expression, op.securityContext, op.isStructuralTemplateAttribute, op.templateKind, op.i18nContext, op.i18nMessage, op.sourceSpan));
break;
case BindingKind.I18n:
case BindingKind.ClassName:
case BindingKind.StyleProperty:
throw new Error(`Unhandled binding of kind ${BindingKind[op.bindingKind]}`);
}
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/chaining.mjs
var CHAINABLE = /* @__PURE__ */ new Set([
Identifiers.attribute,
Identifiers.classProp,
Identifiers.element,
Identifiers.elementContainer,
Identifiers.elementContainerEnd,
Identifiers.elementContainerStart,
Identifiers.elementEnd,
Identifiers.elementStart,
Identifiers.hostProperty,
Identifiers.i18nExp,
Identifiers.listener,
Identifiers.listener,
Identifiers.property,
Identifiers.styleProp,
Identifiers.stylePropInterpolate1,
Identifiers.stylePropInterpolate2,
Identifiers.stylePropInterpolate3,
Identifiers.stylePropInterpolate4,
Identifiers.stylePropInterpolate5,
Identifiers.stylePropInterpolate6,
Identifiers.stylePropInterpolate7,
Identifiers.stylePropInterpolate8,
Identifiers.stylePropInterpolateV,
Identifiers.syntheticHostListener,
Identifiers.syntheticHostProperty,
Identifiers.templateCreate,
Identifiers.twoWayProperty,
Identifiers.twoWayListener,
Identifiers.declareLet
]);
var MAX_CHAIN_LENGTH = 256;
function chain(job) {
for (const unit of job.units) {
chainOperationsInList(unit.create);
chainOperationsInList(unit.update);
}
}
function chainOperationsInList(opList) {
let chain2 = null;
for (const op of opList) {
if (op.kind !== OpKind.Statement || !(op.statement instanceof ExpressionStatement)) {
chain2 = null;
continue;
}
if (!(op.statement.expr instanceof InvokeFunctionExpr) || !(op.statement.expr.fn instanceof ExternalExpr)) {
chain2 = null;
continue;
}
const instruction = op.statement.expr.fn.value;
if (!CHAINABLE.has(instruction)) {
chain2 = null;
continue;
}
if (chain2 !== null && chain2.instruction === instruction && chain2.length < MAX_CHAIN_LENGTH) {
const expression = chain2.expression.callFn(op.statement.expr.args, op.statement.expr.sourceSpan, op.statement.expr.pure);
chain2.expression = expression;
chain2.op.statement = expression.toStmt();
chain2.length++;
OpList.remove(op);
} else {
chain2 = {
op,
instruction,
expression: op.statement.expr,
length: 1
};
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/collapse_singleton_interpolations.mjs
function collapseSingletonInterpolations(job) {
for (const unit of job.units) {
for (const op of unit.update) {
const eligibleOpKind = op.kind === OpKind.Attribute;
if (eligibleOpKind && op.expression instanceof Interpolation2 && op.expression.strings.length === 2 && op.expression.strings.every((s) => s === "")) {
op.expression = op.expression.expressions[0];
}
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/conditionals.mjs
function generateConditionalExpressions(job) {
for (const unit of job.units) {
for (const op of unit.ops()) {
if (op.kind !== OpKind.Conditional) {
continue;
}
let test;
const defaultCase = op.conditions.findIndex((cond) => cond.expr === null);
if (defaultCase >= 0) {
const slot = op.conditions.splice(defaultCase, 1)[0].targetSlot;
test = new SlotLiteralExpr(slot);
} else {
test = literal(-1);
}
let tmp = op.test == null ? null : new AssignTemporaryExpr(op.test, job.allocateXrefId());
for (let i = op.conditions.length - 1; i >= 0; i--) {
let conditionalCase = op.conditions[i];
if (conditionalCase.expr === null) {
continue;
}
if (tmp !== null) {
const useTmp = i === 0 ? tmp : new ReadTemporaryExpr(tmp.xref);
conditionalCase.expr = new BinaryOperatorExpr(BinaryOperator.Identical, useTmp, conditionalCase.expr);
} else if (conditionalCase.alias !== null) {
const caseExpressionTemporaryXref = job.allocateXrefId();
conditionalCase.expr = new AssignTemporaryExpr(conditionalCase.expr, caseExpressionTemporaryXref);
op.contextValue = new ReadTemporaryExpr(caseExpressionTemporaryXref);
}
test = new ConditionalExpr(conditionalCase.expr, new SlotLiteralExpr(conditionalCase.targetSlot), test);
}
op.processed = test;
op.conditions = [];
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/conversion.mjs
var BINARY_OPERATORS = /* @__PURE__ */ new Map([
["&&", BinaryOperator.And],
[">", BinaryOperator.Bigger],
[">=", BinaryOperator.BiggerEquals],
["|", BinaryOperator.BitwiseOr],
["&", BinaryOperator.BitwiseAnd],
["/", BinaryOperator.Divide],
["==", BinaryOperator.Equals],
["===", BinaryOperator.Identical],
["<", BinaryOperator.Lower],
["<=", BinaryOperator.LowerEquals],
["-", BinaryOperator.Minus],
["%", BinaryOperator.Modulo],
["*", BinaryOperator.Multiply],
["!=", BinaryOperator.NotEquals],
["!==", BinaryOperator.NotIdentical],
["??", BinaryOperator.NullishCoalesce],
["||", BinaryOperator.Or],
["+", BinaryOperator.Plus]
]);
function namespaceForKey(namespacePrefixKey) {
var _a2;
const NAMESPACES = /* @__PURE__ */ new Map([
["svg", Namespace.SVG],
["math", Namespace.Math]
]);
if (namespacePrefixKey === null) {
return Namespace.HTML;
}
return (_a2 = NAMESPACES.get(namespacePrefixKey)) != null ? _a2 : Namespace.HTML;
}
function keyForNamespace(namespace) {
const NAMESPACES = /* @__PURE__ */ new Map([
["svg", Namespace.SVG],
["math", Namespace.Math]
]);
for (const [k, n2] of NAMESPACES.entries()) {
if (n2 === namespace) {
return k;
}
}
return null;
}
function prefixWithNamespace(strippedTag, namespace) {
if (namespace === Namespace.HTML) {
return strippedTag;
}
return `:${keyForNamespace(namespace)}:${strippedTag}`;
}
function literalOrArrayLiteral(value) {
if (Array.isArray(value)) {
return literalArr(value.map(literalOrArrayLiteral));
}
return literal(value);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/const_collection.mjs
function collectElementConsts(job) {
const allElementAttributes = /* @__PURE__ */ new Map();
for (const unit of job.units) {
for (const op of unit.create) {
if (op.kind === OpKind.ExtractedAttribute) {
const attributes = allElementAttributes.get(op.target) || new ElementAttributes(job.compatibility);
allElementAttributes.set(op.target, attributes);
attributes.add(op.bindingKind, op.name, op.expression, op.namespace, op.trustedValueFn);
OpList.remove(op);
}
}
}
if (job instanceof ComponentCompilationJob) {
for (const unit of job.units) {
for (const op of unit.create) {
if (op.kind == OpKind.Projection) {
const attributes = allElementAttributes.get(op.xref);
if (attributes !== void 0) {
const attrArray = serializeAttributes(attributes);
if (attrArray.entries.length > 0) {
op.attributes = attrArray;
}
}
} else if (isElementOrContainerOp(op)) {
op.attributes = getConstIndex(job, allElementAttributes, op.xref);
if (op.kind === OpKind.RepeaterCreate && op.emptyView !== null) {
op.emptyAttributes = getConstIndex(job, allElementAttributes, op.emptyView);
}
}
}
}
} else if (job instanceof HostBindingCompilationJob) {
for (const [xref, attributes] of allElementAttributes.entries()) {
if (xref !== job.root.xref) {
throw new Error(`An attribute would be const collected into the host binding's template function, but is not associated with the root xref.`);
}
const attrArray = serializeAttributes(attributes);
if (attrArray.entries.length > 0) {
job.root.attributes = attrArray;
}
}
}
}
function getConstIndex(job, allElementAttributes, xref) {
const attributes = allElementAttributes.get(xref);
if (attributes !== void 0) {
const attrArray = serializeAttributes(attributes);
if (attrArray.entries.length > 0) {
return job.addConst(attrArray);
}
}
return null;
}
var FLYWEIGHT_ARRAY = Object.freeze([]);
var ElementAttributes = class {
get attributes() {
var _a2;
return (_a2 = this.byKind.get(BindingKind.Attribute)) != null ? _a2 : FLYWEIGHT_ARRAY;
}
get classes() {
var _a2;
return (_a2 = this.byKind.get(BindingKind.ClassName)) != null ? _a2 : FLYWEIGHT_ARRAY;
}
get styles() {
var _a2;
return (_a2 = this.byKind.get(BindingKind.StyleProperty)) != null ? _a2 : FLYWEIGHT_ARRAY;
}
get bindings() {
var _a2;
return (_a2 = this.propertyBindings) != null ? _a2 : FLYWEIGHT_ARRAY;
}
get template() {
var _a2;
return (_a2 = this.byKind.get(BindingKind.Template)) != null ? _a2 : FLYWEIGHT_ARRAY;
}
get i18n() {
var _a2;
return (_a2 = this.byKind.get(BindingKind.I18n)) != null ? _a2 : FLYWEIGHT_ARRAY;
}
constructor(compatibility) {
this.compatibility = compatibility;
this.known = /* @__PURE__ */ new Map();
this.byKind = /* @__PURE__ */ new Map();
this.propertyBindings = null;
this.projectAs = null;
}
isKnown(kind, name) {
var _a2;
const nameToValue = (_a2 = this.known.get(kind)) != null ? _a2 : /* @__PURE__ */ new Set();
this.known.set(kind, nameToValue);
if (nameToValue.has(name)) {
return true;
}
nameToValue.add(name);
return false;
}
add(kind, name, value, namespace, trustedValueFn) {
var _a2;
const allowDuplicates = this.compatibility === CompatibilityMode.TemplateDefinitionBuilder && (kind === BindingKind.Attribute || kind === BindingKind.ClassName || kind === BindingKind.StyleProperty);
if (!allowDuplicates && this.isKnown(kind, name)) {
return;
}
if (name === "ngProjectAs") {
if (value === null || !(value instanceof LiteralExpr) || value.value == null || typeof ((_a2 = value.value) == null ? void 0 : _a2.toString()) !== "string") {
throw Error("ngProjectAs must have a string literal value");
}
this.projectAs = value.value.toString();
}
const array = this.arrayFor(kind);
array.push(...getAttributeNameLiterals(namespace, name));
if (kind === BindingKind.Attribute || kind === BindingKind.StyleProperty) {
if (value === null) {
throw Error("Attribute, i18n attribute, & style element attributes must have a value");
}
if (trustedValueFn !== null) {
if (!isStringLiteral(value)) {
throw Error("AssertionError: extracted attribute value should be string literal");
}
array.push(taggedTemplate(trustedValueFn, new TemplateLiteral([new TemplateLiteralElement(value.value)], []), void 0, value.sourceSpan));
} else {
array.push(value);
}
}
}
arrayFor(kind) {
var _a2;
if (kind === BindingKind.Property || kind === BindingKind.TwoWayProperty) {
(_a2 = this.propertyBindings) != null ? _a2 : this.propertyBindings = [];
return this.propertyBindings;
} else {
if (!this.byKind.has(kind)) {
this.byKind.set(kind, []);
}
return this.byKind.get(kind);
}
}
};
function getAttributeNameLiterals(namespace, name) {
const nameLiteral = literal(name);
if (namespace) {
return [literal(0), literal(namespace), nameLiteral];
}
return [nameLiteral];
}
function serializeAttributes({ attributes, bindings, classes, i18n: i18n2, projectAs, styles, template: template2 }) {
const attrArray = [...attributes];
if (projectAs !== null) {
const parsedR3Selector = parseSelectorToR3Selector(projectAs)[0];
attrArray.push(literal(5), literalOrArrayLiteral(parsedR3Selector));
}
if (classes.length > 0) {
attrArray.push(literal(1), ...classes);
}
if (styles.length > 0) {
attrArray.push(literal(2), ...styles);
}
if (bindings.length > 0) {
attrArray.push(literal(3), ...bindings);
}
if (template2.length > 0) {
attrArray.push(literal(4), ...template2);
}
if (i18n2.length > 0) {
attrArray.push(literal(6), ...i18n2);
}
return literalArr(attrArray);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/convert_i18n_bindings.mjs
function convertI18nBindings(job) {
const i18nAttributesByElem = /* @__PURE__ */ new Map();
for (const unit of job.units) {
for (const op of unit.create) {
if (op.kind === OpKind.I18nAttributes) {
i18nAttributesByElem.set(op.target, op);
}
}
for (const op of unit.update) {
switch (op.kind) {
case OpKind.Property:
case OpKind.Attribute:
if (op.i18nContext === null) {
continue;
}
if (!(op.expression instanceof Interpolation2)) {
continue;
}
const i18nAttributesForElem = i18nAttributesByElem.get(op.target);
if (i18nAttributesForElem === void 0) {
throw new Error("AssertionError: An i18n attribute binding instruction requires the owning element to have an I18nAttributes create instruction");
}
if (i18nAttributesForElem.target !== op.target) {
throw new Error("AssertionError: Expected i18nAttributes target element to match binding target element");
}
const ops = [];
for (let i = 0; i < op.expression.expressions.length; i++) {
const expr = op.expression.expressions[i];
if (op.expression.i18nPlaceholders.length !== op.expression.expressions.length) {
throw new Error(`AssertionError: An i18n attribute binding instruction requires the same number of expressions and placeholders, but found ${op.expression.i18nPlaceholders.length} placeholders and ${op.expression.expressions.length} expressions`);
}
ops.push(createI18nExpressionOp(op.i18nContext, i18nAttributesForElem.target, i18nAttributesForElem.xref, i18nAttributesForElem.handle, expr, null, op.expression.i18nPlaceholders[i], I18nParamResolutionTime.Creation, I18nExpressionFor.I18nAttribute, op.name, op.sourceSpan));
}
OpList.replaceWithMany(op, ops);
break;
}
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/resolve_defer_deps_fns.mjs
function resolveDeferDepsFns(job) {
var _a2;
for (const unit of job.units) {
for (const op of unit.create) {
if (op.kind === OpKind.Defer) {
if (op.resolverFn !== null) {
continue;
}
if (op.ownResolverFn !== null) {
if (op.handle.slot === null) {
throw new Error("AssertionError: slot must be assigned before extracting defer deps functions");
}
const fullPathName = (_a2 = unit.fnName) == null ? void 0 : _a2.replace("_Template", "");
op.resolverFn = job.pool.getSharedFunctionReference(
op.ownResolverFn,
`${fullPathName}_Defer_${op.handle.slot}_DepsFn`,
false
);
}
}
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/create_i18n_contexts.mjs
function createI18nContexts(job) {
const attrContextByMessage = /* @__PURE__ */ new Map();
for (const unit of job.units) {
for (const op of unit.ops()) {
switch (op.kind) {
case OpKind.Binding:
case OpKind.Property:
case OpKind.Attribute:
case OpKind.ExtractedAttribute:
if (op.i18nMessage === null) {
continue;
}
if (!attrContextByMessage.has(op.i18nMessage)) {
const i18nContext = createI18nContextOp(I18nContextKind.Attr, job.allocateXrefId(), null, op.i18nMessage, null);
unit.create.push(i18nContext);
attrContextByMessage.set(op.i18nMessage, i18nContext.xref);
}
op.i18nContext = attrContextByMessage.get(op.i18nMessage);
break;
}
}
}
const blockContextByI18nBlock = /* @__PURE__ */ new Map();
for (const unit of job.units) {
for (const op of unit.create) {
switch (op.kind) {
case OpKind.I18nStart:
if (op.xref === op.root) {
const contextOp = createI18nContextOp(I18nContextKind.RootI18n, job.allocateXrefId(), op.xref, op.message, null);
unit.create.push(contextOp);
op.context = contextOp.xref;
blockContextByI18nBlock.set(op.xref, contextOp);
}
break;
}
}
}
for (const unit of job.units) {
for (const op of unit.create) {
if (op.kind === OpKind.I18nStart && op.xref !== op.root) {
const rootContext = blockContextByI18nBlock.get(op.root);
if (rootContext === void 0) {
throw Error("AssertionError: Root i18n block i18n context should have been created.");
}
op.context = rootContext.xref;
blockContextByI18nBlock.set(op.xref, rootContext);
}
}
}
let currentI18nOp = null;
for (const unit of job.units) {
for (const op of unit.create) {
switch (op.kind) {
case OpKind.I18nStart:
currentI18nOp = op;
break;
case OpKind.I18nEnd:
currentI18nOp = null;
break;
case OpKind.IcuStart:
if (currentI18nOp === null) {
throw Error("AssertionError: Unexpected ICU outside of an i18n block.");
}
if (op.message.id !== currentI18nOp.message.id) {
const contextOp = createI18nContextOp(I18nContextKind.Icu, job.allocateXrefId(), currentI18nOp.root, op.message, null);
unit.create.push(contextOp);
op.context = contextOp.xref;
} else {
op.context = currentI18nOp.context;
blockContextByI18nBlock.get(currentI18nOp.xref).contextKind = I18nContextKind.Icu;
}
break;
}
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/deduplicate_text_bindings.mjs
function deduplicateTextBindings(job) {
const seen = /* @__PURE__ */ new Map();
for (const unit of job.units) {
for (const op of unit.update.reversed()) {
if (op.kind === OpKind.Binding && op.isTextAttribute) {
const seenForElement = seen.get(op.target) || /* @__PURE__ */ new Set();
if (seenForElement.has(op.name)) {
if (job.compatibility === CompatibilityMode.TemplateDefinitionBuilder) {
if (op.name === "style" || op.name === "class") {
OpList.remove(op);
}
} else {
}
}
seenForElement.add(op.name);
seen.set(op.target, seenForElement);
}
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/defer_configs.mjs
function configureDeferInstructions(job) {
for (const unit of job.units) {
for (const op of unit.create) {
if (op.kind !== OpKind.Defer) {
continue;
}
if (op.placeholderMinimumTime !== null) {
op.placeholderConfig = new ConstCollectedExpr(literalOrArrayLiteral([op.placeholderMinimumTime]));
}
if (op.loadingMinimumTime !== null || op.loadingAfterTime !== null) {
op.loadingConfig = new ConstCollectedExpr(literalOrArrayLiteral([op.loadingMinimumTime, op.loadingAfterTime]));
}
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/defer_resolve_targets.mjs
function resolveDeferTargetNames(job) {
const scopes = /* @__PURE__ */ new Map();
function getScopeForView2(view) {
if (scopes.has(view.xref)) {
return scopes.get(view.xref);
}
const scope = new Scope();
for (const op of view.create) {
if (!isElementOrContainerOp(op) || op.localRefs === null) {
continue;
}
if (!Array.isArray(op.localRefs)) {
throw new Error("LocalRefs were already processed, but were needed to resolve defer targets.");
}
for (const ref of op.localRefs) {
if (ref.target !== "") {
continue;
}
scope.targets.set(ref.name, { xref: op.xref, slot: op.handle });
}
}
scopes.set(view.xref, scope);
return scope;
}
function resolveTrigger(deferOwnerView, op, placeholderView) {
switch (op.trigger.kind) {
case DeferTriggerKind.Idle:
case DeferTriggerKind.Immediate:
case DeferTriggerKind.Timer:
return;
case DeferTriggerKind.Hover:
case DeferTriggerKind.Interaction:
case DeferTriggerKind.Viewport:
if (op.trigger.targetName === null) {
if (placeholderView === null) {
throw new Error("defer on trigger with no target name must have a placeholder block");
}
const placeholder = job.views.get(placeholderView);
if (placeholder == void 0) {
throw new Error("AssertionError: could not find placeholder view for defer on trigger");
}
for (const placeholderOp of placeholder.create) {
if (hasConsumesSlotTrait(placeholderOp) && (isElementOrContainerOp(placeholderOp) || placeholderOp.kind === OpKind.Projection)) {
op.trigger.targetXref = placeholderOp.xref;
op.trigger.targetView = placeholderView;
op.trigger.targetSlotViewSteps = -1;
op.trigger.targetSlot = placeholderOp.handle;
return;
}
}
return;
}
let view = placeholderView !== null ? job.views.get(placeholderView) : deferOwnerView;
let step = placeholderView !== null ? -1 : 0;
while (view !== null) {
const scope = getScopeForView2(view);
if (scope.targets.has(op.trigger.targetName)) {
const { xref, slot } = scope.targets.get(op.trigger.targetName);
op.trigger.targetXref = xref;
op.trigger.targetView = view.xref;
op.trigger.targetSlotViewSteps = step;
op.trigger.targetSlot = slot;
return;
}
view = view.parent !== null ? job.views.get(view.parent) : null;
step++;
}
break;
default:
throw new Error(`Trigger kind ${op.trigger.kind} not handled`);
}
}
for (const unit of job.units) {
const defers = /* @__PURE__ */ new Map();
for (const op of unit.create) {
switch (op.kind) {
case OpKind.Defer:
defers.set(op.xref, op);
break;
case OpKind.DeferOn:
const deferOp = defers.get(op.defer);
resolveTrigger(unit, op, deferOp.placeholderView);
break;
}
}
}
}
var Scope = class {
constructor() {
this.targets = /* @__PURE__ */ new Map();
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/empty_elements.mjs
var REPLACEMENTS = /* @__PURE__ */ new Map([
[OpKind.ElementEnd, [OpKind.ElementStart, OpKind.Element]],
[OpKind.ContainerEnd, [OpKind.ContainerStart, OpKind.Container]],
[OpKind.I18nEnd, [OpKind.I18nStart, OpKind.I18n]]
]);
var IGNORED_OP_KINDS = /* @__PURE__ */ new Set([OpKind.Pipe]);
function collapseEmptyInstructions(job) {
for (const unit of job.units) {
for (const op of unit.create) {
const opReplacements = REPLACEMENTS.get(op.kind);
if (opReplacements === void 0) {
continue;
}
const [startKind, mergedKind] = opReplacements;
let prevOp = op.prev;
while (prevOp !== null && IGNORED_OP_KINDS.has(prevOp.kind)) {
prevOp = prevOp.prev;
}
if (prevOp !== null && prevOp.kind === startKind) {
prevOp.kind = mergedKind;
OpList.remove(op);
}
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/expand_safe_reads.mjs
function expandSafeReads(job) {
for (const unit of job.units) {
for (const op of unit.ops()) {
transformExpressionsInOp(op, (e) => safeTransform(e, { job }), VisitorContextFlag.None);
transformExpressionsInOp(op, ternaryTransform, VisitorContextFlag.None);
}
}
}
var requiresTemporary = [
InvokeFunctionExpr,
LiteralArrayExpr,
LiteralMapExpr,
SafeInvokeFunctionExpr,
PipeBindingExpr
].map((e) => e.constructor.name);
function needsTemporaryInSafeAccess(e) {
if (e instanceof UnaryOperatorExpr) {
return needsTemporaryInSafeAccess(e.expr);
} else if (e instanceof BinaryOperatorExpr) {
return needsTemporaryInSafeAccess(e.lhs) || needsTemporaryInSafeAccess(e.rhs);
} else if (e instanceof ConditionalExpr) {
if (e.falseCase && needsTemporaryInSafeAccess(e.falseCase))
return true;
return needsTemporaryInSafeAccess(e.condition) || needsTemporaryInSafeAccess(e.trueCase);
} else if (e instanceof NotExpr) {
return needsTemporaryInSafeAccess(e.condition);
} else if (e instanceof AssignTemporaryExpr) {
return needsTemporaryInSafeAccess(e.expr);
} else if (e instanceof ReadPropExpr) {
return needsTemporaryInSafeAccess(e.receiver);
} else if (e instanceof ReadKeyExpr) {
return needsTemporaryInSafeAccess(e.receiver) || needsTemporaryInSafeAccess(e.index);
}
return e instanceof InvokeFunctionExpr || e instanceof LiteralArrayExpr || e instanceof LiteralMapExpr || e instanceof SafeInvokeFunctionExpr || e instanceof PipeBindingExpr;
}
function temporariesIn(e) {
const temporaries = /* @__PURE__ */ new Set();
transformExpressionsInExpression(e, (e2) => {
if (e2 instanceof AssignTemporaryExpr) {
temporaries.add(e2.xref);
}
return e2;
}, VisitorContextFlag.None);
return temporaries;
}
function eliminateTemporaryAssignments(e, tmps, ctx) {
transformExpressionsInExpression(e, (e2) => {
if (e2 instanceof AssignTemporaryExpr && tmps.has(e2.xref)) {
const read = new ReadTemporaryExpr(e2.xref);
return ctx.job.compatibility === CompatibilityMode.TemplateDefinitionBuilder ? new AssignTemporaryExpr(read, read.xref) : read;
}
return e2;
}, VisitorContextFlag.None);
return e;
}
function safeTernaryWithTemporary(guard, body, ctx) {
let result;
if (needsTemporaryInSafeAccess(guard)) {
const xref = ctx.job.allocateXrefId();
result = [new AssignTemporaryExpr(guard, xref), new ReadTemporaryExpr(xref)];
} else {
result = [guard, guard.clone()];
eliminateTemporaryAssignments(result[1], temporariesIn(result[0]), ctx);
}
return new SafeTernaryExpr(result[0], body(result[1]));
}
function isSafeAccessExpression(e) {
return e instanceof SafePropertyReadExpr || e instanceof SafeKeyedReadExpr || e instanceof SafeInvokeFunctionExpr;
}
function isUnsafeAccessExpression(e) {
return e instanceof ReadPropExpr || e instanceof ReadKeyExpr || e instanceof InvokeFunctionExpr;
}
function isAccessExpression(e) {
return isSafeAccessExpression(e) || isUnsafeAccessExpression(e);
}
function deepestSafeTernary(e) {
if (isAccessExpression(e) && e.receiver instanceof SafeTernaryExpr) {
let st = e.receiver;
while (st.expr instanceof SafeTernaryExpr) {
st = st.expr;
}
return st;
}
return null;
}
function safeTransform(e, ctx) {
if (!isAccessExpression(e)) {
return e;
}
const dst = deepestSafeTernary(e);
if (dst) {
if (e instanceof InvokeFunctionExpr) {
dst.expr = dst.expr.callFn(e.args);
return e.receiver;
}
if (e instanceof ReadPropExpr) {
dst.expr = dst.expr.prop(e.name);
return e.receiver;
}
if (e instanceof ReadKeyExpr) {
dst.expr = dst.expr.key(e.index);
return e.receiver;
}
if (e instanceof SafeInvokeFunctionExpr) {
dst.expr = safeTernaryWithTemporary(dst.expr, (r) => r.callFn(e.args), ctx);
return e.receiver;
}
if (e instanceof SafePropertyReadExpr) {
dst.expr = safeTernaryWithTemporary(dst.expr, (r) => r.prop(e.name), ctx);
return e.receiver;
}
if (e instanceof SafeKeyedReadExpr) {
dst.expr = safeTernaryWithTemporary(dst.expr, (r) => r.key(e.index), ctx);
return e.receiver;
}
} else {
if (e instanceof SafeInvokeFunctionExpr) {
return safeTernaryWithTemporary(e.receiver, (r) => r.callFn(e.args), ctx);
}
if (e instanceof SafePropertyReadExpr) {
return safeTernaryWithTemporary(e.receiver, (r) => r.prop(e.name), ctx);
}
if (e instanceof SafeKeyedReadExpr) {
return safeTernaryWithTemporary(e.receiver, (r) => r.key(e.index), ctx);
}
}
return e;
}
function ternaryTransform(e) {
if (!(e instanceof SafeTernaryExpr)) {
return e;
}
return new ConditionalExpr(new BinaryOperatorExpr(BinaryOperator.Equals, e.guard, NULL_EXPR), NULL_EXPR, e.expr);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/extract_i18n_messages.mjs
var ESCAPE = "\uFFFD";
var ELEMENT_MARKER = "#";
var TEMPLATE_MARKER = "*";
var TAG_CLOSE_MARKER = "/";
var CONTEXT_MARKER = ":";
var LIST_START_MARKER = "[";
var LIST_END_MARKER = "]";
var LIST_DELIMITER = "|";
function extractI18nMessages(job) {
const i18nMessagesByContext = /* @__PURE__ */ new Map();
const i18nBlocks = /* @__PURE__ */ new Map();
const i18nContexts = /* @__PURE__ */ new Map();
for (const unit of job.units) {
for (const op of unit.create) {
switch (op.kind) {
case OpKind.I18nContext:
const i18nMessageOp = createI18nMessage(job, op);
unit.create.push(i18nMessageOp);
i18nMessagesByContext.set(op.xref, i18nMessageOp);
i18nContexts.set(op.xref, op);
break;
case OpKind.I18nStart:
i18nBlocks.set(op.xref, op);
break;
}
}
}
let currentIcu = null;
for (const unit of job.units) {
for (const op of unit.create) {
switch (op.kind) {
case OpKind.IcuStart:
currentIcu = op;
OpList.remove(op);
const icuContext = i18nContexts.get(op.context);
if (icuContext.contextKind !== I18nContextKind.Icu) {
continue;
}
const i18nBlock = i18nBlocks.get(icuContext.i18nBlock);
if (i18nBlock.context === icuContext.xref) {
continue;
}
const rootI18nBlock = i18nBlocks.get(i18nBlock.root);
const rootMessage = i18nMessagesByContext.get(rootI18nBlock.context);
if (rootMessage === void 0) {
throw Error("AssertionError: ICU sub-message should belong to a root message.");
}
const subMessage = i18nMessagesByContext.get(icuContext.xref);
subMessage.messagePlaceholder = op.messagePlaceholder;
rootMessage.subMessages.push(subMessage.xref);
break;
case OpKind.IcuEnd:
currentIcu = null;
OpList.remove(op);
break;
case OpKind.IcuPlaceholder:
if (currentIcu === null || currentIcu.context == null) {
throw Error("AssertionError: Unexpected ICU placeholder outside of i18n context");
}
const msg = i18nMessagesByContext.get(currentIcu.context);
msg.postprocessingParams.set(op.name, literal(formatIcuPlaceholder(op)));
OpList.remove(op);
break;
}
}
}
}
function createI18nMessage(job, context, messagePlaceholder) {
let formattedParams = formatParams(context.params);
const formattedPostprocessingParams = formatParams(context.postprocessingParams);
let needsPostprocessing = [...context.params.values()].some((v) => v.length > 1);
return createI18nMessageOp(job.allocateXrefId(), context.xref, context.i18nBlock, context.message, messagePlaceholder != null ? messagePlaceholder : null, formattedParams, formattedPostprocessingParams, needsPostprocessing);
}
function formatIcuPlaceholder(op) {
if (op.strings.length !== op.expressionPlaceholders.length + 1) {
throw Error(`AssertionError: Invalid ICU placeholder with ${op.strings.length} strings and ${op.expressionPlaceholders.length} expressions`);
}
const values = op.expressionPlaceholders.map(formatValue);
return op.strings.flatMap((str, i) => [str, values[i] || ""]).join("");
}
function formatParams(params) {
const formattedParams = /* @__PURE__ */ new Map();
for (const [placeholder, placeholderValues] of params) {
const serializedValues = formatParamValues(placeholderValues);
if (serializedValues !== null) {
formattedParams.set(placeholder, literal(serializedValues));
}
}
return formattedParams;
}
function formatParamValues(values) {
if (values.length === 0) {
return null;
}
const serializedValues = values.map((value) => formatValue(value));
return serializedValues.length === 1 ? serializedValues[0] : `${LIST_START_MARKER}${serializedValues.join(LIST_DELIMITER)}${LIST_END_MARKER}`;
}
function formatValue(value) {
if (value.flags & I18nParamValueFlags.ElementTag && value.flags & I18nParamValueFlags.TemplateTag) {
if (typeof value.value !== "object") {
throw Error("AssertionError: Expected i18n param value to have an element and template slot");
}
const elementValue = formatValue(__spreadProps(__spreadValues({}, value), {
value: value.value.element,
flags: value.flags & ~I18nParamValueFlags.TemplateTag
}));
const templateValue = formatValue(__spreadProps(__spreadValues({}, value), {
value: value.value.template,
flags: value.flags & ~I18nParamValueFlags.ElementTag
}));
if (value.flags & I18nParamValueFlags.OpenTag && value.flags & I18nParamValueFlags.CloseTag) {
return `${templateValue}${elementValue}${templateValue}`;
}
return value.flags & I18nParamValueFlags.CloseTag ? `${elementValue}${templateValue}` : `${templateValue}${elementValue}`;
}
if (value.flags & I18nParamValueFlags.OpenTag && value.flags & I18nParamValueFlags.CloseTag) {
return `${formatValue(__spreadProps(__spreadValues({}, value), { flags: value.flags & ~I18nParamValueFlags.CloseTag }))}${formatValue(__spreadProps(__spreadValues({}, value), { flags: value.flags & ~I18nParamValueFlags.OpenTag }))}`;
}
if (value.flags === I18nParamValueFlags.None) {
return `${value.value}`;
}
let tagMarker = "";
let closeMarker = "";
if (value.flags & I18nParamValueFlags.ElementTag) {
tagMarker = ELEMENT_MARKER;
} else if (value.flags & I18nParamValueFlags.TemplateTag) {
tagMarker = TEMPLATE_MARKER;
}
if (tagMarker !== "") {
closeMarker = value.flags & I18nParamValueFlags.CloseTag ? TAG_CLOSE_MARKER : "";
}
const context = value.subTemplateIndex === null ? "" : `${CONTEXT_MARKER}${value.subTemplateIndex}`;
return `${ESCAPE}${closeMarker}${tagMarker}${value.value}${context}${ESCAPE}`;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/generate_advance.mjs
function generateAdvance(job) {
for (const unit of job.units) {
const slotMap = /* @__PURE__ */ new Map();
for (const op of unit.create) {
if (!hasConsumesSlotTrait(op)) {
continue;
} else if (op.handle.slot === null) {
throw new Error(`AssertionError: expected slots to have been allocated before generating advance() calls`);
}
slotMap.set(op.xref, op.handle.slot);
}
let slotContext = 0;
for (const op of unit.update) {
let consumer = null;
if (hasDependsOnSlotContextTrait(op)) {
consumer = op;
} else {
visitExpressionsInOp(op, (expr) => {
if (consumer === null && hasDependsOnSlotContextTrait(expr)) {
consumer = expr;
}
});
}
if (consumer === null) {
continue;
}
if (!slotMap.has(consumer.target)) {
throw new Error(`AssertionError: reference to unknown slot for target ${consumer.target}`);
}
const slot = slotMap.get(consumer.target);
if (slotContext !== slot) {
const delta = slot - slotContext;
if (delta < 0) {
throw new Error(`AssertionError: slot counter should never need to move backwards`);
}
OpList.insertBefore(createAdvanceOp(delta, consumer.sourceSpan), op);
slotContext = slot;
}
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/generate_projection_def.mjs
function generateProjectionDefs(job) {
const share = job.compatibility === CompatibilityMode.TemplateDefinitionBuilder;
const selectors = [];
let projectionSlotIndex = 0;
for (const unit of job.units) {
for (const op of unit.create) {
if (op.kind === OpKind.Projection) {
selectors.push(op.selector);
op.projectionSlotIndex = projectionSlotIndex++;
}
}
}
if (selectors.length > 0) {
let defExpr = null;
if (selectors.length > 1 || selectors[0] !== "*") {
const def = selectors.map((s) => s === "*" ? s : parseSelectorToR3Selector(s));
defExpr = job.pool.getConstLiteral(literalOrArrayLiteral(def), share);
}
job.contentSelectors = job.pool.getConstLiteral(literalOrArrayLiteral(selectors), share);
job.root.create.prepend([createProjectionDefOp(defExpr)]);
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/generate_variables.mjs
function generateVariables(job) {
recursivelyProcessView(job.root, null);
}
function recursivelyProcessView(view, parentScope) {
const scope = getScopeForView(view, parentScope);
for (const op of view.create) {
switch (op.kind) {
case OpKind.Template:
recursivelyProcessView(view.job.views.get(op.xref), scope);
break;
case OpKind.Projection:
if (op.fallbackView !== null) {
recursivelyProcessView(view.job.views.get(op.fallbackView), scope);
}
break;
case OpKind.RepeaterCreate:
recursivelyProcessView(view.job.views.get(op.xref), scope);
if (op.emptyView) {
recursivelyProcessView(view.job.views.get(op.emptyView), scope);
}
break;
case OpKind.Listener:
case OpKind.TwoWayListener:
op.handlerOps.prepend(generateVariablesInScopeForView(view, scope, true));
break;
}
}
view.update.prepend(generateVariablesInScopeForView(view, scope, false));
}
function getScopeForView(view, parent) {
const scope = {
view: view.xref,
viewContextVariable: {
kind: SemanticVariableKind.Context,
name: null,
view: view.xref
},
contextVariables: /* @__PURE__ */ new Map(),
aliases: view.aliases,
references: [],
letDeclarations: [],
parent
};
for (const identifier of view.contextVariables.keys()) {
scope.contextVariables.set(identifier, {
kind: SemanticVariableKind.Identifier,
name: null,
identifier,
local: false
});
}
for (const op of view.create) {
switch (op.kind) {
case OpKind.ElementStart:
case OpKind.Template:
if (!Array.isArray(op.localRefs)) {
throw new Error(`AssertionError: expected localRefs to be an array`);
}
for (let offset = 0; offset < op.localRefs.length; offset++) {
scope.references.push({
name: op.localRefs[offset].name,
targetId: op.xref,
targetSlot: op.handle,
offset,
variable: {
kind: SemanticVariableKind.Identifier,
name: null,
identifier: op.localRefs[offset].name,
local: false
}
});
}
break;
case OpKind.DeclareLet:
scope.letDeclarations.push({
targetId: op.xref,
targetSlot: op.handle,
variable: {
kind: SemanticVariableKind.Identifier,
name: null,
identifier: op.declaredName,
local: false
}
});
break;
}
}
return scope;
}
function generateVariablesInScopeForView(view, scope, isListener) {
const newOps = [];
if (scope.view !== view.xref) {
newOps.push(createVariableOp(view.job.allocateXrefId(), scope.viewContextVariable, new NextContextExpr(), VariableFlags.None));
}
const scopeView = view.job.views.get(scope.view);
for (const [name, value] of scopeView.contextVariables) {
const context = new ContextExpr(scope.view);
const variable2 = value === CTX_REF ? context : new ReadPropExpr(context, value);
newOps.push(createVariableOp(view.job.allocateXrefId(), scope.contextVariables.get(name), variable2, VariableFlags.None));
}
for (const alias of scopeView.aliases) {
newOps.push(createVariableOp(view.job.allocateXrefId(), alias, alias.expression.clone(), VariableFlags.AlwaysInline));
}
for (const ref of scope.references) {
newOps.push(createVariableOp(view.job.allocateXrefId(), ref.variable, new ReferenceExpr(ref.targetId, ref.targetSlot, ref.offset), VariableFlags.None));
}
if (scope.view !== view.xref || isListener) {
for (const decl of scope.letDeclarations) {
newOps.push(createVariableOp(view.job.allocateXrefId(), decl.variable, new ContextLetReferenceExpr(decl.targetId, decl.targetSlot), VariableFlags.None));
}
}
if (scope.parent !== null) {
newOps.push(...generateVariablesInScopeForView(view, scope.parent, false));
}
return newOps;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/has_const_expression_collection.mjs
function collectConstExpressions(job) {
for (const unit of job.units) {
for (const op of unit.ops()) {
transformExpressionsInOp(op, (expr) => {
if (!(expr instanceof ConstCollectedExpr)) {
return expr;
}
return literal(job.addConst(expr.expr));
}, VisitorContextFlag.None);
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/host_style_property_parsing.mjs
var STYLE_DOT = "style.";
var CLASS_DOT = "class.";
var STYLE_BANG = "style!";
var CLASS_BANG = "class!";
var BANG_IMPORTANT = "!important";
function parseHostStyleProperties(job) {
for (const op of job.root.update) {
if (!(op.kind === OpKind.Binding && op.bindingKind === BindingKind.Property)) {
continue;
}
if (op.name.endsWith(BANG_IMPORTANT)) {
op.name = op.name.substring(0, op.name.length - BANG_IMPORTANT.length);
}
if (op.name.startsWith(STYLE_DOT)) {
op.bindingKind = BindingKind.StyleProperty;
op.name = op.name.substring(STYLE_DOT.length);
if (!isCssCustomProperty(op.name)) {
op.name = hyphenate(op.name);
}
const { property: property2, suffix } = parseProperty(op.name);
op.name = property2;
op.unit = suffix;
} else if (op.name.startsWith(STYLE_BANG)) {
op.bindingKind = BindingKind.StyleProperty;
op.name = "style";
} else if (op.name.startsWith(CLASS_DOT)) {
op.bindingKind = BindingKind.ClassName;
op.name = parseProperty(op.name.substring(CLASS_DOT.length)).property;
} else if (op.name.startsWith(CLASS_BANG)) {
op.bindingKind = BindingKind.ClassName;
op.name = parseProperty(op.name.substring(CLASS_BANG.length)).property;
}
}
}
function isCssCustomProperty(name) {
return name.startsWith("--");
}
function hyphenate(value) {
return value.replace(/[a-z][A-Z]/g, (v) => {
return v.charAt(0) + "-" + v.charAt(1);
}).toLowerCase();
}
function parseProperty(name) {
const overrideIndex = name.indexOf("!important");
if (overrideIndex !== -1) {
name = overrideIndex > 0 ? name.substring(0, overrideIndex) : "";
}
let suffix = null;
let property2 = name;
const unitIndex = name.lastIndexOf(".");
if (unitIndex > 0) {
suffix = name.slice(unitIndex + 1);
property2 = name.substring(0, unitIndex);
}
return { property: property2, suffix };
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/output/map_util.mjs
function mapLiteral(obj, quoted = false) {
return literalMap(Object.keys(obj).map((key) => ({
key,
quoted,
value: obj[key]
})));
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/view/i18n/icu_serializer.mjs
var IcuSerializerVisitor = class {
visitText(text2) {
return text2.value;
}
visitContainer(container) {
return container.children.map((child) => child.visit(this)).join("");
}
visitIcu(icu) {
const strCases = Object.keys(icu.cases).map((k) => `${k} {${icu.cases[k].visit(this)}}`);
const result = `{${icu.expressionPlaceholder}, ${icu.type}, ${strCases.join(" ")}}`;
return result;
}
visitTagPlaceholder(ph) {
return ph.isVoid ? this.formatPh(ph.startName) : `${this.formatPh(ph.startName)}${ph.children.map((child) => child.visit(this)).join("")}${this.formatPh(ph.closeName)}`;
}
visitPlaceholder(ph) {
return this.formatPh(ph.name);
}
visitBlockPlaceholder(ph) {
return `${this.formatPh(ph.startName)}${ph.children.map((child) => child.visit(this)).join("")}${this.formatPh(ph.closeName)}`;
}
visitIcuPlaceholder(ph, context) {
return this.formatPh(ph.name);
}
formatPh(value) {
return `{${formatI18nPlaceholderName(value, false)}}`;
}
};
var serializer = new IcuSerializerVisitor();
function serializeIcuNode(icu) {
return icu.visit(serializer);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/ml_parser/ast.mjs
var NodeWithI18n = class {
constructor(sourceSpan, i18n2) {
this.sourceSpan = sourceSpan;
this.i18n = i18n2;
}
};
var Text4 = class extends NodeWithI18n {
constructor(value, sourceSpan, tokens, i18n2) {
super(sourceSpan, i18n2);
this.value = value;
this.tokens = tokens;
}
visit(visitor, context) {
return visitor.visitText(this, context);
}
};
var Expansion = class extends NodeWithI18n {
constructor(switchValue, type, cases, sourceSpan, switchValueSourceSpan, i18n2) {
super(sourceSpan, i18n2);
this.switchValue = switchValue;
this.type = type;
this.cases = cases;
this.switchValueSourceSpan = switchValueSourceSpan;
}
visit(visitor, context) {
return visitor.visitExpansion(this, context);
}
};
var ExpansionCase = class {
constructor(value, expression, sourceSpan, valueSourceSpan, expSourceSpan) {
this.value = value;
this.expression = expression;
this.sourceSpan = sourceSpan;
this.valueSourceSpan = valueSourceSpan;
this.expSourceSpan = expSourceSpan;
}
visit(visitor, context) {
return visitor.visitExpansionCase(this, context);
}
};
var Attribute = class extends NodeWithI18n {
constructor(name, value, sourceSpan, keySpan, valueSpan, valueTokens, i18n2) {
super(sourceSpan, i18n2);
this.name = name;
this.value = value;
this.keySpan = keySpan;
this.valueSpan = valueSpan;
this.valueTokens = valueTokens;
}
visit(visitor, context) {
return visitor.visitAttribute(this, context);
}
};
var Element2 = class extends NodeWithI18n {
constructor(name, attrs, children, sourceSpan, startSourceSpan, endSourceSpan = null, i18n2) {
super(sourceSpan, i18n2);
this.name = name;
this.attrs = attrs;
this.children = children;
this.startSourceSpan = startSourceSpan;
this.endSourceSpan = endSourceSpan;
}
visit(visitor, context) {
return visitor.visitElement(this, context);
}
};
var Comment2 = class {
constructor(value, sourceSpan) {
this.value = value;
this.sourceSpan = sourceSpan;
}
visit(visitor, context) {
return visitor.visitComment(this, context);
}
};
var Block = class extends NodeWithI18n {
constructor(name, parameters, children, sourceSpan, nameSpan, startSourceSpan, endSourceSpan = null, i18n2) {
super(sourceSpan, i18n2);
this.name = name;
this.parameters = parameters;
this.children = children;
this.nameSpan = nameSpan;
this.startSourceSpan = startSourceSpan;
this.endSourceSpan = endSourceSpan;
}
visit(visitor, context) {
return visitor.visitBlock(this, context);
}
};
var BlockParameter = class {
constructor(expression, sourceSpan) {
this.expression = expression;
this.sourceSpan = sourceSpan;
}
visit(visitor, context) {
return visitor.visitBlockParameter(this, context);
}
};
var LetDeclaration2 = class {
constructor(name, value, sourceSpan, nameSpan, valueSpan) {
this.name = name;
this.value = value;
this.sourceSpan = sourceSpan;
this.nameSpan = nameSpan;
this.valueSpan = valueSpan;
}
visit(visitor, context) {
return visitor.visitLetDeclaration(this, context);
}
};
function visitAll2(visitor, nodes, context = null) {
const result = [];
const visit2 = visitor.visit ? (ast) => visitor.visit(ast, context) || ast.visit(visitor, context) : (ast) => ast.visit(visitor, context);
nodes.forEach((ast) => {
const astResult = visit2(ast);
if (astResult) {
result.push(astResult);
}
});
return result;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/ml_parser/entities.mjs
var NAMED_ENTITIES = {
"AElig": "\xC6",
"AMP": "&",
"amp": "&",
"Aacute": "\xC1",
"Abreve": "\u0102",
"Acirc": "\xC2",
"Acy": "\u0410",
"Afr": "\u{1D504}",
"Agrave": "\xC0",
"Alpha": "\u0391",
"Amacr": "\u0100",
"And": "\u2A53",
"Aogon": "\u0104",
"Aopf": "\u{1D538}",
"ApplyFunction": "\u2061",
"af": "\u2061",
"Aring": "\xC5",
"angst": "\xC5",
"Ascr": "\u{1D49C}",
"Assign": "\u2254",
"colone": "\u2254",
"coloneq": "\u2254",
"Atilde": "\xC3",
"Auml": "\xC4",
"Backslash": "\u2216",
"setminus": "\u2216",
"setmn": "\u2216",
"smallsetminus": "\u2216",
"ssetmn": "\u2216",
"Barv": "\u2AE7",
"Barwed": "\u2306",
"doublebarwedge": "\u2306",
"Bcy": "\u0411",
"Because": "\u2235",
"becaus": "\u2235",
"because": "\u2235",
"Bernoullis": "\u212C",
"Bscr": "\u212C",
"bernou": "\u212C",
"Beta": "\u0392",
"Bfr": "\u{1D505}",
"Bopf": "\u{1D539}",
"Breve": "\u02D8",
"breve": "\u02D8",
"Bumpeq": "\u224E",
"HumpDownHump": "\u224E",
"bump": "\u224E",
"CHcy": "\u0427",
"COPY": "\xA9",
"copy": "\xA9",
"Cacute": "\u0106",
"Cap": "\u22D2",
"CapitalDifferentialD": "\u2145",
"DD": "\u2145",
"Cayleys": "\u212D",
"Cfr": "\u212D",
"Ccaron": "\u010C",
"Ccedil": "\xC7",
"Ccirc": "\u0108",
"Cconint": "\u2230",
"Cdot": "\u010A",
"Cedilla": "\xB8",
"cedil": "\xB8",
"CenterDot": "\xB7",
"centerdot": "\xB7",
"middot": "\xB7",
"Chi": "\u03A7",
"CircleDot": "\u2299",
"odot": "\u2299",
"CircleMinus": "\u2296",
"ominus": "\u2296",
"CirclePlus": "\u2295",
"oplus": "\u2295",
"CircleTimes": "\u2297",
"otimes": "\u2297",
"ClockwiseContourIntegral": "\u2232",
"cwconint": "\u2232",
"CloseCurlyDoubleQuote": "\u201D",
"rdquo": "\u201D",
"rdquor": "\u201D",
"CloseCurlyQuote": "\u2019",
"rsquo": "\u2019",
"rsquor": "\u2019",
"Colon": "\u2237",
"Proportion": "\u2237",
"Colone": "\u2A74",
"Congruent": "\u2261",
"equiv": "\u2261",
"Conint": "\u222F",
"DoubleContourIntegral": "\u222F",
"ContourIntegral": "\u222E",
"conint": "\u222E",
"oint": "\u222E",
"Copf": "\u2102",
"complexes": "\u2102",
"Coproduct": "\u2210",
"coprod": "\u2210",
"CounterClockwiseContourIntegral": "\u2233",
"awconint": "\u2233",
"Cross": "\u2A2F",
"Cscr": "\u{1D49E}",
"Cup": "\u22D3",
"CupCap": "\u224D",
"asympeq": "\u224D",
"DDotrahd": "\u2911",
"DJcy": "\u0402",
"DScy": "\u0405",
"DZcy": "\u040F",
"Dagger": "\u2021",
"ddagger": "\u2021",
"Darr": "\u21A1",
"Dashv": "\u2AE4",
"DoubleLeftTee": "\u2AE4",
"Dcaron": "\u010E",
"Dcy": "\u0414",
"Del": "\u2207",
"nabla": "\u2207",
"Delta": "\u0394",
"Dfr": "\u{1D507}",
"DiacriticalAcute": "\xB4",
"acute": "\xB4",
"DiacriticalDot": "\u02D9",
"dot": "\u02D9",
"DiacriticalDoubleAcute": "\u02DD",
"dblac": "\u02DD",
"DiacriticalGrave": "`",
"grave": "`",
"DiacriticalTilde": "\u02DC",
"tilde": "\u02DC",
"Diamond": "\u22C4",
"diam": "\u22C4",
"diamond": "\u22C4",
"DifferentialD": "\u2146",
"dd": "\u2146",
"Dopf": "\u{1D53B}",
"Dot": "\xA8",
"DoubleDot": "\xA8",
"die": "\xA8",
"uml": "\xA8",
"DotDot": "\u20DC",
"DotEqual": "\u2250",
"doteq": "\u2250",
"esdot": "\u2250",
"DoubleDownArrow": "\u21D3",
"Downarrow": "\u21D3",
"dArr": "\u21D3",
"DoubleLeftArrow": "\u21D0",
"Leftarrow": "\u21D0",
"lArr": "\u21D0",
"DoubleLeftRightArrow": "\u21D4",
"Leftrightarrow": "\u21D4",
"hArr": "\u21D4",
"iff": "\u21D4",
"DoubleLongLeftArrow": "\u27F8",
"Longleftarrow": "\u27F8",
"xlArr": "\u27F8",
"DoubleLongLeftRightArrow": "\u27FA",
"Longleftrightarrow": "\u27FA",
"xhArr": "\u27FA",
"DoubleLongRightArrow": "\u27F9",
"Longrightarrow": "\u27F9",
"xrArr": "\u27F9",
"DoubleRightArrow": "\u21D2",
"Implies": "\u21D2",
"Rightarrow": "\u21D2",
"rArr": "\u21D2",
"DoubleRightTee": "\u22A8",
"vDash": "\u22A8",
"DoubleUpArrow": "\u21D1",
"Uparrow": "\u21D1",
"uArr": "\u21D1",
"DoubleUpDownArrow": "\u21D5",
"Updownarrow": "\u21D5",
"vArr": "\u21D5",
"DoubleVerticalBar": "\u2225",
"par": "\u2225",
"parallel": "\u2225",
"shortparallel": "\u2225",
"spar": "\u2225",
"DownArrow": "\u2193",
"ShortDownArrow": "\u2193",
"darr": "\u2193",
"downarrow": "\u2193",
"DownArrowBar": "\u2913",
"DownArrowUpArrow": "\u21F5",
"duarr": "\u21F5",
"DownBreve": "\u0311",
"DownLeftRightVector": "\u2950",
"DownLeftTeeVector": "\u295E",
"DownLeftVector": "\u21BD",
"leftharpoondown": "\u21BD",
"lhard": "\u21BD",
"DownLeftVectorBar": "\u2956",
"DownRightTeeVector": "\u295F",
"DownRightVector": "\u21C1",
"rhard": "\u21C1",
"rightharpoondown": "\u21C1",
"DownRightVectorBar": "\u2957",
"DownTee": "\u22A4",
"top": "\u22A4",
"DownTeeArrow": "\u21A7",
"mapstodown": "\u21A7",
"Dscr": "\u{1D49F}",
"Dstrok": "\u0110",
"ENG": "\u014A",
"ETH": "\xD0",
"Eacute": "\xC9",
"Ecaron": "\u011A",
"Ecirc": "\xCA",
"Ecy": "\u042D",
"Edot": "\u0116",
"Efr": "\u{1D508}",
"Egrave": "\xC8",
"Element": "\u2208",
"in": "\u2208",
"isin": "\u2208",
"isinv": "\u2208",
"Emacr": "\u0112",
"EmptySmallSquare": "\u25FB",
"EmptyVerySmallSquare": "\u25AB",
"Eogon": "\u0118",
"Eopf": "\u{1D53C}",
"Epsilon": "\u0395",
"Equal": "\u2A75",
"EqualTilde": "\u2242",
"eqsim": "\u2242",
"esim": "\u2242",
"Equilibrium": "\u21CC",
"rightleftharpoons": "\u21CC",
"rlhar": "\u21CC",
"Escr": "\u2130",
"expectation": "\u2130",
"Esim": "\u2A73",
"Eta": "\u0397",
"Euml": "\xCB",
"Exists": "\u2203",
"exist": "\u2203",
"ExponentialE": "\u2147",
"ee": "\u2147",
"exponentiale": "\u2147",
"Fcy": "\u0424",
"Ffr": "\u{1D509}",
"FilledSmallSquare": "\u25FC",
"FilledVerySmallSquare": "\u25AA",
"blacksquare": "\u25AA",
"squarf": "\u25AA",
"squf": "\u25AA",
"Fopf": "\u{1D53D}",
"ForAll": "\u2200",
"forall": "\u2200",
"Fouriertrf": "\u2131",
"Fscr": "\u2131",
"GJcy": "\u0403",
"GT": ">",
"gt": ">",
"Gamma": "\u0393",
"Gammad": "\u03DC",
"Gbreve": "\u011E",
"Gcedil": "\u0122",
"Gcirc": "\u011C",
"Gcy": "\u0413",
"Gdot": "\u0120",
"Gfr": "\u{1D50A}",
"Gg": "\u22D9",
"ggg": "\u22D9",
"Gopf": "\u{1D53E}",
"GreaterEqual": "\u2265",
"ge": "\u2265",
"geq": "\u2265",
"GreaterEqualLess": "\u22DB",
"gel": "\u22DB",
"gtreqless": "\u22DB",
"GreaterFullEqual": "\u2267",
"gE": "\u2267",
"geqq": "\u2267",
"GreaterGreater": "\u2AA2",
"GreaterLess": "\u2277",
"gl": "\u2277",
"gtrless": "\u2277",
"GreaterSlantEqual": "\u2A7E",
"geqslant": "\u2A7E",
"ges": "\u2A7E",
"GreaterTilde": "\u2273",
"gsim": "\u2273",
"gtrsim": "\u2273",
"Gscr": "\u{1D4A2}",
"Gt": "\u226B",
"NestedGreaterGreater": "\u226B",
"gg": "\u226B",
"HARDcy": "\u042A",
"Hacek": "\u02C7",
"caron": "\u02C7",
"Hat": "^",
"Hcirc": "\u0124",
"Hfr": "\u210C",
"Poincareplane": "\u210C",
"HilbertSpace": "\u210B",
"Hscr": "\u210B",
"hamilt": "\u210B",
"Hopf": "\u210D",
"quaternions": "\u210D",
"HorizontalLine": "\u2500",
"boxh": "\u2500",
"Hstrok": "\u0126",
"HumpEqual": "\u224F",
"bumpe": "\u224F",
"bumpeq": "\u224F",
"IEcy": "\u0415",
"IJlig": "\u0132",
"IOcy": "\u0401",
"Iacute": "\xCD",
"Icirc": "\xCE",
"Icy": "\u0418",
"Idot": "\u0130",
"Ifr": "\u2111",
"Im": "\u2111",
"image": "\u2111",
"imagpart": "\u2111",
"Igrave": "\xCC",
"Imacr": "\u012A",
"ImaginaryI": "\u2148",
"ii": "\u2148",
"Int": "\u222C",
"Integral": "\u222B",
"int": "\u222B",
"Intersection": "\u22C2",
"bigcap": "\u22C2",
"xcap": "\u22C2",
"InvisibleComma": "\u2063",
"ic": "\u2063",
"InvisibleTimes": "\u2062",
"it": "\u2062",
"Iogon": "\u012E",
"Iopf": "\u{1D540}",
"Iota": "\u0399",
"Iscr": "\u2110",
"imagline": "\u2110",
"Itilde": "\u0128",
"Iukcy": "\u0406",
"Iuml": "\xCF",
"Jcirc": "\u0134",
"Jcy": "\u0419",
"Jfr": "\u{1D50D}",
"Jopf": "\u{1D541}",
"Jscr": "\u{1D4A5}",
"Jsercy": "\u0408",
"Jukcy": "\u0404",
"KHcy": "\u0425",
"KJcy": "\u040C",
"Kappa": "\u039A",
"Kcedil": "\u0136",
"Kcy": "\u041A",
"Kfr": "\u{1D50E}",
"Kopf": "\u{1D542}",
"Kscr": "\u{1D4A6}",
"LJcy": "\u0409",
"LT": "<",
"lt": "<",
"Lacute": "\u0139",
"Lambda": "\u039B",
"Lang": "\u27EA",
"Laplacetrf": "\u2112",
"Lscr": "\u2112",
"lagran": "\u2112",
"Larr": "\u219E",
"twoheadleftarrow": "\u219E",
"Lcaron": "\u013D",
"Lcedil": "\u013B",
"Lcy": "\u041B",
"LeftAngleBracket": "\u27E8",
"lang": "\u27E8",
"langle": "\u27E8",
"LeftArrow": "\u2190",
"ShortLeftArrow": "\u2190",
"larr": "\u2190",
"leftarrow": "\u2190",
"slarr": "\u2190",
"LeftArrowBar": "\u21E4",
"larrb": "\u21E4",
"LeftArrowRightArrow": "\u21C6",
"leftrightarrows": "\u21C6",
"lrarr": "\u21C6",
"LeftCeiling": "\u2308",
"lceil": "\u2308",
"LeftDoubleBracket": "\u27E6",
"lobrk": "\u27E6",
"LeftDownTeeVector": "\u2961",
"LeftDownVector": "\u21C3",
"dharl": "\u21C3",
"downharpoonleft": "\u21C3",
"LeftDownVectorBar": "\u2959",
"LeftFloor": "\u230A",
"lfloor": "\u230A",
"LeftRightArrow": "\u2194",
"harr": "\u2194",
"leftrightarrow": "\u2194",
"LeftRightVector": "\u294E",
"LeftTee": "\u22A3",
"dashv": "\u22A3",
"LeftTeeArrow": "\u21A4",
"mapstoleft": "\u21A4",
"LeftTeeVector": "\u295A",
"LeftTriangle": "\u22B2",
"vartriangleleft": "\u22B2",
"vltri": "\u22B2",
"LeftTriangleBar": "\u29CF",
"LeftTriangleEqual": "\u22B4",
"ltrie": "\u22B4",
"trianglelefteq": "\u22B4",
"LeftUpDownVector": "\u2951",
"LeftUpTeeVector": "\u2960",
"LeftUpVector": "\u21BF",
"uharl": "\u21BF",
"upharpoonleft": "\u21BF",
"LeftUpVectorBar": "\u2958",
"LeftVector": "\u21BC",
"leftharpoonup": "\u21BC",
"lharu": "\u21BC",
"LeftVectorBar": "\u2952",
"LessEqualGreater": "\u22DA",
"leg": "\u22DA",
"lesseqgtr": "\u22DA",
"LessFullEqual": "\u2266",
"lE": "\u2266",
"leqq": "\u2266",
"LessGreater": "\u2276",
"lessgtr": "\u2276",
"lg": "\u2276",
"LessLess": "\u2AA1",
"LessSlantEqual": "\u2A7D",
"leqslant": "\u2A7D",
"les": "\u2A7D",
"LessTilde": "\u2272",
"lesssim": "\u2272",
"lsim": "\u2272",
"Lfr": "\u{1D50F}",
"Ll": "\u22D8",
"Lleftarrow": "\u21DA",
"lAarr": "\u21DA",
"Lmidot": "\u013F",
"LongLeftArrow": "\u27F5",
"longleftarrow": "\u27F5",
"xlarr": "\u27F5",
"LongLeftRightArrow": "\u27F7",
"longleftrightarrow": "\u27F7",
"xharr": "\u27F7",
"LongRightArrow": "\u27F6",
"longrightarrow": "\u27F6",
"xrarr": "\u27F6",
"Lopf": "\u{1D543}",
"LowerLeftArrow": "\u2199",
"swarr": "\u2199",
"swarrow": "\u2199",
"LowerRightArrow": "\u2198",
"searr": "\u2198",
"searrow": "\u2198",
"Lsh": "\u21B0",
"lsh": "\u21B0",
"Lstrok": "\u0141",
"Lt": "\u226A",
"NestedLessLess": "\u226A",
"ll": "\u226A",
"Map": "\u2905",
"Mcy": "\u041C",
"MediumSpace": "\u205F",
"Mellintrf": "\u2133",
"Mscr": "\u2133",
"phmmat": "\u2133",
"Mfr": "\u{1D510}",
"MinusPlus": "\u2213",
"mnplus": "\u2213",
"mp": "\u2213",
"Mopf": "\u{1D544}",
"Mu": "\u039C",
"NJcy": "\u040A",
"Nacute": "\u0143",
"Ncaron": "\u0147",
"Ncedil": "\u0145",
"Ncy": "\u041D",
"NegativeMediumSpace": "\u200B",
"NegativeThickSpace": "\u200B",
"NegativeThinSpace": "\u200B",
"NegativeVeryThinSpace": "\u200B",
"ZeroWidthSpace": "\u200B",
"NewLine": "\n",
"Nfr": "\u{1D511}",
"NoBreak": "\u2060",
"NonBreakingSpace": "\xA0",
"nbsp": "\xA0",
"Nopf": "\u2115",
"naturals": "\u2115",
"Not": "\u2AEC",
"NotCongruent": "\u2262",
"nequiv": "\u2262",
"NotCupCap": "\u226D",
"NotDoubleVerticalBar": "\u2226",
"npar": "\u2226",
"nparallel": "\u2226",
"nshortparallel": "\u2226",
"nspar": "\u2226",
"NotElement": "\u2209",
"notin": "\u2209",
"notinva": "\u2209",
"NotEqual": "\u2260",
"ne": "\u2260",
"NotEqualTilde": "\u2242\u0338",
"nesim": "\u2242\u0338",
"NotExists": "\u2204",
"nexist": "\u2204",
"nexists": "\u2204",
"NotGreater": "\u226F",
"ngt": "\u226F",
"ngtr": "\u226F",
"NotGreaterEqual": "\u2271",
"nge": "\u2271",
"ngeq": "\u2271",
"NotGreaterFullEqual": "\u2267\u0338",
"ngE": "\u2267\u0338",
"ngeqq": "\u2267\u0338",
"NotGreaterGreater": "\u226B\u0338",
"nGtv": "\u226B\u0338",
"NotGreaterLess": "\u2279",
"ntgl": "\u2279",
"NotGreaterSlantEqual": "\u2A7E\u0338",
"ngeqslant": "\u2A7E\u0338",
"nges": "\u2A7E\u0338",
"NotGreaterTilde": "\u2275",
"ngsim": "\u2275",
"NotHumpDownHump": "\u224E\u0338",
"nbump": "\u224E\u0338",
"NotHumpEqual": "\u224F\u0338",
"nbumpe": "\u224F\u0338",
"NotLeftTriangle": "\u22EA",
"nltri": "\u22EA",
"ntriangleleft": "\u22EA",
"NotLeftTriangleBar": "\u29CF\u0338",
"NotLeftTriangleEqual": "\u22EC",
"nltrie": "\u22EC",
"ntrianglelefteq": "\u22EC",
"NotLess": "\u226E",
"nless": "\u226E",
"nlt": "\u226E",
"NotLessEqual": "\u2270",
"nle": "\u2270",
"nleq": "\u2270",
"NotLessGreater": "\u2278",
"ntlg": "\u2278",
"NotLessLess": "\u226A\u0338",
"nLtv": "\u226A\u0338",
"NotLessSlantEqual": "\u2A7D\u0338",
"nleqslant": "\u2A7D\u0338",
"nles": "\u2A7D\u0338",
"NotLessTilde": "\u2274",
"nlsim": "\u2274",
"NotNestedGreaterGreater": "\u2AA2\u0338",
"NotNestedLessLess": "\u2AA1\u0338",
"NotPrecedes": "\u2280",
"npr": "\u2280",
"nprec": "\u2280",
"NotPrecedesEqual": "\u2AAF\u0338",
"npre": "\u2AAF\u0338",
"npreceq": "\u2AAF\u0338",
"NotPrecedesSlantEqual": "\u22E0",
"nprcue": "\u22E0",
"NotReverseElement": "\u220C",
"notni": "\u220C",
"notniva": "\u220C",
"NotRightTriangle": "\u22EB",
"nrtri": "\u22EB",
"ntriangleright": "\u22EB",
"NotRightTriangleBar": "\u29D0\u0338",
"NotRightTriangleEqual": "\u22ED",
"nrtrie": "\u22ED",
"ntrianglerighteq": "\u22ED",
"NotSquareSubset": "\u228F\u0338",
"NotSquareSubsetEqual": "\u22E2",
"nsqsube": "\u22E2",
"NotSquareSuperset": "\u2290\u0338",
"NotSquareSupersetEqual": "\u22E3",
"nsqsupe": "\u22E3",
"NotSubset": "\u2282\u20D2",
"nsubset": "\u2282\u20D2",
"vnsub": "\u2282\u20D2",
"NotSubsetEqual": "\u2288",
"nsube": "\u2288",
"nsubseteq": "\u2288",
"NotSucceeds": "\u2281",
"nsc": "\u2281",
"nsucc": "\u2281",
"NotSucceedsEqual": "\u2AB0\u0338",
"nsce": "\u2AB0\u0338",
"nsucceq": "\u2AB0\u0338",
"NotSucceedsSlantEqual": "\u22E1",
"nsccue": "\u22E1",
"NotSucceedsTilde": "\u227F\u0338",
"NotSuperset": "\u2283\u20D2",
"nsupset": "\u2283\u20D2",
"vnsup": "\u2283\u20D2",
"NotSupersetEqual": "\u2289",
"nsupe": "\u2289",
"nsupseteq": "\u2289",
"NotTilde": "\u2241",
"nsim": "\u2241",
"NotTildeEqual": "\u2244",
"nsime": "\u2244",
"nsimeq": "\u2244",
"NotTildeFullEqual": "\u2247",
"ncong": "\u2247",
"NotTildeTilde": "\u2249",
"nap": "\u2249",
"napprox": "\u2249",
"NotVerticalBar": "\u2224",
"nmid": "\u2224",
"nshortmid": "\u2224",
"nsmid": "\u2224",
"Nscr": "\u{1D4A9}",
"Ntilde": "\xD1",
"Nu": "\u039D",
"OElig": "\u0152",
"Oacute": "\xD3",
"Ocirc": "\xD4",
"Ocy": "\u041E",
"Odblac": "\u0150",
"Ofr": "\u{1D512}",
"Ograve": "\xD2",
"Omacr": "\u014C",
"Omega": "\u03A9",
"ohm": "\u03A9",
"Omicron": "\u039F",
"Oopf": "\u{1D546}",
"OpenCurlyDoubleQuote": "\u201C",
"ldquo": "\u201C",
"OpenCurlyQuote": "\u2018",
"lsquo": "\u2018",
"Or": "\u2A54",
"Oscr": "\u{1D4AA}",
"Oslash": "\xD8",
"Otilde": "\xD5",
"Otimes": "\u2A37",
"Ouml": "\xD6",
"OverBar": "\u203E",
"oline": "\u203E",
"OverBrace": "\u23DE",
"OverBracket": "\u23B4",
"tbrk": "\u23B4",
"OverParenthesis": "\u23DC",
"PartialD": "\u2202",
"part": "\u2202",
"Pcy": "\u041F",
"Pfr": "\u{1D513}",
"Phi": "\u03A6",
"Pi": "\u03A0",
"PlusMinus": "\xB1",
"plusmn": "\xB1",
"pm": "\xB1",
"Popf": "\u2119",
"primes": "\u2119",
"Pr": "\u2ABB",
"Precedes": "\u227A",
"pr": "\u227A",
"prec": "\u227A",
"PrecedesEqual": "\u2AAF",
"pre": "\u2AAF",
"preceq": "\u2AAF",
"PrecedesSlantEqual": "\u227C",
"prcue": "\u227C",
"preccurlyeq": "\u227C",
"PrecedesTilde": "\u227E",
"precsim": "\u227E",
"prsim": "\u227E",
"Prime": "\u2033",
"Product": "\u220F",
"prod": "\u220F",
"Proportional": "\u221D",
"prop": "\u221D",
"propto": "\u221D",
"varpropto": "\u221D",
"vprop": "\u221D",
"Pscr": "\u{1D4AB}",
"Psi": "\u03A8",
"QUOT": '"',
"quot": '"',
"Qfr": "\u{1D514}",
"Qopf": "\u211A",
"rationals": "\u211A",
"Qscr": "\u{1D4AC}",
"RBarr": "\u2910",
"drbkarow": "\u2910",
"REG": "\xAE",
"circledR": "\xAE",
"reg": "\xAE",
"Racute": "\u0154",
"Rang": "\u27EB",
"Rarr": "\u21A0",
"twoheadrightarrow": "\u21A0",
"Rarrtl": "\u2916",
"Rcaron": "\u0158",
"Rcedil": "\u0156",
"Rcy": "\u0420",
"Re": "\u211C",
"Rfr": "\u211C",
"real": "\u211C",
"realpart": "\u211C",
"ReverseElement": "\u220B",
"SuchThat": "\u220B",
"ni": "\u220B",
"niv": "\u220B",
"ReverseEquilibrium": "\u21CB",
"leftrightharpoons": "\u21CB",
"lrhar": "\u21CB",
"ReverseUpEquilibrium": "\u296F",
"duhar": "\u296F",
"Rho": "\u03A1",
"RightAngleBracket": "\u27E9",
"rang": "\u27E9",
"rangle": "\u27E9",
"RightArrow": "\u2192",
"ShortRightArrow": "\u2192",
"rarr": "\u2192",
"rightarrow": "\u2192",
"srarr": "\u2192",
"RightArrowBar": "\u21E5",
"rarrb": "\u21E5",
"RightArrowLeftArrow": "\u21C4",
"rightleftarrows": "\u21C4",
"rlarr": "\u21C4",
"RightCeiling": "\u2309",
"rceil": "\u2309",
"RightDoubleBracket": "\u27E7",
"robrk": "\u27E7",
"RightDownTeeVector": "\u295D",
"RightDownVector": "\u21C2",
"dharr": "\u21C2",
"downharpoonright": "\u21C2",
"RightDownVectorBar": "\u2955",
"RightFloor": "\u230B",
"rfloor": "\u230B",
"RightTee": "\u22A2",
"vdash": "\u22A2",
"RightTeeArrow": "\u21A6",
"map": "\u21A6",
"mapsto": "\u21A6",
"RightTeeVector": "\u295B",
"RightTriangle": "\u22B3",
"vartriangleright": "\u22B3",
"vrtri": "\u22B3",
"RightTriangleBar": "\u29D0",
"RightTriangleEqual": "\u22B5",
"rtrie": "\u22B5",
"trianglerighteq": "\u22B5",
"RightUpDownVector": "\u294F",
"RightUpTeeVector": "\u295C",
"RightUpVector": "\u21BE",
"uharr": "\u21BE",
"upharpoonright": "\u21BE",
"RightUpVectorBar": "\u2954",
"RightVector": "\u21C0",
"rharu": "\u21C0",
"rightharpoonup": "\u21C0",
"RightVectorBar": "\u2953",
"Ropf": "\u211D",
"reals": "\u211D",
"RoundImplies": "\u2970",
"Rrightarrow": "\u21DB",
"rAarr": "\u21DB",
"Rscr": "\u211B",
"realine": "\u211B",
"Rsh": "\u21B1",
"rsh": "\u21B1",
"RuleDelayed": "\u29F4",
"SHCHcy": "\u0429",
"SHcy": "\u0428",
"SOFTcy": "\u042C",
"Sacute": "\u015A",
"Sc": "\u2ABC",
"Scaron": "\u0160",
"Scedil": "\u015E",
"Scirc": "\u015C",
"Scy": "\u0421",
"Sfr": "\u{1D516}",
"ShortUpArrow": "\u2191",
"UpArrow": "\u2191",
"uarr": "\u2191",
"uparrow": "\u2191",
"Sigma": "\u03A3",
"SmallCircle": "\u2218",
"compfn": "\u2218",
"Sopf": "\u{1D54A}",
"Sqrt": "\u221A",
"radic": "\u221A",
"Square": "\u25A1",
"squ": "\u25A1",
"square": "\u25A1",
"SquareIntersection": "\u2293",
"sqcap": "\u2293",
"SquareSubset": "\u228F",
"sqsub": "\u228F",
"sqsubset": "\u228F",
"SquareSubsetEqual": "\u2291",
"sqsube": "\u2291",
"sqsubseteq": "\u2291",
"SquareSuperset": "\u2290",
"sqsup": "\u2290",
"sqsupset": "\u2290",
"SquareSupersetEqual": "\u2292",
"sqsupe": "\u2292",
"sqsupseteq": "\u2292",
"SquareUnion": "\u2294",
"sqcup": "\u2294",
"Sscr": "\u{1D4AE}",
"Star": "\u22C6",
"sstarf": "\u22C6",
"Sub": "\u22D0",
"Subset": "\u22D0",
"SubsetEqual": "\u2286",
"sube": "\u2286",
"subseteq": "\u2286",
"Succeeds": "\u227B",
"sc": "\u227B",
"succ": "\u227B",
"SucceedsEqual": "\u2AB0",
"sce": "\u2AB0",
"succeq": "\u2AB0",
"SucceedsSlantEqual": "\u227D",
"sccue": "\u227D",
"succcurlyeq": "\u227D",
"SucceedsTilde": "\u227F",
"scsim": "\u227F",
"succsim": "\u227F",
"Sum": "\u2211",
"sum": "\u2211",
"Sup": "\u22D1",
"Supset": "\u22D1",
"Superset": "\u2283",
"sup": "\u2283",
"supset": "\u2283",
"SupersetEqual": "\u2287",
"supe": "\u2287",
"supseteq": "\u2287",
"THORN": "\xDE",
"TRADE": "\u2122",
"trade": "\u2122",
"TSHcy": "\u040B",
"TScy": "\u0426",
"Tab": " ",
"Tau": "\u03A4",
"Tcaron": "\u0164",
"Tcedil": "\u0162",
"Tcy": "\u0422",
"Tfr": "\u{1D517}",
"Therefore": "\u2234",
"there4": "\u2234",
"therefore": "\u2234",
"Theta": "\u0398",
"ThickSpace": "\u205F\u200A",
"ThinSpace": "\u2009",
"thinsp": "\u2009",
"Tilde": "\u223C",
"sim": "\u223C",
"thicksim": "\u223C",
"thksim": "\u223C",
"TildeEqual": "\u2243",
"sime": "\u2243",
"simeq": "\u2243",
"TildeFullEqual": "\u2245",
"cong": "\u2245",
"TildeTilde": "\u2248",
"ap": "\u2248",
"approx": "\u2248",
"asymp": "\u2248",
"thickapprox": "\u2248",
"thkap": "\u2248",
"Topf": "\u{1D54B}",
"TripleDot": "\u20DB",
"tdot": "\u20DB",
"Tscr": "\u{1D4AF}",
"Tstrok": "\u0166",
"Uacute": "\xDA",
"Uarr": "\u219F",
"Uarrocir": "\u2949",
"Ubrcy": "\u040E",
"Ubreve": "\u016C",
"Ucirc": "\xDB",
"Ucy": "\u0423",
"Udblac": "\u0170",
"Ufr": "\u{1D518}",
"Ugrave": "\xD9",
"Umacr": "\u016A",
"UnderBar": "_",
"lowbar": "_",
"UnderBrace": "\u23DF",
"UnderBracket": "\u23B5",
"bbrk": "\u23B5",
"UnderParenthesis": "\u23DD",
"Union": "\u22C3",
"bigcup": "\u22C3",
"xcup": "\u22C3",
"UnionPlus": "\u228E",
"uplus": "\u228E",
"Uogon": "\u0172",
"Uopf": "\u{1D54C}",
"UpArrowBar": "\u2912",
"UpArrowDownArrow": "\u21C5",
"udarr": "\u21C5",
"UpDownArrow": "\u2195",
"updownarrow": "\u2195",
"varr": "\u2195",
"UpEquilibrium": "\u296E",
"udhar": "\u296E",
"UpTee": "\u22A5",
"bot": "\u22A5",
"bottom": "\u22A5",
"perp": "\u22A5",
"UpTeeArrow": "\u21A5",
"mapstoup": "\u21A5",
"UpperLeftArrow": "\u2196",
"nwarr": "\u2196",
"nwarrow": "\u2196",
"UpperRightArrow": "\u2197",
"nearr": "\u2197",
"nearrow": "\u2197",
"Upsi": "\u03D2",
"upsih": "\u03D2",
"Upsilon": "\u03A5",
"Uring": "\u016E",
"Uscr": "\u{1D4B0}",
"Utilde": "\u0168",
"Uuml": "\xDC",
"VDash": "\u22AB",
"Vbar": "\u2AEB",
"Vcy": "\u0412",
"Vdash": "\u22A9",
"Vdashl": "\u2AE6",
"Vee": "\u22C1",
"bigvee": "\u22C1",
"xvee": "\u22C1",
"Verbar": "\u2016",
"Vert": "\u2016",
"VerticalBar": "\u2223",
"mid": "\u2223",
"shortmid": "\u2223",
"smid": "\u2223",
"VerticalLine": "|",
"verbar": "|",
"vert": "|",
"VerticalSeparator": "\u2758",
"VerticalTilde": "\u2240",
"wr": "\u2240",
"wreath": "\u2240",
"VeryThinSpace": "\u200A",
"hairsp": "\u200A",
"Vfr": "\u{1D519}",
"Vopf": "\u{1D54D}",
"Vscr": "\u{1D4B1}",
"Vvdash": "\u22AA",
"Wcirc": "\u0174",
"Wedge": "\u22C0",
"bigwedge": "\u22C0",
"xwedge": "\u22C0",
"Wfr": "\u{1D51A}",
"Wopf": "\u{1D54E}",
"Wscr": "\u{1D4B2}",
"Xfr": "\u{1D51B}",
"Xi": "\u039E",
"Xopf": "\u{1D54F}",
"Xscr": "\u{1D4B3}",
"YAcy": "\u042F",
"YIcy": "\u0407",
"YUcy": "\u042E",
"Yacute": "\xDD",
"Ycirc": "\u0176",
"Ycy": "\u042B",
"Yfr": "\u{1D51C}",
"Yopf": "\u{1D550}",
"Yscr": "\u{1D4B4}",
"Yuml": "\u0178",
"ZHcy": "\u0416",
"Zacute": "\u0179",
"Zcaron": "\u017D",
"Zcy": "\u0417",
"Zdot": "\u017B",
"Zeta": "\u0396",
"Zfr": "\u2128",
"zeetrf": "\u2128",
"Zopf": "\u2124",
"integers": "\u2124",
"Zscr": "\u{1D4B5}",
"aacute": "\xE1",
"abreve": "\u0103",
"ac": "\u223E",
"mstpos": "\u223E",
"acE": "\u223E\u0333",
"acd": "\u223F",
"acirc": "\xE2",
"acy": "\u0430",
"aelig": "\xE6",
"afr": "\u{1D51E}",
"agrave": "\xE0",
"alefsym": "\u2135",
"aleph": "\u2135",
"alpha": "\u03B1",
"amacr": "\u0101",
"amalg": "\u2A3F",
"and": "\u2227",
"wedge": "\u2227",
"andand": "\u2A55",
"andd": "\u2A5C",
"andslope": "\u2A58",
"andv": "\u2A5A",
"ang": "\u2220",
"angle": "\u2220",
"ange": "\u29A4",
"angmsd": "\u2221",
"measuredangle": "\u2221",
"angmsdaa": "\u29A8",
"angmsdab": "\u29A9",
"angmsdac": "\u29AA",
"angmsdad": "\u29AB",
"angmsdae": "\u29AC",
"angmsdaf": "\u29AD",
"angmsdag": "\u29AE",
"angmsdah": "\u29AF",
"angrt": "\u221F",
"angrtvb": "\u22BE",
"angrtvbd": "\u299D",
"angsph": "\u2222",
"angzarr": "\u237C",
"aogon": "\u0105",
"aopf": "\u{1D552}",
"apE": "\u2A70",
"apacir": "\u2A6F",
"ape": "\u224A",
"approxeq": "\u224A",
"apid": "\u224B",
"apos": "'",
"aring": "\xE5",
"ascr": "\u{1D4B6}",
"ast": "*",
"midast": "*",
"atilde": "\xE3",
"auml": "\xE4",
"awint": "\u2A11",
"bNot": "\u2AED",
"backcong": "\u224C",
"bcong": "\u224C",
"backepsilon": "\u03F6",
"bepsi": "\u03F6",
"backprime": "\u2035",
"bprime": "\u2035",
"backsim": "\u223D",
"bsim": "\u223D",
"backsimeq": "\u22CD",
"bsime": "\u22CD",
"barvee": "\u22BD",
"barwed": "\u2305",
"barwedge": "\u2305",
"bbrktbrk": "\u23B6",
"bcy": "\u0431",
"bdquo": "\u201E",
"ldquor": "\u201E",
"bemptyv": "\u29B0",
"beta": "\u03B2",
"beth": "\u2136",
"between": "\u226C",
"twixt": "\u226C",
"bfr": "\u{1D51F}",
"bigcirc": "\u25EF",
"xcirc": "\u25EF",
"bigodot": "\u2A00",
"xodot": "\u2A00",
"bigoplus": "\u2A01",
"xoplus": "\u2A01",
"bigotimes": "\u2A02",
"xotime": "\u2A02",
"bigsqcup": "\u2A06",
"xsqcup": "\u2A06",
"bigstar": "\u2605",
"starf": "\u2605",
"bigtriangledown": "\u25BD",
"xdtri": "\u25BD",
"bigtriangleup": "\u25B3",
"xutri": "\u25B3",
"biguplus": "\u2A04",
"xuplus": "\u2A04",
"bkarow": "\u290D",
"rbarr": "\u290D",
"blacklozenge": "\u29EB",
"lozf": "\u29EB",
"blacktriangle": "\u25B4",
"utrif": "\u25B4",
"blacktriangledown": "\u25BE",
"dtrif": "\u25BE",
"blacktriangleleft": "\u25C2",
"ltrif": "\u25C2",
"blacktriangleright": "\u25B8",
"rtrif": "\u25B8",
"blank": "\u2423",
"blk12": "\u2592",
"blk14": "\u2591",
"blk34": "\u2593",
"block": "\u2588",
"bne": "=\u20E5",
"bnequiv": "\u2261\u20E5",
"bnot": "\u2310",
"bopf": "\u{1D553}",
"bowtie": "\u22C8",
"boxDL": "\u2557",
"boxDR": "\u2554",
"boxDl": "\u2556",
"boxDr": "\u2553",
"boxH": "\u2550",
"boxHD": "\u2566",
"boxHU": "\u2569",
"boxHd": "\u2564",
"boxHu": "\u2567",
"boxUL": "\u255D",
"boxUR": "\u255A",
"boxUl": "\u255C",
"boxUr": "\u2559",
"boxV": "\u2551",
"boxVH": "\u256C",
"boxVL": "\u2563",
"boxVR": "\u2560",
"boxVh": "\u256B",
"boxVl": "\u2562",
"boxVr": "\u255F",
"boxbox": "\u29C9",
"boxdL": "\u2555",
"boxdR": "\u2552",
"boxdl": "\u2510",
"boxdr": "\u250C",
"boxhD": "\u2565",
"boxhU": "\u2568",
"boxhd": "\u252C",
"boxhu": "\u2534",
"boxminus": "\u229F",
"minusb": "\u229F",
"boxplus": "\u229E",
"plusb": "\u229E",
"boxtimes": "\u22A0",
"timesb": "\u22A0",
"boxuL": "\u255B",
"boxuR": "\u2558",
"boxul": "\u2518",
"boxur": "\u2514",
"boxv": "\u2502",
"boxvH": "\u256A",
"boxvL": "\u2561",
"boxvR": "\u255E",
"boxvh": "\u253C",
"boxvl": "\u2524",
"boxvr": "\u251C",
"brvbar": "\xA6",
"bscr": "\u{1D4B7}",
"bsemi": "\u204F",
"bsol": "\\",
"bsolb": "\u29C5",
"bsolhsub": "\u27C8",
"bull": "\u2022",
"bullet": "\u2022",
"bumpE": "\u2AAE",
"cacute": "\u0107",
"cap": "\u2229",
"capand": "\u2A44",
"capbrcup": "\u2A49",
"capcap": "\u2A4B",
"capcup": "\u2A47",
"capdot": "\u2A40",
"caps": "\u2229\uFE00",
"caret": "\u2041",
"ccaps": "\u2A4D",
"ccaron": "\u010D",
"ccedil": "\xE7",
"ccirc": "\u0109",
"ccups": "\u2A4C",
"ccupssm": "\u2A50",
"cdot": "\u010B",
"cemptyv": "\u29B2",
"cent": "\xA2",
"cfr": "\u{1D520}",
"chcy": "\u0447",
"check": "\u2713",
"checkmark": "\u2713",
"chi": "\u03C7",
"cir": "\u25CB",
"cirE": "\u29C3",
"circ": "\u02C6",
"circeq": "\u2257",
"cire": "\u2257",
"circlearrowleft": "\u21BA",
"olarr": "\u21BA",
"circlearrowright": "\u21BB",
"orarr": "\u21BB",
"circledS": "\u24C8",
"oS": "\u24C8",
"circledast": "\u229B",
"oast": "\u229B",
"circledcirc": "\u229A",
"ocir": "\u229A",
"circleddash": "\u229D",
"odash": "\u229D",
"cirfnint": "\u2A10",
"cirmid": "\u2AEF",
"cirscir": "\u29C2",
"clubs": "\u2663",
"clubsuit": "\u2663",
"colon": ":",
"comma": ",",
"commat": "@",
"comp": "\u2201",
"complement": "\u2201",
"congdot": "\u2A6D",
"copf": "\u{1D554}",
"copysr": "\u2117",
"crarr": "\u21B5",
"cross": "\u2717",
"cscr": "\u{1D4B8}",
"csub": "\u2ACF",
"csube": "\u2AD1",
"csup": "\u2AD0",
"csupe": "\u2AD2",
"ctdot": "\u22EF",
"cudarrl": "\u2938",
"cudarrr": "\u2935",
"cuepr": "\u22DE",
"curlyeqprec": "\u22DE",
"cuesc": "\u22DF",
"curlyeqsucc": "\u22DF",
"cularr": "\u21B6",
"curvearrowleft": "\u21B6",
"cularrp": "\u293D",
"cup": "\u222A",
"cupbrcap": "\u2A48",
"cupcap": "\u2A46",
"cupcup": "\u2A4A",
"cupdot": "\u228D",
"cupor": "\u2A45",
"cups": "\u222A\uFE00",
"curarr": "\u21B7",
"curvearrowright": "\u21B7",
"curarrm": "\u293C",
"curlyvee": "\u22CE",
"cuvee": "\u22CE",
"curlywedge": "\u22CF",
"cuwed": "\u22CF",
"curren": "\xA4",
"cwint": "\u2231",
"cylcty": "\u232D",
"dHar": "\u2965",
"dagger": "\u2020",
"daleth": "\u2138",
"dash": "\u2010",
"hyphen": "\u2010",
"dbkarow": "\u290F",
"rBarr": "\u290F",
"dcaron": "\u010F",
"dcy": "\u0434",
"ddarr": "\u21CA",
"downdownarrows": "\u21CA",
"ddotseq": "\u2A77",
"eDDot": "\u2A77",
"deg": "\xB0",
"delta": "\u03B4",
"demptyv": "\u29B1",
"dfisht": "\u297F",
"dfr": "\u{1D521}",
"diamondsuit": "\u2666",
"diams": "\u2666",
"digamma": "\u03DD",
"gammad": "\u03DD",
"disin": "\u22F2",
"div": "\xF7",
"divide": "\xF7",
"divideontimes": "\u22C7",
"divonx": "\u22C7",
"djcy": "\u0452",
"dlcorn": "\u231E",
"llcorner": "\u231E",
"dlcrop": "\u230D",
"dollar": "$",
"dopf": "\u{1D555}",
"doteqdot": "\u2251",
"eDot": "\u2251",
"dotminus": "\u2238",
"minusd": "\u2238",
"dotplus": "\u2214",
"plusdo": "\u2214",
"dotsquare": "\u22A1",
"sdotb": "\u22A1",
"drcorn": "\u231F",
"lrcorner": "\u231F",
"drcrop": "\u230C",
"dscr": "\u{1D4B9}",
"dscy": "\u0455",
"dsol": "\u29F6",
"dstrok": "\u0111",
"dtdot": "\u22F1",
"dtri": "\u25BF",
"triangledown": "\u25BF",
"dwangle": "\u29A6",
"dzcy": "\u045F",
"dzigrarr": "\u27FF",
"eacute": "\xE9",
"easter": "\u2A6E",
"ecaron": "\u011B",
"ecir": "\u2256",
"eqcirc": "\u2256",
"ecirc": "\xEA",
"ecolon": "\u2255",
"eqcolon": "\u2255",
"ecy": "\u044D",
"edot": "\u0117",
"efDot": "\u2252",
"fallingdotseq": "\u2252",
"efr": "\u{1D522}",
"eg": "\u2A9A",
"egrave": "\xE8",
"egs": "\u2A96",
"eqslantgtr": "\u2A96",
"egsdot": "\u2A98",
"el": "\u2A99",
"elinters": "\u23E7",
"ell": "\u2113",
"els": "\u2A95",
"eqslantless": "\u2A95",
"elsdot": "\u2A97",
"emacr": "\u0113",
"empty": "\u2205",
"emptyset": "\u2205",
"emptyv": "\u2205",
"varnothing": "\u2205",
"emsp13": "\u2004",
"emsp14": "\u2005",
"emsp": "\u2003",
"eng": "\u014B",
"ensp": "\u2002",
"eogon": "\u0119",
"eopf": "\u{1D556}",
"epar": "\u22D5",
"eparsl": "\u29E3",
"eplus": "\u2A71",
"epsi": "\u03B5",
"epsilon": "\u03B5",
"epsiv": "\u03F5",
"straightepsilon": "\u03F5",
"varepsilon": "\u03F5",
"equals": "=",
"equest": "\u225F",
"questeq": "\u225F",
"equivDD": "\u2A78",
"eqvparsl": "\u29E5",
"erDot": "\u2253",
"risingdotseq": "\u2253",
"erarr": "\u2971",
"escr": "\u212F",
"eta": "\u03B7",
"eth": "\xF0",
"euml": "\xEB",
"euro": "\u20AC",
"excl": "!",
"fcy": "\u0444",
"female": "\u2640",
"ffilig": "\uFB03",
"fflig": "\uFB00",
"ffllig": "\uFB04",
"ffr": "\u{1D523}",
"filig": "\uFB01",
"fjlig": "fj",
"flat": "\u266D",
"fllig": "\uFB02",
"fltns": "\u25B1",
"fnof": "\u0192",
"fopf": "\u{1D557}",
"fork": "\u22D4",
"pitchfork": "\u22D4",
"forkv": "\u2AD9",
"fpartint": "\u2A0D",
"frac12": "\xBD",
"half": "\xBD",
"frac13": "\u2153",
"frac14": "\xBC",
"frac15": "\u2155",
"frac16": "\u2159",
"frac18": "\u215B",
"frac23": "\u2154",
"frac25": "\u2156",
"frac34": "\xBE",
"frac35": "\u2157",
"frac38": "\u215C",
"frac45": "\u2158",
"frac56": "\u215A",
"frac58": "\u215D",
"frac78": "\u215E",
"frasl": "\u2044",
"frown": "\u2322",
"sfrown": "\u2322",
"fscr": "\u{1D4BB}",
"gEl": "\u2A8C",
"gtreqqless": "\u2A8C",
"gacute": "\u01F5",
"gamma": "\u03B3",
"gap": "\u2A86",
"gtrapprox": "\u2A86",
"gbreve": "\u011F",
"gcirc": "\u011D",
"gcy": "\u0433",
"gdot": "\u0121",
"gescc": "\u2AA9",
"gesdot": "\u2A80",
"gesdoto": "\u2A82",
"gesdotol": "\u2A84",
"gesl": "\u22DB\uFE00",
"gesles": "\u2A94",
"gfr": "\u{1D524}",
"gimel": "\u2137",
"gjcy": "\u0453",
"glE": "\u2A92",
"gla": "\u2AA5",
"glj": "\u2AA4",
"gnE": "\u2269",
"gneqq": "\u2269",
"gnap": "\u2A8A",
"gnapprox": "\u2A8A",
"gne": "\u2A88",
"gneq": "\u2A88",
"gnsim": "\u22E7",
"gopf": "\u{1D558}",
"gscr": "\u210A",
"gsime": "\u2A8E",
"gsiml": "\u2A90",
"gtcc": "\u2AA7",
"gtcir": "\u2A7A",
"gtdot": "\u22D7",
"gtrdot": "\u22D7",
"gtlPar": "\u2995",
"gtquest": "\u2A7C",
"gtrarr": "\u2978",
"gvertneqq": "\u2269\uFE00",
"gvnE": "\u2269\uFE00",
"hardcy": "\u044A",
"harrcir": "\u2948",
"harrw": "\u21AD",
"leftrightsquigarrow": "\u21AD",
"hbar": "\u210F",
"hslash": "\u210F",
"planck": "\u210F",
"plankv": "\u210F",
"hcirc": "\u0125",
"hearts": "\u2665",
"heartsuit": "\u2665",
"hellip": "\u2026",
"mldr": "\u2026",
"hercon": "\u22B9",
"hfr": "\u{1D525}",
"hksearow": "\u2925",
"searhk": "\u2925",
"hkswarow": "\u2926",
"swarhk": "\u2926",
"hoarr": "\u21FF",
"homtht": "\u223B",
"hookleftarrow": "\u21A9",
"larrhk": "\u21A9",
"hookrightarrow": "\u21AA",
"rarrhk": "\u21AA",
"hopf": "\u{1D559}",
"horbar": "\u2015",
"hscr": "\u{1D4BD}",
"hstrok": "\u0127",
"hybull": "\u2043",
"iacute": "\xED",
"icirc": "\xEE",
"icy": "\u0438",
"iecy": "\u0435",
"iexcl": "\xA1",
"ifr": "\u{1D526}",
"igrave": "\xEC",
"iiiint": "\u2A0C",
"qint": "\u2A0C",
"iiint": "\u222D",
"tint": "\u222D",
"iinfin": "\u29DC",
"iiota": "\u2129",
"ijlig": "\u0133",
"imacr": "\u012B",
"imath": "\u0131",
"inodot": "\u0131",
"imof": "\u22B7",
"imped": "\u01B5",
"incare": "\u2105",
"infin": "\u221E",
"infintie": "\u29DD",
"intcal": "\u22BA",
"intercal": "\u22BA",
"intlarhk": "\u2A17",
"intprod": "\u2A3C",
"iprod": "\u2A3C",
"iocy": "\u0451",
"iogon": "\u012F",
"iopf": "\u{1D55A}",
"iota": "\u03B9",
"iquest": "\xBF",
"iscr": "\u{1D4BE}",
"isinE": "\u22F9",
"isindot": "\u22F5",
"isins": "\u22F4",
"isinsv": "\u22F3",
"itilde": "\u0129",
"iukcy": "\u0456",
"iuml": "\xEF",
"jcirc": "\u0135",
"jcy": "\u0439",
"jfr": "\u{1D527}",
"jmath": "\u0237",
"jopf": "\u{1D55B}",
"jscr": "\u{1D4BF}",
"jsercy": "\u0458",
"jukcy": "\u0454",
"kappa": "\u03BA",
"kappav": "\u03F0",
"varkappa": "\u03F0",
"kcedil": "\u0137",
"kcy": "\u043A",
"kfr": "\u{1D528}",
"kgreen": "\u0138",
"khcy": "\u0445",
"kjcy": "\u045C",
"kopf": "\u{1D55C}",
"kscr": "\u{1D4C0}",
"lAtail": "\u291B",
"lBarr": "\u290E",
"lEg": "\u2A8B",
"lesseqqgtr": "\u2A8B",
"lHar": "\u2962",
"lacute": "\u013A",
"laemptyv": "\u29B4",
"lambda": "\u03BB",
"langd": "\u2991",
"lap": "\u2A85",
"lessapprox": "\u2A85",
"laquo": "\xAB",
"larrbfs": "\u291F",
"larrfs": "\u291D",
"larrlp": "\u21AB",
"looparrowleft": "\u21AB",
"larrpl": "\u2939",
"larrsim": "\u2973",
"larrtl": "\u21A2",
"leftarrowtail": "\u21A2",
"lat": "\u2AAB",
"latail": "\u2919",
"late": "\u2AAD",
"lates": "\u2AAD\uFE00",
"lbarr": "\u290C",
"lbbrk": "\u2772",
"lbrace": "{",
"lcub": "{",
"lbrack": "[",
"lsqb": "[",
"lbrke": "\u298B",
"lbrksld": "\u298F",
"lbrkslu": "\u298D",
"lcaron": "\u013E",
"lcedil": "\u013C",
"lcy": "\u043B",
"ldca": "\u2936",
"ldrdhar": "\u2967",
"ldrushar": "\u294B",
"ldsh": "\u21B2",
"le": "\u2264",
"leq": "\u2264",
"leftleftarrows": "\u21C7",
"llarr": "\u21C7",
"leftthreetimes": "\u22CB",
"lthree": "\u22CB",
"lescc": "\u2AA8",
"lesdot": "\u2A7F",
"lesdoto": "\u2A81",
"lesdotor": "\u2A83",
"lesg": "\u22DA\uFE00",
"lesges": "\u2A93",
"lessdot": "\u22D6",
"ltdot": "\u22D6",
"lfisht": "\u297C",
"lfr": "\u{1D529}",
"lgE": "\u2A91",
"lharul": "\u296A",
"lhblk": "\u2584",
"ljcy": "\u0459",
"llhard": "\u296B",
"lltri": "\u25FA",
"lmidot": "\u0140",
"lmoust": "\u23B0",
"lmoustache": "\u23B0",
"lnE": "\u2268",
"lneqq": "\u2268",
"lnap": "\u2A89",
"lnapprox": "\u2A89",
"lne": "\u2A87",
"lneq": "\u2A87",
"lnsim": "\u22E6",
"loang": "\u27EC",
"loarr": "\u21FD",
"longmapsto": "\u27FC",
"xmap": "\u27FC",
"looparrowright": "\u21AC",
"rarrlp": "\u21AC",
"lopar": "\u2985",
"lopf": "\u{1D55D}",
"loplus": "\u2A2D",
"lotimes": "\u2A34",
"lowast": "\u2217",
"loz": "\u25CA",
"lozenge": "\u25CA",
"lpar": "(",
"lparlt": "\u2993",
"lrhard": "\u296D",
"lrm": "\u200E",
"lrtri": "\u22BF",
"lsaquo": "\u2039",
"lscr": "\u{1D4C1}",
"lsime": "\u2A8D",
"lsimg": "\u2A8F",
"lsquor": "\u201A",
"sbquo": "\u201A",
"lstrok": "\u0142",
"ltcc": "\u2AA6",
"ltcir": "\u2A79",
"ltimes": "\u22C9",
"ltlarr": "\u2976",
"ltquest": "\u2A7B",
"ltrPar": "\u2996",
"ltri": "\u25C3",
"triangleleft": "\u25C3",
"lurdshar": "\u294A",
"luruhar": "\u2966",
"lvertneqq": "\u2268\uFE00",
"lvnE": "\u2268\uFE00",
"mDDot": "\u223A",
"macr": "\xAF",
"strns": "\xAF",
"male": "\u2642",
"malt": "\u2720",
"maltese": "\u2720",
"marker": "\u25AE",
"mcomma": "\u2A29",
"mcy": "\u043C",
"mdash": "\u2014",
"mfr": "\u{1D52A}",
"mho": "\u2127",
"micro": "\xB5",
"midcir": "\u2AF0",
"minus": "\u2212",
"minusdu": "\u2A2A",
"mlcp": "\u2ADB",
"models": "\u22A7",
"mopf": "\u{1D55E}",
"mscr": "\u{1D4C2}",
"mu": "\u03BC",
"multimap": "\u22B8",
"mumap": "\u22B8",
"nGg": "\u22D9\u0338",
"nGt": "\u226B\u20D2",
"nLeftarrow": "\u21CD",
"nlArr": "\u21CD",
"nLeftrightarrow": "\u21CE",
"nhArr": "\u21CE",
"nLl": "\u22D8\u0338",
"nLt": "\u226A\u20D2",
"nRightarrow": "\u21CF",
"nrArr": "\u21CF",
"nVDash": "\u22AF",
"nVdash": "\u22AE",
"nacute": "\u0144",
"nang": "\u2220\u20D2",
"napE": "\u2A70\u0338",
"napid": "\u224B\u0338",
"napos": "\u0149",
"natur": "\u266E",
"natural": "\u266E",
"ncap": "\u2A43",
"ncaron": "\u0148",
"ncedil": "\u0146",
"ncongdot": "\u2A6D\u0338",
"ncup": "\u2A42",
"ncy": "\u043D",
"ndash": "\u2013",
"neArr": "\u21D7",
"nearhk": "\u2924",
"nedot": "\u2250\u0338",
"nesear": "\u2928",
"toea": "\u2928",
"nfr": "\u{1D52B}",
"nharr": "\u21AE",
"nleftrightarrow": "\u21AE",
"nhpar": "\u2AF2",
"nis": "\u22FC",
"nisd": "\u22FA",
"njcy": "\u045A",
"nlE": "\u2266\u0338",
"nleqq": "\u2266\u0338",
"nlarr": "\u219A",
"nleftarrow": "\u219A",
"nldr": "\u2025",
"nopf": "\u{1D55F}",
"not": "\xAC",
"notinE": "\u22F9\u0338",
"notindot": "\u22F5\u0338",
"notinvb": "\u22F7",
"notinvc": "\u22F6",
"notnivb": "\u22FE",
"notnivc": "\u22FD",
"nparsl": "\u2AFD\u20E5",
"npart": "\u2202\u0338",
"npolint": "\u2A14",
"nrarr": "\u219B",
"nrightarrow": "\u219B",
"nrarrc": "\u2933\u0338",
"nrarrw": "\u219D\u0338",
"nscr": "\u{1D4C3}",
"nsub": "\u2284",
"nsubE": "\u2AC5\u0338",
"nsubseteqq": "\u2AC5\u0338",
"nsup": "\u2285",
"nsupE": "\u2AC6\u0338",
"nsupseteqq": "\u2AC6\u0338",
"ntilde": "\xF1",
"nu": "\u03BD",
"num": "#",
"numero": "\u2116",
"numsp": "\u2007",
"nvDash": "\u22AD",
"nvHarr": "\u2904",
"nvap": "\u224D\u20D2",
"nvdash": "\u22AC",
"nvge": "\u2265\u20D2",
"nvgt": ">\u20D2",
"nvinfin": "\u29DE",
"nvlArr": "\u2902",
"nvle": "\u2264\u20D2",
"nvlt": "<\u20D2",
"nvltrie": "\u22B4\u20D2",
"nvrArr": "\u2903",
"nvrtrie": "\u22B5\u20D2",
"nvsim": "\u223C\u20D2",
"nwArr": "\u21D6",
"nwarhk": "\u2923",
"nwnear": "\u2927",
"oacute": "\xF3",
"ocirc": "\xF4",
"ocy": "\u043E",
"odblac": "\u0151",
"odiv": "\u2A38",
"odsold": "\u29BC",
"oelig": "\u0153",
"ofcir": "\u29BF",
"ofr": "\u{1D52C}",
"ogon": "\u02DB",
"ograve": "\xF2",
"ogt": "\u29C1",
"ohbar": "\u29B5",
"olcir": "\u29BE",
"olcross": "\u29BB",
"olt": "\u29C0",
"omacr": "\u014D",
"omega": "\u03C9",
"omicron": "\u03BF",
"omid": "\u29B6",
"oopf": "\u{1D560}",
"opar": "\u29B7",
"operp": "\u29B9",
"or": "\u2228",
"vee": "\u2228",
"ord": "\u2A5D",
"order": "\u2134",
"orderof": "\u2134",
"oscr": "\u2134",
"ordf": "\xAA",
"ordm": "\xBA",
"origof": "\u22B6",
"oror": "\u2A56",
"orslope": "\u2A57",
"orv": "\u2A5B",
"oslash": "\xF8",
"osol": "\u2298",
"otilde": "\xF5",
"otimesas": "\u2A36",
"ouml": "\xF6",
"ovbar": "\u233D",
"para": "\xB6",
"parsim": "\u2AF3",
"parsl": "\u2AFD",
"pcy": "\u043F",
"percnt": "%",
"period": ".",
"permil": "\u2030",
"pertenk": "\u2031",
"pfr": "\u{1D52D}",
"phi": "\u03C6",
"phiv": "\u03D5",
"straightphi": "\u03D5",
"varphi": "\u03D5",
"phone": "\u260E",
"pi": "\u03C0",
"piv": "\u03D6",
"varpi": "\u03D6",
"planckh": "\u210E",
"plus": "+",
"plusacir": "\u2A23",
"pluscir": "\u2A22",
"plusdu": "\u2A25",
"pluse": "\u2A72",
"plussim": "\u2A26",
"plustwo": "\u2A27",
"pointint": "\u2A15",
"popf": "\u{1D561}",
"pound": "\xA3",
"prE": "\u2AB3",
"prap": "\u2AB7",
"precapprox": "\u2AB7",
"precnapprox": "\u2AB9",
"prnap": "\u2AB9",
"precneqq": "\u2AB5",
"prnE": "\u2AB5",
"precnsim": "\u22E8",
"prnsim": "\u22E8",
"prime": "\u2032",
"profalar": "\u232E",
"profline": "\u2312",
"profsurf": "\u2313",
"prurel": "\u22B0",
"pscr": "\u{1D4C5}",
"psi": "\u03C8",
"puncsp": "\u2008",
"qfr": "\u{1D52E}",
"qopf": "\u{1D562}",
"qprime": "\u2057",
"qscr": "\u{1D4C6}",
"quatint": "\u2A16",
"quest": "?",
"rAtail": "\u291C",
"rHar": "\u2964",
"race": "\u223D\u0331",
"racute": "\u0155",
"raemptyv": "\u29B3",
"rangd": "\u2992",
"range": "\u29A5",
"raquo": "\xBB",
"rarrap": "\u2975",
"rarrbfs": "\u2920",
"rarrc": "\u2933",
"rarrfs": "\u291E",
"rarrpl": "\u2945",
"rarrsim": "\u2974",
"rarrtl": "\u21A3",
"rightarrowtail": "\u21A3",
"rarrw": "\u219D",
"rightsquigarrow": "\u219D",
"ratail": "\u291A",
"ratio": "\u2236",
"rbbrk": "\u2773",
"rbrace": "}",
"rcub": "}",
"rbrack": "]",
"rsqb": "]",
"rbrke": "\u298C",
"rbrksld": "\u298E",
"rbrkslu": "\u2990",
"rcaron": "\u0159",
"rcedil": "\u0157",
"rcy": "\u0440",
"rdca": "\u2937",
"rdldhar": "\u2969",
"rdsh": "\u21B3",
"rect": "\u25AD",
"rfisht": "\u297D",
"rfr": "\u{1D52F}",
"rharul": "\u296C",
"rho": "\u03C1",
"rhov": "\u03F1",
"varrho": "\u03F1",
"rightrightarrows": "\u21C9",
"rrarr": "\u21C9",
"rightthreetimes": "\u22CC",
"rthree": "\u22CC",
"ring": "\u02DA",
"rlm": "\u200F",
"rmoust": "\u23B1",
"rmoustache": "\u23B1",
"rnmid": "\u2AEE",
"roang": "\u27ED",
"roarr": "\u21FE",
"ropar": "\u2986",
"ropf": "\u{1D563}",
"roplus": "\u2A2E",
"rotimes": "\u2A35",
"rpar": ")",
"rpargt": "\u2994",
"rppolint": "\u2A12",
"rsaquo": "\u203A",
"rscr": "\u{1D4C7}",
"rtimes": "\u22CA",
"rtri": "\u25B9",
"triangleright": "\u25B9",
"rtriltri": "\u29CE",
"ruluhar": "\u2968",
"rx": "\u211E",
"sacute": "\u015B",
"scE": "\u2AB4",
"scap": "\u2AB8",
"succapprox": "\u2AB8",
"scaron": "\u0161",
"scedil": "\u015F",
"scirc": "\u015D",
"scnE": "\u2AB6",
"succneqq": "\u2AB6",
"scnap": "\u2ABA",
"succnapprox": "\u2ABA",
"scnsim": "\u22E9",
"succnsim": "\u22E9",
"scpolint": "\u2A13",
"scy": "\u0441",
"sdot": "\u22C5",
"sdote": "\u2A66",
"seArr": "\u21D8",
"sect": "\xA7",
"semi": ";",
"seswar": "\u2929",
"tosa": "\u2929",
"sext": "\u2736",
"sfr": "\u{1D530}",
"sharp": "\u266F",
"shchcy": "\u0449",
"shcy": "\u0448",
"shy": "\xAD",
"sigma": "\u03C3",
"sigmaf": "\u03C2",
"sigmav": "\u03C2",
"varsigma": "\u03C2",
"simdot": "\u2A6A",
"simg": "\u2A9E",
"simgE": "\u2AA0",
"siml": "\u2A9D",
"simlE": "\u2A9F",
"simne": "\u2246",
"simplus": "\u2A24",
"simrarr": "\u2972",
"smashp": "\u2A33",
"smeparsl": "\u29E4",
"smile": "\u2323",
"ssmile": "\u2323",
"smt": "\u2AAA",
"smte": "\u2AAC",
"smtes": "\u2AAC\uFE00",
"softcy": "\u044C",
"sol": "/",
"solb": "\u29C4",
"solbar": "\u233F",
"sopf": "\u{1D564}",
"spades": "\u2660",
"spadesuit": "\u2660",
"sqcaps": "\u2293\uFE00",
"sqcups": "\u2294\uFE00",
"sscr": "\u{1D4C8}",
"star": "\u2606",
"sub": "\u2282",
"subset": "\u2282",
"subE": "\u2AC5",
"subseteqq": "\u2AC5",
"subdot": "\u2ABD",
"subedot": "\u2AC3",
"submult": "\u2AC1",
"subnE": "\u2ACB",
"subsetneqq": "\u2ACB",
"subne": "\u228A",
"subsetneq": "\u228A",
"subplus": "\u2ABF",
"subrarr": "\u2979",
"subsim": "\u2AC7",
"subsub": "\u2AD5",
"subsup": "\u2AD3",
"sung": "\u266A",
"sup1": "\xB9",
"sup2": "\xB2",
"sup3": "\xB3",
"supE": "\u2AC6",
"supseteqq": "\u2AC6",
"supdot": "\u2ABE",
"supdsub": "\u2AD8",
"supedot": "\u2AC4",
"suphsol": "\u27C9",
"suphsub": "\u2AD7",
"suplarr": "\u297B",
"supmult": "\u2AC2",
"supnE": "\u2ACC",
"supsetneqq": "\u2ACC",
"supne": "\u228B",
"supsetneq": "\u228B",
"supplus": "\u2AC0",
"supsim": "\u2AC8",
"supsub": "\u2AD4",
"supsup": "\u2AD6",
"swArr": "\u21D9",
"swnwar": "\u292A",
"szlig": "\xDF",
"target": "\u2316",
"tau": "\u03C4",
"tcaron": "\u0165",
"tcedil": "\u0163",
"tcy": "\u0442",
"telrec": "\u2315",
"tfr": "\u{1D531}",
"theta": "\u03B8",
"thetasym": "\u03D1",
"thetav": "\u03D1",
"vartheta": "\u03D1",
"thorn": "\xFE",
"times": "\xD7",
"timesbar": "\u2A31",
"timesd": "\u2A30",
"topbot": "\u2336",
"topcir": "\u2AF1",
"topf": "\u{1D565}",
"topfork": "\u2ADA",
"tprime": "\u2034",
"triangle": "\u25B5",
"utri": "\u25B5",
"triangleq": "\u225C",
"trie": "\u225C",
"tridot": "\u25EC",
"triminus": "\u2A3A",
"triplus": "\u2A39",
"trisb": "\u29CD",
"tritime": "\u2A3B",
"trpezium": "\u23E2",
"tscr": "\u{1D4C9}",
"tscy": "\u0446",
"tshcy": "\u045B",
"tstrok": "\u0167",
"uHar": "\u2963",
"uacute": "\xFA",
"ubrcy": "\u045E",
"ubreve": "\u016D",
"ucirc": "\xFB",
"ucy": "\u0443",
"udblac": "\u0171",
"ufisht": "\u297E",
"ufr": "\u{1D532}",
"ugrave": "\xF9",
"uhblk": "\u2580",
"ulcorn": "\u231C",
"ulcorner": "\u231C",
"ulcrop": "\u230F",
"ultri": "\u25F8",
"umacr": "\u016B",
"uogon": "\u0173",
"uopf": "\u{1D566}",
"upsi": "\u03C5",
"upsilon": "\u03C5",
"upuparrows": "\u21C8",
"uuarr": "\u21C8",
"urcorn": "\u231D",
"urcorner": "\u231D",
"urcrop": "\u230E",
"uring": "\u016F",
"urtri": "\u25F9",
"uscr": "\u{1D4CA}",
"utdot": "\u22F0",
"utilde": "\u0169",
"uuml": "\xFC",
"uwangle": "\u29A7",
"vBar": "\u2AE8",
"vBarv": "\u2AE9",
"vangrt": "\u299C",
"varsubsetneq": "\u228A\uFE00",
"vsubne": "\u228A\uFE00",
"varsubsetneqq": "\u2ACB\uFE00",
"vsubnE": "\u2ACB\uFE00",
"varsupsetneq": "\u228B\uFE00",
"vsupne": "\u228B\uFE00",
"varsupsetneqq": "\u2ACC\uFE00",
"vsupnE": "\u2ACC\uFE00",
"vcy": "\u0432",
"veebar": "\u22BB",
"veeeq": "\u225A",
"vellip": "\u22EE",
"vfr": "\u{1D533}",
"vopf": "\u{1D567}",
"vscr": "\u{1D4CB}",
"vzigzag": "\u299A",
"wcirc": "\u0175",
"wedbar": "\u2A5F",
"wedgeq": "\u2259",
"weierp": "\u2118",
"wp": "\u2118",
"wfr": "\u{1D534}",
"wopf": "\u{1D568}",
"wscr": "\u{1D4CC}",
"xfr": "\u{1D535}",
"xi": "\u03BE",
"xnis": "\u22FB",
"xopf": "\u{1D569}",
"xscr": "\u{1D4CD}",
"yacute": "\xFD",
"yacy": "\u044F",
"ycirc": "\u0177",
"ycy": "\u044B",
"yen": "\xA5",
"yfr": "\u{1D536}",
"yicy": "\u0457",
"yopf": "\u{1D56A}",
"yscr": "\u{1D4CE}",
"yucy": "\u044E",
"yuml": "\xFF",
"zacute": "\u017A",
"zcaron": "\u017E",
"zcy": "\u0437",
"zdot": "\u017C",
"zeta": "\u03B6",
"zfr": "\u{1D537}",
"zhcy": "\u0436",
"zigrarr": "\u21DD",
"zopf": "\u{1D56B}",
"zscr": "\u{1D4CF}",
"zwj": "\u200D",
"zwnj": "\u200C"
};
var NGSP_UNICODE = "\uE500";
NAMED_ENTITIES["ngsp"] = NGSP_UNICODE;
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/ml_parser/lexer.mjs
var TokenError = class extends ParseError {
constructor(errorMsg, tokenType, span) {
super(span, errorMsg);
this.tokenType = tokenType;
}
};
var TokenizeResult = class {
constructor(tokens, errors, nonNormalizedIcuExpressions) {
this.tokens = tokens;
this.errors = errors;
this.nonNormalizedIcuExpressions = nonNormalizedIcuExpressions;
}
};
function tokenize(source, url, getTagDefinition, options = {}) {
const tokenizer = new _Tokenizer(new ParseSourceFile(source, url), getTagDefinition, options);
tokenizer.tokenize();
return new TokenizeResult(mergeTextTokens(tokenizer.tokens), tokenizer.errors, tokenizer.nonNormalizedIcuExpressions);
}
var _CR_OR_CRLF_REGEXP = /\r\n?/g;
function _unexpectedCharacterErrorMsg(charCode) {
const char = charCode === $EOF ? "EOF" : String.fromCharCode(charCode);
return `Unexpected character "${char}"`;
}
function _unknownEntityErrorMsg(entitySrc) {
return `Unknown entity "${entitySrc}" - use the ";" or ";" syntax`;
}
function _unparsableEntityErrorMsg(type, entityStr) {
return `Unable to parse entity "${entityStr}" - ${type} character reference entities must end with ";"`;
}
var CharacterReferenceType;
(function(CharacterReferenceType2) {
CharacterReferenceType2["HEX"] = "hexadecimal";
CharacterReferenceType2["DEC"] = "decimal";
})(CharacterReferenceType || (CharacterReferenceType = {}));
var _ControlFlowError = class {
constructor(error) {
this.error = error;
}
};
var _Tokenizer = class {
constructor(_file, _getTagDefinition, options) {
var _a2, _b2;
this._getTagDefinition = _getTagDefinition;
this._currentTokenStart = null;
this._currentTokenType = null;
this._expansionCaseStack = [];
this._inInterpolation = false;
this.tokens = [];
this.errors = [];
this.nonNormalizedIcuExpressions = [];
this._tokenizeIcu = options.tokenizeExpansionForms || false;
this._interpolationConfig = options.interpolationConfig || DEFAULT_INTERPOLATION_CONFIG;
this._leadingTriviaCodePoints = options.leadingTriviaChars && options.leadingTriviaChars.map((c) => c.codePointAt(0) || 0);
const 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;
this._i18nNormalizeLineEndingsInICUs = options.i18nNormalizeLineEndingsInICUs || false;
this._tokenizeBlocks = (_a2 = options.tokenizeBlocks) != null ? _a2 : true;
this._tokenizeLet = (_b2 = options.tokenizeLet) != null ? _b2 : true;
try {
this._cursor.init();
} catch (e) {
this.handleError(e);
}
}
_processCarriageReturns(content) {
if (this._preserveLineEndings) {
return content;
}
return content.replace(_CR_OR_CRLF_REGEXP, "\n");
}
tokenize() {
while (this._cursor.peek() !== $EOF) {
const 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._tokenizeLet && this._cursor.peek() === $AT && !this._inInterpolation && this._attemptStr("@let")) {
this._consumeLetDeclaration(start);
} else if (this._tokenizeBlocks && this._attemptCharCode($AT)) {
this._consumeBlockStart(start);
} else if (this._tokenizeBlocks && !this._inInterpolation && !this._isInExpansionCase() && !this._isInExpansionForm() && this._attemptCharCode($RBRACE)) {
this._consumeBlockEnd(start);
} else if (!(this._tokenizeIcu && this._tokenizeExpansionForm())) {
this._consumeWithInterpolation(5, 8, () => this._isTextEnd(), () => this._isTagStart());
}
} catch (e) {
this.handleError(e);
}
}
this._beginToken(33);
this._endToken([]);
}
_getBlockName() {
let spacesInNameAllowed = false;
const nameCursor = this._cursor.clone();
this._attemptCharCodeUntilFn((code) => {
if (isWhitespace(code)) {
return !spacesInNameAllowed;
}
if (isBlockNameChar(code)) {
spacesInNameAllowed = true;
return false;
}
return true;
});
return this._cursor.getChars(nameCursor).trim();
}
_consumeBlockStart(start) {
this._beginToken(24, start);
const startToken = this._endToken([this._getBlockName()]);
if (this._cursor.peek() === $LPAREN) {
this._cursor.advance();
this._consumeBlockParameters();
this._attemptCharCodeUntilFn(isNotWhitespace);
if (this._attemptCharCode($RPAREN)) {
this._attemptCharCodeUntilFn(isNotWhitespace);
} else {
startToken.type = 28;
return;
}
}
if (this._attemptCharCode($LBRACE)) {
this._beginToken(25);
this._endToken([]);
} else {
startToken.type = 28;
}
}
_consumeBlockEnd(start) {
this._beginToken(26, start);
this._endToken([]);
}
_consumeBlockParameters() {
this._attemptCharCodeUntilFn(isBlockParameterChar);
while (this._cursor.peek() !== $RPAREN && this._cursor.peek() !== $EOF) {
this._beginToken(27);
const start = this._cursor.clone();
let inQuote = null;
let openParens = 0;
while (this._cursor.peek() !== $SEMICOLON && this._cursor.peek() !== $EOF || inQuote !== null) {
const char = this._cursor.peek();
if (char === $BACKSLASH) {
this._cursor.advance();
} else if (char === inQuote) {
inQuote = null;
} else if (inQuote === null && isQuote(char)) {
inQuote = char;
} else if (char === $LPAREN && inQuote === null) {
openParens++;
} else if (char === $RPAREN && inQuote === null) {
if (openParens === 0) {
break;
} else if (openParens > 0) {
openParens--;
}
}
this._cursor.advance();
}
this._endToken([this._cursor.getChars(start)]);
this._attemptCharCodeUntilFn(isBlockParameterChar);
}
}
_consumeLetDeclaration(start) {
this._beginToken(29, start);
if (isWhitespace(this._cursor.peek())) {
this._attemptCharCodeUntilFn(isNotWhitespace);
} else {
const token = this._endToken([this._cursor.getChars(start)]);
token.type = 32;
return;
}
const startToken = this._endToken([this._getLetDeclarationName()]);
this._attemptCharCodeUntilFn(isNotWhitespace);
if (!this._attemptCharCode($EQ)) {
startToken.type = 32;
return;
}
this._attemptCharCodeUntilFn((code) => isNotWhitespace(code) && !isNewLine(code));
this._consumeLetDeclarationValue();
const endChar = this._cursor.peek();
if (endChar === $SEMICOLON) {
this._beginToken(31);
this._endToken([]);
this._cursor.advance();
} else {
startToken.type = 32;
startToken.sourceSpan = this._cursor.getSpan(start);
}
}
_getLetDeclarationName() {
const nameCursor = this._cursor.clone();
let allowDigit = false;
this._attemptCharCodeUntilFn((code) => {
if (isAsciiLetter(code) || code === $$ || code === $_ || allowDigit && isDigit(code)) {
allowDigit = true;
return false;
}
return true;
});
return this._cursor.getChars(nameCursor).trim();
}
_consumeLetDeclarationValue() {
const start = this._cursor.clone();
this._beginToken(30, start);
while (this._cursor.peek() !== $EOF) {
const char = this._cursor.peek();
if (char === $SEMICOLON) {
break;
}
if (isQuote(char)) {
this._cursor.advance();
this._attemptCharCodeUntilFn((inner) => {
if (inner === $BACKSLASH) {
this._cursor.advance();
return false;
}
return inner === char;
});
}
this._cursor.advance();
}
this._endToken([this._cursor.getChars(start)]);
}
_tokenizeExpansionForm() {
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;
}
_beginToken(type, start = this._cursor.clone()) {
this._currentTokenStart = start;
this._currentTokenType = type;
}
_endToken(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));
}
const token = {
type: this._currentTokenType,
parts,
sourceSpan: (end != null ? end : this._cursor).getSpan(this._currentTokenStart, this._leadingTriviaCodePoints)
};
this.tokens.push(token);
this._currentTokenStart = null;
this._currentTokenType = null;
return token;
}
_createError(msg, span) {
if (this._isInExpansionForm()) {
msg += ` (Do you have an unescaped "{" in your template? Use "{{ '{' }}") to escape it.)`;
}
const error = new TokenError(msg, this._currentTokenType, span);
this._currentTokenStart = null;
this._currentTokenType = null;
return new _ControlFlowError(error);
}
handleError(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;
}
}
_attemptCharCode(charCode) {
if (this._cursor.peek() === charCode) {
this._cursor.advance();
return true;
}
return false;
}
_attemptCharCodeCaseInsensitive(charCode) {
if (compareCharCodeCaseInsensitive(this._cursor.peek(), charCode)) {
this._cursor.advance();
return true;
}
return false;
}
_requireCharCode(charCode) {
const location = this._cursor.clone();
if (!this._attemptCharCode(charCode)) {
throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(location));
}
}
_attemptStr(chars2) {
const len = chars2.length;
if (this._cursor.charsLeft() < len) {
return false;
}
const initialPosition = this._cursor.clone();
for (let i = 0; i < len; i++) {
if (!this._attemptCharCode(chars2.charCodeAt(i))) {
this._cursor = initialPosition;
return false;
}
}
return true;
}
_attemptStrCaseInsensitive(chars2) {
for (let i = 0; i < chars2.length; i++) {
if (!this._attemptCharCodeCaseInsensitive(chars2.charCodeAt(i))) {
return false;
}
}
return true;
}
_requireStr(chars2) {
const location = this._cursor.clone();
if (!this._attemptStr(chars2)) {
throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(location));
}
}
_attemptCharCodeUntilFn(predicate) {
while (!predicate(this._cursor.peek())) {
this._cursor.advance();
}
}
_requireCharCodeUntilFn(predicate, len) {
const start = this._cursor.clone();
this._attemptCharCodeUntilFn(predicate);
if (this._cursor.diff(start) < len) {
throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(start));
}
}
_attemptUntilChar(char) {
while (this._cursor.peek() !== char) {
this._cursor.advance();
}
}
_readChar() {
const char = String.fromCodePoint(this._cursor.peek());
this._cursor.advance();
return char;
}
_consumeEntity(textTokenType) {
this._beginToken(9);
const start = this._cursor.clone();
this._cursor.advance();
if (this._attemptCharCode($HASH)) {
const isHex = this._attemptCharCode($x) || this._attemptCharCode($X);
const codeStart = this._cursor.clone();
this._attemptCharCodeUntilFn(isDigitEntityEnd);
if (this._cursor.peek() != $SEMICOLON) {
this._cursor.advance();
const entityType = isHex ? CharacterReferenceType.HEX : CharacterReferenceType.DEC;
throw this._createError(_unparsableEntityErrorMsg(entityType, this._cursor.getChars(start)), this._cursor.getSpan());
}
const strNum = this._cursor.getChars(codeStart);
this._cursor.advance();
try {
const charCode = parseInt(strNum, isHex ? 16 : 10);
this._endToken([String.fromCharCode(charCode), this._cursor.getChars(start)]);
} catch (e) {
throw this._createError(_unknownEntityErrorMsg(this._cursor.getChars(start)), this._cursor.getSpan());
}
} else {
const nameStart = this._cursor.clone();
this._attemptCharCodeUntilFn(isNamedEntityEnd);
if (this._cursor.peek() != $SEMICOLON) {
this._beginToken(textTokenType, start);
this._cursor = nameStart;
this._endToken(["&"]);
} else {
const name = this._cursor.getChars(nameStart);
this._cursor.advance();
const char = NAMED_ENTITIES[name];
if (!char) {
throw this._createError(_unknownEntityErrorMsg(name), this._cursor.getSpan(start));
}
this._endToken([char, `&${name};`]);
}
}
}
_consumeRawText(consumeEntities, endMarkerPredicate) {
this._beginToken(consumeEntities ? 6 : 7);
const parts = [];
while (true) {
const tagCloseStart = this._cursor.clone();
const foundEndMarker = endMarkerPredicate();
this._cursor = tagCloseStart;
if (foundEndMarker) {
break;
}
if (consumeEntities && this._cursor.peek() === $AMPERSAND) {
this._endToken([this._processCarriageReturns(parts.join(""))]);
parts.length = 0;
this._consumeEntity(6);
this._beginToken(6);
} else {
parts.push(this._readChar());
}
}
this._endToken([this._processCarriageReturns(parts.join(""))]);
}
_consumeComment(start) {
this._beginToken(10, start);
this._requireCharCode($MINUS);
this._endToken([]);
this._consumeRawText(false, () => this._attemptStr("-->"));
this._beginToken(11);
this._requireStr("-->");
this._endToken([]);
}
_consumeCdata(start) {
this._beginToken(12, start);
this._requireStr("CDATA[");
this._endToken([]);
this._consumeRawText(false, () => this._attemptStr("]]>"));
this._beginToken(13);
this._requireStr("]]>");
this._endToken([]);
}
_consumeDocType(start) {
this._beginToken(18, start);
const contentStart = this._cursor.clone();
this._attemptUntilChar($GT);
const content = this._cursor.getChars(contentStart);
this._cursor.advance();
this._endToken([content]);
}
_consumePrefixAndName() {
const nameOrPrefixStart = this._cursor.clone();
let prefix = "";
while (this._cursor.peek() !== $COLON && !isPrefixEnd(this._cursor.peek())) {
this._cursor.advance();
}
let 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);
const name = this._cursor.getChars(nameStart);
return [prefix, name];
}
_consumeTagOpen(start) {
let tagName;
let prefix;
let openTagToken;
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._cursor.peek() !== $LT && this._cursor.peek() !== $EOF) {
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) {
if (openTagToken) {
openTagToken.type = 4;
} else {
this._beginToken(5, start);
this._endToken(["<"]);
}
return;
}
throw e;
}
const contentTokenType = this._getTagDefinition(tagName).getContentType(prefix);
if (contentTokenType === TagContentType.RAW_TEXT) {
this._consumeRawTextWithTagClose(prefix, tagName, false);
} else if (contentTokenType === TagContentType.ESCAPABLE_RAW_TEXT) {
this._consumeRawTextWithTagClose(prefix, tagName, true);
}
}
_consumeRawTextWithTagClose(prefix, tagName, consumeEntities) {
this._consumeRawText(consumeEntities, () => {
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(3);
this._requireCharCodeUntilFn((code) => code === $GT, 3);
this._cursor.advance();
this._endToken([prefix, tagName]);
}
_consumeTagOpenStart(start) {
this._beginToken(0, start);
const parts = this._consumePrefixAndName();
return this._endToken(parts);
}
_consumeAttributeName() {
const attrNameStart = this._cursor.peek();
if (attrNameStart === $SQ || attrNameStart === $DQ) {
throw this._createError(_unexpectedCharacterErrorMsg(attrNameStart), this._cursor.getSpan());
}
this._beginToken(14);
const prefixAndName = this._consumePrefixAndName();
this._endToken(prefixAndName);
}
_consumeAttributeValue() {
if (this._cursor.peek() === $SQ || this._cursor.peek() === $DQ) {
const quoteChar = this._cursor.peek();
this._consumeQuote(quoteChar);
const endPredicate = () => this._cursor.peek() === quoteChar;
this._consumeWithInterpolation(16, 17, endPredicate, endPredicate);
this._consumeQuote(quoteChar);
} else {
const endPredicate = () => isNameEnd(this._cursor.peek());
this._consumeWithInterpolation(16, 17, endPredicate, endPredicate);
}
}
_consumeQuote(quoteChar) {
this._beginToken(15);
this._requireCharCode(quoteChar);
this._endToken([String.fromCodePoint(quoteChar)]);
}
_consumeTagOpenEnd() {
const tokenType = this._attemptCharCode($SLASH) ? 2 : 1;
this._beginToken(tokenType);
this._requireCharCode($GT);
this._endToken([]);
}
_consumeTagClose(start) {
this._beginToken(3, start);
this._attemptCharCodeUntilFn(isNotWhitespace);
const prefixAndName = this._consumePrefixAndName();
this._attemptCharCodeUntilFn(isNotWhitespace);
this._requireCharCode($GT);
this._endToken(prefixAndName);
}
_consumeExpansionFormStart() {
this._beginToken(19);
this._requireCharCode($LBRACE);
this._endToken([]);
this._expansionCaseStack.push(19);
this._beginToken(7);
const condition = this._readUntil($COMMA);
const normalizedCondition = this._processCarriageReturns(condition);
if (this._i18nNormalizeLineEndingsInICUs) {
this._endToken([normalizedCondition]);
} else {
const conditionToken = this._endToken([condition]);
if (normalizedCondition !== condition) {
this.nonNormalizedIcuExpressions.push(conditionToken);
}
}
this._requireCharCode($COMMA);
this._attemptCharCodeUntilFn(isNotWhitespace);
this._beginToken(7);
const type = this._readUntil($COMMA);
this._endToken([type]);
this._requireCharCode($COMMA);
this._attemptCharCodeUntilFn(isNotWhitespace);
}
_consumeExpansionCaseStart() {
this._beginToken(20);
const value = this._readUntil($LBRACE).trim();
this._endToken([value]);
this._attemptCharCodeUntilFn(isNotWhitespace);
this._beginToken(21);
this._requireCharCode($LBRACE);
this._endToken([]);
this._attemptCharCodeUntilFn(isNotWhitespace);
this._expansionCaseStack.push(21);
}
_consumeExpansionCaseEnd() {
this._beginToken(22);
this._requireCharCode($RBRACE);
this._endToken([]);
this._attemptCharCodeUntilFn(isNotWhitespace);
this._expansionCaseStack.pop();
}
_consumeExpansionFormEnd() {
this._beginToken(23);
this._requireCharCode($RBRACE);
this._endToken([]);
this._expansionCaseStack.pop();
}
_consumeWithInterpolation(textTokenType, interpolationTokenType, endPredicate, endInterpolation) {
this._beginToken(textTokenType);
const parts = [];
while (!endPredicate()) {
const current = this._cursor.clone();
if (this._interpolationConfig && this._attemptStr(this._interpolationConfig.start)) {
this._endToken([this._processCarriageReturns(parts.join(""))], current);
parts.length = 0;
this._consumeInterpolation(interpolationTokenType, current, endInterpolation);
this._beginToken(textTokenType);
} else if (this._cursor.peek() === $AMPERSAND) {
this._endToken([this._processCarriageReturns(parts.join(""))]);
parts.length = 0;
this._consumeEntity(textTokenType);
this._beginToken(textTokenType);
} else {
parts.push(this._readChar());
}
}
this._inInterpolation = false;
this._endToken([this._processCarriageReturns(parts.join(""))]);
}
_consumeInterpolation(interpolationTokenType, interpolationStart, prematureEndPredicate) {
const parts = [];
this._beginToken(interpolationTokenType, interpolationStart);
parts.push(this._interpolationConfig.start);
const expressionStart = this._cursor.clone();
let inQuote = null;
let inComment = false;
while (this._cursor.peek() !== $EOF && (prematureEndPredicate === null || !prematureEndPredicate())) {
const current = this._cursor.clone();
if (this._isTagStart()) {
this._cursor = current;
parts.push(this._getProcessedChars(expressionStart, current));
this._endToken(parts);
return;
}
if (inQuote === null) {
if (this._attemptStr(this._interpolationConfig.end)) {
parts.push(this._getProcessedChars(expressionStart, current));
parts.push(this._interpolationConfig.end);
this._endToken(parts);
return;
} else if (this._attemptStr("//")) {
inComment = true;
}
}
const char = this._cursor.peek();
this._cursor.advance();
if (char === $BACKSLASH) {
this._cursor.advance();
} else if (char === inQuote) {
inQuote = null;
} else if (!inComment && inQuote === null && isQuote(char)) {
inQuote = char;
}
}
parts.push(this._getProcessedChars(expressionStart, this._cursor));
this._endToken(parts);
}
_getProcessedChars(start, end) {
return this._processCarriageReturns(end.getChars(start));
}
_isTextEnd() {
if (this._isTagStart() || this._cursor.peek() === $EOF) {
return true;
}
if (this._tokenizeIcu && !this._inInterpolation) {
if (this.isExpansionFormStart()) {
return true;
}
if (this._cursor.peek() === $RBRACE && this._isInExpansionCase()) {
return true;
}
}
if (this._tokenizeBlocks && !this._inInterpolation && !this._isInExpansion() && (this._cursor.peek() === $AT || this._cursor.peek() === $RBRACE)) {
return true;
}
return false;
}
_isTagStart() {
if (this._cursor.peek() === $LT) {
const tmp = this._cursor.clone();
tmp.advance();
const code = tmp.peek();
if ($a <= code && code <= $z || $A <= code && code <= $Z || code === $SLASH || code === $BANG) {
return true;
}
}
return false;
}
_readUntil(char) {
const start = this._cursor.clone();
this._attemptUntilChar(char);
return this._cursor.getChars(start);
}
_isInExpansion() {
return this._isInExpansionCase() || this._isInExpansionForm();
}
_isInExpansionCase() {
return this._expansionCaseStack.length > 0 && this._expansionCaseStack[this._expansionCaseStack.length - 1] === 21;
}
_isInExpansionForm() {
return this._expansionCaseStack.length > 0 && this._expansionCaseStack[this._expansionCaseStack.length - 1] === 19;
}
isExpansionFormStart() {
if (this._cursor.peek() !== $LBRACE) {
return false;
}
if (this._interpolationConfig) {
const start = this._cursor.clone();
const isInterpolation = this._attemptStr(this._interpolationConfig.start);
this._cursor = start;
return !isInterpolation;
}
return true;
}
};
function isNotWhitespace(code) {
return !isWhitespace(code) || code === $EOF;
}
function isNameEnd(code) {
return isWhitespace(code) || code === $GT || code === $LT || code === $SLASH || code === $SQ || code === $DQ || code === $EQ || code === $EOF;
}
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 !== $RBRACE;
}
function compareCharCodeCaseInsensitive(code1, code2) {
return toUpperCaseCharCode(code1) === toUpperCaseCharCode(code2);
}
function toUpperCaseCharCode(code) {
return code >= $a && code <= $z ? code - $a + $A : code;
}
function isBlockNameChar(code) {
return isAsciiLetter(code) || isDigit(code) || code === $_;
}
function isBlockParameterChar(code) {
return code !== $SEMICOLON && isNotWhitespace(code);
}
function mergeTextTokens(srcTokens) {
const dstTokens = [];
let lastDstToken = void 0;
for (let i = 0; i < srcTokens.length; i++) {
const token = srcTokens[i];
if (lastDstToken && lastDstToken.type === 5 && token.type === 5 || lastDstToken && lastDstToken.type === 16 && token.type === 16) {
lastDstToken.parts[0] += token.parts[0];
lastDstToken.sourceSpan.end = token.sourceSpan.end;
} else {
lastDstToken = token;
dstTokens.push(lastDstToken);
}
}
return dstTokens;
}
var PlainCharacterCursor = class {
constructor(fileOrCursor, range) {
if (fileOrCursor instanceof PlainCharacterCursor) {
this.file = fileOrCursor.file;
this.input = fileOrCursor.input;
this.end = fileOrCursor.end;
const state = fileOrCursor.state;
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
};
}
}
clone() {
return new PlainCharacterCursor(this);
}
peek() {
return this.state.peek;
}
charsLeft() {
return this.end - this.state.offset;
}
diff(other) {
return this.state.offset - other.state.offset;
}
advance() {
this.advanceState(this.state);
}
init() {
this.updatePeek(this.state);
}
getSpan(start, leadingTriviaCodePoints) {
start = start || this;
let fullStart = start;
if (leadingTriviaCodePoints) {
while (this.diff(start) > 0 && leadingTriviaCodePoints.indexOf(start.peek()) !== -1) {
if (fullStart === start) {
start = start.clone();
}
start.advance();
}
}
const startLocation = this.locationFromCursor(start);
const endLocation = this.locationFromCursor(this);
const fullStartLocation = fullStart !== start ? this.locationFromCursor(fullStart) : startLocation;
return new ParseSourceSpan(startLocation, endLocation, fullStartLocation);
}
getChars(start) {
return this.input.substring(start.state.offset, this.state.offset);
}
charAt(pos) {
return this.input.charCodeAt(pos);
}
advanceState(state) {
if (state.offset >= this.end) {
this.state = state;
throw new CursorError('Unexpected character "EOF"', this);
}
const currentChar = this.charAt(state.offset);
if (currentChar === $LF) {
state.line++;
state.column = 0;
} else if (!isNewLine(currentChar)) {
state.column++;
}
state.offset++;
this.updatePeek(state);
}
updatePeek(state) {
state.peek = state.offset >= this.end ? $EOF : this.charAt(state.offset);
}
locationFromCursor(cursor) {
return new ParseLocation(cursor.file, cursor.state.offset, cursor.state.line, cursor.state.column);
}
};
var EscapedCharacterCursor = class extends PlainCharacterCursor {
constructor(fileOrCursor, range) {
if (fileOrCursor instanceof EscapedCharacterCursor) {
super(fileOrCursor);
this.internalState = __spreadValues({}, fileOrCursor.internalState);
} else {
super(fileOrCursor, range);
this.internalState = this.state;
}
}
advance() {
this.state = this.internalState;
super.advance();
this.processEscapeSequence();
}
init() {
super.init();
this.processEscapeSequence();
}
clone() {
return new EscapedCharacterCursor(this);
}
getChars(start) {
const cursor = start.clone();
let chars2 = "";
while (cursor.internalState.offset < this.internalState.offset) {
chars2 += String.fromCodePoint(cursor.peek());
cursor.advance();
}
return chars2;
}
processEscapeSequence() {
const peek = () => this.internalState.peek;
if (peek() === $BACKSLASH) {
this.internalState = __spreadValues({}, this.state);
this.advanceState(this.internalState);
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;
} else if (peek() === $u) {
this.advanceState(this.internalState);
if (peek() === $LBRACE) {
this.advanceState(this.internalState);
const digitStart = this.clone();
let length = 0;
while (peek() !== $RBRACE) {
this.advanceState(this.internalState);
length++;
}
this.state.peek = this.decodeHexDigits(digitStart, length);
} else {
const 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) {
this.advanceState(this.internalState);
const digitStart = this.clone();
this.advanceState(this.internalState);
this.state.peek = this.decodeHexDigits(digitStart, 2);
} else if (isOctalDigit(peek())) {
let octal = "";
let length = 0;
let previous = this.clone();
while (isOctalDigit(peek()) && length < 3) {
previous = this.clone();
octal += String.fromCodePoint(peek());
this.advanceState(this.internalState);
length++;
}
this.state.peek = parseInt(octal, 8);
this.internalState = previous.internalState;
} else if (isNewLine(this.internalState.peek)) {
this.advanceState(this.internalState);
this.state = this.internalState;
} else {
this.state.peek = this.internalState.peek;
}
}
}
decodeHexDigits(start, length) {
const hex = this.input.slice(start.internalState.offset, start.internalState.offset + length);
const charCode = parseInt(hex, 16);
if (!isNaN(charCode)) {
return charCode;
} else {
start.state = start.internalState;
throw new CursorError("Invalid hexadecimal escape sequence", start);
}
}
};
var CursorError = class {
constructor(msg, cursor) {
this.msg = msg;
this.cursor = cursor;
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/ml_parser/parser.mjs
var TreeError = class extends ParseError {
static create(elementName, span, msg) {
return new TreeError(elementName, span, msg);
}
constructor(elementName, span, msg) {
super(span, msg);
this.elementName = elementName;
}
};
var ParseTreeResult = class {
constructor(rootNodes, errors) {
this.rootNodes = rootNodes;
this.errors = errors;
}
};
var Parser = class {
constructor(getTagDefinition) {
this.getTagDefinition = getTagDefinition;
}
parse(source, url, options) {
const tokenizeResult = tokenize(source, url, this.getTagDefinition, options);
const parser = new _TreeBuilder(tokenizeResult.tokens, this.getTagDefinition);
parser.build();
return new ParseTreeResult(parser.rootNodes, tokenizeResult.errors.concat(parser.errors));
}
};
var _TreeBuilder = class {
constructor(tokens, getTagDefinition) {
this.tokens = tokens;
this.getTagDefinition = getTagDefinition;
this._index = -1;
this._containerStack = [];
this.rootNodes = [];
this.errors = [];
this._advance();
}
build() {
while (this._peek.type !== 33) {
if (this._peek.type === 0 || this._peek.type === 4) {
this._consumeStartTag(this._advance());
} else if (this._peek.type === 3) {
this._consumeEndTag(this._advance());
} else if (this._peek.type === 12) {
this._closeVoidElement();
this._consumeCdata(this._advance());
} else if (this._peek.type === 10) {
this._closeVoidElement();
this._consumeComment(this._advance());
} else if (this._peek.type === 5 || this._peek.type === 7 || this._peek.type === 6) {
this._closeVoidElement();
this._consumeText(this._advance());
} else if (this._peek.type === 19) {
this._consumeExpansion(this._advance());
} else if (this._peek.type === 24) {
this._closeVoidElement();
this._consumeBlockOpen(this._advance());
} else if (this._peek.type === 26) {
this._closeVoidElement();
this._consumeBlockClose(this._advance());
} else if (this._peek.type === 28) {
this._closeVoidElement();
this._consumeIncompleteBlock(this._advance());
} else if (this._peek.type === 29) {
this._closeVoidElement();
this._consumeLet(this._advance());
} else if (this._peek.type === 32) {
this._closeVoidElement();
this._consumeIncompleteLet(this._advance());
} else {
this._advance();
}
}
for (const leftoverContainer of this._containerStack) {
if (leftoverContainer instanceof Block) {
this.errors.push(TreeError.create(leftoverContainer.name, leftoverContainer.sourceSpan, `Unclosed block "${leftoverContainer.name}"`));
}
}
}
_advance() {
const prev = this._peek;
if (this._index < this.tokens.length - 1) {
this._index++;
}
this._peek = this.tokens[this._index];
return prev;
}
_advanceIf(type) {
if (this._peek.type === type) {
return this._advance();
}
return null;
}
_consumeCdata(_startToken) {
this._consumeText(this._advance());
this._advanceIf(13);
}
_consumeComment(token) {
const text2 = this._advanceIf(7);
const endToken = this._advanceIf(11);
const value = text2 != null ? text2.parts[0].trim() : null;
const sourceSpan = endToken == null ? token.sourceSpan : new ParseSourceSpan(token.sourceSpan.start, endToken.sourceSpan.end, token.sourceSpan.fullStart);
this._addToParent(new Comment2(value, sourceSpan));
}
_consumeExpansion(token) {
const switchValue = this._advance();
const type = this._advance();
const cases = [];
while (this._peek.type === 20) {
const expCase = this._parseExpansionCase();
if (!expCase)
return;
cases.push(expCase);
}
if (this._peek.type !== 23) {
this.errors.push(TreeError.create(null, this._peek.sourceSpan, `Invalid ICU message. Missing '}'.`));
return;
}
const sourceSpan = new ParseSourceSpan(token.sourceSpan.start, this._peek.sourceSpan.end, token.sourceSpan.fullStart);
this._addToParent(new Expansion(switchValue.parts[0], type.parts[0], cases, sourceSpan, switchValue.sourceSpan));
this._advance();
}
_parseExpansionCase() {
const value = this._advance();
if (this._peek.type !== 21) {
this.errors.push(TreeError.create(null, this._peek.sourceSpan, `Invalid ICU message. Missing '{'.`));
return null;
}
const start = this._advance();
const exp = this._collectExpansionExpTokens(start);
if (!exp)
return null;
const end = this._advance();
exp.push({ type: 33, parts: [], sourceSpan: end.sourceSpan });
const expansionCaseParser = new _TreeBuilder(exp, this.getTagDefinition);
expansionCaseParser.build();
if (expansionCaseParser.errors.length > 0) {
this.errors = this.errors.concat(expansionCaseParser.errors);
return null;
}
const sourceSpan = new ParseSourceSpan(value.sourceSpan.start, end.sourceSpan.end, value.sourceSpan.fullStart);
const expSourceSpan = new ParseSourceSpan(start.sourceSpan.start, end.sourceSpan.end, start.sourceSpan.fullStart);
return new ExpansionCase(value.parts[0], expansionCaseParser.rootNodes, sourceSpan, value.sourceSpan, expSourceSpan);
}
_collectExpansionExpTokens(start) {
const exp = [];
const expansionFormStack = [21];
while (true) {
if (this._peek.type === 19 || this._peek.type === 21) {
expansionFormStack.push(this._peek.type);
}
if (this._peek.type === 22) {
if (lastOnStack(expansionFormStack, 21)) {
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 === 23) {
if (lastOnStack(expansionFormStack, 19)) {
expansionFormStack.pop();
} else {
this.errors.push(TreeError.create(null, start.sourceSpan, `Invalid ICU message. Missing '}'.`));
return null;
}
}
if (this._peek.type === 33) {
this.errors.push(TreeError.create(null, start.sourceSpan, `Invalid ICU message. Missing '}'.`));
return null;
}
exp.push(this._advance());
}
}
_consumeText(token) {
const tokens = [token];
const startSpan = token.sourceSpan;
let text2 = token.parts[0];
if (text2.length > 0 && text2[0] === "\n") {
const parent = this._getContainer();
if (parent != null && parent.children.length === 0 && this.getTagDefinition(parent.name).ignoreFirstLf) {
text2 = text2.substring(1);
tokens[0] = { type: token.type, sourceSpan: token.sourceSpan, parts: [text2] };
}
}
while (this._peek.type === 8 || this._peek.type === 5 || this._peek.type === 9) {
token = this._advance();
tokens.push(token);
if (token.type === 8) {
text2 += token.parts.join("").replace(/&([^;]+);/g, decodeEntity);
} else if (token.type === 9) {
text2 += token.parts[0];
} else {
text2 += token.parts.join("");
}
}
if (text2.length > 0) {
const endSpan = token.sourceSpan;
this._addToParent(new Text4(text2, new ParseSourceSpan(startSpan.start, endSpan.end, startSpan.fullStart, startSpan.details), tokens));
}
}
_closeVoidElement() {
const el = this._getContainer();
if (el instanceof Element2 && this.getTagDefinition(el.name).isVoid) {
this._containerStack.pop();
}
}
_consumeStartTag(startTagToken) {
const [prefix, name] = startTagToken.parts;
const attrs = [];
while (this._peek.type === 14) {
attrs.push(this._consumeAttr(this._advance()));
}
const fullName = this._getElementFullName(prefix, name, this._getClosestParentElement());
let selfClosing = false;
if (this._peek.type === 2) {
this._advance();
selfClosing = true;
const tagDef = this.getTagDefinition(fullName);
if (!(tagDef.canSelfClose || getNsPrefix(fullName) !== null || tagDef.isVoid)) {
this.errors.push(TreeError.create(fullName, startTagToken.sourceSpan, `Only void, custom and foreign elements can be self closed "${startTagToken.parts[1]}"`));
}
} else if (this._peek.type === 1) {
this._advance();
selfClosing = false;
}
const end = this._peek.sourceSpan.fullStart;
const span = new ParseSourceSpan(startTagToken.sourceSpan.start, end, startTagToken.sourceSpan.fullStart);
const startSpan = new ParseSourceSpan(startTagToken.sourceSpan.start, end, startTagToken.sourceSpan.fullStart);
const el = new Element2(fullName, attrs, [], span, startSpan, void 0);
const parentEl = this._getContainer();
this._pushContainer(el, parentEl instanceof Element2 && this.getTagDefinition(parentEl.name).isClosedByChild(el.name));
if (selfClosing) {
this._popContainer(fullName, Element2, span);
} else if (startTagToken.type === 4) {
this._popContainer(fullName, Element2, null);
this.errors.push(TreeError.create(fullName, span, `Opening tag "${fullName}" not terminated.`));
}
}
_pushContainer(node, isClosedByChild) {
if (isClosedByChild) {
this._containerStack.pop();
}
this._addToParent(node);
this._containerStack.push(node);
}
_consumeEndTag(endTagToken) {
const fullName = this._getElementFullName(endTagToken.parts[0], endTagToken.parts[1], this._getClosestParentElement());
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._popContainer(fullName, Element2, endTagToken.sourceSpan)) {
const 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));
}
}
_popContainer(expectedName, expectedType, endSourceSpan) {
let unexpectedCloseTagDetected = false;
for (let stackIndex = this._containerStack.length - 1; stackIndex >= 0; stackIndex--) {
const node = this._containerStack[stackIndex];
if ((node.name === expectedName || expectedName === null) && node instanceof expectedType) {
node.endSourceSpan = endSourceSpan;
node.sourceSpan.end = endSourceSpan !== null ? endSourceSpan.end : node.sourceSpan.end;
this._containerStack.splice(stackIndex, this._containerStack.length - stackIndex);
return !unexpectedCloseTagDetected;
}
if (node instanceof Block || node instanceof Element2 && !this.getTagDefinition(node.name).closedByParent) {
unexpectedCloseTagDetected = true;
}
}
return false;
}
_consumeAttr(attrName) {
const fullName = mergeNsAndName(attrName.parts[0], attrName.parts[1]);
let attrEnd = attrName.sourceSpan.end;
if (this._peek.type === 15) {
this._advance();
}
let value = "";
const valueTokens = [];
let valueStartSpan = void 0;
let valueEnd = void 0;
const nextTokenType = this._peek.type;
if (nextTokenType === 16) {
valueStartSpan = this._peek.sourceSpan;
valueEnd = this._peek.sourceSpan.end;
while (this._peek.type === 16 || this._peek.type === 17 || this._peek.type === 9) {
const valueToken = this._advance();
valueTokens.push(valueToken);
if (valueToken.type === 17) {
value += valueToken.parts.join("").replace(/&([^;]+);/g, decodeEntity);
} else if (valueToken.type === 9) {
value += valueToken.parts[0];
} else {
value += valueToken.parts.join("");
}
valueEnd = attrEnd = valueToken.sourceSpan.end;
}
}
if (this._peek.type === 15) {
const quoteToken = this._advance();
attrEnd = quoteToken.sourceSpan.end;
}
const valueSpan = valueStartSpan && valueEnd && new ParseSourceSpan(valueStartSpan.start, valueEnd, valueStartSpan.fullStart);
return new Attribute(fullName, value, new ParseSourceSpan(attrName.sourceSpan.start, attrEnd, attrName.sourceSpan.fullStart), attrName.sourceSpan, valueSpan, valueTokens.length > 0 ? valueTokens : void 0, void 0);
}
_consumeBlockOpen(token) {
const parameters = [];
while (this._peek.type === 27) {
const paramToken = this._advance();
parameters.push(new BlockParameter(paramToken.parts[0], paramToken.sourceSpan));
}
if (this._peek.type === 25) {
this._advance();
}
const end = this._peek.sourceSpan.fullStart;
const span = new ParseSourceSpan(token.sourceSpan.start, end, token.sourceSpan.fullStart);
const startSpan = new ParseSourceSpan(token.sourceSpan.start, end, token.sourceSpan.fullStart);
const block = new Block(token.parts[0], parameters, [], span, token.sourceSpan, startSpan);
this._pushContainer(block, false);
}
_consumeBlockClose(token) {
if (!this._popContainer(null, Block, token.sourceSpan)) {
this.errors.push(TreeError.create(null, token.sourceSpan, `Unexpected closing block. The block may have been closed earlier. If you meant to write the } character, you should use the "}" HTML entity instead.`));
}
}
_consumeIncompleteBlock(token) {
const parameters = [];
while (this._peek.type === 27) {
const paramToken = this._advance();
parameters.push(new BlockParameter(paramToken.parts[0], paramToken.sourceSpan));
}
const end = this._peek.sourceSpan.fullStart;
const span = new ParseSourceSpan(token.sourceSpan.start, end, token.sourceSpan.fullStart);
const startSpan = new ParseSourceSpan(token.sourceSpan.start, end, token.sourceSpan.fullStart);
const block = new Block(token.parts[0], parameters, [], span, token.sourceSpan, startSpan);
this._pushContainer(block, false);
this._popContainer(null, Block, null);
this.errors.push(TreeError.create(token.parts[0], span, `Incomplete block "${token.parts[0]}". If you meant to write the @ character, you should use the "@" HTML entity instead.`));
}
_consumeLet(startToken) {
const name = startToken.parts[0];
let valueToken;
let endToken;
if (this._peek.type !== 30) {
this.errors.push(TreeError.create(startToken.parts[0], startToken.sourceSpan, `Invalid @let declaration "${name}". Declaration must have a value.`));
return;
} else {
valueToken = this._advance();
}
if (this._peek.type !== 31) {
this.errors.push(TreeError.create(startToken.parts[0], startToken.sourceSpan, `Unterminated @let declaration "${name}". Declaration must be terminated with a semicolon.`));
return;
} else {
endToken = this._advance();
}
const end = endToken.sourceSpan.fullStart;
const span = new ParseSourceSpan(startToken.sourceSpan.start, end, startToken.sourceSpan.fullStart);
const startOffset = startToken.sourceSpan.toString().lastIndexOf(name);
const nameStart = startToken.sourceSpan.start.moveBy(startOffset);
const nameSpan = new ParseSourceSpan(nameStart, startToken.sourceSpan.end);
const node = new LetDeclaration2(name, valueToken.parts[0], span, nameSpan, valueToken.sourceSpan);
this._addToParent(node);
}
_consumeIncompleteLet(token) {
var _a2;
const name = (_a2 = token.parts[0]) != null ? _a2 : "";
const nameString = name ? ` "${name}"` : "";
if (name.length > 0) {
const startOffset = token.sourceSpan.toString().lastIndexOf(name);
const nameStart = token.sourceSpan.start.moveBy(startOffset);
const nameSpan = new ParseSourceSpan(nameStart, token.sourceSpan.end);
const valueSpan = new ParseSourceSpan(token.sourceSpan.start, token.sourceSpan.start.moveBy(0));
const node = new LetDeclaration2(name, "", token.sourceSpan, nameSpan, valueSpan);
this._addToParent(node);
}
this.errors.push(TreeError.create(token.parts[0], token.sourceSpan, `Incomplete @let declaration${nameString}. @let declarations must be written as \`@let = ;\``));
}
_getContainer() {
return this._containerStack.length > 0 ? this._containerStack[this._containerStack.length - 1] : null;
}
_getClosestParentElement() {
for (let i = this._containerStack.length - 1; i > -1; i--) {
if (this._containerStack[i] instanceof Element2) {
return this._containerStack[i];
}
}
return null;
}
_addToParent(node) {
const parent = this._getContainer();
if (parent === null) {
this.rootNodes.push(node);
} else {
parent.children.push(node);
}
}
_getElementFullName(prefix, localName, parentElement) {
if (prefix === "") {
prefix = this.getTagDefinition(localName).implicitNamespacePrefix || "";
if (prefix === "" && parentElement != null) {
const parentTagName = splitNsName(parentElement.name)[1];
const parentTagDefinition = this.getTagDefinition(parentTagName);
if (!parentTagDefinition.preventNamespaceInheritance) {
prefix = getNsPrefix(parentElement.name);
}
}
}
return mergeNsAndName(prefix, localName);
}
};
function lastOnStack(stack, element2) {
return stack.length > 0 && stack[stack.length - 1] === element2;
}
function decodeEntity(match, entity) {
if (NAMED_ENTITIES[entity] !== void 0) {
return NAMED_ENTITIES[entity] || match;
}
if (/^#x[a-f0-9]+$/i.test(entity)) {
return String.fromCodePoint(parseInt(entity.slice(2), 16));
}
if (/^#\d+$/.test(entity)) {
return String.fromCodePoint(parseInt(entity.slice(1), 10));
}
return match;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/ml_parser/html_whitespaces.mjs
var PRESERVE_WS_ATTR_NAME = "ngPreserveWhitespaces";
var SKIP_WS_TRIM_TAGS = /* @__PURE__ */ new Set(["pre", "template", "textarea", "script", "style"]);
var WS_CHARS = " \f\n\r \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((attr) => attr.name === PRESERVE_WS_ATTR_NAME);
}
function replaceNgsp(value) {
return value.replace(new RegExp(NGSP_UNICODE, "g"), " ");
}
var WhitespaceVisitor = class {
constructor(preserveSignificantWhitespace, originalNodeMap, requireContext = true) {
this.preserveSignificantWhitespace = preserveSignificantWhitespace;
this.originalNodeMap = originalNodeMap;
this.requireContext = requireContext;
this.icuExpansionDepth = 0;
}
visitElement(element2, context) {
var _a2, _b2;
if (SKIP_WS_TRIM_TAGS.has(element2.name) || hasPreserveWhitespacesAttr(element2.attrs)) {
const newElement2 = new Element2(element2.name, visitAllWithSiblings(this, element2.attrs), element2.children, element2.sourceSpan, element2.startSourceSpan, element2.endSourceSpan, element2.i18n);
(_a2 = this.originalNodeMap) == null ? void 0 : _a2.set(newElement2, element2);
return newElement2;
}
const newElement = new Element2(element2.name, element2.attrs, visitAllWithSiblings(this, element2.children), element2.sourceSpan, element2.startSourceSpan, element2.endSourceSpan, element2.i18n);
(_b2 = this.originalNodeMap) == null ? void 0 : _b2.set(newElement, element2);
return newElement;
}
visitAttribute(attribute2, context) {
return attribute2.name !== PRESERVE_WS_ATTR_NAME ? attribute2 : null;
}
visitText(text2, context) {
var _a2;
const isNotBlank = text2.value.match(NO_WS_REGEXP);
const hasExpansionSibling = context && (context.prev instanceof Expansion || context.next instanceof Expansion);
const inIcuExpansion = this.icuExpansionDepth > 0;
if (inIcuExpansion && this.preserveSignificantWhitespace)
return text2;
if (isNotBlank || hasExpansionSibling) {
const tokens = text2.tokens.map((token) => token.type === 5 ? createWhitespaceProcessedTextToken(token) : token);
if (!this.preserveSignificantWhitespace && tokens.length > 0) {
const firstToken = tokens[0];
tokens.splice(0, 1, trimLeadingWhitespace(firstToken, context));
const lastToken = tokens[tokens.length - 1];
tokens.splice(tokens.length - 1, 1, trimTrailingWhitespace(lastToken, context));
}
const processed = processWhitespace(text2.value);
const value = this.preserveSignificantWhitespace ? processed : trimLeadingAndTrailingWhitespace(processed, context);
const result = new Text4(value, text2.sourceSpan, tokens, text2.i18n);
(_a2 = this.originalNodeMap) == null ? void 0 : _a2.set(result, text2);
return result;
}
return null;
}
visitComment(comment, context) {
return comment;
}
visitExpansion(expansion, context) {
var _a2;
this.icuExpansionDepth++;
let newExpansion;
try {
newExpansion = new Expansion(expansion.switchValue, expansion.type, visitAllWithSiblings(this, expansion.cases), expansion.sourceSpan, expansion.switchValueSourceSpan, expansion.i18n);
} finally {
this.icuExpansionDepth--;
}
(_a2 = this.originalNodeMap) == null ? void 0 : _a2.set(newExpansion, expansion);
return newExpansion;
}
visitExpansionCase(expansionCase, context) {
var _a2;
const newExpansionCase = new ExpansionCase(expansionCase.value, visitAllWithSiblings(this, expansionCase.expression), expansionCase.sourceSpan, expansionCase.valueSourceSpan, expansionCase.expSourceSpan);
(_a2 = this.originalNodeMap) == null ? void 0 : _a2.set(newExpansionCase, expansionCase);
return newExpansionCase;
}
visitBlock(block, context) {
var _a2;
const newBlock = new Block(block.name, block.parameters, visitAllWithSiblings(this, block.children), block.sourceSpan, block.nameSpan, block.startSourceSpan, block.endSourceSpan);
(_a2 = this.originalNodeMap) == null ? void 0 : _a2.set(newBlock, block);
return newBlock;
}
visitBlockParameter(parameter, context) {
return parameter;
}
visitLetDeclaration(decl, context) {
return decl;
}
visit(_node, context) {
if (this.requireContext && !context) {
throw new Error(`WhitespaceVisitor requires context. Visit via \`visitAllWithSiblings\` to get this context.`);
}
return false;
}
};
function trimLeadingWhitespace(token, context) {
if (token.type !== 5)
return token;
const isFirstTokenInTag = !(context == null ? void 0 : context.prev);
if (!isFirstTokenInTag)
return token;
return transformTextToken(token, (text2) => text2.trimStart());
}
function trimTrailingWhitespace(token, context) {
if (token.type !== 5)
return token;
const isLastTokenInTag = !(context == null ? void 0 : context.next);
if (!isLastTokenInTag)
return token;
return transformTextToken(token, (text2) => text2.trimEnd());
}
function trimLeadingAndTrailingWhitespace(text2, context) {
const isFirstTokenInTag = !(context == null ? void 0 : context.prev);
const isLastTokenInTag = !(context == null ? void 0 : context.next);
const maybeTrimmedStart = isFirstTokenInTag ? text2.trimStart() : text2;
const maybeTrimmed = isLastTokenInTag ? maybeTrimmedStart.trimEnd() : maybeTrimmedStart;
return maybeTrimmed;
}
function createWhitespaceProcessedTextToken({ type, parts, sourceSpan }) {
return { type, parts: [processWhitespace(parts[0])], sourceSpan };
}
function transformTextToken({ type, parts, sourceSpan }, transform2) {
return { type, parts: [transform2(parts[0])], sourceSpan };
}
function processWhitespace(text2) {
return replaceNgsp(text2).replace(WS_REPLACE_REGEXP, " ");
}
function visitAllWithSiblings(visitor, nodes) {
const result = [];
nodes.forEach((ast, i) => {
const context = { prev: nodes[i - 1], next: nodes[i + 1] };
const astResult = ast.visit(visitor, context);
if (astResult) {
result.push(astResult);
}
});
return result;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/expression_parser/lexer.mjs
var TokenType;
(function(TokenType2) {
TokenType2[TokenType2["Character"] = 0] = "Character";
TokenType2[TokenType2["Identifier"] = 1] = "Identifier";
TokenType2[TokenType2["PrivateIdentifier"] = 2] = "PrivateIdentifier";
TokenType2[TokenType2["Keyword"] = 3] = "Keyword";
TokenType2[TokenType2["String"] = 4] = "String";
TokenType2[TokenType2["Operator"] = 5] = "Operator";
TokenType2[TokenType2["Number"] = 6] = "Number";
TokenType2[TokenType2["Error"] = 7] = "Error";
})(TokenType || (TokenType = {}));
var KEYWORDS = ["var", "let", "as", "null", "undefined", "true", "false", "if", "else", "this"];
var Lexer = class {
tokenize(text2) {
const scanner = new _Scanner(text2);
const tokens = [];
let token = scanner.scanToken();
while (token != null) {
tokens.push(token);
token = scanner.scanToken();
}
return tokens;
}
};
var Token = class {
constructor(index, end, type, numValue, strValue) {
this.index = index;
this.end = end;
this.type = type;
this.numValue = numValue;
this.strValue = strValue;
}
isCharacter(code) {
return this.type == TokenType.Character && this.numValue == code;
}
isNumber() {
return this.type == TokenType.Number;
}
isString() {
return this.type == TokenType.String;
}
isOperator(operator) {
return this.type == TokenType.Operator && this.strValue == operator;
}
isIdentifier() {
return this.type == TokenType.Identifier;
}
isPrivateIdentifier() {
return this.type == TokenType.PrivateIdentifier;
}
isKeyword() {
return this.type == TokenType.Keyword;
}
isKeywordLet() {
return this.type == TokenType.Keyword && this.strValue == "let";
}
isKeywordAs() {
return this.type == TokenType.Keyword && this.strValue == "as";
}
isKeywordNull() {
return this.type == TokenType.Keyword && this.strValue == "null";
}
isKeywordUndefined() {
return this.type == TokenType.Keyword && this.strValue == "undefined";
}
isKeywordTrue() {
return this.type == TokenType.Keyword && this.strValue == "true";
}
isKeywordFalse() {
return this.type == TokenType.Keyword && this.strValue == "false";
}
isKeywordThis() {
return this.type == TokenType.Keyword && this.strValue == "this";
}
isError() {
return this.type == TokenType.Error;
}
toNumber() {
return this.type == TokenType.Number ? this.numValue : -1;
}
toString() {
switch (this.type) {
case TokenType.Character:
case TokenType.Identifier:
case TokenType.Keyword:
case TokenType.Operator:
case TokenType.PrivateIdentifier:
case TokenType.String:
case TokenType.Error:
return this.strValue;
case TokenType.Number:
return this.numValue.toString();
default:
return null;
}
}
};
function newCharacterToken(index, end, code) {
return new Token(index, end, TokenType.Character, code, String.fromCharCode(code));
}
function newIdentifierToken(index, end, text2) {
return new Token(index, end, TokenType.Identifier, 0, text2);
}
function newPrivateIdentifierToken(index, end, text2) {
return new Token(index, end, TokenType.PrivateIdentifier, 0, text2);
}
function newKeywordToken(index, end, text2) {
return new Token(index, end, TokenType.Keyword, 0, text2);
}
function newOperatorToken(index, end, text2) {
return new Token(index, end, TokenType.Operator, 0, text2);
}
function newStringToken(index, end, text2) {
return new Token(index, end, TokenType.String, 0, text2);
}
function newNumberToken(index, end, n2) {
return new Token(index, end, TokenType.Number, n2, "");
}
function newErrorToken(index, end, message) {
return new Token(index, end, TokenType.Error, 0, message);
}
var EOF = new Token(-1, -1, TokenType.Character, 0, "");
var _Scanner = class {
constructor(input) {
this.input = input;
this.peek = 0;
this.index = -1;
this.length = input.length;
this.advance();
}
advance() {
this.peek = ++this.index >= this.length ? $EOF : this.input.charCodeAt(this.index);
}
scanToken() {
const input = this.input, length = this.length;
let peek = this.peek, index = this.index;
while (peek <= $SPACE) {
if (++index >= length) {
peek = $EOF;
break;
} else {
peek = input.charCodeAt(index);
}
}
this.peek = peek;
this.index = index;
if (index >= length) {
return null;
}
if (isIdentifierStart(peek))
return this.scanIdentifier();
if (isDigit(peek))
return this.scanNumber(index);
const start = index;
switch (peek) {
case $PERIOD:
this.advance();
return isDigit(this.peek) ? this.scanNumber(start) : newCharacterToken(start, this.index, $PERIOD);
case $LPAREN:
case $RPAREN:
case $LBRACE:
case $RBRACE:
case $LBRACKET:
case $RBRACKET:
case $COMMA:
case $COLON:
case $SEMICOLON:
return this.scanCharacter(start, peek);
case $SQ:
case $DQ:
return this.scanString();
case $HASH:
return this.scanPrivateIdentifier();
case $PLUS:
case $MINUS:
case $STAR:
case $SLASH:
case $PERCENT:
case $CARET:
return this.scanOperator(start, String.fromCharCode(peek));
case $QUESTION:
return this.scanQuestion(start);
case $LT:
case $GT:
return this.scanComplexOperator(start, String.fromCharCode(peek), $EQ, "=");
case $BANG:
case $EQ:
return this.scanComplexOperator(start, String.fromCharCode(peek), $EQ, "=", $EQ, "=");
case $AMPERSAND:
return this.scanComplexOperator(start, "&", $AMPERSAND, "&");
case $BAR:
return this.scanComplexOperator(start, "|", $BAR, "|");
case $NBSP:
while (isWhitespace(this.peek))
this.advance();
return this.scanToken();
}
this.advance();
return this.error(`Unexpected character [${String.fromCharCode(peek)}]`, 0);
}
scanCharacter(start, code) {
this.advance();
return newCharacterToken(start, this.index, code);
}
scanOperator(start, str) {
this.advance();
return newOperatorToken(start, this.index, str);
}
scanComplexOperator(start, one, twoCode, two, threeCode, three) {
this.advance();
let str = one;
if (this.peek == twoCode) {
this.advance();
str += two;
}
if (threeCode != null && this.peek == threeCode) {
this.advance();
str += three;
}
return newOperatorToken(start, this.index, str);
}
scanIdentifier() {
const start = this.index;
this.advance();
while (isIdentifierPart(this.peek))
this.advance();
const str = this.input.substring(start, this.index);
return KEYWORDS.indexOf(str) > -1 ? newKeywordToken(start, this.index, str) : newIdentifierToken(start, this.index, str);
}
scanPrivateIdentifier() {
const start = this.index;
this.advance();
if (!isIdentifierStart(this.peek)) {
return this.error("Invalid character [#]", -1);
}
while (isIdentifierPart(this.peek))
this.advance();
const identifierName2 = this.input.substring(start, this.index);
return newPrivateIdentifierToken(start, this.index, identifierName2);
}
scanNumber(start) {
let simple = this.index === start;
let hasSeparators = false;
this.advance();
while (true) {
if (isDigit(this.peek)) {
} else if (this.peek === $_) {
if (!isDigit(this.input.charCodeAt(this.index - 1)) || !isDigit(this.input.charCodeAt(this.index + 1))) {
return this.error("Invalid numeric separator", 0);
}
hasSeparators = true;
} else if (this.peek === $PERIOD) {
simple = false;
} else if (isExponentStart(this.peek)) {
this.advance();
if (isExponentSign(this.peek))
this.advance();
if (!isDigit(this.peek))
return this.error("Invalid exponent", -1);
simple = false;
} else {
break;
}
this.advance();
}
let str = this.input.substring(start, this.index);
if (hasSeparators) {
str = str.replace(/_/g, "");
}
const value = simple ? parseIntAutoRadix(str) : parseFloat(str);
return newNumberToken(start, this.index, value);
}
scanString() {
const start = this.index;
const quote = this.peek;
this.advance();
let buffer = "";
let marker = this.index;
const input = this.input;
while (this.peek != quote) {
if (this.peek == $BACKSLASH) {
buffer += input.substring(marker, this.index);
let unescapedCode;
this.advance();
if (this.peek == $u) {
const hex = input.substring(this.index + 1, this.index + 5);
if (/^[0-9a-f]+$/i.test(hex)) {
unescapedCode = parseInt(hex, 16);
} else {
return this.error(`Invalid unicode escape [\\u${hex}]`, 0);
}
for (let i = 0; i < 5; i++) {
this.advance();
}
} else {
unescapedCode = unescape2(this.peek);
this.advance();
}
buffer += String.fromCharCode(unescapedCode);
marker = this.index;
} else if (this.peek == $EOF) {
return this.error("Unterminated quote", 0);
} else {
this.advance();
}
}
const last = input.substring(marker, this.index);
this.advance();
return newStringToken(start, this.index, buffer + last);
}
scanQuestion(start) {
this.advance();
let str = "?";
if (this.peek === $QUESTION || this.peek === $PERIOD) {
str += this.peek === $PERIOD ? "." : "?";
this.advance();
}
return newOperatorToken(start, this.index, str);
}
error(message, offset) {
const position = this.index + offset;
return newErrorToken(position, this.index, `Lexer Error: ${message} at column ${position} in expression [${this.input}]`);
}
};
function isIdentifierStart(code) {
return $a <= code && code <= $z || $A <= code && code <= $Z || code == $_ || code == $$;
}
function isIdentifierPart(code) {
return isAsciiLetter(code) || isDigit(code) || code == $_ || code == $$;
}
function isExponentStart(code) {
return code == $e || code == $E;
}
function isExponentSign(code) {
return code == $MINUS || code == $PLUS;
}
function unescape2(code) {
switch (code) {
case $n:
return $LF;
case $f:
return $FF;
case $r:
return $CR;
case $t:
return $TAB;
case $v:
return $VTAB;
default:
return code;
}
}
function parseIntAutoRadix(text2) {
const result = parseInt(text2);
if (isNaN(result)) {
throw new Error("Invalid integer literal when parsing " + text2);
}
return result;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/expression_parser/parser.mjs
var SplitInterpolation = class {
constructor(strings, expressions, offsets) {
this.strings = strings;
this.expressions = expressions;
this.offsets = offsets;
}
};
var TemplateBindingParseResult = class {
constructor(templateBindings, warnings, errors) {
this.templateBindings = templateBindings;
this.warnings = warnings;
this.errors = errors;
}
};
var Parser2 = class {
constructor(_lexer) {
this._lexer = _lexer;
this.errors = [];
}
parseAction(input, location, absoluteOffset, interpolationConfig = DEFAULT_INTERPOLATION_CONFIG) {
this._checkNoInterpolation(input, location, interpolationConfig);
const sourceToLex = this._stripComments(input);
const tokens = this._lexer.tokenize(sourceToLex);
const ast = new _ParseAST(input, location, absoluteOffset, tokens, 1, this.errors, 0).parseChain();
return new ASTWithSource(ast, input, location, absoluteOffset, this.errors);
}
parseBinding(input, location, absoluteOffset, interpolationConfig = DEFAULT_INTERPOLATION_CONFIG) {
const ast = this._parseBindingAst(input, location, absoluteOffset, interpolationConfig);
return new ASTWithSource(ast, input, location, absoluteOffset, this.errors);
}
checkSimpleExpression(ast) {
const checker = new SimpleExpressionChecker();
ast.visit(checker);
return checker.errors;
}
parseSimpleBinding(input, location, absoluteOffset, interpolationConfig = DEFAULT_INTERPOLATION_CONFIG) {
const ast = this._parseBindingAst(input, location, absoluteOffset, interpolationConfig);
const errors = this.checkSimpleExpression(ast);
if (errors.length > 0) {
this._reportError(`Host binding expression cannot contain ${errors.join(" ")}`, input, location);
}
return new ASTWithSource(ast, input, location, absoluteOffset, this.errors);
}
_reportError(message, input, errLocation, ctxLocation) {
this.errors.push(new ParserError(message, input, errLocation, ctxLocation));
}
_parseBindingAst(input, location, absoluteOffset, interpolationConfig) {
this._checkNoInterpolation(input, location, interpolationConfig);
const sourceToLex = this._stripComments(input);
const tokens = this._lexer.tokenize(sourceToLex);
return new _ParseAST(input, location, absoluteOffset, tokens, 0, this.errors, 0).parseChain();
}
parseTemplateBindings(templateKey, templateValue, templateUrl, absoluteKeyOffset, absoluteValueOffset) {
const tokens = this._lexer.tokenize(templateValue);
const parser = new _ParseAST(templateValue, templateUrl, absoluteValueOffset, tokens, 0, this.errors, 0);
return parser.parseTemplateBindings({
source: templateKey,
span: new AbsoluteSourceSpan(absoluteKeyOffset, absoluteKeyOffset + templateKey.length)
});
}
parseInterpolation(input, location, absoluteOffset, interpolatedTokens, interpolationConfig = DEFAULT_INTERPOLATION_CONFIG) {
const { strings, expressions, offsets } = this.splitInterpolation(input, location, interpolatedTokens, interpolationConfig);
if (expressions.length === 0)
return null;
const expressionNodes = [];
for (let i = 0; i < expressions.length; ++i) {
const expressionText = expressions[i].text;
const sourceToLex = this._stripComments(expressionText);
const tokens = this._lexer.tokenize(sourceToLex);
const ast = new _ParseAST(input, location, absoluteOffset, tokens, 0, this.errors, offsets[i]).parseChain();
expressionNodes.push(ast);
}
return this.createInterpolationAst(strings.map((s) => s.text), expressionNodes, input, location, absoluteOffset);
}
parseInterpolationExpression(expression, location, absoluteOffset) {
const sourceToLex = this._stripComments(expression);
const tokens = this._lexer.tokenize(sourceToLex);
const ast = new _ParseAST(expression, location, absoluteOffset, tokens, 0, this.errors, 0).parseChain();
const strings = ["", ""];
return this.createInterpolationAst(strings, [ast], expression, location, absoluteOffset);
}
createInterpolationAst(strings, expressions, input, location, absoluteOffset) {
const span = new ParseSpan(0, input.length);
const interpolation = new Interpolation(span, span.toAbsolute(absoluteOffset), strings, expressions);
return new ASTWithSource(interpolation, input, location, absoluteOffset, this.errors);
}
splitInterpolation(input, location, interpolatedTokens, interpolationConfig = DEFAULT_INTERPOLATION_CONFIG) {
var _a2;
const strings = [];
const expressions = [];
const offsets = [];
const inputToTemplateIndexMap = interpolatedTokens ? getIndexMapForOriginalTemplate(interpolatedTokens) : null;
let i = 0;
let atInterpolation = false;
let extendLastString = false;
let { start: interpStart, end: interpEnd } = interpolationConfig;
while (i < input.length) {
if (!atInterpolation) {
const start = i;
i = input.indexOf(interpStart, i);
if (i === -1) {
i = input.length;
}
const text2 = input.substring(start, i);
strings.push({ text: text2, start, end: i });
atInterpolation = true;
} else {
const fullStart = i;
const exprStart = fullStart + interpStart.length;
const exprEnd = this._getInterpolationEndIndex(input, interpEnd, exprStart);
if (exprEnd === -1) {
atInterpolation = false;
extendLastString = true;
break;
}
const fullEnd = exprEnd + interpEnd.length;
const text2 = input.substring(exprStart, exprEnd);
if (text2.trim().length === 0) {
this._reportError("Blank expressions are not allowed in interpolated strings", input, `at column ${i} in`, location);
}
expressions.push({ text: text2, start: fullStart, end: fullEnd });
const startInOriginalTemplate = (_a2 = inputToTemplateIndexMap == null ? void 0 : inputToTemplateIndexMap.get(fullStart)) != null ? _a2 : fullStart;
const offset = startInOriginalTemplate + interpStart.length;
offsets.push(offset);
i = fullEnd;
atInterpolation = false;
}
}
if (!atInterpolation) {
if (extendLastString) {
const piece = strings[strings.length - 1];
piece.text += input.substring(i);
piece.end = input.length;
} else {
strings.push({ text: input.substring(i), start: i, end: input.length });
}
}
return new SplitInterpolation(strings, expressions, offsets);
}
wrapLiteralPrimitive(input, location, absoluteOffset) {
const span = new ParseSpan(0, input == null ? 0 : input.length);
return new ASTWithSource(new LiteralPrimitive(span, span.toAbsolute(absoluteOffset), input), input, location, absoluteOffset, this.errors);
}
_stripComments(input) {
const i = this._commentStart(input);
return i != null ? input.substring(0, i) : input;
}
_commentStart(input) {
let outerQuote = null;
for (let i = 0; i < input.length - 1; i++) {
const char = input.charCodeAt(i);
const nextChar = input.charCodeAt(i + 1);
if (char === $SLASH && nextChar == $SLASH && outerQuote == null)
return i;
if (outerQuote === char) {
outerQuote = null;
} else if (outerQuote == null && isQuote(char)) {
outerQuote = char;
}
}
return null;
}
_checkNoInterpolation(input, location, { start, end }) {
let startIndex = -1;
let endIndex = -1;
for (const charIndex of this._forEachUnquotedChar(input, 0)) {
if (startIndex === -1) {
if (input.startsWith(start)) {
startIndex = charIndex;
}
} else {
endIndex = this._getInterpolationEndIndex(input, end, charIndex);
if (endIndex > -1) {
break;
}
}
}
if (startIndex > -1 && endIndex > -1) {
this._reportError(`Got interpolation (${start}${end}) where expression was expected`, input, `at column ${startIndex} in`, location);
}
}
_getInterpolationEndIndex(input, expressionEnd, start) {
for (const charIndex of this._forEachUnquotedChar(input, start)) {
if (input.startsWith(expressionEnd, charIndex)) {
return charIndex;
}
if (input.startsWith("//", charIndex)) {
return input.indexOf(expressionEnd, charIndex);
}
}
return -1;
}
*_forEachUnquotedChar(input, start) {
let currentQuote = null;
let escapeCount = 0;
for (let i = start; i < input.length; i++) {
const char = input[i];
if (isQuote(input.charCodeAt(i)) && (currentQuote === null || currentQuote === char) && escapeCount % 2 === 0) {
currentQuote = currentQuote === null ? char : null;
} else if (currentQuote === null) {
yield i;
}
escapeCount = char === "\\" ? escapeCount + 1 : 0;
}
}
};
var ParseContextFlags;
(function(ParseContextFlags2) {
ParseContextFlags2[ParseContextFlags2["None"] = 0] = "None";
ParseContextFlags2[ParseContextFlags2["Writable"] = 1] = "Writable";
})(ParseContextFlags || (ParseContextFlags = {}));
var _ParseAST = class {
constructor(input, location, absoluteOffset, tokens, parseFlags, errors, offset) {
this.input = input;
this.location = location;
this.absoluteOffset = absoluteOffset;
this.tokens = tokens;
this.parseFlags = parseFlags;
this.errors = errors;
this.offset = offset;
this.rparensExpected = 0;
this.rbracketsExpected = 0;
this.rbracesExpected = 0;
this.context = ParseContextFlags.None;
this.sourceSpanCache = /* @__PURE__ */ new Map();
this.index = 0;
}
peek(offset) {
const i = this.index + offset;
return i < this.tokens.length ? this.tokens[i] : EOF;
}
get next() {
return this.peek(0);
}
get atEOF() {
return this.index >= this.tokens.length;
}
get inputIndex() {
return this.atEOF ? this.currentEndIndex : this.next.index + this.offset;
}
get currentEndIndex() {
if (this.index > 0) {
const curToken = this.peek(-1);
return curToken.end + this.offset;
}
if (this.tokens.length === 0) {
return this.input.length + this.offset;
}
return this.next.index + this.offset;
}
get currentAbsoluteOffset() {
return this.absoluteOffset + this.inputIndex;
}
span(start, artificialEndIndex) {
let endIndex = this.currentEndIndex;
if (artificialEndIndex !== void 0 && artificialEndIndex > this.currentEndIndex) {
endIndex = artificialEndIndex;
}
if (start > endIndex) {
const tmp = endIndex;
endIndex = start;
start = tmp;
}
return new ParseSpan(start, endIndex);
}
sourceSpan(start, artificialEndIndex) {
const serial = `${start}@${this.inputIndex}:${artificialEndIndex}`;
if (!this.sourceSpanCache.has(serial)) {
this.sourceSpanCache.set(serial, this.span(start, artificialEndIndex).toAbsolute(this.absoluteOffset));
}
return this.sourceSpanCache.get(serial);
}
advance() {
this.index++;
}
withContext(context, cb) {
this.context |= context;
const ret = cb();
this.context ^= context;
return ret;
}
consumeOptionalCharacter(code) {
if (this.next.isCharacter(code)) {
this.advance();
return true;
} else {
return false;
}
}
peekKeywordLet() {
return this.next.isKeywordLet();
}
peekKeywordAs() {
return this.next.isKeywordAs();
}
expectCharacter(code) {
if (this.consumeOptionalCharacter(code))
return;
this.error(`Missing expected ${String.fromCharCode(code)}`);
}
consumeOptionalOperator(op) {
if (this.next.isOperator(op)) {
this.advance();
return true;
} else {
return false;
}
}
expectOperator(operator) {
if (this.consumeOptionalOperator(operator))
return;
this.error(`Missing expected operator ${operator}`);
}
prettyPrintToken(tok) {
return tok === EOF ? "end of input" : `token ${tok}`;
}
expectIdentifierOrKeyword() {
const n2 = this.next;
if (!n2.isIdentifier() && !n2.isKeyword()) {
if (n2.isPrivateIdentifier()) {
this._reportErrorForPrivateIdentifier(n2, "expected identifier or keyword");
} else {
this.error(`Unexpected ${this.prettyPrintToken(n2)}, expected identifier or keyword`);
}
return null;
}
this.advance();
return n2.toString();
}
expectIdentifierOrKeywordOrString() {
const n2 = this.next;
if (!n2.isIdentifier() && !n2.isKeyword() && !n2.isString()) {
if (n2.isPrivateIdentifier()) {
this._reportErrorForPrivateIdentifier(n2, "expected identifier, keyword or string");
} else {
this.error(`Unexpected ${this.prettyPrintToken(n2)}, expected identifier, keyword, or string`);
}
return "";
}
this.advance();
return n2.toString();
}
parseChain() {
const exprs = [];
const start = this.inputIndex;
while (this.index < this.tokens.length) {
const expr = this.parsePipe();
exprs.push(expr);
if (this.consumeOptionalCharacter($SEMICOLON)) {
if (!(this.parseFlags & 1)) {
this.error("Binding expression cannot contain chained expression");
}
while (this.consumeOptionalCharacter($SEMICOLON)) {
}
} else if (this.index < this.tokens.length) {
const errorIndex = this.index;
this.error(`Unexpected token '${this.next}'`);
if (this.index === errorIndex) {
break;
}
}
}
if (exprs.length === 0) {
const artificialStart = this.offset;
const artificialEnd = this.offset + this.input.length;
return new EmptyExpr(this.span(artificialStart, artificialEnd), this.sourceSpan(artificialStart, artificialEnd));
}
if (exprs.length == 1)
return exprs[0];
return new Chain(this.span(start), this.sourceSpan(start), exprs);
}
parsePipe() {
const start = this.inputIndex;
let result = this.parseExpression();
if (this.consumeOptionalOperator("|")) {
if (this.parseFlags & 1) {
this.error(`Cannot have a pipe in an action expression`);
}
do {
const nameStart = this.inputIndex;
let nameId = this.expectIdentifierOrKeyword();
let nameSpan;
let fullSpanEnd = void 0;
if (nameId !== null) {
nameSpan = this.sourceSpan(nameStart);
} else {
nameId = "";
fullSpanEnd = this.next.index !== -1 ? this.next.index : this.input.length + this.offset;
nameSpan = new ParseSpan(fullSpanEnd, fullSpanEnd).toAbsolute(this.absoluteOffset);
}
const args = [];
while (this.consumeOptionalCharacter($COLON)) {
args.push(this.parseExpression());
}
result = new BindingPipe(this.span(start), this.sourceSpan(start, fullSpanEnd), result, nameId, args, nameSpan);
} while (this.consumeOptionalOperator("|"));
}
return result;
}
parseExpression() {
return this.parseConditional();
}
parseConditional() {
const start = this.inputIndex;
const result = this.parseLogicalOr();
if (this.consumeOptionalOperator("?")) {
const yes = this.parsePipe();
let no;
if (!this.consumeOptionalCharacter($COLON)) {
const end = this.inputIndex;
const expression = this.input.substring(start, end);
this.error(`Conditional expression ${expression} requires all 3 expressions`);
no = new EmptyExpr(this.span(start), this.sourceSpan(start));
} else {
no = this.parsePipe();
}
return new Conditional(this.span(start), this.sourceSpan(start), result, yes, no);
} else {
return result;
}
}
parseLogicalOr() {
const start = this.inputIndex;
let result = this.parseLogicalAnd();
while (this.consumeOptionalOperator("||")) {
const right = this.parseLogicalAnd();
result = new Binary(this.span(start), this.sourceSpan(start), "||", result, right);
}
return result;
}
parseLogicalAnd() {
const start = this.inputIndex;
let result = this.parseNullishCoalescing();
while (this.consumeOptionalOperator("&&")) {
const right = this.parseNullishCoalescing();
result = new Binary(this.span(start), this.sourceSpan(start), "&&", result, right);
}
return result;
}
parseNullishCoalescing() {
const start = this.inputIndex;
let result = this.parseEquality();
while (this.consumeOptionalOperator("??")) {
const right = this.parseEquality();
result = new Binary(this.span(start), this.sourceSpan(start), "??", result, right);
}
return result;
}
parseEquality() {
const start = this.inputIndex;
let result = this.parseRelational();
while (this.next.type == TokenType.Operator) {
const operator = this.next.strValue;
switch (operator) {
case "==":
case "===":
case "!=":
case "!==":
this.advance();
const right = this.parseRelational();
result = new Binary(this.span(start), this.sourceSpan(start), operator, result, right);
continue;
}
break;
}
return result;
}
parseRelational() {
const start = this.inputIndex;
let result = this.parseAdditive();
while (this.next.type == TokenType.Operator) {
const operator = this.next.strValue;
switch (operator) {
case "<":
case ">":
case "<=":
case ">=":
this.advance();
const right = this.parseAdditive();
result = new Binary(this.span(start), this.sourceSpan(start), operator, result, right);
continue;
}
break;
}
return result;
}
parseAdditive() {
const start = this.inputIndex;
let result = this.parseMultiplicative();
while (this.next.type == TokenType.Operator) {
const operator = this.next.strValue;
switch (operator) {
case "+":
case "-":
this.advance();
let right = this.parseMultiplicative();
result = new Binary(this.span(start), this.sourceSpan(start), operator, result, right);
continue;
}
break;
}
return result;
}
parseMultiplicative() {
const start = this.inputIndex;
let result = this.parsePrefix();
while (this.next.type == TokenType.Operator) {
const operator = this.next.strValue;
switch (operator) {
case "*":
case "%":
case "/":
this.advance();
let right = this.parsePrefix();
result = new Binary(this.span(start), this.sourceSpan(start), operator, result, right);
continue;
}
break;
}
return result;
}
parsePrefix() {
if (this.next.type == TokenType.Operator) {
const start = this.inputIndex;
const operator = this.next.strValue;
let result;
switch (operator) {
case "+":
this.advance();
result = this.parsePrefix();
return Unary.createPlus(this.span(start), this.sourceSpan(start), result);
case "-":
this.advance();
result = this.parsePrefix();
return Unary.createMinus(this.span(start), this.sourceSpan(start), result);
case "!":
this.advance();
result = this.parsePrefix();
return new PrefixNot(this.span(start), this.sourceSpan(start), result);
}
}
return this.parseCallChain();
}
parseCallChain() {
const start = this.inputIndex;
let result = this.parsePrimary();
while (true) {
if (this.consumeOptionalCharacter($PERIOD)) {
result = this.parseAccessMember(result, start, false);
} else if (this.consumeOptionalOperator("?.")) {
if (this.consumeOptionalCharacter($LPAREN)) {
result = this.parseCall(result, start, true);
} else {
result = this.consumeOptionalCharacter($LBRACKET) ? this.parseKeyedReadOrWrite(result, start, true) : this.parseAccessMember(result, start, true);
}
} else if (this.consumeOptionalCharacter($LBRACKET)) {
result = this.parseKeyedReadOrWrite(result, start, false);
} else if (this.consumeOptionalCharacter($LPAREN)) {
result = this.parseCall(result, start, false);
} else if (this.consumeOptionalOperator("!")) {
result = new NonNullAssert(this.span(start), this.sourceSpan(start), result);
} else {
return result;
}
}
}
parsePrimary() {
const start = this.inputIndex;
if (this.consumeOptionalCharacter($LPAREN)) {
this.rparensExpected++;
const result = this.parsePipe();
this.rparensExpected--;
this.expectCharacter($RPAREN);
return result;
} else if (this.next.isKeywordNull()) {
this.advance();
return new LiteralPrimitive(this.span(start), this.sourceSpan(start), null);
} else if (this.next.isKeywordUndefined()) {
this.advance();
return new LiteralPrimitive(this.span(start), this.sourceSpan(start), void 0);
} else if (this.next.isKeywordTrue()) {
this.advance();
return new LiteralPrimitive(this.span(start), this.sourceSpan(start), true);
} else if (this.next.isKeywordFalse()) {
this.advance();
return new LiteralPrimitive(this.span(start), this.sourceSpan(start), false);
} else if (this.next.isKeywordThis()) {
this.advance();
return new ThisReceiver(this.span(start), this.sourceSpan(start));
} else if (this.consumeOptionalCharacter($LBRACKET)) {
this.rbracketsExpected++;
const elements = this.parseExpressionList($RBRACKET);
this.rbracketsExpected--;
this.expectCharacter($RBRACKET);
return new LiteralArray(this.span(start), this.sourceSpan(start), elements);
} else if (this.next.isCharacter($LBRACE)) {
return this.parseLiteralMap();
} else if (this.next.isIdentifier()) {
return this.parseAccessMember(new ImplicitReceiver(this.span(start), this.sourceSpan(start)), start, false);
} else if (this.next.isNumber()) {
const value = this.next.toNumber();
this.advance();
return new LiteralPrimitive(this.span(start), this.sourceSpan(start), value);
} else if (this.next.isString()) {
const literalValue = this.next.toString();
this.advance();
return new LiteralPrimitive(this.span(start), this.sourceSpan(start), literalValue);
} else if (this.next.isPrivateIdentifier()) {
this._reportErrorForPrivateIdentifier(this.next, null);
return new EmptyExpr(this.span(start), this.sourceSpan(start));
} else if (this.index >= this.tokens.length) {
this.error(`Unexpected end of expression: ${this.input}`);
return new EmptyExpr(this.span(start), this.sourceSpan(start));
} else {
this.error(`Unexpected token ${this.next}`);
return new EmptyExpr(this.span(start), this.sourceSpan(start));
}
}
parseExpressionList(terminator) {
const result = [];
do {
if (!this.next.isCharacter(terminator)) {
result.push(this.parsePipe());
} else {
break;
}
} while (this.consumeOptionalCharacter($COMMA));
return result;
}
parseLiteralMap() {
const keys = [];
const values = [];
const start = this.inputIndex;
this.expectCharacter($LBRACE);
if (!this.consumeOptionalCharacter($RBRACE)) {
this.rbracesExpected++;
do {
const keyStart = this.inputIndex;
const quoted = this.next.isString();
const key = this.expectIdentifierOrKeywordOrString();
const literalMapKey = { key, quoted };
keys.push(literalMapKey);
if (quoted) {
this.expectCharacter($COLON);
values.push(this.parsePipe());
} else if (this.consumeOptionalCharacter($COLON)) {
values.push(this.parsePipe());
} else {
literalMapKey.isShorthandInitialized = true;
const span = this.span(keyStart);
const sourceSpan = this.sourceSpan(keyStart);
values.push(new PropertyRead(span, sourceSpan, sourceSpan, new ImplicitReceiver(span, sourceSpan), key));
}
} while (this.consumeOptionalCharacter($COMMA) && !this.next.isCharacter($RBRACE));
this.rbracesExpected--;
this.expectCharacter($RBRACE);
}
return new LiteralMap(this.span(start), this.sourceSpan(start), keys, values);
}
parseAccessMember(readReceiver, start, isSafe) {
const nameStart = this.inputIndex;
const id = this.withContext(ParseContextFlags.Writable, () => {
var _a2;
const id2 = (_a2 = this.expectIdentifierOrKeyword()) != null ? _a2 : "";
if (id2.length === 0) {
this.error(`Expected identifier for property access`, readReceiver.span.end);
}
return id2;
});
const nameSpan = this.sourceSpan(nameStart);
let receiver;
if (isSafe) {
if (this.consumeOptionalOperator("=")) {
this.error("The '?.' operator cannot be used in the assignment");
receiver = new EmptyExpr(this.span(start), this.sourceSpan(start));
} else {
receiver = new SafePropertyRead(this.span(start), this.sourceSpan(start), nameSpan, readReceiver, id);
}
} else {
if (this.consumeOptionalOperator("=")) {
if (!(this.parseFlags & 1)) {
this.error("Bindings cannot contain assignments");
return new EmptyExpr(this.span(start), this.sourceSpan(start));
}
const value = this.parseConditional();
receiver = new PropertyWrite(this.span(start), this.sourceSpan(start), nameSpan, readReceiver, id, value);
} else {
receiver = new PropertyRead(this.span(start), this.sourceSpan(start), nameSpan, readReceiver, id);
}
}
return receiver;
}
parseCall(receiver, start, isSafe) {
const argumentStart = this.inputIndex;
this.rparensExpected++;
const args = this.parseCallArguments();
const argumentSpan = this.span(argumentStart, this.inputIndex).toAbsolute(this.absoluteOffset);
this.expectCharacter($RPAREN);
this.rparensExpected--;
const span = this.span(start);
const sourceSpan = this.sourceSpan(start);
return isSafe ? new SafeCall(span, sourceSpan, receiver, args, argumentSpan) : new Call(span, sourceSpan, receiver, args, argumentSpan);
}
parseCallArguments() {
if (this.next.isCharacter($RPAREN))
return [];
const positionals = [];
do {
positionals.push(this.parsePipe());
} while (this.consumeOptionalCharacter($COMMA));
return positionals;
}
expectTemplateBindingKey() {
let result = "";
let operatorFound = false;
const start = this.currentAbsoluteOffset;
do {
result += this.expectIdentifierOrKeywordOrString();
operatorFound = this.consumeOptionalOperator("-");
if (operatorFound) {
result += "-";
}
} while (operatorFound);
return {
source: result,
span: new AbsoluteSourceSpan(start, start + result.length)
};
}
parseTemplateBindings(templateKey) {
const bindings = [];
bindings.push(...this.parseDirectiveKeywordBindings(templateKey));
while (this.index < this.tokens.length) {
const letBinding = this.parseLetBinding();
if (letBinding) {
bindings.push(letBinding);
} else {
const key = this.expectTemplateBindingKey();
const binding = this.parseAsBinding(key);
if (binding) {
bindings.push(binding);
} else {
key.source = templateKey.source + key.source.charAt(0).toUpperCase() + key.source.substring(1);
bindings.push(...this.parseDirectiveKeywordBindings(key));
}
}
this.consumeStatementTerminator();
}
return new TemplateBindingParseResult(bindings, [], this.errors);
}
parseKeyedReadOrWrite(receiver, start, isSafe) {
return this.withContext(ParseContextFlags.Writable, () => {
this.rbracketsExpected++;
const key = this.parsePipe();
if (key instanceof EmptyExpr) {
this.error(`Key access cannot be empty`);
}
this.rbracketsExpected--;
this.expectCharacter($RBRACKET);
if (this.consumeOptionalOperator("=")) {
if (isSafe) {
this.error("The '?.' operator cannot be used in the assignment");
} else {
const value = this.parseConditional();
return new KeyedWrite(this.span(start), this.sourceSpan(start), receiver, key, value);
}
} else {
return isSafe ? new SafeKeyedRead(this.span(start), this.sourceSpan(start), receiver, key) : new KeyedRead(this.span(start), this.sourceSpan(start), receiver, key);
}
return new EmptyExpr(this.span(start), this.sourceSpan(start));
});
}
parseDirectiveKeywordBindings(key) {
const bindings = [];
this.consumeOptionalCharacter($COLON);
const value = this.getDirectiveBoundTarget();
let spanEnd = this.currentAbsoluteOffset;
const asBinding = this.parseAsBinding(key);
if (!asBinding) {
this.consumeStatementTerminator();
spanEnd = this.currentAbsoluteOffset;
}
const sourceSpan = new AbsoluteSourceSpan(key.span.start, spanEnd);
bindings.push(new ExpressionBinding(sourceSpan, key, value));
if (asBinding) {
bindings.push(asBinding);
}
return bindings;
}
getDirectiveBoundTarget() {
if (this.next === EOF || this.peekKeywordAs() || this.peekKeywordLet()) {
return null;
}
const ast = this.parsePipe();
const { start, end } = ast.span;
const value = this.input.substring(start, end);
return new ASTWithSource(ast, value, this.location, this.absoluteOffset + start, this.errors);
}
parseAsBinding(value) {
if (!this.peekKeywordAs()) {
return null;
}
this.advance();
const key = this.expectTemplateBindingKey();
this.consumeStatementTerminator();
const sourceSpan = new AbsoluteSourceSpan(value.span.start, this.currentAbsoluteOffset);
return new VariableBinding(sourceSpan, key, value);
}
parseLetBinding() {
if (!this.peekKeywordLet()) {
return null;
}
const spanStart = this.currentAbsoluteOffset;
this.advance();
const key = this.expectTemplateBindingKey();
let value = null;
if (this.consumeOptionalOperator("=")) {
value = this.expectTemplateBindingKey();
}
this.consumeStatementTerminator();
const sourceSpan = new AbsoluteSourceSpan(spanStart, this.currentAbsoluteOffset);
return new VariableBinding(sourceSpan, key, value);
}
consumeStatementTerminator() {
this.consumeOptionalCharacter($SEMICOLON) || this.consumeOptionalCharacter($COMMA);
}
error(message, index = null) {
this.errors.push(new ParserError(message, this.input, this.locationText(index), this.location));
this.skip();
}
locationText(index = null) {
if (index == null)
index = this.index;
return index < this.tokens.length ? `at column ${this.tokens[index].index + 1} in` : `at the end of the expression`;
}
_reportErrorForPrivateIdentifier(token, extraMessage) {
let errorMessage = `Private identifiers are not supported. Unexpected private identifier: ${token}`;
if (extraMessage !== null) {
errorMessage += `, ${extraMessage}`;
}
this.error(errorMessage);
}
skip() {
let n2 = this.next;
while (this.index < this.tokens.length && !n2.isCharacter($SEMICOLON) && !n2.isOperator("|") && (this.rparensExpected <= 0 || !n2.isCharacter($RPAREN)) && (this.rbracesExpected <= 0 || !n2.isCharacter($RBRACE)) && (this.rbracketsExpected <= 0 || !n2.isCharacter($RBRACKET)) && (!(this.context & ParseContextFlags.Writable) || !n2.isOperator("="))) {
if (this.next.isError()) {
this.errors.push(new ParserError(this.next.toString(), this.input, this.locationText(), this.location));
}
this.advance();
n2 = this.next;
}
}
};
var SimpleExpressionChecker = class extends RecursiveAstVisitor2 {
constructor() {
super(...arguments);
this.errors = [];
}
visitPipe() {
this.errors.push("pipes");
}
};
function getIndexMapForOriginalTemplate(interpolatedTokens) {
let offsetMap = /* @__PURE__ */ new Map();
let consumedInOriginalTemplate = 0;
let consumedInInput = 0;
let tokenIndex = 0;
while (tokenIndex < interpolatedTokens.length) {
const currentToken = interpolatedTokens[tokenIndex];
if (currentToken.type === 9) {
const [decoded, encoded] = currentToken.parts;
consumedInOriginalTemplate += encoded.length;
consumedInInput += decoded.length;
} else {
const lengthOfParts = currentToken.parts.reduce((sum, current) => sum + current.length, 0);
consumedInInput += lengthOfParts;
consumedInOriginalTemplate += lengthOfParts;
}
offsetMap.set(consumedInInput, consumedInOriginalTemplate);
tokenIndex++;
}
return offsetMap;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/schema/dom_security_schema.mjs
var _SECURITY_SCHEMA;
function SECURITY_SCHEMA() {
if (!_SECURITY_SCHEMA) {
_SECURITY_SCHEMA = {};
registerContext(SecurityContext.HTML, ["iframe|srcdoc", "*|innerHTML", "*|outerHTML"]);
registerContext(SecurityContext.STYLE, ["*|style"]);
registerContext(SecurityContext.URL, [
"*|formAction",
"area|href",
"area|ping",
"audio|src",
"a|href",
"a|ping",
"blockquote|cite",
"body|background",
"del|cite",
"form|action",
"img|src",
"input|src",
"ins|cite",
"q|cite",
"source|src",
"track|src",
"video|poster",
"video|src"
]);
registerContext(SecurityContext.RESOURCE_URL, [
"applet|code",
"applet|codebase",
"base|href",
"embed|src",
"frame|src",
"head|profile",
"html|manifest",
"iframe|src",
"link|href",
"media|src",
"object|codebase",
"object|data",
"script|src"
]);
}
return _SECURITY_SCHEMA;
}
function registerContext(ctx, specs) {
for (const spec of specs)
_SECURITY_SCHEMA[spec.toLowerCase()] = ctx;
}
var IFRAME_SECURITY_SENSITIVE_ATTRS = /* @__PURE__ */ new Set([
"sandbox",
"allow",
"allowfullscreen",
"referrerpolicy",
"csp",
"fetchpriority"
]);
function isIframeSecuritySensitiveAttr(attrName) {
return IFRAME_SECURITY_SENSITIVE_ATTRS.has(attrName.toLowerCase());
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/schema/element_schema_registry.mjs
var ElementSchemaRegistry = class {
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/schema/dom_element_schema_registry.mjs
var BOOLEAN = "boolean";
var NUMBER = "number";
var STRING = "string";
var OBJECT = "object";
var SCHEMA = [
"[Element]|textContent,%ariaAtomic,%ariaAutoComplete,%ariaBusy,%ariaChecked,%ariaColCount,%ariaColIndex,%ariaColSpan,%ariaCurrent,%ariaDescription,%ariaDisabled,%ariaExpanded,%ariaHasPopup,%ariaHidden,%ariaKeyShortcuts,%ariaLabel,%ariaLevel,%ariaLive,%ariaModal,%ariaMultiLine,%ariaMultiSelectable,%ariaOrientation,%ariaPlaceholder,%ariaPosInSet,%ariaPressed,%ariaReadOnly,%ariaRelevant,%ariaRequired,%ariaRoleDescription,%ariaRowCount,%ariaRowIndex,%ariaRowSpan,%ariaSelected,%ariaSetSize,%ariaSort,%ariaValueMax,%ariaValueMin,%ariaValueNow,%ariaValueText,%classList,className,elementTiming,id,innerHTML,*beforecopy,*beforecut,*beforepaste,*fullscreenchange,*fullscreenerror,*search,*webkitfullscreenchange,*webkitfullscreenerror,outerHTML,%part,#scrollLeft,#scrollTop,slot,*message,*mozfullscreenchange,*mozfullscreenerror,*mozpointerlockchange,*mozpointerlockerror,*webglcontextcreationerror,*webglcontextlost,*webglcontextrestored",
"[HTMLElement]^[Element]|accessKey,autocapitalize,!autofocus,contentEditable,dir,!draggable,enterKeyHint,!hidden,!inert,innerText,inputMode,lang,nonce,*abort,*animationend,*animationiteration,*animationstart,*auxclick,*beforexrselect,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*copy,*cuechange,*cut,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*formdata,*gotpointercapture,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*lostpointercapture,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*paste,*pause,*play,*playing,*pointercancel,*pointerdown,*pointerenter,*pointerleave,*pointermove,*pointerout,*pointerover,*pointerrawupdate,*pointerup,*progress,*ratechange,*reset,*resize,*scroll,*securitypolicyviolation,*seeked,*seeking,*select,*selectionchange,*selectstart,*slotchange,*stalled,*submit,*suspend,*timeupdate,*toggle,*transitioncancel,*transitionend,*transitionrun,*transitionstart,*volumechange,*waiting,*webkitanimationend,*webkitanimationiteration,*webkitanimationstart,*webkittransitionend,*wheel,outerText,!spellcheck,%style,#tabIndex,title,!translate,virtualKeyboardPolicy",
"abbr,address,article,aside,b,bdi,bdo,cite,content,code,dd,dfn,dt,em,figcaption,figure,footer,header,hgroup,i,kbd,main,mark,nav,noscript,rb,rp,rt,rtc,ruby,s,samp,section,small,strong,sub,sup,u,var,wbr^[HTMLElement]|accessKey,autocapitalize,!autofocus,contentEditable,dir,!draggable,enterKeyHint,!hidden,innerText,inputMode,lang,nonce,*abort,*animationend,*animationiteration,*animationstart,*auxclick,*beforexrselect,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*copy,*cuechange,*cut,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*formdata,*gotpointercapture,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*lostpointercapture,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*paste,*pause,*play,*playing,*pointercancel,*pointerdown,*pointerenter,*pointerleave,*pointermove,*pointerout,*pointerover,*pointerrawupdate,*pointerup,*progress,*ratechange,*reset,*resize,*scroll,*securitypolicyviolation,*seeked,*seeking,*select,*selectionchange,*selectstart,*slotchange,*stalled,*submit,*suspend,*timeupdate,*toggle,*transitioncancel,*transitionend,*transitionrun,*transitionstart,*volumechange,*waiting,*webkitanimationend,*webkitanimationiteration,*webkitanimationstart,*webkittransitionend,*wheel,outerText,!spellcheck,%style,#tabIndex,title,!translate,virtualKeyboardPolicy",
"media^[HTMLElement]|!autoplay,!controls,%controlsList,%crossOrigin,#currentTime,!defaultMuted,#defaultPlaybackRate,!disableRemotePlayback,!loop,!muted,*encrypted,*waitingforkey,#playbackRate,preload,!preservesPitch,src,%srcObject,#volume",
":svg:^[HTMLElement]|!autofocus,nonce,*abort,*animationend,*animationiteration,*animationstart,*auxclick,*beforexrselect,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*copy,*cuechange,*cut,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*formdata,*gotpointercapture,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*lostpointercapture,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*paste,*pause,*play,*playing,*pointercancel,*pointerdown,*pointerenter,*pointerleave,*pointermove,*pointerout,*pointerover,*pointerrawupdate,*pointerup,*progress,*ratechange,*reset,*resize,*scroll,*securitypolicyviolation,*seeked,*seeking,*select,*selectionchange,*selectstart,*slotchange,*stalled,*submit,*suspend,*timeupdate,*toggle,*transitioncancel,*transitionend,*transitionrun,*transitionstart,*volumechange,*waiting,*webkitanimationend,*webkitanimationiteration,*webkitanimationstart,*webkittransitionend,*wheel,%style,#tabIndex",
":svg:graphics^:svg:|",
":svg:animation^:svg:|*begin,*end,*repeat",
":svg:geometry^:svg:|",
":svg:componentTransferFunction^:svg:|",
":svg:gradient^:svg:|",
":svg:textContent^:svg:graphics|",
":svg:textPositioning^:svg:textContent|",
"a^[HTMLElement]|charset,coords,download,hash,host,hostname,href,hreflang,name,password,pathname,ping,port,protocol,referrerPolicy,rel,%relList,rev,search,shape,target,text,type,username",
"area^[HTMLElement]|alt,coords,download,hash,host,hostname,href,!noHref,password,pathname,ping,port,protocol,referrerPolicy,rel,%relList,search,shape,target,username",
"audio^media|",
"br^[HTMLElement]|clear",
"base^[HTMLElement]|href,target",
"body^[HTMLElement]|aLink,background,bgColor,link,*afterprint,*beforeprint,*beforeunload,*blur,*error,*focus,*hashchange,*languagechange,*load,*message,*messageerror,*offline,*online,*pagehide,*pageshow,*popstate,*rejectionhandled,*resize,*scroll,*storage,*unhandledrejection,*unload,text,vLink",
"button^[HTMLElement]|!disabled,formAction,formEnctype,formMethod,!formNoValidate,formTarget,name,type,value",
"canvas^[HTMLElement]|#height,#width",
"content^[HTMLElement]|select",
"dl^[HTMLElement]|!compact",
"data^[HTMLElement]|value",
"datalist^[HTMLElement]|",
"details^[HTMLElement]|!open",
"dialog^[HTMLElement]|!open,returnValue",
"dir^[HTMLElement]|!compact",
"div^[HTMLElement]|align",
"embed^[HTMLElement]|align,height,name,src,type,width",
"fieldset^[HTMLElement]|!disabled,name",
"font^[HTMLElement]|color,face,size",
"form^[HTMLElement]|acceptCharset,action,autocomplete,encoding,enctype,method,name,!noValidate,target",
"frame^[HTMLElement]|frameBorder,longDesc,marginHeight,marginWidth,name,!noResize,scrolling,src",
"frameset^[HTMLElement]|cols,*afterprint,*beforeprint,*beforeunload,*blur,*error,*focus,*hashchange,*languagechange,*load,*message,*messageerror,*offline,*online,*pagehide,*pageshow,*popstate,*rejectionhandled,*resize,*scroll,*storage,*unhandledrejection,*unload,rows",
"hr^[HTMLElement]|align,color,!noShade,size,width",
"head^[HTMLElement]|",
"h1,h2,h3,h4,h5,h6^[HTMLElement]|align",
"html^[HTMLElement]|version",
"iframe^[HTMLElement]|align,allow,!allowFullscreen,!allowPaymentRequest,csp,frameBorder,height,loading,longDesc,marginHeight,marginWidth,name,referrerPolicy,%sandbox,scrolling,src,srcdoc,width",
"img^[HTMLElement]|align,alt,border,%crossOrigin,decoding,#height,#hspace,!isMap,loading,longDesc,lowsrc,name,referrerPolicy,sizes,src,srcset,useMap,#vspace,#width",
"input^[HTMLElement]|accept,align,alt,autocomplete,!checked,!defaultChecked,defaultValue,dirName,!disabled,%files,formAction,formEnctype,formMethod,!formNoValidate,formTarget,#height,!incremental,!indeterminate,max,#maxLength,min,#minLength,!multiple,name,pattern,placeholder,!readOnly,!required,selectionDirection,#selectionEnd,#selectionStart,#size,src,step,type,useMap,value,%valueAsDate,#valueAsNumber,#width",
"li^[HTMLElement]|type,#value",
"label^[HTMLElement]|htmlFor",
"legend^[HTMLElement]|align",
"link^[HTMLElement]|as,charset,%crossOrigin,!disabled,href,hreflang,imageSizes,imageSrcset,integrity,media,referrerPolicy,rel,%relList,rev,%sizes,target,type",
"map^[HTMLElement]|name",
"marquee^[HTMLElement]|behavior,bgColor,direction,height,#hspace,#loop,#scrollAmount,#scrollDelay,!trueSpeed,#vspace,width",
"menu^[HTMLElement]|!compact",
"meta^[HTMLElement]|content,httpEquiv,media,name,scheme",
"meter^[HTMLElement]|#high,#low,#max,#min,#optimum,#value",
"ins,del^[HTMLElement]|cite,dateTime",
"ol^[HTMLElement]|!compact,!reversed,#start,type",
"object^[HTMLElement]|align,archive,border,code,codeBase,codeType,data,!declare,height,#hspace,name,standby,type,useMap,#vspace,width",
"optgroup^[HTMLElement]|!disabled,label",
"option^[HTMLElement]|!defaultSelected,!disabled,label,!selected,text,value",
"output^[HTMLElement]|defaultValue,%htmlFor,name,value",
"p^[HTMLElement]|align",
"param^[HTMLElement]|name,type,value,valueType",
"picture^[HTMLElement]|",
"pre^[HTMLElement]|#width",
"progress^[HTMLElement]|#max,#value",
"q,blockquote,cite^[HTMLElement]|",
"script^[HTMLElement]|!async,charset,%crossOrigin,!defer,event,htmlFor,integrity,!noModule,%referrerPolicy,src,text,type",
"select^[HTMLElement]|autocomplete,!disabled,#length,!multiple,name,!required,#selectedIndex,#size,value",
"slot^[HTMLElement]|name",
"source^[HTMLElement]|#height,media,sizes,src,srcset,type,#width",
"span^[HTMLElement]|",
"style^[HTMLElement]|!disabled,media,type",
"caption^[HTMLElement]|align",
"th,td^[HTMLElement]|abbr,align,axis,bgColor,ch,chOff,#colSpan,headers,height,!noWrap,#rowSpan,scope,vAlign,width",
"col,colgroup^[HTMLElement]|align,ch,chOff,#span,vAlign,width",
"table^[HTMLElement]|align,bgColor,border,%caption,cellPadding,cellSpacing,frame,rules,summary,%tFoot,%tHead,width",
"tr^[HTMLElement]|align,bgColor,ch,chOff,vAlign",
"tfoot,thead,tbody^[HTMLElement]|align,ch,chOff,vAlign",
"template^[HTMLElement]|",
"textarea^[HTMLElement]|autocomplete,#cols,defaultValue,dirName,!disabled,#maxLength,#minLength,name,placeholder,!readOnly,!required,#rows,selectionDirection,#selectionEnd,#selectionStart,value,wrap",
"time^[HTMLElement]|dateTime",
"title^[HTMLElement]|text",
"track^[HTMLElement]|!default,kind,label,src,srclang",
"ul^[HTMLElement]|!compact,type",
"unknown^[HTMLElement]|",
"video^media|!disablePictureInPicture,#height,*enterpictureinpicture,*leavepictureinpicture,!playsInline,poster,#width",
":svg:a^:svg:graphics|",
":svg:animate^:svg:animation|",
":svg:animateMotion^:svg:animation|",
":svg:animateTransform^:svg:animation|",
":svg:circle^:svg:geometry|",
":svg:clipPath^:svg:graphics|",
":svg:defs^:svg:graphics|",
":svg:desc^:svg:|",
":svg:discard^:svg:|",
":svg:ellipse^:svg:geometry|",
":svg:feBlend^:svg:|",
":svg:feColorMatrix^:svg:|",
":svg:feComponentTransfer^:svg:|",
":svg:feComposite^:svg:|",
":svg:feConvolveMatrix^:svg:|",
":svg:feDiffuseLighting^:svg:|",
":svg:feDisplacementMap^:svg:|",
":svg:feDistantLight^:svg:|",
":svg:feDropShadow^:svg:|",
":svg:feFlood^:svg:|",
":svg:feFuncA^:svg:componentTransferFunction|",
":svg:feFuncB^:svg:componentTransferFunction|",
":svg:feFuncG^:svg:componentTransferFunction|",
":svg:feFuncR^:svg:componentTransferFunction|",
":svg:feGaussianBlur^:svg:|",
":svg:feImage^:svg:|",
":svg:feMerge^:svg:|",
":svg:feMergeNode^:svg:|",
":svg:feMorphology^:svg:|",
":svg:feOffset^:svg:|",
":svg:fePointLight^:svg:|",
":svg:feSpecularLighting^:svg:|",
":svg:feSpotLight^:svg:|",
":svg:feTile^:svg:|",
":svg:feTurbulence^:svg:|",
":svg:filter^:svg:|",
":svg:foreignObject^:svg:graphics|",
":svg:g^:svg:graphics|",
":svg:image^:svg:graphics|decoding",
":svg:line^:svg:geometry|",
":svg:linearGradient^:svg:gradient|",
":svg:mpath^:svg:|",
":svg:marker^:svg:|",
":svg:mask^:svg:|",
":svg:metadata^:svg:|",
":svg:path^:svg:geometry|",
":svg:pattern^:svg:|",
":svg:polygon^:svg:geometry|",
":svg:polyline^:svg:geometry|",
":svg:radialGradient^:svg:gradient|",
":svg:rect^:svg:geometry|",
":svg:svg^:svg:graphics|#currentScale,#zoomAndPan",
":svg:script^:svg:|type",
":svg:set^:svg:animation|",
":svg:stop^:svg:|",
":svg:style^:svg:|!disabled,media,title,type",
":svg:switch^:svg:graphics|",
":svg:symbol^:svg:|",
":svg:tspan^:svg:textPositioning|",
":svg:text^:svg:textPositioning|",
":svg:textPath^:svg:textContent|",
":svg:title^:svg:|",
":svg:use^:svg:graphics|",
":svg:view^:svg:|#zoomAndPan",
"data^[HTMLElement]|value",
"keygen^[HTMLElement]|!autofocus,challenge,!disabled,form,keytype,name",
"menuitem^[HTMLElement]|type,label,icon,!disabled,!checked,radiogroup,!default",
"summary^[HTMLElement]|",
"time^[HTMLElement]|dateTime",
":svg:cursor^:svg:|",
":math:^[HTMLElement]|!autofocus,nonce,*abort,*animationend,*animationiteration,*animationstart,*auxclick,*beforeinput,*beforematch,*beforetoggle,*beforexrselect,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contentvisibilityautostatechange,*contextlost,*contextmenu,*contextrestored,*copy,*cuechange,*cut,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*formdata,*gotpointercapture,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*lostpointercapture,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*paste,*pause,*play,*playing,*pointercancel,*pointerdown,*pointerenter,*pointerleave,*pointermove,*pointerout,*pointerover,*pointerrawupdate,*pointerup,*progress,*ratechange,*reset,*resize,*scroll,*scrollend,*securitypolicyviolation,*seeked,*seeking,*select,*selectionchange,*selectstart,*slotchange,*stalled,*submit,*suspend,*timeupdate,*toggle,*transitioncancel,*transitionend,*transitionrun,*transitionstart,*volumechange,*waiting,*webkitanimationend,*webkitanimationiteration,*webkitanimationstart,*webkittransitionend,*wheel,%style,#tabIndex",
":math:math^:math:|",
":math:maction^:math:|",
":math:menclose^:math:|",
":math:merror^:math:|",
":math:mfenced^:math:|",
":math:mfrac^:math:|",
":math:mi^:math:|",
":math:mmultiscripts^:math:|",
":math:mn^:math:|",
":math:mo^:math:|",
":math:mover^:math:|",
":math:mpadded^:math:|",
":math:mphantom^:math:|",
":math:mroot^:math:|",
":math:mrow^:math:|",
":math:ms^:math:|",
":math:mspace^:math:|",
":math:msqrt^:math:|",
":math:mstyle^:math:|",
":math:msub^:math:|",
":math:msubsup^:math:|",
":math:msup^:math:|",
":math:mtable^:math:|",
":math:mtd^:math:|",
":math:mtext^:math:|",
":math:mtr^:math:|",
":math:munder^:math:|",
":math:munderover^:math:|",
":math:semantics^:math:|"
];
var _ATTR_TO_PROP = new Map(Object.entries({
"class": "className",
"for": "htmlFor",
"formaction": "formAction",
"innerHtml": "innerHTML",
"readonly": "readOnly",
"tabindex": "tabIndex"
}));
var _PROP_TO_ATTR = Array.from(_ATTR_TO_PROP).reduce((inverted, [propertyName, attributeName]) => {
inverted.set(propertyName, attributeName);
return inverted;
}, /* @__PURE__ */ new Map());
var DomElementSchemaRegistry = class extends ElementSchemaRegistry {
constructor() {
super();
this._schema = /* @__PURE__ */ new Map();
this._eventSchema = /* @__PURE__ */ new Map();
SCHEMA.forEach((encodedType) => {
const type = /* @__PURE__ */ new Map();
const events = /* @__PURE__ */ new Set();
const [strType, strProperties] = encodedType.split("|");
const properties = strProperties.split(",");
const [typeNames, superName] = strType.split("^");
typeNames.split(",").forEach((tag) => {
this._schema.set(tag.toLowerCase(), type);
this._eventSchema.set(tag.toLowerCase(), events);
});
const superType = superName && this._schema.get(superName.toLowerCase());
if (superType) {
for (const [prop, value] of superType) {
type.set(prop, value);
}
for (const superEvent of this._eventSchema.get(superName.toLowerCase())) {
events.add(superEvent);
}
}
properties.forEach((property2) => {
if (property2.length > 0) {
switch (property2[0]) {
case "*":
events.add(property2.substring(1));
break;
case "!":
type.set(property2.substring(1), BOOLEAN);
break;
case "#":
type.set(property2.substring(1), NUMBER);
break;
case "%":
type.set(property2.substring(1), OBJECT);
break;
default:
type.set(property2, STRING);
}
}
});
});
}
hasProperty(tagName, propName, schemaMetas) {
if (schemaMetas.some((schema) => schema.name === NO_ERRORS_SCHEMA.name)) {
return true;
}
if (tagName.indexOf("-") > -1) {
if (isNgContainer(tagName) || isNgContent(tagName)) {
return false;
}
if (schemaMetas.some((schema) => schema.name === CUSTOM_ELEMENTS_SCHEMA.name)) {
return true;
}
}
const elementProperties = this._schema.get(tagName.toLowerCase()) || this._schema.get("unknown");
return elementProperties.has(propName);
}
hasElement(tagName, schemaMetas) {
if (schemaMetas.some((schema) => schema.name === NO_ERRORS_SCHEMA.name)) {
return true;
}
if (tagName.indexOf("-") > -1) {
if (isNgContainer(tagName) || isNgContent(tagName)) {
return true;
}
if (schemaMetas.some((schema) => schema.name === CUSTOM_ELEMENTS_SCHEMA.name)) {
return true;
}
}
return this._schema.has(tagName.toLowerCase());
}
securityContext(tagName, propName, isAttribute) {
if (isAttribute) {
propName = this.getMappedPropName(propName);
}
tagName = tagName.toLowerCase();
propName = propName.toLowerCase();
let ctx = SECURITY_SCHEMA()[tagName + "|" + propName];
if (ctx) {
return ctx;
}
ctx = SECURITY_SCHEMA()["*|" + propName];
return ctx ? ctx : SecurityContext.NONE;
}
getMappedPropName(propName) {
var _a2;
return (_a2 = _ATTR_TO_PROP.get(propName)) != null ? _a2 : propName;
}
getDefaultComponentElementName() {
return "ng-component";
}
validateProperty(name) {
if (name.toLowerCase().startsWith("on")) {
const msg = `Binding to event property '${name}' is disallowed for security reasons, please use (${name.slice(2)})=...
If '${name}' is a directive input, make sure the directive is imported by the current module.`;
return { error: true, msg };
} else {
return { error: false };
}
}
validateAttribute(name) {
if (name.toLowerCase().startsWith("on")) {
const msg = `Binding to event attribute '${name}' is disallowed for security reasons, please use (${name.slice(2)})=...`;
return { error: true, msg };
} else {
return { error: false };
}
}
allKnownElementNames() {
return Array.from(this._schema.keys());
}
allKnownAttributesOfElement(tagName) {
const elementProperties = this._schema.get(tagName.toLowerCase()) || this._schema.get("unknown");
return Array.from(elementProperties.keys()).map((prop) => {
var _a2;
return (_a2 = _PROP_TO_ATTR.get(prop)) != null ? _a2 : prop;
});
}
allKnownEventsOfElement(tagName) {
var _a2;
return Array.from((_a2 = this._eventSchema.get(tagName.toLowerCase())) != null ? _a2 : []);
}
normalizeAnimationStyleProperty(propName) {
return dashCaseToCamelCase(propName);
}
normalizeAnimationStyleValue(camelCaseProp, userProvidedProp, val) {
let unit = "";
const strVal = val.toString().trim();
let errorMsg = null;
if (_isPixelDimensionStyle(camelCaseProp) && val !== 0 && val !== "0") {
if (typeof val === "number") {
unit = "px";
} else {
const valAndSuffixMatch = val.match(/^[+-]?[\d\.]+([a-z]*)$/);
if (valAndSuffixMatch && valAndSuffixMatch[1].length == 0) {
errorMsg = `Please provide a CSS unit value for ${userProvidedProp}:${val}`;
}
}
}
return { error: errorMsg, value: strVal + unit };
}
};
function _isPixelDimensionStyle(prop) {
switch (prop) {
case "width":
case "height":
case "minWidth":
case "minHeight":
case "maxWidth":
case "maxHeight":
case "left":
case "top":
case "bottom":
case "right":
case "fontSize":
case "outlineWidth":
case "outlineOffset":
case "paddingTop":
case "paddingLeft":
case "paddingBottom":
case "paddingRight":
case "marginTop":
case "marginLeft":
case "marginBottom":
case "marginRight":
case "borderRadius":
case "borderWidth":
case "borderTopWidth":
case "borderLeftWidth":
case "borderRightWidth":
case "borderBottomWidth":
case "textIndent":
return true;
default:
return false;
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/ml_parser/html_tags.mjs
var HtmlTagDefinition = class {
constructor({ closedByChildren, implicitNamespacePrefix, contentType = TagContentType.PARSABLE_DATA, closedByParent = false, isVoid = false, ignoreFirstLf = false, preventNamespaceInheritance = false, canSelfClose = false } = {}) {
this.closedByChildren = {};
this.closedByParent = false;
if (closedByChildren && closedByChildren.length > 0) {
closedByChildren.forEach((tagName) => this.closedByChildren[tagName] = true);
}
this.isVoid = isVoid;
this.closedByParent = closedByParent || isVoid;
this.implicitNamespacePrefix = implicitNamespacePrefix || null;
this.contentType = contentType;
this.ignoreFirstLf = ignoreFirstLf;
this.preventNamespaceInheritance = preventNamespaceInheritance;
this.canSelfClose = canSelfClose != null ? canSelfClose : isVoid;
}
isClosedByChild(name) {
return this.isVoid || name.toLowerCase() in this.closedByChildren;
}
getContentType(prefix) {
if (typeof this.contentType === "object") {
const overrideType = prefix === void 0 ? void 0 : this.contentType[prefix];
return overrideType != null ? overrideType : this.contentType.default;
}
return this.contentType;
}
};
var DEFAULT_TAG_DEFINITION;
var TAG_DEFINITIONS;
function getHtmlTagDefinition(tagName) {
var _a2, _b2;
if (!TAG_DEFINITIONS) {
DEFAULT_TAG_DEFINITION = new HtmlTagDefinition({ canSelfClose: true });
TAG_DEFINITIONS = Object.assign(/* @__PURE__ */ Object.create(null), {
"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" }),
"foreignObject": new HtmlTagDefinition({
implicitNamespacePrefix: "svg",
preventNamespaceInheritance: true
}),
"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: {
default: TagContentType.ESCAPABLE_RAW_TEXT,
svg: TagContentType.PARSABLE_DATA
}
}),
"textarea": new HtmlTagDefinition({
contentType: TagContentType.ESCAPABLE_RAW_TEXT,
ignoreFirstLf: true
})
});
new DomElementSchemaRegistry().allKnownElementNames().forEach((knownTagName) => {
if (!TAG_DEFINITIONS[knownTagName] && getNsPrefix(knownTagName) === null) {
TAG_DEFINITIONS[knownTagName] = new HtmlTagDefinition({ canSelfClose: false });
}
});
}
return (_b2 = (_a2 = TAG_DEFINITIONS[tagName]) != null ? _a2 : TAG_DEFINITIONS[tagName.toLowerCase()]) != null ? _b2 : DEFAULT_TAG_DEFINITION;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/i18n/serializers/placeholder.mjs
var TAG_TO_PLACEHOLDER_NAMES = {
"A": "LINK",
"B": "BOLD_TEXT",
"BR": "LINE_BREAK",
"EM": "EMPHASISED_TEXT",
"H1": "HEADING_LEVEL1",
"H2": "HEADING_LEVEL2",
"H3": "HEADING_LEVEL3",
"H4": "HEADING_LEVEL4",
"H5": "HEADING_LEVEL5",
"H6": "HEADING_LEVEL6",
"HR": "HORIZONTAL_RULE",
"I": "ITALIC_TEXT",
"LI": "LIST_ITEM",
"LINK": "MEDIA_LINK",
"OL": "ORDERED_LIST",
"P": "PARAGRAPH",
"Q": "QUOTATION",
"S": "STRIKETHROUGH_TEXT",
"SMALL": "SMALL_TEXT",
"SUB": "SUBSTRIPT",
"SUP": "SUPERSCRIPT",
"TBODY": "TABLE_BODY",
"TD": "TABLE_CELL",
"TFOOT": "TABLE_FOOTER",
"TH": "TABLE_HEADER_CELL",
"THEAD": "TABLE_HEADER",
"TR": "TABLE_ROW",
"TT": "MONOSPACED_TEXT",
"U": "UNDERLINED_TEXT",
"UL": "UNORDERED_LIST"
};
var PlaceholderRegistry = class {
constructor() {
this._placeHolderNameCounts = {};
this._signatureToName = {};
}
getStartTagPlaceholderName(tag, attrs, isVoid) {
const signature = this._hashTag(tag, attrs, isVoid);
if (this._signatureToName[signature]) {
return this._signatureToName[signature];
}
const upperTag = tag.toUpperCase();
const baseName = TAG_TO_PLACEHOLDER_NAMES[upperTag] || `TAG_${upperTag}`;
const name = this._generateUniqueName(isVoid ? baseName : `START_${baseName}`);
this._signatureToName[signature] = name;
return name;
}
getCloseTagPlaceholderName(tag) {
const signature = this._hashClosingTag(tag);
if (this._signatureToName[signature]) {
return this._signatureToName[signature];
}
const upperTag = tag.toUpperCase();
const baseName = TAG_TO_PLACEHOLDER_NAMES[upperTag] || `TAG_${upperTag}`;
const name = this._generateUniqueName(`CLOSE_${baseName}`);
this._signatureToName[signature] = name;
return name;
}
getPlaceholderName(name, content) {
const upperName = name.toUpperCase();
const signature = `PH: ${upperName}=${content}`;
if (this._signatureToName[signature]) {
return this._signatureToName[signature];
}
const uniqueName = this._generateUniqueName(upperName);
this._signatureToName[signature] = uniqueName;
return uniqueName;
}
getUniquePlaceholder(name) {
return this._generateUniqueName(name.toUpperCase());
}
getStartBlockPlaceholderName(name, parameters) {
const signature = this._hashBlock(name, parameters);
if (this._signatureToName[signature]) {
return this._signatureToName[signature];
}
const placeholder = this._generateUniqueName(`START_BLOCK_${this._toSnakeCase(name)}`);
this._signatureToName[signature] = placeholder;
return placeholder;
}
getCloseBlockPlaceholderName(name) {
const signature = this._hashClosingBlock(name);
if (this._signatureToName[signature]) {
return this._signatureToName[signature];
}
const placeholder = this._generateUniqueName(`CLOSE_BLOCK_${this._toSnakeCase(name)}`);
this._signatureToName[signature] = placeholder;
return placeholder;
}
_hashTag(tag, attrs, isVoid) {
const start = `<${tag}`;
const strAttrs = Object.keys(attrs).sort().map((name) => ` ${name}=${attrs[name]}`).join("");
const end = isVoid ? "/>" : `>${tag}>`;
return start + strAttrs + end;
}
_hashClosingTag(tag) {
return this._hashTag(`/${tag}`, {}, false);
}
_hashBlock(name, parameters) {
const params = parameters.length === 0 ? "" : ` (${parameters.sort().join("; ")})`;
return `@${name}${params} {}`;
}
_hashClosingBlock(name) {
return this._hashBlock(`close_${name}`, []);
}
_toSnakeCase(name) {
return name.toUpperCase().replace(/[^A-Z0-9]/g, "_");
}
_generateUniqueName(base) {
const seen = this._placeHolderNameCounts.hasOwnProperty(base);
if (!seen) {
this._placeHolderNameCounts[base] = 1;
return base;
}
const id = this._placeHolderNameCounts[base];
this._placeHolderNameCounts[base] = id + 1;
return `${base}_${id}`;
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/i18n/i18n_parser.mjs
var _expParser = new Parser2(new Lexer());
function createI18nMessageFactory(interpolationConfig, containerBlocks, retainEmptyTokens) {
const visitor = new _I18nVisitor(_expParser, interpolationConfig, containerBlocks, retainEmptyTokens);
return (nodes, meaning, description, customId, visitNodeFn) => visitor.toI18nMessage(nodes, meaning, description, customId, visitNodeFn);
}
function noopVisitNodeFn(_html, i18n2) {
return i18n2;
}
var _I18nVisitor = class {
constructor(_expressionParser, _interpolationConfig, _containerBlocks, _retainEmptyTokens) {
this._expressionParser = _expressionParser;
this._interpolationConfig = _interpolationConfig;
this._containerBlocks = _containerBlocks;
this._retainEmptyTokens = _retainEmptyTokens;
}
toI18nMessage(nodes, meaning = "", description = "", customId = "", visitNodeFn) {
const context = {
isIcu: nodes.length == 1 && nodes[0] instanceof Expansion,
icuDepth: 0,
placeholderRegistry: new PlaceholderRegistry(),
placeholderToContent: {},
placeholderToMessage: {},
visitNodeFn: visitNodeFn || noopVisitNodeFn
};
const i18nodes = visitAll2(this, nodes, context);
return new Message(i18nodes, context.placeholderToContent, context.placeholderToMessage, meaning, description, customId);
}
visitElement(el, context) {
var _a2;
const children = visitAll2(this, el.children, context);
const attrs = {};
el.attrs.forEach((attr) => {
attrs[attr.name] = attr.value;
});
const isVoid = getHtmlTagDefinition(el.name).isVoid;
const startPhName = context.placeholderRegistry.getStartTagPlaceholderName(el.name, attrs, isVoid);
context.placeholderToContent[startPhName] = {
text: el.startSourceSpan.toString(),
sourceSpan: el.startSourceSpan
};
let closePhName = "";
if (!isVoid) {
closePhName = context.placeholderRegistry.getCloseTagPlaceholderName(el.name);
context.placeholderToContent[closePhName] = {
text: `${el.name}>`,
sourceSpan: (_a2 = el.endSourceSpan) != null ? _a2 : el.sourceSpan
};
}
const node = new TagPlaceholder(el.name, attrs, startPhName, closePhName, children, isVoid, el.sourceSpan, el.startSourceSpan, el.endSourceSpan);
return context.visitNodeFn(el, node);
}
visitAttribute(attribute2, context) {
const node = attribute2.valueTokens === void 0 || attribute2.valueTokens.length === 1 ? new Text2(attribute2.value, attribute2.valueSpan || attribute2.sourceSpan) : this._visitTextWithInterpolation(attribute2.valueTokens, attribute2.valueSpan || attribute2.sourceSpan, context, attribute2.i18n);
return context.visitNodeFn(attribute2, node);
}
visitText(text2, context) {
const node = text2.tokens.length === 1 ? new Text2(text2.value, text2.sourceSpan) : this._visitTextWithInterpolation(text2.tokens, text2.sourceSpan, context, text2.i18n);
return context.visitNodeFn(text2, node);
}
visitComment(comment, context) {
return null;
}
visitExpansion(icu, context) {
context.icuDepth++;
const i18nIcuCases = {};
const i18nIcu = new Icu2(icu.switchValue, icu.type, i18nIcuCases, icu.sourceSpan);
icu.cases.forEach((caze) => {
i18nIcuCases[caze.value] = new Container(caze.expression.map((node2) => node2.visit(this, context)), caze.expSourceSpan);
});
context.icuDepth--;
if (context.isIcu || context.icuDepth > 0) {
const expPh = context.placeholderRegistry.getUniquePlaceholder(`VAR_${icu.type}`);
i18nIcu.expressionPlaceholder = expPh;
context.placeholderToContent[expPh] = {
text: icu.switchValue,
sourceSpan: icu.switchValueSourceSpan
};
return context.visitNodeFn(icu, i18nIcu);
}
const phName = context.placeholderRegistry.getPlaceholderName("ICU", icu.sourceSpan.toString());
context.placeholderToMessage[phName] = this.toI18nMessage([icu], "", "", "", void 0);
const node = new IcuPlaceholder(i18nIcu, phName, icu.sourceSpan);
return context.visitNodeFn(icu, node);
}
visitExpansionCase(_icuCase, _context) {
throw new Error("Unreachable code");
}
visitBlock(block, context) {
var _a2;
const children = visitAll2(this, block.children, context);
if (this._containerBlocks.has(block.name)) {
return new Container(children, block.sourceSpan);
}
const parameters = block.parameters.map((param) => param.expression);
const startPhName = context.placeholderRegistry.getStartBlockPlaceholderName(block.name, parameters);
const closePhName = context.placeholderRegistry.getCloseBlockPlaceholderName(block.name);
context.placeholderToContent[startPhName] = {
text: block.startSourceSpan.toString(),
sourceSpan: block.startSourceSpan
};
context.placeholderToContent[closePhName] = {
text: block.endSourceSpan ? block.endSourceSpan.toString() : "}",
sourceSpan: (_a2 = block.endSourceSpan) != null ? _a2 : block.sourceSpan
};
const node = new BlockPlaceholder(block.name, parameters, startPhName, closePhName, children, block.sourceSpan, block.startSourceSpan, block.endSourceSpan);
return context.visitNodeFn(block, node);
}
visitBlockParameter(_parameter, _context) {
throw new Error("Unreachable code");
}
visitLetDeclaration(decl, context) {
return null;
}
_visitTextWithInterpolation(tokens, sourceSpan, context, previousI18n) {
const nodes = [];
let hasInterpolation = false;
for (const token of tokens) {
switch (token.type) {
case 8:
case 17:
hasInterpolation = true;
const expression = token.parts[1];
const baseName = extractPlaceholderName(expression) || "INTERPOLATION";
const phName = context.placeholderRegistry.getPlaceholderName(baseName, expression);
context.placeholderToContent[phName] = {
text: token.parts.join(""),
sourceSpan: token.sourceSpan
};
nodes.push(new Placeholder(expression, phName, token.sourceSpan));
break;
default:
if (token.parts[0].length > 0 || this._retainEmptyTokens) {
const previous = nodes[nodes.length - 1];
if (previous instanceof Text2) {
previous.value += token.parts[0];
previous.sourceSpan = new ParseSourceSpan(previous.sourceSpan.start, token.sourceSpan.end, previous.sourceSpan.fullStart, previous.sourceSpan.details);
} else {
nodes.push(new Text2(token.parts[0], token.sourceSpan));
}
} else {
if (this._retainEmptyTokens) {
nodes.push(new Text2(token.parts[0], token.sourceSpan));
}
}
break;
}
}
if (hasInterpolation) {
reusePreviousSourceSpans(nodes, previousI18n);
return new Container(nodes, sourceSpan);
} else {
return nodes[0];
}
}
};
function reusePreviousSourceSpans(nodes, previousI18n) {
if (previousI18n instanceof Message) {
assertSingleContainerMessage(previousI18n);
previousI18n = previousI18n.nodes[0];
}
if (previousI18n instanceof Container) {
assertEquivalentNodes(previousI18n.children, nodes);
for (let i = 0; i < nodes.length; i++) {
nodes[i].sourceSpan = previousI18n.children[i].sourceSpan;
}
}
}
function assertSingleContainerMessage(message) {
const nodes = message.nodes;
if (nodes.length !== 1 || !(nodes[0] instanceof Container)) {
throw new Error("Unexpected previous i18n message - expected it to consist of only a single `Container` node.");
}
}
function assertEquivalentNodes(previousNodes, nodes) {
if (previousNodes.length !== nodes.length) {
throw new Error(`
The number of i18n message children changed between first and second pass.
First pass (${previousNodes.length} tokens):
${previousNodes.map((node) => `"${node.sourceSpan.toString()}"`).join("\n")}
Second pass (${nodes.length} tokens):
${nodes.map((node) => `"${node.sourceSpan.toString()}"`).join("\n")}
`.trim());
}
if (previousNodes.some((node, i) => nodes[i].constructor !== node.constructor)) {
throw new Error("The types of the i18n message children changed between first and second pass.");
}
}
var _CUSTOM_PH_EXP = /\/\/[\s\S]*i18n[\s\S]*\([\s\S]*ph[\s\S]*=[\s\S]*("|')([\s\S]*?)\1[\s\S]*\)/g;
function extractPlaceholderName(input) {
return input.split(_CUSTOM_PH_EXP)[2];
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/i18n/parse_util.mjs
var I18nError = class extends ParseError {
constructor(span, msg) {
super(span, msg);
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/schema/trusted_types_sinks.mjs
var TRUSTED_TYPES_SINKS = /* @__PURE__ */ new Set([
"iframe|srcdoc",
"*|innerhtml",
"*|outerhtml",
"embed|src",
"object|codebase",
"object|data"
]);
function isTrustedTypesSink(tagName, propName) {
tagName = tagName.toLowerCase();
propName = propName.toLowerCase();
return TRUSTED_TYPES_SINKS.has(tagName + "|" + propName) || TRUSTED_TYPES_SINKS.has("*|" + propName);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/view/i18n/meta.mjs
var setI18nRefs = (originalNodeMap) => {
return (trimmedNode, i18nNode) => {
var _a2;
const originalNode = (_a2 = originalNodeMap.get(trimmedNode)) != null ? _a2 : trimmedNode;
if (originalNode instanceof NodeWithI18n) {
if (i18nNode instanceof IcuPlaceholder && originalNode.i18n instanceof Message) {
i18nNode.previousMessage = originalNode.i18n;
}
originalNode.i18n = i18nNode;
}
return i18nNode;
};
};
var I18nMetaVisitor = class {
constructor(interpolationConfig = DEFAULT_INTERPOLATION_CONFIG, keepI18nAttrs = false, enableI18nLegacyMessageIdFormat = false, containerBlocks = DEFAULT_CONTAINER_BLOCKS, preserveSignificantWhitespace = true, retainEmptyTokens = !preserveSignificantWhitespace) {
this.interpolationConfig = interpolationConfig;
this.keepI18nAttrs = keepI18nAttrs;
this.enableI18nLegacyMessageIdFormat = enableI18nLegacyMessageIdFormat;
this.containerBlocks = containerBlocks;
this.preserveSignificantWhitespace = preserveSignificantWhitespace;
this.retainEmptyTokens = retainEmptyTokens;
this.hasI18nMeta = false;
this._errors = [];
}
_generateI18nMessage(nodes, meta = "", visitNodeFn) {
const { meaning, description, customId } = this._parseMetadata(meta);
const createI18nMessage2 = createI18nMessageFactory(this.interpolationConfig, this.containerBlocks, this.retainEmptyTokens);
const message = createI18nMessage2(nodes, meaning, description, customId, visitNodeFn);
this._setMessageId(message, meta);
this._setLegacyIds(message, meta);
return message;
}
visitAllWithErrors(nodes) {
const result = nodes.map((node) => node.visit(this, null));
return new ParseTreeResult(result, this._errors);
}
visitElement(element2) {
let message = void 0;
if (hasI18nAttrs(element2)) {
this.hasI18nMeta = true;
const attrs = [];
const attrsMeta = {};
for (const attr of element2.attrs) {
if (attr.name === I18N_ATTR) {
const i18n2 = element2.i18n || attr.value;
const originalNodeMap = /* @__PURE__ */ new Map();
const trimmedNodes = this.preserveSignificantWhitespace ? element2.children : visitAllWithSiblings(new WhitespaceVisitor(false, originalNodeMap), element2.children);
message = this._generateI18nMessage(trimmedNodes, i18n2, setI18nRefs(originalNodeMap));
if (message.nodes.length === 0) {
message = void 0;
}
element2.i18n = message;
} else if (attr.name.startsWith(I18N_ATTR_PREFIX)) {
const name = attr.name.slice(I18N_ATTR_PREFIX.length);
if (isTrustedTypesSink(element2.name, name)) {
this._reportError(attr, `Translating attribute '${name}' is disallowed for security reasons.`);
} else {
attrsMeta[name] = attr.value;
}
} else {
attrs.push(attr);
}
}
if (Object.keys(attrsMeta).length) {
for (const attr of attrs) {
const meta = attrsMeta[attr.name];
if (meta !== void 0 && attr.value) {
attr.i18n = this._generateI18nMessage([attr], attr.i18n || meta);
}
}
}
if (!this.keepI18nAttrs) {
element2.attrs = attrs;
}
}
visitAll2(this, element2.children, message);
return element2;
}
visitExpansion(expansion, currentMessage) {
let message;
const meta = expansion.i18n;
this.hasI18nMeta = true;
if (meta instanceof IcuPlaceholder) {
const name = meta.name;
message = this._generateI18nMessage([expansion], meta);
const icu = icuFromI18nMessage(message);
icu.name = name;
if (currentMessage !== null) {
currentMessage.placeholderToMessage[name] = message;
}
} else {
message = this._generateI18nMessage([expansion], currentMessage || meta);
}
expansion.i18n = message;
return expansion;
}
visitText(text2) {
return text2;
}
visitAttribute(attribute2) {
return attribute2;
}
visitComment(comment) {
return comment;
}
visitExpansionCase(expansionCase) {
return expansionCase;
}
visitBlock(block, context) {
visitAll2(this, block.children, context);
return block;
}
visitBlockParameter(parameter, context) {
return parameter;
}
visitLetDeclaration(decl, context) {
return decl;
}
_parseMetadata(meta) {
return typeof meta === "string" ? parseI18nMeta(meta) : meta instanceof Message ? meta : {};
}
_setMessageId(message, meta) {
if (!message.id) {
message.id = meta instanceof Message && meta.id || decimalDigest(message, this.preserveSignificantWhitespace);
}
}
_setLegacyIds(message, meta) {
if (this.enableI18nLegacyMessageIdFormat) {
message.legacyIds = [
computeDigest(message),
computeDecimalDigest(
message,
this.preserveSignificantWhitespace
)
];
} else if (typeof meta !== "string") {
const previousMessage = meta instanceof Message ? meta : meta instanceof IcuPlaceholder ? meta.previousMessage : void 0;
message.legacyIds = previousMessage ? previousMessage.legacyIds : [];
}
}
_reportError(node, msg) {
this._errors.push(new I18nError(node.sourceSpan, msg));
}
};
var I18N_MEANING_SEPARATOR = "|";
var I18N_ID_SEPARATOR = "@@";
function parseI18nMeta(meta = "") {
let customId;
let meaning;
let description;
meta = meta.trim();
if (meta) {
const idIndex = meta.indexOf(I18N_ID_SEPARATOR);
const descIndex = meta.indexOf(I18N_MEANING_SEPARATOR);
let meaningAndDesc;
[meaningAndDesc, customId] = idIndex > -1 ? [meta.slice(0, idIndex), meta.slice(idIndex + 2)] : [meta, ""];
[meaning, description] = descIndex > -1 ? [meaningAndDesc.slice(0, descIndex), meaningAndDesc.slice(descIndex + 1)] : ["", meaningAndDesc];
}
return { customId, meaning, description };
}
function i18nMetaToJSDoc(meta) {
const tags = [];
if (meta.description) {
tags.push({ tagName: "desc", text: meta.description });
} else {
tags.push({ tagName: "suppress", text: "{msgDescriptions}" });
}
if (meta.meaning) {
tags.push({ tagName: "meaning", text: meta.meaning });
}
return jsDocComment(tags);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/view/i18n/get_msg_utils.mjs
var GOOG_GET_MSG = "goog.getMsg";
function createGoogleGetMsgStatements(variable2, message, closureVar, placeholderValues) {
const messageString = serializeI18nMessageForGetMsg(message);
const args = [literal(messageString)];
if (Object.keys(placeholderValues).length) {
args.push(mapLiteral(formatI18nPlaceholderNamesInMap(placeholderValues, true), true));
args.push(mapLiteral({
original_code: literalMap(Object.keys(placeholderValues).map((param) => ({
key: formatI18nPlaceholderName(param),
quoted: true,
value: message.placeholders[param] ? literal(message.placeholders[param].sourceSpan.toString()) : literal(message.placeholderToMessage[param].nodes.map((node) => node.sourceSpan.toString()).join(""))
})))
}));
}
const googGetMsgStmt = closureVar.set(variable(GOOG_GET_MSG).callFn(args)).toConstDecl();
googGetMsgStmt.addLeadingComment(i18nMetaToJSDoc(message));
const i18nAssignmentStmt = new ExpressionStatement(variable2.set(closureVar));
return [googGetMsgStmt, i18nAssignmentStmt];
}
var GetMsgSerializerVisitor = class {
formatPh(value) {
return `{$${formatI18nPlaceholderName(value)}}`;
}
visitText(text2) {
return text2.value;
}
visitContainer(container) {
return container.children.map((child) => child.visit(this)).join("");
}
visitIcu(icu) {
return serializeIcuNode(icu);
}
visitTagPlaceholder(ph) {
return ph.isVoid ? this.formatPh(ph.startName) : `${this.formatPh(ph.startName)}${ph.children.map((child) => child.visit(this)).join("")}${this.formatPh(ph.closeName)}`;
}
visitPlaceholder(ph) {
return this.formatPh(ph.name);
}
visitBlockPlaceholder(ph) {
return `${this.formatPh(ph.startName)}${ph.children.map((child) => child.visit(this)).join("")}${this.formatPh(ph.closeName)}`;
}
visitIcuPlaceholder(ph, context) {
return this.formatPh(ph.name);
}
};
var serializerVisitor2 = new GetMsgSerializerVisitor();
function serializeI18nMessageForGetMsg(message) {
return message.nodes.map((node) => node.visit(serializerVisitor2, null)).join("");
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/view/i18n/localize_utils.mjs
function createLocalizeStatements(variable2, message, params) {
const { messageParts, placeHolders } = serializeI18nMessageForLocalize(message);
const sourceSpan = getSourceSpan(message);
const expressions = placeHolders.map((ph) => params[ph.text]);
const localizedString2 = localizedString(message, messageParts, placeHolders, expressions, sourceSpan);
const variableInitialization = variable2.set(localizedString2);
return [new ExpressionStatement(variableInitialization)];
}
var LocalizeSerializerVisitor = class {
constructor(placeholderToMessage, pieces) {
this.placeholderToMessage = placeholderToMessage;
this.pieces = pieces;
}
visitText(text2) {
if (this.pieces[this.pieces.length - 1] instanceof LiteralPiece) {
this.pieces[this.pieces.length - 1].text += text2.value;
} else {
const sourceSpan = new ParseSourceSpan(text2.sourceSpan.fullStart, text2.sourceSpan.end, text2.sourceSpan.fullStart, text2.sourceSpan.details);
this.pieces.push(new LiteralPiece(text2.value, sourceSpan));
}
}
visitContainer(container) {
container.children.forEach((child) => child.visit(this));
}
visitIcu(icu) {
this.pieces.push(new LiteralPiece(serializeIcuNode(icu), icu.sourceSpan));
}
visitTagPlaceholder(ph) {
var _a2, _b2;
this.pieces.push(this.createPlaceholderPiece(ph.startName, (_a2 = ph.startSourceSpan) != null ? _a2 : ph.sourceSpan));
if (!ph.isVoid) {
ph.children.forEach((child) => child.visit(this));
this.pieces.push(this.createPlaceholderPiece(ph.closeName, (_b2 = ph.endSourceSpan) != null ? _b2 : ph.sourceSpan));
}
}
visitPlaceholder(ph) {
this.pieces.push(this.createPlaceholderPiece(ph.name, ph.sourceSpan));
}
visitBlockPlaceholder(ph) {
var _a2, _b2;
this.pieces.push(this.createPlaceholderPiece(ph.startName, (_a2 = ph.startSourceSpan) != null ? _a2 : ph.sourceSpan));
ph.children.forEach((child) => child.visit(this));
this.pieces.push(this.createPlaceholderPiece(ph.closeName, (_b2 = ph.endSourceSpan) != null ? _b2 : ph.sourceSpan));
}
visitIcuPlaceholder(ph) {
this.pieces.push(this.createPlaceholderPiece(ph.name, ph.sourceSpan, this.placeholderToMessage[ph.name]));
}
createPlaceholderPiece(name, sourceSpan, associatedMessage) {
return new PlaceholderPiece(formatI18nPlaceholderName(name, false), sourceSpan, associatedMessage);
}
};
function serializeI18nMessageForLocalize(message) {
const pieces = [];
const serializerVisitor3 = new LocalizeSerializerVisitor(message.placeholderToMessage, pieces);
message.nodes.forEach((node) => node.visit(serializerVisitor3));
return processMessagePieces(pieces);
}
function getSourceSpan(message) {
const startNode = message.nodes[0];
const endNode = message.nodes[message.nodes.length - 1];
return new ParseSourceSpan(startNode.sourceSpan.fullStart, endNode.sourceSpan.end, startNode.sourceSpan.fullStart, startNode.sourceSpan.details);
}
function processMessagePieces(pieces) {
const messageParts = [];
const placeHolders = [];
if (pieces[0] instanceof PlaceholderPiece) {
messageParts.push(createEmptyMessagePart(pieces[0].sourceSpan.start));
}
for (let i = 0; i < pieces.length; i++) {
const part = pieces[i];
if (part instanceof LiteralPiece) {
messageParts.push(part);
} else {
placeHolders.push(part);
if (pieces[i - 1] instanceof PlaceholderPiece) {
messageParts.push(createEmptyMessagePart(pieces[i - 1].sourceSpan.end));
}
}
}
if (pieces[pieces.length - 1] instanceof PlaceholderPiece) {
messageParts.push(createEmptyMessagePart(pieces[pieces.length - 1].sourceSpan.end));
}
return { messageParts, placeHolders };
}
function createEmptyMessagePart(location) {
return new LiteralPiece("", new ParseSourceSpan(location, location));
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/i18n_const_collection.mjs
var NG_I18N_CLOSURE_MODE = "ngI18nClosureMode";
var TRANSLATION_VAR_PREFIX = "i18n_";
var I18N_ICU_MAPPING_PREFIX = "I18N_EXP_";
var ESCAPE2 = "\uFFFD";
var CLOSURE_TRANSLATION_VAR_PREFIX = "MSG_";
function getTranslationConstPrefix(extra) {
return `${CLOSURE_TRANSLATION_VAR_PREFIX}${extra}`.toUpperCase();
}
function declareI18nVariable(variable2) {
return new DeclareVarStmt(variable2.name, void 0, INFERRED_TYPE, void 0, variable2.sourceSpan);
}
function collectI18nConsts(job) {
var _a2, _b2;
const fileBasedI18nSuffix = job.relativeContextFilePath.replace(/[^A-Za-z0-9]/g, "_").toUpperCase() + "_";
const extractedAttributesByI18nContext = /* @__PURE__ */ new Map();
const i18nAttributesByElement = /* @__PURE__ */ new Map();
const i18nExpressionsByElement = /* @__PURE__ */ new Map();
const messages = /* @__PURE__ */ new Map();
for (const unit of job.units) {
for (const op of unit.ops()) {
if (op.kind === OpKind.ExtractedAttribute && op.i18nContext !== null) {
const attributes = (_a2 = extractedAttributesByI18nContext.get(op.i18nContext)) != null ? _a2 : [];
attributes.push(op);
extractedAttributesByI18nContext.set(op.i18nContext, attributes);
} else if (op.kind === OpKind.I18nAttributes) {
i18nAttributesByElement.set(op.target, op);
} else if (op.kind === OpKind.I18nExpression && op.usage === I18nExpressionFor.I18nAttribute) {
const expressions = (_b2 = i18nExpressionsByElement.get(op.target)) != null ? _b2 : [];
expressions.push(op);
i18nExpressionsByElement.set(op.target, expressions);
} else if (op.kind === OpKind.I18nMessage) {
messages.set(op.xref, op);
}
}
}
const i18nValuesByContext = /* @__PURE__ */ new Map();
const messageConstIndices = /* @__PURE__ */ new Map();
for (const unit of job.units) {
for (const op of unit.create) {
if (op.kind === OpKind.I18nMessage) {
if (op.messagePlaceholder === null) {
const { mainVar, statements } = collectMessage(job, fileBasedI18nSuffix, messages, op);
if (op.i18nBlock !== null) {
const i18nConst = job.addConst(mainVar, statements);
messageConstIndices.set(op.i18nBlock, i18nConst);
} else {
job.constsInitializers.push(...statements);
i18nValuesByContext.set(op.i18nContext, mainVar);
const attributesForMessage = extractedAttributesByI18nContext.get(op.i18nContext);
if (attributesForMessage !== void 0) {
for (const attr of attributesForMessage) {
attr.expression = mainVar.clone();
}
}
}
}
OpList.remove(op);
}
}
}
for (const unit of job.units) {
for (const elem of unit.create) {
if (isElementOrContainerOp(elem)) {
const i18nAttributes2 = i18nAttributesByElement.get(elem.xref);
if (i18nAttributes2 === void 0) {
continue;
}
let i18nExpressions = i18nExpressionsByElement.get(elem.xref);
if (i18nExpressions === void 0) {
throw new Error("AssertionError: Could not find any i18n expressions associated with an I18nAttributes instruction");
}
const seenPropertyNames = /* @__PURE__ */ new Set();
i18nExpressions = i18nExpressions.filter((i18nExpr) => {
const seen = seenPropertyNames.has(i18nExpr.name);
seenPropertyNames.add(i18nExpr.name);
return !seen;
});
const i18nAttributeConfig = i18nExpressions.flatMap((i18nExpr) => {
const i18nExprValue = i18nValuesByContext.get(i18nExpr.context);
if (i18nExprValue === void 0) {
throw new Error("AssertionError: Could not find i18n expression's value");
}
return [literal(i18nExpr.name), i18nExprValue];
});
i18nAttributes2.i18nAttributesConfig = job.addConst(new LiteralArrayExpr(i18nAttributeConfig));
}
}
}
for (const unit of job.units) {
for (const op of unit.create) {
if (op.kind === OpKind.I18nStart) {
const msgIndex = messageConstIndices.get(op.root);
if (msgIndex === void 0) {
throw new Error("AssertionError: Could not find corresponding i18n block index for an i18n message op; was an i18n message incorrectly assumed to correspond to an attribute?");
}
op.messageIndex = msgIndex;
}
}
}
}
function collectMessage(job, fileBasedI18nSuffix, messages, messageOp) {
var _a2;
const statements = [];
const subMessagePlaceholders = /* @__PURE__ */ new Map();
for (const subMessageId of messageOp.subMessages) {
const subMessage = messages.get(subMessageId);
const { mainVar: subMessageVar, statements: subMessageStatements } = collectMessage(job, fileBasedI18nSuffix, messages, subMessage);
statements.push(...subMessageStatements);
const subMessages = (_a2 = subMessagePlaceholders.get(subMessage.messagePlaceholder)) != null ? _a2 : [];
subMessages.push(subMessageVar);
subMessagePlaceholders.set(subMessage.messagePlaceholder, subMessages);
}
addSubMessageParams(messageOp, subMessagePlaceholders);
messageOp.params = new Map([...messageOp.params.entries()].sort());
const mainVar = variable(job.pool.uniqueName(TRANSLATION_VAR_PREFIX));
const closureVar = i18nGenerateClosureVar(job.pool, messageOp.message.id, fileBasedI18nSuffix, job.i18nUseExternalIds);
let transformFn = void 0;
if (messageOp.needsPostprocessing || messageOp.postprocessingParams.size > 0) {
const postprocessingParams = Object.fromEntries([...messageOp.postprocessingParams.entries()].sort());
const formattedPostprocessingParams = formatI18nPlaceholderNamesInMap(
postprocessingParams,
false
);
const extraTransformFnParams = [];
if (messageOp.postprocessingParams.size > 0) {
extraTransformFnParams.push(mapLiteral(formattedPostprocessingParams, true));
}
transformFn = (expr) => importExpr(Identifiers.i18nPostprocess).callFn([expr, ...extraTransformFnParams]);
}
statements.push(...getTranslationDeclStmts(messageOp.message, mainVar, closureVar, messageOp.params, transformFn));
return { mainVar, statements };
}
function addSubMessageParams(messageOp, subMessagePlaceholders) {
for (const [placeholder, subMessages] of subMessagePlaceholders) {
if (subMessages.length === 1) {
messageOp.params.set(placeholder, subMessages[0]);
} else {
messageOp.params.set(placeholder, literal(`${ESCAPE2}${I18N_ICU_MAPPING_PREFIX}${placeholder}${ESCAPE2}`));
messageOp.postprocessingParams.set(placeholder, literalArr(subMessages));
}
}
}
function getTranslationDeclStmts(message, variable2, closureVar, params, transformFn) {
const paramsObject = Object.fromEntries(params);
const statements = [
declareI18nVariable(variable2),
ifStmt(createClosureModeGuard(), createGoogleGetMsgStatements(variable2, message, closureVar, paramsObject), createLocalizeStatements(variable2, message, formatI18nPlaceholderNamesInMap(paramsObject, false)))
];
if (transformFn) {
statements.push(new ExpressionStatement(variable2.set(transformFn(variable2))));
}
return statements;
}
function createClosureModeGuard() {
return typeofExpr(variable(NG_I18N_CLOSURE_MODE)).notIdentical(literal("undefined", STRING_TYPE)).and(variable(NG_I18N_CLOSURE_MODE));
}
function i18nGenerateClosureVar(pool, messageId, fileBasedI18nSuffix, useExternalIds) {
let name;
const suffix = fileBasedI18nSuffix;
if (useExternalIds) {
const prefix = getTranslationConstPrefix(`EXTERNAL_`);
const uniqueSuffix = pool.uniqueName(suffix);
name = `${prefix}${sanitizeIdentifier(messageId)}$$${uniqueSuffix}`;
} else {
const prefix = getTranslationConstPrefix(suffix);
name = pool.uniqueName(prefix);
}
return variable(name);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/i18n_text_extraction.mjs
function convertI18nText(job) {
var _a2, _b2, _c2;
for (const unit of job.units) {
let currentI18n = null;
let currentIcu = null;
const textNodeI18nBlocks = /* @__PURE__ */ new Map();
const textNodeIcus = /* @__PURE__ */ new Map();
const icuPlaceholderByText = /* @__PURE__ */ new Map();
for (const op of unit.create) {
switch (op.kind) {
case OpKind.I18nStart:
if (op.context === null) {
throw Error("I18n op should have its context set.");
}
currentI18n = op;
break;
case OpKind.I18nEnd:
currentI18n = null;
break;
case OpKind.IcuStart:
if (op.context === null) {
throw Error("Icu op should have its context set.");
}
currentIcu = op;
break;
case OpKind.IcuEnd:
currentIcu = null;
break;
case OpKind.Text:
if (currentI18n !== null) {
textNodeI18nBlocks.set(op.xref, currentI18n);
textNodeIcus.set(op.xref, currentIcu);
if (op.icuPlaceholder !== null) {
const icuPlaceholderOp = createIcuPlaceholderOp(job.allocateXrefId(), op.icuPlaceholder, [op.initialValue]);
OpList.replace(op, icuPlaceholderOp);
icuPlaceholderByText.set(op.xref, icuPlaceholderOp);
} else {
OpList.remove(op);
}
}
break;
}
}
for (const op of unit.update) {
switch (op.kind) {
case OpKind.InterpolateText:
if (!textNodeI18nBlocks.has(op.target)) {
continue;
}
const i18nOp = textNodeI18nBlocks.get(op.target);
const icuOp = textNodeIcus.get(op.target);
const icuPlaceholder = icuPlaceholderByText.get(op.target);
const contextId = icuOp ? icuOp.context : i18nOp.context;
const resolutionTime = icuOp ? I18nParamResolutionTime.Postproccessing : I18nParamResolutionTime.Creation;
const ops = [];
for (let i = 0; i < op.interpolation.expressions.length; i++) {
const expr = op.interpolation.expressions[i];
ops.push(createI18nExpressionOp(contextId, i18nOp.xref, i18nOp.xref, i18nOp.handle, expr, (_a2 = icuPlaceholder == null ? void 0 : icuPlaceholder.xref) != null ? _a2 : null, (_b2 = op.interpolation.i18nPlaceholders[i]) != null ? _b2 : null, resolutionTime, I18nExpressionFor.I18nText, "", (_c2 = expr.sourceSpan) != null ? _c2 : op.sourceSpan));
}
OpList.replaceWithMany(op, ops);
if (icuPlaceholder !== void 0) {
icuPlaceholder.strings = op.interpolation.strings;
}
break;
}
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/local_refs.mjs
function liftLocalRefs(job) {
for (const unit of job.units) {
for (const op of unit.create) {
switch (op.kind) {
case OpKind.ElementStart:
case OpKind.Template:
if (!Array.isArray(op.localRefs)) {
throw new Error(`AssertionError: expected localRefs to be an array still`);
}
op.numSlotsUsed += op.localRefs.length;
if (op.localRefs.length > 0) {
const localRefs = serializeLocalRefs(op.localRefs);
op.localRefs = job.addConst(localRefs);
} else {
op.localRefs = null;
}
break;
}
}
}
}
function serializeLocalRefs(refs) {
const constRefs = [];
for (const ref of refs) {
constRefs.push(literal(ref.name), literal(ref.target));
}
return literalArr(constRefs);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/namespace.mjs
function emitNamespaceChanges(job) {
for (const unit of job.units) {
let activeNamespace = Namespace.HTML;
for (const op of unit.create) {
if (op.kind !== OpKind.ElementStart) {
continue;
}
if (op.namespace !== activeNamespace) {
OpList.insertBefore(createNamespaceOp(op.namespace), op);
activeNamespace = op.namespace;
}
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/parse_extracted_styles.mjs
function parse(value) {
const styles = [];
let i = 0;
let parenDepth = 0;
let quote = 0;
let valueStart = 0;
let propStart = 0;
let currentProp = null;
while (i < value.length) {
const token = value.charCodeAt(i++);
switch (token) {
case 40:
parenDepth++;
break;
case 41:
parenDepth--;
break;
case 39:
if (quote === 0) {
quote = 39;
} else if (quote === 39 && value.charCodeAt(i - 1) !== 92) {
quote = 0;
}
break;
case 34:
if (quote === 0) {
quote = 34;
} else if (quote === 34 && value.charCodeAt(i - 1) !== 92) {
quote = 0;
}
break;
case 58:
if (!currentProp && parenDepth === 0 && quote === 0) {
currentProp = hyphenate2(value.substring(propStart, i - 1).trim());
valueStart = i;
}
break;
case 59:
if (currentProp && valueStart > 0 && parenDepth === 0 && quote === 0) {
const styleVal = value.substring(valueStart, i - 1).trim();
styles.push(currentProp, styleVal);
propStart = i;
valueStart = 0;
currentProp = null;
}
break;
}
}
if (currentProp && valueStart) {
const styleVal = value.slice(valueStart).trim();
styles.push(currentProp, styleVal);
}
return styles;
}
function hyphenate2(value) {
return value.replace(/[a-z][A-Z]/g, (v) => {
return v.charAt(0) + "-" + v.charAt(1);
}).toLowerCase();
}
function parseExtractedStyles(job) {
const elements = /* @__PURE__ */ new Map();
for (const unit of job.units) {
for (const op of unit.create) {
if (isElementOrContainerOp(op)) {
elements.set(op.xref, op);
}
}
}
for (const unit of job.units) {
for (const op of unit.create) {
if (op.kind === OpKind.ExtractedAttribute && op.bindingKind === BindingKind.Attribute && isStringLiteral(op.expression)) {
const target = elements.get(op.target);
if (target !== void 0 && target.kind === OpKind.Template && target.templateKind === TemplateKind.Structural) {
continue;
}
if (op.name === "style") {
const parsedStyles = parse(op.expression.value);
for (let i = 0; i < parsedStyles.length - 1; i += 2) {
OpList.insertBefore(createExtractedAttributeOp(op.target, BindingKind.StyleProperty, null, parsedStyles[i], literal(parsedStyles[i + 1]), null, null, SecurityContext.STYLE), op);
}
OpList.remove(op);
} else if (op.name === "class") {
const parsedClasses = op.expression.value.trim().split(/\s+/g);
for (const parsedClass of parsedClasses) {
OpList.insertBefore(createExtractedAttributeOp(op.target, BindingKind.ClassName, null, parsedClass, null, null, null, SecurityContext.NONE), op);
}
OpList.remove(op);
}
}
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/naming.mjs
function nameFunctionsAndVariables(job) {
addNamesToView(job.root, job.componentName, { index: 0 }, job.compatibility === CompatibilityMode.TemplateDefinitionBuilder);
}
function addNamesToView(unit, baseName, state, compatibility) {
if (unit.fnName === null) {
unit.fnName = unit.job.pool.uniqueName(
sanitizeIdentifier(`${baseName}_${unit.job.fnSuffix}`),
false
);
}
const varNames = /* @__PURE__ */ new Map();
for (const op of unit.ops()) {
switch (op.kind) {
case OpKind.Property:
case OpKind.HostProperty:
if (op.isAnimationTrigger) {
op.name = "@" + op.name;
}
break;
case OpKind.Listener:
if (op.handlerFnName !== null) {
break;
}
if (!op.hostListener && op.targetSlot.slot === null) {
throw new Error(`Expected a slot to be assigned`);
}
let animation = "";
if (op.isAnimationListener) {
op.name = `@${op.name}.${op.animationPhase}`;
animation = "animation";
}
if (op.hostListener) {
op.handlerFnName = `${baseName}_${animation}${op.name}_HostBindingHandler`;
} else {
op.handlerFnName = `${unit.fnName}_${op.tag.replace("-", "_")}_${animation}${op.name}_${op.targetSlot.slot}_listener`;
}
op.handlerFnName = sanitizeIdentifier(op.handlerFnName);
break;
case OpKind.TwoWayListener:
if (op.handlerFnName !== null) {
break;
}
if (op.targetSlot.slot === null) {
throw new Error(`Expected a slot to be assigned`);
}
op.handlerFnName = sanitizeIdentifier(`${unit.fnName}_${op.tag.replace("-", "_")}_${op.name}_${op.targetSlot.slot}_listener`);
break;
case OpKind.Variable:
varNames.set(op.xref, getVariableName(unit, op.variable, state));
break;
case OpKind.RepeaterCreate:
if (!(unit instanceof ViewCompilationUnit)) {
throw new Error(`AssertionError: must be compiling a component`);
}
if (op.handle.slot === null) {
throw new Error(`Expected slot to be assigned`);
}
if (op.emptyView !== null) {
const emptyView = unit.job.views.get(op.emptyView);
addNamesToView(emptyView, `${baseName}_${op.functionNameSuffix}Empty_${op.handle.slot + 2}`, state, compatibility);
}
addNamesToView(unit.job.views.get(op.xref), `${baseName}_${op.functionNameSuffix}_${op.handle.slot + 1}`, state, compatibility);
break;
case OpKind.Projection:
if (!(unit instanceof ViewCompilationUnit)) {
throw new Error(`AssertionError: must be compiling a component`);
}
if (op.handle.slot === null) {
throw new Error(`Expected slot to be assigned`);
}
if (op.fallbackView !== null) {
const fallbackView = unit.job.views.get(op.fallbackView);
addNamesToView(fallbackView, `${baseName}_ProjectionFallback_${op.handle.slot}`, state, compatibility);
}
break;
case OpKind.Template:
if (!(unit instanceof ViewCompilationUnit)) {
throw new Error(`AssertionError: must be compiling a component`);
}
const childView = unit.job.views.get(op.xref);
if (op.handle.slot === null) {
throw new Error(`Expected slot to be assigned`);
}
const suffix = op.functionNameSuffix.length === 0 ? "" : `_${op.functionNameSuffix}`;
addNamesToView(childView, `${baseName}${suffix}_${op.handle.slot}`, state, compatibility);
break;
case OpKind.StyleProp:
op.name = normalizeStylePropName(op.name);
if (compatibility) {
op.name = stripImportant(op.name);
}
break;
case OpKind.ClassProp:
if (compatibility) {
op.name = stripImportant(op.name);
}
break;
}
}
for (const op of unit.ops()) {
visitExpressionsInOp(op, (expr) => {
if (!(expr instanceof ReadVariableExpr) || expr.name !== null) {
return;
}
if (!varNames.has(expr.xref)) {
throw new Error(`Variable ${expr.xref} not yet named`);
}
expr.name = varNames.get(expr.xref);
});
}
}
function getVariableName(unit, variable2, state) {
if (variable2.name === null) {
switch (variable2.kind) {
case SemanticVariableKind.Context:
variable2.name = `ctx_r${state.index++}`;
break;
case SemanticVariableKind.Identifier:
if (unit.job.compatibility === CompatibilityMode.TemplateDefinitionBuilder) {
const compatPrefix = variable2.identifier === "ctx" ? "i" : "";
variable2.name = `${variable2.identifier}_${compatPrefix}r${++state.index}`;
} else {
variable2.name = `${variable2.identifier}_i${state.index++}`;
}
break;
default:
variable2.name = `_r${++state.index}`;
break;
}
}
return variable2.name;
}
function normalizeStylePropName(name) {
return name.startsWith("--") ? name : hyphenate2(name);
}
function stripImportant(name) {
const importantIndex = name.indexOf("!important");
if (importantIndex > -1) {
return name.substring(0, importantIndex);
}
return name;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/next_context_merging.mjs
function mergeNextContextExpressions(job) {
for (const unit of job.units) {
for (const op of unit.create) {
if (op.kind === OpKind.Listener || op.kind === OpKind.TwoWayListener) {
mergeNextContextsInOps(op.handlerOps);
}
}
mergeNextContextsInOps(unit.update);
}
}
function mergeNextContextsInOps(ops) {
for (const op of ops) {
if (op.kind !== OpKind.Statement || !(op.statement instanceof ExpressionStatement) || !(op.statement.expr instanceof NextContextExpr)) {
continue;
}
const mergeSteps = op.statement.expr.steps;
let tryToMerge = true;
for (let candidate = op.next; candidate.kind !== OpKind.ListEnd && tryToMerge; candidate = candidate.next) {
visitExpressionsInOp(candidate, (expr, flags) => {
if (!isIrExpression(expr)) {
return expr;
}
if (!tryToMerge) {
return;
}
if (flags & VisitorContextFlag.InChildOperation) {
return;
}
switch (expr.kind) {
case ExpressionKind.NextContext:
expr.steps += mergeSteps;
OpList.remove(op);
tryToMerge = false;
break;
case ExpressionKind.GetCurrentView:
case ExpressionKind.Reference:
case ExpressionKind.ContextLetReference:
tryToMerge = false;
break;
}
return;
});
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/ng_container.mjs
var CONTAINER_TAG = "ng-container";
function generateNgContainerOps(job) {
for (const unit of job.units) {
const updatedElementXrefs = /* @__PURE__ */ new Set();
for (const op of unit.create) {
if (op.kind === OpKind.ElementStart && op.tag === CONTAINER_TAG) {
op.kind = OpKind.ContainerStart;
updatedElementXrefs.add(op.xref);
}
if (op.kind === OpKind.ElementEnd && updatedElementXrefs.has(op.xref)) {
op.kind = OpKind.ContainerEnd;
}
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/nonbindable.mjs
function lookupElement3(elements, xref) {
const el = elements.get(xref);
if (el === void 0) {
throw new Error("All attributes should have an element-like target.");
}
return el;
}
function disableBindings(job) {
const elements = /* @__PURE__ */ new Map();
for (const view of job.units) {
for (const op of view.create) {
if (!isElementOrContainerOp(op)) {
continue;
}
elements.set(op.xref, op);
}
}
for (const unit of job.units) {
for (const op of unit.create) {
if ((op.kind === OpKind.ElementStart || op.kind === OpKind.ContainerStart) && op.nonBindable) {
OpList.insertAfter(createDisableBindingsOp(op.xref), op);
}
if ((op.kind === OpKind.ElementEnd || op.kind === OpKind.ContainerEnd) && lookupElement3(elements, op.xref).nonBindable) {
OpList.insertBefore(createEnableBindingsOp(op.xref), op);
}
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/nullish_coalescing.mjs
function generateNullishCoalesceExpressions(job) {
for (const unit of job.units) {
for (const op of unit.ops()) {
transformExpressionsInOp(op, (expr) => {
if (!(expr instanceof BinaryOperatorExpr) || expr.operator !== BinaryOperator.NullishCoalesce) {
return expr;
}
const assignment = new AssignTemporaryExpr(expr.lhs.clone(), job.allocateXrefId());
const read = new ReadTemporaryExpr(assignment.xref);
return new ConditionalExpr(new BinaryOperatorExpr(BinaryOperator.And, new BinaryOperatorExpr(BinaryOperator.NotIdentical, assignment, NULL_EXPR), new BinaryOperatorExpr(BinaryOperator.NotIdentical, read, new LiteralExpr(void 0))), read.clone(), expr.rhs);
}, VisitorContextFlag.None);
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/ordering.mjs
function kindTest(kind) {
return (op) => op.kind === kind;
}
function kindWithInterpolationTest(kind, interpolation) {
return (op) => {
return op.kind === kind && interpolation === op.expression instanceof Interpolation2;
};
}
function basicListenerKindTest(op) {
return op.kind === OpKind.Listener && !(op.hostListener && op.isAnimationListener) || op.kind === OpKind.TwoWayListener;
}
function nonInterpolationPropertyKindTest(op) {
return (op.kind === OpKind.Property || op.kind === OpKind.TwoWayProperty) && !(op.expression instanceof Interpolation2);
}
var CREATE_ORDERING = [
{ test: (op) => op.kind === OpKind.Listener && op.hostListener && op.isAnimationListener },
{ test: basicListenerKindTest }
];
var UPDATE_ORDERING = [
{ test: kindTest(OpKind.StyleMap), transform: keepLast },
{ test: kindTest(OpKind.ClassMap), transform: keepLast },
{ test: kindTest(OpKind.StyleProp) },
{ test: kindTest(OpKind.ClassProp) },
{ test: kindWithInterpolationTest(OpKind.Attribute, true) },
{ test: kindWithInterpolationTest(OpKind.Property, true) },
{ test: nonInterpolationPropertyKindTest },
{ test: kindWithInterpolationTest(OpKind.Attribute, false) }
];
var UPDATE_HOST_ORDERING = [
{ test: kindWithInterpolationTest(OpKind.HostProperty, true) },
{ test: kindWithInterpolationTest(OpKind.HostProperty, false) },
{ test: kindTest(OpKind.Attribute) },
{ test: kindTest(OpKind.StyleMap), transform: keepLast },
{ test: kindTest(OpKind.ClassMap), transform: keepLast },
{ test: kindTest(OpKind.StyleProp) },
{ test: kindTest(OpKind.ClassProp) }
];
var handledOpKinds = /* @__PURE__ */ new Set([
OpKind.Listener,
OpKind.TwoWayListener,
OpKind.StyleMap,
OpKind.ClassMap,
OpKind.StyleProp,
OpKind.ClassProp,
OpKind.Property,
OpKind.TwoWayProperty,
OpKind.HostProperty,
OpKind.Attribute
]);
function orderOps(job) {
for (const unit of job.units) {
orderWithin(unit.create, CREATE_ORDERING);
const ordering = unit.job.kind === CompilationJobKind.Host ? UPDATE_HOST_ORDERING : UPDATE_ORDERING;
orderWithin(unit.update, ordering);
}
}
function orderWithin(opList, ordering) {
let opsToOrder = [];
let firstTargetInGroup = null;
for (const op of opList) {
const currentTarget = hasDependsOnSlotContextTrait(op) ? op.target : null;
if (!handledOpKinds.has(op.kind) || currentTarget !== firstTargetInGroup && firstTargetInGroup !== null && currentTarget !== null) {
OpList.insertBefore(reorder(opsToOrder, ordering), op);
opsToOrder = [];
firstTargetInGroup = null;
}
if (handledOpKinds.has(op.kind)) {
opsToOrder.push(op);
OpList.remove(op);
firstTargetInGroup = currentTarget != null ? currentTarget : firstTargetInGroup;
}
}
opList.push(reorder(opsToOrder, ordering));
}
function reorder(ops, ordering) {
const groups = Array.from(ordering, () => new Array());
for (const op of ops) {
const groupIndex = ordering.findIndex((o) => o.test(op));
groups[groupIndex].push(op);
}
return groups.flatMap((group, i) => {
const transform2 = ordering[i].transform;
return transform2 ? transform2(group) : group;
});
}
function keepLast(ops) {
return ops.slice(ops.length - 1);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/phase_remove_content_selectors.mjs
function removeContentSelectors(job) {
for (const unit of job.units) {
const elements = createOpXrefMap(unit);
for (const op of unit.ops()) {
switch (op.kind) {
case OpKind.Binding:
const target = lookupInXrefMap(elements, op.target);
if (isSelectAttribute(op.name) && target.kind === OpKind.Projection) {
OpList.remove(op);
}
break;
}
}
}
}
function isSelectAttribute(name) {
return name.toLowerCase() === "select";
}
function lookupInXrefMap(map, xref) {
const el = map.get(xref);
if (el === void 0) {
throw new Error("All attributes should have an slottable target.");
}
return el;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/pipe_creation.mjs
function createPipes(job) {
for (const unit of job.units) {
processPipeBindingsInView(unit);
}
}
function processPipeBindingsInView(unit) {
for (const updateOp of unit.update) {
visitExpressionsInOp(updateOp, (expr, flags) => {
if (!isIrExpression(expr)) {
return;
}
if (expr.kind !== ExpressionKind.PipeBinding) {
return;
}
if (flags & VisitorContextFlag.InChildOperation) {
throw new Error(`AssertionError: pipe bindings should not appear in child expressions`);
}
if (unit.job.compatibility) {
const slotHandle = updateOp.target;
if (slotHandle == void 0) {
throw new Error(`AssertionError: expected slot handle to be assigned for pipe creation`);
}
addPipeToCreationBlock(unit, updateOp.target, expr);
} else {
unit.create.push(createPipeOp(expr.target, expr.targetSlot, expr.name));
}
});
}
}
function addPipeToCreationBlock(unit, afterTargetXref, binding) {
for (let op = unit.create.head.next; op.kind !== OpKind.ListEnd; op = op.next) {
if (!hasConsumesSlotTrait(op)) {
continue;
}
if (op.xref !== afterTargetXref) {
continue;
}
while (op.next.kind === OpKind.Pipe) {
op = op.next;
}
const pipe2 = createPipeOp(binding.target, binding.targetSlot, binding.name);
OpList.insertBefore(pipe2, op.next);
return;
}
throw new Error(`AssertionError: unable to find insertion point for pipe ${binding.name}`);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/pipe_variadic.mjs
function createVariadicPipes(job) {
for (const unit of job.units) {
for (const op of unit.update) {
transformExpressionsInOp(op, (expr) => {
if (!(expr instanceof PipeBindingExpr)) {
return expr;
}
if (expr.args.length <= 4) {
return expr;
}
return new PipeBindingVariadicExpr(expr.target, expr.targetSlot, expr.name, literalArr(expr.args), expr.args.length);
}, VisitorContextFlag.None);
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/propagate_i18n_blocks.mjs
function propagateI18nBlocks(job) {
propagateI18nBlocksToTemplates(job.root, 0);
}
function propagateI18nBlocksToTemplates(unit, subTemplateIndex) {
let i18nBlock = null;
for (const op of unit.create) {
switch (op.kind) {
case OpKind.I18nStart:
op.subTemplateIndex = subTemplateIndex === 0 ? null : subTemplateIndex;
i18nBlock = op;
break;
case OpKind.I18nEnd:
if (i18nBlock.subTemplateIndex === null) {
subTemplateIndex = 0;
}
i18nBlock = null;
break;
case OpKind.Template:
subTemplateIndex = propagateI18nBlocksForView(unit.job.views.get(op.xref), i18nBlock, op.i18nPlaceholder, subTemplateIndex);
break;
case OpKind.RepeaterCreate:
const forView = unit.job.views.get(op.xref);
subTemplateIndex = propagateI18nBlocksForView(forView, i18nBlock, op.i18nPlaceholder, subTemplateIndex);
if (op.emptyView !== null) {
subTemplateIndex = propagateI18nBlocksForView(unit.job.views.get(op.emptyView), i18nBlock, op.emptyI18nPlaceholder, subTemplateIndex);
}
break;
}
}
return subTemplateIndex;
}
function propagateI18nBlocksForView(view, i18nBlock, i18nPlaceholder, subTemplateIndex) {
if (i18nPlaceholder !== void 0) {
if (i18nBlock === null) {
throw Error("Expected template with i18n placeholder to be in an i18n block.");
}
subTemplateIndex++;
wrapTemplateWithI18n(view, i18nBlock);
}
return propagateI18nBlocksToTemplates(view, subTemplateIndex);
}
function wrapTemplateWithI18n(unit, parentI18n) {
var _a2;
if (((_a2 = unit.create.head.next) == null ? void 0 : _a2.kind) !== OpKind.I18nStart) {
const id = unit.job.allocateXrefId();
OpList.insertAfter(
createI18nStartOp(id, parentI18n.message, parentI18n.root, null),
unit.create.head
);
OpList.insertBefore(createI18nEndOp(id, null), unit.create.tail);
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/pure_function_extraction.mjs
function extractPureFunctions(job) {
for (const view of job.units) {
for (const op of view.ops()) {
visitExpressionsInOp(op, (expr) => {
if (!(expr instanceof PureFunctionExpr) || expr.body === null) {
return;
}
const constantDef = new PureFunctionConstant(expr.args.length);
expr.fn = job.pool.getSharedConstant(constantDef, expr.body);
expr.body = null;
});
}
}
}
var PureFunctionConstant = class extends GenericKeyFn {
constructor(numArgs) {
super();
this.numArgs = numArgs;
}
keyOf(expr) {
if (expr instanceof PureFunctionParameterExpr) {
return `param(${expr.index})`;
} else {
return super.keyOf(expr);
}
}
toSharedConstantDeclaration(declName, keyExpr) {
const fnParams = [];
for (let idx = 0; idx < this.numArgs; idx++) {
fnParams.push(new FnParam("a" + idx));
}
const returnExpr = transformExpressionsInExpression(keyExpr, (expr) => {
if (!(expr instanceof PureFunctionParameterExpr)) {
return expr;
}
return variable("a" + expr.index);
}, VisitorContextFlag.None);
return new DeclareVarStmt(declName, new ArrowFunctionExpr(fnParams, returnExpr), void 0, StmtModifier.Final);
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/pure_literal_structures.mjs
function generatePureLiteralStructures(job) {
for (const unit of job.units) {
for (const op of unit.update) {
transformExpressionsInOp(op, (expr, flags) => {
if (flags & VisitorContextFlag.InChildOperation) {
return expr;
}
if (expr instanceof LiteralArrayExpr) {
return transformLiteralArray(expr);
} else if (expr instanceof LiteralMapExpr) {
return transformLiteralMap(expr);
}
return expr;
}, VisitorContextFlag.None);
}
}
}
function transformLiteralArray(expr) {
const derivedEntries = [];
const nonConstantArgs = [];
for (const entry of expr.entries) {
if (entry.isConstant()) {
derivedEntries.push(entry);
} else {
const idx = nonConstantArgs.length;
nonConstantArgs.push(entry);
derivedEntries.push(new PureFunctionParameterExpr(idx));
}
}
return new PureFunctionExpr(literalArr(derivedEntries), nonConstantArgs);
}
function transformLiteralMap(expr) {
let derivedEntries = [];
const nonConstantArgs = [];
for (const entry of expr.entries) {
if (entry.value.isConstant()) {
derivedEntries.push(entry);
} else {
const idx = nonConstantArgs.length;
nonConstantArgs.push(entry.value);
derivedEntries.push(new LiteralMapEntry(entry.key, new PureFunctionParameterExpr(idx), entry.quoted));
}
}
return new PureFunctionExpr(literalMap(derivedEntries), nonConstantArgs);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/instruction.mjs
function element(slot, tag, constIndex, localRefIndex, sourceSpan) {
return elementOrContainerBase(Identifiers.element, slot, tag, constIndex, localRefIndex, sourceSpan);
}
function elementStart(slot, tag, constIndex, localRefIndex, sourceSpan) {
return elementOrContainerBase(Identifiers.elementStart, slot, tag, constIndex, localRefIndex, sourceSpan);
}
function elementOrContainerBase(instruction, slot, tag, constIndex, localRefIndex, sourceSpan) {
const args = [literal(slot)];
if (tag !== null) {
args.push(literal(tag));
}
if (localRefIndex !== null) {
args.push(
literal(constIndex),
literal(localRefIndex)
);
} else if (constIndex !== null) {
args.push(literal(constIndex));
}
return call(instruction, args, sourceSpan);
}
function elementEnd(sourceSpan) {
return call(Identifiers.elementEnd, [], sourceSpan);
}
function elementContainerStart(slot, constIndex, localRefIndex, sourceSpan) {
return elementOrContainerBase(
Identifiers.elementContainerStart,
slot,
null,
constIndex,
localRefIndex,
sourceSpan
);
}
function elementContainer(slot, constIndex, localRefIndex, sourceSpan) {
return elementOrContainerBase(
Identifiers.elementContainer,
slot,
null,
constIndex,
localRefIndex,
sourceSpan
);
}
function elementContainerEnd() {
return call(Identifiers.elementContainerEnd, [], null);
}
function template(slot, templateFnRef, decls, vars, tag, constIndex, localRefs, sourceSpan) {
const args = [
literal(slot),
templateFnRef,
literal(decls),
literal(vars),
literal(tag),
literal(constIndex)
];
if (localRefs !== null) {
args.push(literal(localRefs));
args.push(importExpr(Identifiers.templateRefExtractor));
}
while (args[args.length - 1].isEquivalent(NULL_EXPR)) {
args.pop();
}
return call(Identifiers.templateCreate, args, sourceSpan);
}
function disableBindings2() {
return call(Identifiers.disableBindings, [], null);
}
function enableBindings() {
return call(Identifiers.enableBindings, [], null);
}
function listener(name, handlerFn, eventTargetResolver, syntheticHost, sourceSpan) {
const args = [literal(name), handlerFn];
if (eventTargetResolver !== null) {
args.push(literal(false));
args.push(importExpr(eventTargetResolver));
}
return call(syntheticHost ? Identifiers.syntheticHostListener : Identifiers.listener, args, sourceSpan);
}
function twoWayBindingSet(target, value) {
return importExpr(Identifiers.twoWayBindingSet).callFn([target, value]);
}
function twoWayListener(name, handlerFn, sourceSpan) {
return call(Identifiers.twoWayListener, [literal(name), handlerFn], sourceSpan);
}
function pipe(slot, name) {
return call(Identifiers.pipe, [literal(slot), literal(name)], null);
}
function namespaceHTML() {
return call(Identifiers.namespaceHTML, [], null);
}
function namespaceSVG() {
return call(Identifiers.namespaceSVG, [], null);
}
function namespaceMath() {
return call(Identifiers.namespaceMathML, [], null);
}
function advance(delta, sourceSpan) {
return call(Identifiers.advance, delta > 1 ? [literal(delta)] : [], sourceSpan);
}
function reference(slot) {
return importExpr(Identifiers.reference).callFn([literal(slot)]);
}
function nextContext(steps) {
return importExpr(Identifiers.nextContext).callFn(steps === 1 ? [] : [literal(steps)]);
}
function getCurrentView() {
return importExpr(Identifiers.getCurrentView).callFn([]);
}
function restoreView(savedView) {
return importExpr(Identifiers.restoreView).callFn([savedView]);
}
function resetView(returnValue) {
return importExpr(Identifiers.resetView).callFn([returnValue]);
}
function text(slot, initialValue, sourceSpan) {
const args = [literal(slot, null)];
if (initialValue !== "") {
args.push(literal(initialValue));
}
return call(Identifiers.text, args, sourceSpan);
}
function defer(selfSlot, primarySlot, dependencyResolverFn, loadingSlot, placeholderSlot, errorSlot, loadingConfig, placeholderConfig, enableTimerScheduling, sourceSpan) {
const args = [
literal(selfSlot),
literal(primarySlot),
dependencyResolverFn != null ? dependencyResolverFn : literal(null),
literal(loadingSlot),
literal(placeholderSlot),
literal(errorSlot),
loadingConfig != null ? loadingConfig : literal(null),
placeholderConfig != null ? placeholderConfig : literal(null),
enableTimerScheduling ? importExpr(Identifiers.deferEnableTimerScheduling) : literal(null)
];
let expr;
while ((expr = args[args.length - 1]) !== null && expr instanceof LiteralExpr && expr.value === null) {
args.pop();
}
return call(Identifiers.defer, args, sourceSpan);
}
var deferTriggerToR3TriggerInstructionsMap = /* @__PURE__ */ new Map([
[DeferTriggerKind.Idle, [Identifiers.deferOnIdle, Identifiers.deferPrefetchOnIdle]],
[
DeferTriggerKind.Immediate,
[Identifiers.deferOnImmediate, Identifiers.deferPrefetchOnImmediate]
],
[DeferTriggerKind.Timer, [Identifiers.deferOnTimer, Identifiers.deferPrefetchOnTimer]],
[DeferTriggerKind.Hover, [Identifiers.deferOnHover, Identifiers.deferPrefetchOnHover]],
[
DeferTriggerKind.Interaction,
[Identifiers.deferOnInteraction, Identifiers.deferPrefetchOnInteraction]
],
[
DeferTriggerKind.Viewport,
[Identifiers.deferOnViewport, Identifiers.deferPrefetchOnViewport]
]
]);
function deferOn(trigger, args, prefetch, sourceSpan) {
const instructions = deferTriggerToR3TriggerInstructionsMap.get(trigger);
if (instructions === void 0) {
throw new Error(`Unable to determine instruction for trigger ${trigger}`);
}
const instructionToCall = prefetch ? instructions[1] : instructions[0];
return call(instructionToCall, args.map((a) => literal(a)), sourceSpan);
}
function projectionDef(def) {
return call(Identifiers.projectionDef, def ? [def] : [], null);
}
function projection(slot, projectionSlotIndex, attributes, fallbackFnName, fallbackDecls, fallbackVars, sourceSpan) {
const args = [literal(slot)];
if (projectionSlotIndex !== 0 || attributes !== null || fallbackFnName !== null) {
args.push(literal(projectionSlotIndex));
if (attributes !== null) {
args.push(attributes);
}
if (fallbackFnName !== null) {
if (attributes === null) {
args.push(literal(null));
}
args.push(variable(fallbackFnName), literal(fallbackDecls), literal(fallbackVars));
}
}
return call(Identifiers.projection, args, sourceSpan);
}
function i18nStart(slot, constIndex, subTemplateIndex, sourceSpan) {
const args = [literal(slot), literal(constIndex)];
if (subTemplateIndex !== null) {
args.push(literal(subTemplateIndex));
}
return call(Identifiers.i18nStart, args, sourceSpan);
}
function repeaterCreate(slot, viewFnName, decls, vars, tag, constIndex, trackByFn, trackByUsesComponentInstance, emptyViewFnName, emptyDecls, emptyVars, emptyTag, emptyConstIndex, sourceSpan) {
const args = [
literal(slot),
variable(viewFnName),
literal(decls),
literal(vars),
literal(tag),
literal(constIndex),
trackByFn
];
if (trackByUsesComponentInstance || emptyViewFnName !== null) {
args.push(literal(trackByUsesComponentInstance));
if (emptyViewFnName !== null) {
args.push(variable(emptyViewFnName), literal(emptyDecls), literal(emptyVars));
if (emptyTag !== null || emptyConstIndex !== null) {
args.push(literal(emptyTag));
}
if (emptyConstIndex !== null) {
args.push(literal(emptyConstIndex));
}
}
}
return call(Identifiers.repeaterCreate, args, sourceSpan);
}
function repeater(collection, sourceSpan) {
return call(Identifiers.repeater, [collection], sourceSpan);
}
function deferWhen(prefetch, expr, sourceSpan) {
return call(prefetch ? Identifiers.deferPrefetchWhen : Identifiers.deferWhen, [expr], sourceSpan);
}
function declareLet(slot, sourceSpan) {
return call(Identifiers.declareLet, [literal(slot)], sourceSpan);
}
function storeLet(value, sourceSpan) {
return importExpr(Identifiers.storeLet).callFn([value], sourceSpan);
}
function readContextLet(slot) {
return importExpr(Identifiers.readContextLet).callFn([literal(slot)]);
}
function i18n(slot, constIndex, subTemplateIndex, sourceSpan) {
const args = [literal(slot), literal(constIndex)];
if (subTemplateIndex) {
args.push(literal(subTemplateIndex));
}
return call(Identifiers.i18n, args, sourceSpan);
}
function i18nEnd(endSourceSpan) {
return call(Identifiers.i18nEnd, [], endSourceSpan);
}
function i18nAttributes(slot, i18nAttributesConfig) {
const args = [literal(slot), literal(i18nAttributesConfig)];
return call(Identifiers.i18nAttributes, args, null);
}
function property(name, expression, sanitizer, sourceSpan) {
const args = [literal(name), expression];
if (sanitizer !== null) {
args.push(sanitizer);
}
return call(Identifiers.property, args, sourceSpan);
}
function twoWayProperty(name, expression, sanitizer, sourceSpan) {
const args = [literal(name), expression];
if (sanitizer !== null) {
args.push(sanitizer);
}
return call(Identifiers.twoWayProperty, args, sourceSpan);
}
function attribute(name, expression, sanitizer, namespace) {
const args = [literal(name), expression];
if (sanitizer !== null || namespace !== null) {
args.push(sanitizer != null ? sanitizer : literal(null));
}
if (namespace !== null) {
args.push(literal(namespace));
}
return call(Identifiers.attribute, args, null);
}
function styleProp(name, expression, unit, sourceSpan) {
const args = [literal(name), expression];
if (unit !== null) {
args.push(literal(unit));
}
return call(Identifiers.styleProp, args, sourceSpan);
}
function classProp(name, expression, sourceSpan) {
return call(Identifiers.classProp, [literal(name), expression], sourceSpan);
}
function styleMap(expression, sourceSpan) {
return call(Identifiers.styleMap, [expression], sourceSpan);
}
function classMap(expression, sourceSpan) {
return call(Identifiers.classMap, [expression], sourceSpan);
}
var PIPE_BINDINGS = [
Identifiers.pipeBind1,
Identifiers.pipeBind2,
Identifiers.pipeBind3,
Identifiers.pipeBind4
];
function pipeBind(slot, varOffset, args) {
if (args.length < 1 || args.length > PIPE_BINDINGS.length) {
throw new Error(`pipeBind() argument count out of bounds`);
}
const instruction = PIPE_BINDINGS[args.length - 1];
return importExpr(instruction).callFn([literal(slot), literal(varOffset), ...args]);
}
function pipeBindV(slot, varOffset, args) {
return importExpr(Identifiers.pipeBindV).callFn([literal(slot), literal(varOffset), args]);
}
function textInterpolate(strings, expressions, sourceSpan) {
const interpolationArgs = collateInterpolationArgs(strings, expressions);
return callVariadicInstruction(TEXT_INTERPOLATE_CONFIG, [], interpolationArgs, [], sourceSpan);
}
function i18nExp(expr, sourceSpan) {
return call(Identifiers.i18nExp, [expr], sourceSpan);
}
function i18nApply(slot, sourceSpan) {
return call(Identifiers.i18nApply, [literal(slot)], sourceSpan);
}
function propertyInterpolate(name, strings, expressions, sanitizer, sourceSpan) {
const interpolationArgs = collateInterpolationArgs(strings, expressions);
const extraArgs = [];
if (sanitizer !== null) {
extraArgs.push(sanitizer);
}
return callVariadicInstruction(PROPERTY_INTERPOLATE_CONFIG, [literal(name)], interpolationArgs, extraArgs, sourceSpan);
}
function attributeInterpolate(name, strings, expressions, sanitizer, sourceSpan) {
const interpolationArgs = collateInterpolationArgs(strings, expressions);
const extraArgs = [];
if (sanitizer !== null) {
extraArgs.push(sanitizer);
}
return callVariadicInstruction(ATTRIBUTE_INTERPOLATE_CONFIG, [literal(name)], interpolationArgs, extraArgs, sourceSpan);
}
function stylePropInterpolate(name, strings, expressions, unit, sourceSpan) {
const interpolationArgs = collateInterpolationArgs(strings, expressions);
const extraArgs = [];
if (unit !== null) {
extraArgs.push(literal(unit));
}
return callVariadicInstruction(STYLE_PROP_INTERPOLATE_CONFIG, [literal(name)], interpolationArgs, extraArgs, sourceSpan);
}
function styleMapInterpolate(strings, expressions, sourceSpan) {
const interpolationArgs = collateInterpolationArgs(strings, expressions);
return callVariadicInstruction(STYLE_MAP_INTERPOLATE_CONFIG, [], interpolationArgs, [], sourceSpan);
}
function classMapInterpolate(strings, expressions, sourceSpan) {
const interpolationArgs = collateInterpolationArgs(strings, expressions);
return callVariadicInstruction(CLASS_MAP_INTERPOLATE_CONFIG, [], interpolationArgs, [], sourceSpan);
}
function hostProperty(name, expression, sanitizer, sourceSpan) {
const args = [literal(name), expression];
if (sanitizer !== null) {
args.push(sanitizer);
}
return call(Identifiers.hostProperty, args, sourceSpan);
}
function syntheticHostProperty(name, expression, sourceSpan) {
return call(Identifiers.syntheticHostProperty, [literal(name), expression], sourceSpan);
}
function pureFunction(varOffset, fn2, args) {
return callVariadicInstructionExpr(PURE_FUNCTION_CONFIG, [literal(varOffset), fn2], args, [], null);
}
function collateInterpolationArgs(strings, expressions) {
if (strings.length < 1 || expressions.length !== strings.length - 1) {
throw new Error(`AssertionError: expected specific shape of args for strings/expressions in interpolation`);
}
const interpolationArgs = [];
if (expressions.length === 1 && strings[0] === "" && strings[1] === "") {
interpolationArgs.push(expressions[0]);
} else {
let idx;
for (idx = 0; idx < expressions.length; idx++) {
interpolationArgs.push(literal(strings[idx]), expressions[idx]);
}
interpolationArgs.push(literal(strings[idx]));
}
return interpolationArgs;
}
function call(instruction, args, sourceSpan) {
const expr = importExpr(instruction).callFn(args, sourceSpan);
return createStatementOp(new ExpressionStatement(expr, sourceSpan));
}
function conditional(condition, contextValue, sourceSpan) {
const args = [condition];
if (contextValue !== null) {
args.push(contextValue);
}
return call(Identifiers.conditional, args, sourceSpan);
}
var TEXT_INTERPOLATE_CONFIG = {
constant: [
Identifiers.textInterpolate,
Identifiers.textInterpolate1,
Identifiers.textInterpolate2,
Identifiers.textInterpolate3,
Identifiers.textInterpolate4,
Identifiers.textInterpolate5,
Identifiers.textInterpolate6,
Identifiers.textInterpolate7,
Identifiers.textInterpolate8
],
variable: Identifiers.textInterpolateV,
mapping: (n2) => {
if (n2 % 2 === 0) {
throw new Error(`Expected odd number of arguments`);
}
return (n2 - 1) / 2;
}
};
var PROPERTY_INTERPOLATE_CONFIG = {
constant: [
Identifiers.propertyInterpolate,
Identifiers.propertyInterpolate1,
Identifiers.propertyInterpolate2,
Identifiers.propertyInterpolate3,
Identifiers.propertyInterpolate4,
Identifiers.propertyInterpolate5,
Identifiers.propertyInterpolate6,
Identifiers.propertyInterpolate7,
Identifiers.propertyInterpolate8
],
variable: Identifiers.propertyInterpolateV,
mapping: (n2) => {
if (n2 % 2 === 0) {
throw new Error(`Expected odd number of arguments`);
}
return (n2 - 1) / 2;
}
};
var STYLE_PROP_INTERPOLATE_CONFIG = {
constant: [
Identifiers.styleProp,
Identifiers.stylePropInterpolate1,
Identifiers.stylePropInterpolate2,
Identifiers.stylePropInterpolate3,
Identifiers.stylePropInterpolate4,
Identifiers.stylePropInterpolate5,
Identifiers.stylePropInterpolate6,
Identifiers.stylePropInterpolate7,
Identifiers.stylePropInterpolate8
],
variable: Identifiers.stylePropInterpolateV,
mapping: (n2) => {
if (n2 % 2 === 0) {
throw new Error(`Expected odd number of arguments`);
}
return (n2 - 1) / 2;
}
};
var ATTRIBUTE_INTERPOLATE_CONFIG = {
constant: [
Identifiers.attribute,
Identifiers.attributeInterpolate1,
Identifiers.attributeInterpolate2,
Identifiers.attributeInterpolate3,
Identifiers.attributeInterpolate4,
Identifiers.attributeInterpolate5,
Identifiers.attributeInterpolate6,
Identifiers.attributeInterpolate7,
Identifiers.attributeInterpolate8
],
variable: Identifiers.attributeInterpolateV,
mapping: (n2) => {
if (n2 % 2 === 0) {
throw new Error(`Expected odd number of arguments`);
}
return (n2 - 1) / 2;
}
};
var STYLE_MAP_INTERPOLATE_CONFIG = {
constant: [
Identifiers.styleMap,
Identifiers.styleMapInterpolate1,
Identifiers.styleMapInterpolate2,
Identifiers.styleMapInterpolate3,
Identifiers.styleMapInterpolate4,
Identifiers.styleMapInterpolate5,
Identifiers.styleMapInterpolate6,
Identifiers.styleMapInterpolate7,
Identifiers.styleMapInterpolate8
],
variable: Identifiers.styleMapInterpolateV,
mapping: (n2) => {
if (n2 % 2 === 0) {
throw new Error(`Expected odd number of arguments`);
}
return (n2 - 1) / 2;
}
};
var CLASS_MAP_INTERPOLATE_CONFIG = {
constant: [
Identifiers.classMap,
Identifiers.classMapInterpolate1,
Identifiers.classMapInterpolate2,
Identifiers.classMapInterpolate3,
Identifiers.classMapInterpolate4,
Identifiers.classMapInterpolate5,
Identifiers.classMapInterpolate6,
Identifiers.classMapInterpolate7,
Identifiers.classMapInterpolate8
],
variable: Identifiers.classMapInterpolateV,
mapping: (n2) => {
if (n2 % 2 === 0) {
throw new Error(`Expected odd number of arguments`);
}
return (n2 - 1) / 2;
}
};
var PURE_FUNCTION_CONFIG = {
constant: [
Identifiers.pureFunction0,
Identifiers.pureFunction1,
Identifiers.pureFunction2,
Identifiers.pureFunction3,
Identifiers.pureFunction4,
Identifiers.pureFunction5,
Identifiers.pureFunction6,
Identifiers.pureFunction7,
Identifiers.pureFunction8
],
variable: Identifiers.pureFunctionV,
mapping: (n2) => n2
};
function callVariadicInstructionExpr(config, baseArgs, interpolationArgs, extraArgs, sourceSpan) {
const n2 = config.mapping(interpolationArgs.length);
if (n2 < config.constant.length) {
return importExpr(config.constant[n2]).callFn([...baseArgs, ...interpolationArgs, ...extraArgs], sourceSpan);
} else if (config.variable !== null) {
return importExpr(config.variable).callFn([...baseArgs, literalArr(interpolationArgs), ...extraArgs], sourceSpan);
} else {
throw new Error(`AssertionError: unable to call variadic function`);
}
}
function callVariadicInstruction(config, baseArgs, interpolationArgs, extraArgs, sourceSpan) {
return createStatementOp(callVariadicInstructionExpr(config, baseArgs, interpolationArgs, extraArgs, sourceSpan).toStmt());
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/reify.mjs
var GLOBAL_TARGET_RESOLVERS = /* @__PURE__ */ new Map([
["window", Identifiers.resolveWindow],
["document", Identifiers.resolveDocument],
["body", Identifiers.resolveBody]
]);
function reify(job) {
for (const unit of job.units) {
reifyCreateOperations(unit, unit.create);
reifyUpdateOperations(unit, unit.update);
}
}
function reifyCreateOperations(unit, ops) {
var _a2, _b2, _c2, _d2, _e2, _f2, _g2;
for (const op of ops) {
transformExpressionsInOp(op, reifyIrExpression, VisitorContextFlag.None);
switch (op.kind) {
case OpKind.Text:
OpList.replace(op, text(op.handle.slot, op.initialValue, op.sourceSpan));
break;
case OpKind.ElementStart:
OpList.replace(op, elementStart(op.handle.slot, op.tag, op.attributes, op.localRefs, op.startSourceSpan));
break;
case OpKind.Element:
OpList.replace(op, element(op.handle.slot, op.tag, op.attributes, op.localRefs, op.wholeSourceSpan));
break;
case OpKind.ElementEnd:
OpList.replace(op, elementEnd(op.sourceSpan));
break;
case OpKind.ContainerStart:
OpList.replace(op, elementContainerStart(op.handle.slot, op.attributes, op.localRefs, op.startSourceSpan));
break;
case OpKind.Container:
OpList.replace(op, elementContainer(op.handle.slot, op.attributes, op.localRefs, op.wholeSourceSpan));
break;
case OpKind.ContainerEnd:
OpList.replace(op, elementContainerEnd());
break;
case OpKind.I18nStart:
OpList.replace(op, i18nStart(op.handle.slot, op.messageIndex, op.subTemplateIndex, op.sourceSpan));
break;
case OpKind.I18nEnd:
OpList.replace(op, i18nEnd(op.sourceSpan));
break;
case OpKind.I18n:
OpList.replace(op, i18n(op.handle.slot, op.messageIndex, op.subTemplateIndex, op.sourceSpan));
break;
case OpKind.I18nAttributes:
if (op.i18nAttributesConfig === null) {
throw new Error(`AssertionError: i18nAttributesConfig was not set`);
}
OpList.replace(op, i18nAttributes(op.handle.slot, op.i18nAttributesConfig));
break;
case OpKind.Template:
if (!(unit instanceof ViewCompilationUnit)) {
throw new Error(`AssertionError: must be compiling a component`);
}
if (Array.isArray(op.localRefs)) {
throw new Error(`AssertionError: local refs array should have been extracted into a constant`);
}
const childView = unit.job.views.get(op.xref);
OpList.replace(op, template(op.handle.slot, variable(childView.fnName), childView.decls, childView.vars, op.tag, op.attributes, op.localRefs, op.startSourceSpan));
break;
case OpKind.DisableBindings:
OpList.replace(op, disableBindings2());
break;
case OpKind.EnableBindings:
OpList.replace(op, enableBindings());
break;
case OpKind.Pipe:
OpList.replace(op, pipe(op.handle.slot, op.name));
break;
case OpKind.DeclareLet:
OpList.replace(op, declareLet(op.handle.slot, op.sourceSpan));
break;
case OpKind.Listener:
const listenerFn = reifyListenerHandler(unit, op.handlerFnName, op.handlerOps, op.consumesDollarEvent);
const eventTargetResolver = op.eventTarget ? GLOBAL_TARGET_RESOLVERS.get(op.eventTarget) : null;
if (eventTargetResolver === void 0) {
throw new Error(`Unexpected global target '${op.eventTarget}' defined for '${op.name}' event. Supported list of global targets: window,document,body.`);
}
OpList.replace(op, listener(op.name, listenerFn, eventTargetResolver, op.hostListener && op.isAnimationListener, op.sourceSpan));
break;
case OpKind.TwoWayListener:
OpList.replace(op, twoWayListener(op.name, reifyListenerHandler(unit, op.handlerFnName, op.handlerOps, true), op.sourceSpan));
break;
case OpKind.Variable:
if (op.variable.name === null) {
throw new Error(`AssertionError: unnamed variable ${op.xref}`);
}
OpList.replace(op, createStatementOp(new DeclareVarStmt(op.variable.name, op.initializer, void 0, StmtModifier.Final)));
break;
case OpKind.Namespace:
switch (op.active) {
case Namespace.HTML:
OpList.replace(op, namespaceHTML());
break;
case Namespace.SVG:
OpList.replace(op, namespaceSVG());
break;
case Namespace.Math:
OpList.replace(op, namespaceMath());
break;
}
break;
case OpKind.Defer:
const timerScheduling = !!op.loadingMinimumTime || !!op.loadingAfterTime || !!op.placeholderMinimumTime;
OpList.replace(op, defer(op.handle.slot, op.mainSlot.slot, op.resolverFn, (_b2 = (_a2 = op.loadingSlot) == null ? void 0 : _a2.slot) != null ? _b2 : null, (_d2 = (_c2 = op.placeholderSlot) == null ? void 0 : _c2.slot) != null ? _d2 : null, (_f2 = (_e2 = op.errorSlot) == null ? void 0 : _e2.slot) != null ? _f2 : null, op.loadingConfig, op.placeholderConfig, timerScheduling, op.sourceSpan));
break;
case OpKind.DeferOn:
let args = [];
switch (op.trigger.kind) {
case DeferTriggerKind.Idle:
case DeferTriggerKind.Immediate:
break;
case DeferTriggerKind.Timer:
args = [op.trigger.delay];
break;
case DeferTriggerKind.Interaction:
case DeferTriggerKind.Hover:
case DeferTriggerKind.Viewport:
if (((_g2 = op.trigger.targetSlot) == null ? void 0 : _g2.slot) == null || op.trigger.targetSlotViewSteps === null) {
throw new Error(`Slot or view steps not set in trigger reification for trigger kind ${op.trigger.kind}`);
}
args = [op.trigger.targetSlot.slot];
if (op.trigger.targetSlotViewSteps !== 0) {
args.push(op.trigger.targetSlotViewSteps);
}
break;
default:
throw new Error(`AssertionError: Unsupported reification of defer trigger kind ${op.trigger.kind}`);
}
OpList.replace(op, deferOn(op.trigger.kind, args, op.prefetch, op.sourceSpan));
break;
case OpKind.ProjectionDef:
OpList.replace(op, projectionDef(op.def));
break;
case OpKind.Projection:
if (op.handle.slot === null) {
throw new Error("No slot was assigned for project instruction");
}
let fallbackViewFnName = null;
let fallbackDecls = null;
let fallbackVars = null;
if (op.fallbackView !== null) {
if (!(unit instanceof ViewCompilationUnit)) {
throw new Error(`AssertionError: must be compiling a component`);
}
const fallbackView = unit.job.views.get(op.fallbackView);
if (fallbackView === void 0) {
throw new Error("AssertionError: projection had fallback view xref, but fallback view was not found");
}
if (fallbackView.fnName === null || fallbackView.decls === null || fallbackView.vars === null) {
throw new Error(`AssertionError: expected projection fallback view to have been named and counted`);
}
fallbackViewFnName = fallbackView.fnName;
fallbackDecls = fallbackView.decls;
fallbackVars = fallbackView.vars;
}
OpList.replace(op, projection(op.handle.slot, op.projectionSlotIndex, op.attributes, fallbackViewFnName, fallbackDecls, fallbackVars, op.sourceSpan));
break;
case OpKind.RepeaterCreate:
if (op.handle.slot === null) {
throw new Error("No slot was assigned for repeater instruction");
}
if (!(unit instanceof ViewCompilationUnit)) {
throw new Error(`AssertionError: must be compiling a component`);
}
const repeaterView = unit.job.views.get(op.xref);
if (repeaterView.fnName === null) {
throw new Error(`AssertionError: expected repeater primary view to have been named`);
}
let emptyViewFnName = null;
let emptyDecls = null;
let emptyVars = null;
if (op.emptyView !== null) {
const emptyView = unit.job.views.get(op.emptyView);
if (emptyView === void 0) {
throw new Error("AssertionError: repeater had empty view xref, but empty view was not found");
}
if (emptyView.fnName === null || emptyView.decls === null || emptyView.vars === null) {
throw new Error(`AssertionError: expected repeater empty view to have been named and counted`);
}
emptyViewFnName = emptyView.fnName;
emptyDecls = emptyView.decls;
emptyVars = emptyView.vars;
}
OpList.replace(op, repeaterCreate(op.handle.slot, repeaterView.fnName, op.decls, op.vars, op.tag, op.attributes, op.trackByFn, op.usesComponentInstance, emptyViewFnName, emptyDecls, emptyVars, op.emptyTag, op.emptyAttributes, op.wholeSourceSpan));
break;
case OpKind.Statement:
break;
default:
throw new Error(`AssertionError: Unsupported reification of create op ${OpKind[op.kind]}`);
}
}
}
function reifyUpdateOperations(_unit, ops) {
for (const op of ops) {
transformExpressionsInOp(op, reifyIrExpression, VisitorContextFlag.None);
switch (op.kind) {
case OpKind.Advance:
OpList.replace(op, advance(op.delta, op.sourceSpan));
break;
case OpKind.Property:
if (op.expression instanceof Interpolation2) {
OpList.replace(op, propertyInterpolate(op.name, op.expression.strings, op.expression.expressions, op.sanitizer, op.sourceSpan));
} else {
OpList.replace(op, property(op.name, op.expression, op.sanitizer, op.sourceSpan));
}
break;
case OpKind.TwoWayProperty:
OpList.replace(op, twoWayProperty(op.name, op.expression, op.sanitizer, op.sourceSpan));
break;
case OpKind.StyleProp:
if (op.expression instanceof Interpolation2) {
OpList.replace(op, stylePropInterpolate(op.name, op.expression.strings, op.expression.expressions, op.unit, op.sourceSpan));
} else {
OpList.replace(op, styleProp(op.name, op.expression, op.unit, op.sourceSpan));
}
break;
case OpKind.ClassProp:
OpList.replace(op, classProp(op.name, op.expression, op.sourceSpan));
break;
case OpKind.StyleMap:
if (op.expression instanceof Interpolation2) {
OpList.replace(op, styleMapInterpolate(op.expression.strings, op.expression.expressions, op.sourceSpan));
} else {
OpList.replace(op, styleMap(op.expression, op.sourceSpan));
}
break;
case OpKind.ClassMap:
if (op.expression instanceof Interpolation2) {
OpList.replace(op, classMapInterpolate(op.expression.strings, op.expression.expressions, op.sourceSpan));
} else {
OpList.replace(op, classMap(op.expression, op.sourceSpan));
}
break;
case OpKind.I18nExpression:
OpList.replace(op, i18nExp(op.expression, op.sourceSpan));
break;
case OpKind.I18nApply:
OpList.replace(op, i18nApply(op.handle.slot, op.sourceSpan));
break;
case OpKind.InterpolateText:
OpList.replace(op, textInterpolate(op.interpolation.strings, op.interpolation.expressions, op.sourceSpan));
break;
case OpKind.Attribute:
if (op.expression instanceof Interpolation2) {
OpList.replace(op, attributeInterpolate(op.name, op.expression.strings, op.expression.expressions, op.sanitizer, op.sourceSpan));
} else {
OpList.replace(op, attribute(op.name, op.expression, op.sanitizer, op.namespace));
}
break;
case OpKind.HostProperty:
if (op.expression instanceof Interpolation2) {
throw new Error("not yet handled");
} else {
if (op.isAnimationTrigger) {
OpList.replace(op, syntheticHostProperty(op.name, op.expression, op.sourceSpan));
} else {
OpList.replace(op, hostProperty(op.name, op.expression, op.sanitizer, op.sourceSpan));
}
}
break;
case OpKind.Variable:
if (op.variable.name === null) {
throw new Error(`AssertionError: unnamed variable ${op.xref}`);
}
OpList.replace(op, createStatementOp(new DeclareVarStmt(op.variable.name, op.initializer, void 0, StmtModifier.Final)));
break;
case OpKind.Conditional:
if (op.processed === null) {
throw new Error(`Conditional test was not set.`);
}
OpList.replace(op, conditional(op.processed, op.contextValue, op.sourceSpan));
break;
case OpKind.Repeater:
OpList.replace(op, repeater(op.collection, op.sourceSpan));
break;
case OpKind.DeferWhen:
OpList.replace(op, deferWhen(op.prefetch, op.expr, op.sourceSpan));
break;
case OpKind.StoreLet:
throw new Error(`AssertionError: unexpected storeLet ${op.declaredName}`);
case OpKind.Statement:
break;
default:
throw new Error(`AssertionError: Unsupported reification of update op ${OpKind[op.kind]}`);
}
}
}
function reifyIrExpression(expr) {
if (!isIrExpression(expr)) {
return expr;
}
switch (expr.kind) {
case ExpressionKind.NextContext:
return nextContext(expr.steps);
case ExpressionKind.Reference:
return reference(expr.targetSlot.slot + 1 + expr.offset);
case ExpressionKind.LexicalRead:
throw new Error(`AssertionError: unresolved LexicalRead of ${expr.name}`);
case ExpressionKind.TwoWayBindingSet:
throw new Error(`AssertionError: unresolved TwoWayBindingSet`);
case ExpressionKind.RestoreView:
if (typeof expr.view === "number") {
throw new Error(`AssertionError: unresolved RestoreView`);
}
return restoreView(expr.view);
case ExpressionKind.ResetView:
return resetView(expr.expr);
case ExpressionKind.GetCurrentView:
return getCurrentView();
case ExpressionKind.ReadVariable:
if (expr.name === null) {
throw new Error(`Read of unnamed variable ${expr.xref}`);
}
return variable(expr.name);
case ExpressionKind.ReadTemporaryExpr:
if (expr.name === null) {
throw new Error(`Read of unnamed temporary ${expr.xref}`);
}
return variable(expr.name);
case ExpressionKind.AssignTemporaryExpr:
if (expr.name === null) {
throw new Error(`Assign of unnamed temporary ${expr.xref}`);
}
return variable(expr.name).set(expr.expr);
case ExpressionKind.PureFunctionExpr:
if (expr.fn === null) {
throw new Error(`AssertionError: expected PureFunctions to have been extracted`);
}
return pureFunction(expr.varOffset, expr.fn, expr.args);
case ExpressionKind.PureFunctionParameterExpr:
throw new Error(`AssertionError: expected PureFunctionParameterExpr to have been extracted`);
case ExpressionKind.PipeBinding:
return pipeBind(expr.targetSlot.slot, expr.varOffset, expr.args);
case ExpressionKind.PipeBindingVariadic:
return pipeBindV(expr.targetSlot.slot, expr.varOffset, expr.args);
case ExpressionKind.SlotLiteralExpr:
return literal(expr.slot.slot);
case ExpressionKind.ContextLetReference:
return readContextLet(expr.targetSlot.slot);
case ExpressionKind.StoreLet:
return storeLet(expr.value, expr.sourceSpan);
default:
throw new Error(`AssertionError: Unsupported reification of ir.Expression kind: ${ExpressionKind[expr.kind]}`);
}
}
function reifyListenerHandler(unit, name, handlerOps, consumesDollarEvent) {
reifyUpdateOperations(unit, handlerOps);
const handlerStmts = [];
for (const op of handlerOps) {
if (op.kind !== OpKind.Statement) {
throw new Error(`AssertionError: expected reified statements, but found op ${OpKind[op.kind]}`);
}
handlerStmts.push(op.statement);
}
const params = [];
if (consumesDollarEvent) {
params.push(new FnParam("$event"));
}
return fn(params, handlerStmts, void 0, void 0, name);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/remove_empty_bindings.mjs
function removeEmptyBindings(job) {
for (const unit of job.units) {
for (const op of unit.update) {
switch (op.kind) {
case OpKind.Attribute:
case OpKind.Binding:
case OpKind.ClassProp:
case OpKind.ClassMap:
case OpKind.Property:
case OpKind.StyleProp:
case OpKind.StyleMap:
if (op.expression instanceof EmptyExpr2) {
OpList.remove(op);
}
break;
}
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/remove_i18n_contexts.mjs
function removeI18nContexts(job) {
for (const unit of job.units) {
for (const op of unit.create) {
switch (op.kind) {
case OpKind.I18nContext:
OpList.remove(op);
break;
case OpKind.I18nStart:
op.context = null;
break;
}
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/remove_unused_i18n_attrs.mjs
function removeUnusedI18nAttributesOps(job) {
for (const unit of job.units) {
const ownersWithI18nExpressions = /* @__PURE__ */ new Set();
for (const op of unit.update) {
switch (op.kind) {
case OpKind.I18nExpression:
ownersWithI18nExpressions.add(op.i18nOwner);
}
}
for (const op of unit.create) {
switch (op.kind) {
case OpKind.I18nAttributes:
if (ownersWithI18nExpressions.has(op.xref)) {
continue;
}
OpList.remove(op);
}
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/resolve_contexts.mjs
function resolveContexts(job) {
for (const unit of job.units) {
processLexicalScope(unit, unit.create);
processLexicalScope(unit, unit.update);
}
}
function processLexicalScope(view, ops) {
const scope = /* @__PURE__ */ new Map();
scope.set(view.xref, variable("ctx"));
for (const op of ops) {
switch (op.kind) {
case OpKind.Variable:
switch (op.variable.kind) {
case SemanticVariableKind.Context:
scope.set(op.variable.view, new ReadVariableExpr(op.xref));
break;
}
break;
case OpKind.Listener:
case OpKind.TwoWayListener:
processLexicalScope(view, op.handlerOps);
break;
}
}
if (view === view.job.root) {
scope.set(view.xref, variable("ctx"));
}
for (const op of ops) {
transformExpressionsInOp(op, (expr) => {
if (expr instanceof ContextExpr) {
if (!scope.has(expr.view)) {
throw new Error(`No context found for reference to view ${expr.view} from view ${view.xref}`);
}
return scope.get(expr.view);
} else {
return expr;
}
}, VisitorContextFlag.None);
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/resolve_dollar_event.mjs
function resolveDollarEvent(job) {
for (const unit of job.units) {
transformDollarEvent(unit.create);
transformDollarEvent(unit.update);
}
}
function transformDollarEvent(ops) {
for (const op of ops) {
if (op.kind === OpKind.Listener || op.kind === OpKind.TwoWayListener) {
transformExpressionsInOp(op, (expr) => {
if (expr instanceof LexicalReadExpr && expr.name === "$event") {
if (op.kind === OpKind.Listener) {
op.consumesDollarEvent = true;
}
return new ReadVarExpr(expr.name);
}
return expr;
}, VisitorContextFlag.InChildOperation);
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/resolve_i18n_element_placeholders.mjs
function resolveI18nElementPlaceholders(job) {
const i18nContexts = /* @__PURE__ */ new Map();
const elements = /* @__PURE__ */ new Map();
for (const unit of job.units) {
for (const op of unit.create) {
switch (op.kind) {
case OpKind.I18nContext:
i18nContexts.set(op.xref, op);
break;
case OpKind.ElementStart:
elements.set(op.xref, op);
break;
}
}
}
resolvePlaceholdersForView(job, job.root, i18nContexts, elements);
}
function resolvePlaceholdersForView(job, unit, i18nContexts, elements, pendingStructuralDirective) {
let currentOps = null;
let pendingStructuralDirectiveCloses = /* @__PURE__ */ new Map();
for (const op of unit.create) {
switch (op.kind) {
case OpKind.I18nStart:
if (!op.context) {
throw Error("Could not find i18n context for i18n op");
}
currentOps = { i18nBlock: op, i18nContext: i18nContexts.get(op.context) };
break;
case OpKind.I18nEnd:
currentOps = null;
break;
case OpKind.ElementStart:
if (op.i18nPlaceholder !== void 0) {
if (currentOps === null) {
throw Error("i18n tag placeholder should only occur inside an i18n block");
}
recordElementStart(op, currentOps.i18nContext, currentOps.i18nBlock, pendingStructuralDirective);
if (pendingStructuralDirective && op.i18nPlaceholder.closeName) {
pendingStructuralDirectiveCloses.set(op.xref, pendingStructuralDirective);
}
pendingStructuralDirective = void 0;
}
break;
case OpKind.ElementEnd:
const startOp = elements.get(op.xref);
if (startOp && startOp.i18nPlaceholder !== void 0) {
if (currentOps === null) {
throw Error("AssertionError: i18n tag placeholder should only occur inside an i18n block");
}
recordElementClose(startOp, currentOps.i18nContext, currentOps.i18nBlock, pendingStructuralDirectiveCloses.get(op.xref));
pendingStructuralDirectiveCloses.delete(op.xref);
}
break;
case OpKind.Projection:
if (op.i18nPlaceholder !== void 0) {
if (currentOps === null) {
throw Error("i18n tag placeholder should only occur inside an i18n block");
}
recordElementStart(op, currentOps.i18nContext, currentOps.i18nBlock, pendingStructuralDirective);
recordElementClose(op, currentOps.i18nContext, currentOps.i18nBlock, pendingStructuralDirective);
pendingStructuralDirective = void 0;
}
break;
case OpKind.Template:
const view = job.views.get(op.xref);
if (op.i18nPlaceholder === void 0) {
resolvePlaceholdersForView(job, view, i18nContexts, elements);
} else {
if (currentOps === null) {
throw Error("i18n tag placeholder should only occur inside an i18n block");
}
if (op.templateKind === TemplateKind.Structural) {
resolvePlaceholdersForView(job, view, i18nContexts, elements, op);
} else {
recordTemplateStart(job, view, op.handle.slot, op.i18nPlaceholder, currentOps.i18nContext, currentOps.i18nBlock, pendingStructuralDirective);
resolvePlaceholdersForView(job, view, i18nContexts, elements);
recordTemplateClose(job, view, op.handle.slot, op.i18nPlaceholder, currentOps.i18nContext, currentOps.i18nBlock, pendingStructuralDirective);
pendingStructuralDirective = void 0;
}
}
break;
case OpKind.RepeaterCreate:
if (pendingStructuralDirective !== void 0) {
throw Error("AssertionError: Unexpected structural directive associated with @for block");
}
const forSlot = op.handle.slot + 1;
const forView = job.views.get(op.xref);
if (op.i18nPlaceholder === void 0) {
resolvePlaceholdersForView(job, forView, i18nContexts, elements);
} else {
if (currentOps === null) {
throw Error("i18n tag placeholder should only occur inside an i18n block");
}
recordTemplateStart(job, forView, forSlot, op.i18nPlaceholder, currentOps.i18nContext, currentOps.i18nBlock, pendingStructuralDirective);
resolvePlaceholdersForView(job, forView, i18nContexts, elements);
recordTemplateClose(job, forView, forSlot, op.i18nPlaceholder, currentOps.i18nContext, currentOps.i18nBlock, pendingStructuralDirective);
pendingStructuralDirective = void 0;
}
if (op.emptyView !== null) {
const emptySlot = op.handle.slot + 2;
const emptyView = job.views.get(op.emptyView);
if (op.emptyI18nPlaceholder === void 0) {
resolvePlaceholdersForView(job, emptyView, i18nContexts, elements);
} else {
if (currentOps === null) {
throw Error("i18n tag placeholder should only occur inside an i18n block");
}
recordTemplateStart(job, emptyView, emptySlot, op.emptyI18nPlaceholder, currentOps.i18nContext, currentOps.i18nBlock, pendingStructuralDirective);
resolvePlaceholdersForView(job, emptyView, i18nContexts, elements);
recordTemplateClose(job, emptyView, emptySlot, op.emptyI18nPlaceholder, currentOps.i18nContext, currentOps.i18nBlock, pendingStructuralDirective);
pendingStructuralDirective = void 0;
}
}
break;
}
}
}
function recordElementStart(op, i18nContext, i18nBlock, structuralDirective) {
const { startName, closeName } = op.i18nPlaceholder;
let flags = I18nParamValueFlags.ElementTag | I18nParamValueFlags.OpenTag;
let value = op.handle.slot;
if (structuralDirective !== void 0) {
flags |= I18nParamValueFlags.TemplateTag;
value = { element: value, template: structuralDirective.handle.slot };
}
if (!closeName) {
flags |= I18nParamValueFlags.CloseTag;
}
addParam(i18nContext.params, startName, value, i18nBlock.subTemplateIndex, flags);
}
function recordElementClose(op, i18nContext, i18nBlock, structuralDirective) {
const { closeName } = op.i18nPlaceholder;
if (closeName) {
let flags = I18nParamValueFlags.ElementTag | I18nParamValueFlags.CloseTag;
let value = op.handle.slot;
if (structuralDirective !== void 0) {
flags |= I18nParamValueFlags.TemplateTag;
value = { element: value, template: structuralDirective.handle.slot };
}
addParam(i18nContext.params, closeName, value, i18nBlock.subTemplateIndex, flags);
}
}
function recordTemplateStart(job, view, slot, i18nPlaceholder, i18nContext, i18nBlock, structuralDirective) {
let { startName, closeName } = i18nPlaceholder;
let flags = I18nParamValueFlags.TemplateTag | I18nParamValueFlags.OpenTag;
if (!closeName) {
flags |= I18nParamValueFlags.CloseTag;
}
if (structuralDirective !== void 0) {
addParam(i18nContext.params, startName, structuralDirective.handle.slot, i18nBlock.subTemplateIndex, flags);
}
addParam(i18nContext.params, startName, slot, getSubTemplateIndexForTemplateTag(job, i18nBlock, view), flags);
}
function recordTemplateClose(job, view, slot, i18nPlaceholder, i18nContext, i18nBlock, structuralDirective) {
const { closeName } = i18nPlaceholder;
const flags = I18nParamValueFlags.TemplateTag | I18nParamValueFlags.CloseTag;
if (closeName) {
addParam(i18nContext.params, closeName, slot, getSubTemplateIndexForTemplateTag(job, i18nBlock, view), flags);
if (structuralDirective !== void 0) {
addParam(i18nContext.params, closeName, structuralDirective.handle.slot, i18nBlock.subTemplateIndex, flags);
}
}
}
function getSubTemplateIndexForTemplateTag(job, i18nOp, view) {
for (const childOp of view.create) {
if (childOp.kind === OpKind.I18nStart) {
return childOp.subTemplateIndex;
}
}
return i18nOp.subTemplateIndex;
}
function addParam(params, placeholder, value, subTemplateIndex, flags) {
var _a2;
const values = (_a2 = params.get(placeholder)) != null ? _a2 : [];
values.push({ value, subTemplateIndex, flags });
params.set(placeholder, values);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/resolve_i18n_expression_placeholders.mjs
function resolveI18nExpressionPlaceholders(job) {
var _a2;
const subTemplateIndices = /* @__PURE__ */ new Map();
const i18nContexts = /* @__PURE__ */ new Map();
const icuPlaceholders = /* @__PURE__ */ new Map();
for (const unit of job.units) {
for (const op of unit.create) {
switch (op.kind) {
case OpKind.I18nStart:
subTemplateIndices.set(op.xref, op.subTemplateIndex);
break;
case OpKind.I18nContext:
i18nContexts.set(op.xref, op);
break;
case OpKind.IcuPlaceholder:
icuPlaceholders.set(op.xref, op);
break;
}
}
}
const expressionIndices = /* @__PURE__ */ new Map();
const referenceIndex = (op) => op.usage === I18nExpressionFor.I18nText ? op.i18nOwner : op.context;
for (const unit of job.units) {
for (const op of unit.update) {
if (op.kind === OpKind.I18nExpression) {
const index = expressionIndices.get(referenceIndex(op)) || 0;
const subTemplateIndex = (_a2 = subTemplateIndices.get(op.i18nOwner)) != null ? _a2 : null;
const value = {
value: index,
subTemplateIndex,
flags: I18nParamValueFlags.ExpressionIndex
};
updatePlaceholder(op, value, i18nContexts, icuPlaceholders);
expressionIndices.set(referenceIndex(op), index + 1);
}
}
}
}
function updatePlaceholder(op, value, i18nContexts, icuPlaceholders) {
if (op.i18nPlaceholder !== null) {
const i18nContext = i18nContexts.get(op.context);
const params = op.resolutionTime === I18nParamResolutionTime.Creation ? i18nContext.params : i18nContext.postprocessingParams;
const values = params.get(op.i18nPlaceholder) || [];
values.push(value);
params.set(op.i18nPlaceholder, values);
}
if (op.icuPlaceholder !== null) {
const icuPlaceholderOp = icuPlaceholders.get(op.icuPlaceholder);
icuPlaceholderOp == null ? void 0 : icuPlaceholderOp.expressionPlaceholders.push(value);
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/resolve_names.mjs
function resolveNames(job) {
for (const unit of job.units) {
processLexicalScope2(unit, unit.create, null);
processLexicalScope2(unit, unit.update, null);
}
}
function processLexicalScope2(unit, ops, savedView) {
const scope = /* @__PURE__ */ new Map();
const localDefinitions = /* @__PURE__ */ new Map();
for (const op of ops) {
switch (op.kind) {
case OpKind.Variable:
switch (op.variable.kind) {
case SemanticVariableKind.Identifier:
if (op.variable.local) {
if (localDefinitions.has(op.variable.identifier)) {
continue;
}
localDefinitions.set(op.variable.identifier, op.xref);
} else if (scope.has(op.variable.identifier)) {
continue;
}
scope.set(op.variable.identifier, op.xref);
break;
case SemanticVariableKind.Alias:
if (scope.has(op.variable.identifier)) {
continue;
}
scope.set(op.variable.identifier, op.xref);
break;
case SemanticVariableKind.SavedView:
savedView = {
view: op.variable.view,
variable: op.xref
};
break;
}
break;
case OpKind.Listener:
case OpKind.TwoWayListener:
processLexicalScope2(unit, op.handlerOps, savedView);
break;
}
}
for (const op of ops) {
if (op.kind == OpKind.Listener || op.kind === OpKind.TwoWayListener) {
continue;
}
transformExpressionsInOp(op, (expr) => {
if (expr instanceof LexicalReadExpr) {
if (localDefinitions.has(expr.name)) {
return new ReadVariableExpr(localDefinitions.get(expr.name));
} else if (scope.has(expr.name)) {
return new ReadVariableExpr(scope.get(expr.name));
} else {
return new ReadPropExpr(new ContextExpr(unit.job.root.xref), expr.name);
}
} else if (expr instanceof RestoreViewExpr && typeof expr.view === "number") {
if (savedView === null || savedView.view !== expr.view) {
throw new Error(`AssertionError: no saved view ${expr.view} from view ${unit.xref}`);
}
expr.view = new ReadVariableExpr(savedView.variable);
return expr;
} else {
return expr;
}
}, VisitorContextFlag.None);
}
for (const op of ops) {
visitExpressionsInOp(op, (expr) => {
if (expr instanceof LexicalReadExpr) {
throw new Error(`AssertionError: no lexical reads should remain, but found read of ${expr.name}`);
}
});
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/resolve_sanitizers.mjs
var sanitizerFns = /* @__PURE__ */ new Map([
[SecurityContext.HTML, Identifiers.sanitizeHtml],
[SecurityContext.RESOURCE_URL, Identifiers.sanitizeResourceUrl],
[SecurityContext.SCRIPT, Identifiers.sanitizeScript],
[SecurityContext.STYLE, Identifiers.sanitizeStyle],
[SecurityContext.URL, Identifiers.sanitizeUrl]
]);
var trustedValueFns = /* @__PURE__ */ new Map([
[SecurityContext.HTML, Identifiers.trustConstantHtml],
[SecurityContext.RESOURCE_URL, Identifiers.trustConstantResourceUrl]
]);
function resolveSanitizers(job) {
var _a2, _b2;
for (const unit of job.units) {
const elements = createOpXrefMap(unit);
if (job.kind !== CompilationJobKind.Host) {
for (const op of unit.create) {
if (op.kind === OpKind.ExtractedAttribute) {
const trustedValueFn = (_a2 = trustedValueFns.get(getOnlySecurityContext(op.securityContext))) != null ? _a2 : null;
op.trustedValueFn = trustedValueFn !== null ? importExpr(trustedValueFn) : null;
}
}
}
for (const op of unit.update) {
switch (op.kind) {
case OpKind.Property:
case OpKind.Attribute:
case OpKind.HostProperty:
let sanitizerFn = null;
if (Array.isArray(op.securityContext) && op.securityContext.length === 2 && op.securityContext.indexOf(SecurityContext.URL) > -1 && op.securityContext.indexOf(SecurityContext.RESOURCE_URL) > -1) {
sanitizerFn = Identifiers.sanitizeUrlOrResourceUrl;
} else {
sanitizerFn = (_b2 = sanitizerFns.get(getOnlySecurityContext(op.securityContext))) != null ? _b2 : null;
}
op.sanitizer = sanitizerFn !== null ? importExpr(sanitizerFn) : null;
if (op.sanitizer === null) {
let isIframe = false;
if (job.kind === CompilationJobKind.Host || op.kind === OpKind.HostProperty) {
isIframe = true;
} else {
const ownerOp = elements.get(op.target);
if (ownerOp === void 0 || !isElementOrContainerOp(ownerOp)) {
throw Error("Property should have an element-like owner");
}
isIframe = isIframeElement(ownerOp);
}
if (isIframe && isIframeSecuritySensitiveAttr(op.name)) {
op.sanitizer = importExpr(Identifiers.validateIframeAttribute);
}
}
break;
}
}
}
}
function isIframeElement(op) {
var _a2;
return op.kind === OpKind.ElementStart && ((_a2 = op.tag) == null ? void 0 : _a2.toLowerCase()) === "iframe";
}
function getOnlySecurityContext(securityContext) {
if (Array.isArray(securityContext)) {
if (securityContext.length > 1) {
throw Error(`AssertionError: Ambiguous security context`);
}
return securityContext[0] || SecurityContext.NONE;
}
return securityContext;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/transform_two_way_binding_set.mjs
function transformTwoWayBindingSet(job) {
for (const unit of job.units) {
for (const op of unit.create) {
if (op.kind === OpKind.TwoWayListener) {
transformExpressionsInOp(op, (expr) => {
if (!(expr instanceof TwoWayBindingSetExpr)) {
return expr;
}
const { target, value } = expr;
if (target instanceof ReadPropExpr || target instanceof ReadKeyExpr) {
return twoWayBindingSet(target, value).or(target.set(value));
}
if (target instanceof ReadVariableExpr) {
return twoWayBindingSet(target, value);
}
throw new Error(`Unsupported expression in two-way action binding.`);
}, VisitorContextFlag.InChildOperation);
}
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/save_restore_view.mjs
function saveAndRestoreView(job) {
for (const unit of job.units) {
unit.create.prepend([
createVariableOp(unit.job.allocateXrefId(), {
kind: SemanticVariableKind.SavedView,
name: null,
view: unit.xref
}, new GetCurrentViewExpr(), VariableFlags.None)
]);
for (const op of unit.create) {
if (op.kind !== OpKind.Listener && op.kind !== OpKind.TwoWayListener) {
continue;
}
let needsRestoreView = unit !== job.root;
if (!needsRestoreView) {
for (const handlerOp of op.handlerOps) {
visitExpressionsInOp(handlerOp, (expr) => {
if (expr instanceof ReferenceExpr || expr instanceof ContextLetReferenceExpr) {
needsRestoreView = true;
}
});
}
}
if (needsRestoreView) {
addSaveRestoreViewOperationToListener(unit, op);
}
}
}
}
function addSaveRestoreViewOperationToListener(unit, op) {
op.handlerOps.prepend([
createVariableOp(unit.job.allocateXrefId(), {
kind: SemanticVariableKind.Context,
name: null,
view: unit.xref
}, new RestoreViewExpr(unit.xref), VariableFlags.None)
]);
for (const handlerOp of op.handlerOps) {
if (handlerOp.kind === OpKind.Statement && handlerOp.statement instanceof ReturnStatement) {
handlerOp.statement.value = new ResetViewExpr(handlerOp.statement.value);
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/slot_allocation.mjs
function allocateSlots(job) {
const slotMap = /* @__PURE__ */ new Map();
for (const unit of job.units) {
let slotCount = 0;
for (const op of unit.create) {
if (!hasConsumesSlotTrait(op)) {
continue;
}
op.handle.slot = slotCount;
slotMap.set(op.xref, op.handle.slot);
slotCount += op.numSlotsUsed;
}
unit.decls = slotCount;
}
for (const unit of job.units) {
for (const op of unit.ops()) {
if (op.kind === OpKind.Template || op.kind === OpKind.RepeaterCreate) {
const childView = job.views.get(op.xref);
op.decls = childView.decls;
}
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/style_binding_specialization.mjs
function specializeStyleBindings(job) {
for (const unit of job.units) {
for (const op of unit.update) {
if (op.kind !== OpKind.Binding) {
continue;
}
switch (op.bindingKind) {
case BindingKind.ClassName:
if (op.expression instanceof Interpolation2) {
throw new Error(`Unexpected interpolation in ClassName binding`);
}
OpList.replace(op, createClassPropOp(op.target, op.name, op.expression, op.sourceSpan));
break;
case BindingKind.StyleProperty:
OpList.replace(op, createStylePropOp(op.target, op.name, op.expression, op.unit, op.sourceSpan));
break;
case BindingKind.Property:
case BindingKind.Template:
if (op.name === "style") {
OpList.replace(op, createStyleMapOp(op.target, op.expression, op.sourceSpan));
} else if (op.name === "class") {
OpList.replace(op, createClassMapOp(op.target, op.expression, op.sourceSpan));
}
break;
}
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/temporary_variables.mjs
function generateTemporaryVariables(job) {
for (const unit of job.units) {
unit.create.prepend(generateTemporaries(unit.create));
unit.update.prepend(generateTemporaries(unit.update));
}
}
function generateTemporaries(ops) {
let opCount = 0;
let generatedStatements = [];
for (const op of ops) {
const finalReads = /* @__PURE__ */ new Map();
visitExpressionsInOp(op, (expr, flag) => {
if (flag & VisitorContextFlag.InChildOperation) {
return;
}
if (expr instanceof ReadTemporaryExpr) {
finalReads.set(expr.xref, expr);
}
});
let count = 0;
const assigned = /* @__PURE__ */ new Set();
const released = /* @__PURE__ */ new Set();
const defs = /* @__PURE__ */ new Map();
visitExpressionsInOp(op, (expr, flag) => {
if (flag & VisitorContextFlag.InChildOperation) {
return;
}
if (expr instanceof AssignTemporaryExpr) {
if (!assigned.has(expr.xref)) {
assigned.add(expr.xref);
defs.set(expr.xref, `tmp_${opCount}_${count++}`);
}
assignName(defs, expr);
} else if (expr instanceof ReadTemporaryExpr) {
if (finalReads.get(expr.xref) === expr) {
released.add(expr.xref);
count--;
}
assignName(defs, expr);
}
});
generatedStatements.push(...Array.from(new Set(defs.values())).map((name) => createStatementOp(new DeclareVarStmt(name))));
opCount++;
if (op.kind === OpKind.Listener || op.kind === OpKind.TwoWayListener) {
op.handlerOps.prepend(generateTemporaries(op.handlerOps));
}
}
return generatedStatements;
}
function assignName(names, expr) {
const name = names.get(expr.xref);
if (name === void 0) {
throw new Error(`Found xref with unassigned name: ${expr.xref}`);
}
expr.name = name;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/track_fn_generation.mjs
function generateTrackFns(job) {
for (const unit of job.units) {
for (const op of unit.create) {
if (op.kind !== OpKind.RepeaterCreate) {
continue;
}
if (op.trackByFn !== null) {
continue;
}
let usesComponentContext = false;
op.track = transformExpressionsInExpression(op.track, (expr) => {
if (expr instanceof PipeBindingExpr || expr instanceof PipeBindingVariadicExpr) {
throw new Error(`Illegal State: Pipes are not allowed in this context`);
}
if (expr instanceof TrackContextExpr) {
usesComponentContext = true;
return variable("this");
}
return expr;
}, VisitorContextFlag.None);
let fn2;
const fnParams = [new FnParam("$index"), new FnParam("$item")];
if (usesComponentContext) {
fn2 = new FunctionExpr(fnParams, [new ReturnStatement(op.track)]);
} else {
fn2 = arrowFn(fnParams, op.track);
}
op.trackByFn = job.pool.getSharedFunctionReference(fn2, "_forTrack");
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/track_fn_optimization.mjs
function optimizeTrackFns(job) {
for (const unit of job.units) {
for (const op of unit.create) {
if (op.kind !== OpKind.RepeaterCreate) {
continue;
}
if (op.track instanceof ReadVarExpr && op.track.name === "$index") {
op.trackByFn = importExpr(Identifiers.repeaterTrackByIndex);
} else if (op.track instanceof ReadVarExpr && op.track.name === "$item") {
op.trackByFn = importExpr(Identifiers.repeaterTrackByIdentity);
} else if (isTrackByFunctionCall(job.root.xref, op.track)) {
op.usesComponentInstance = true;
if (op.track.receiver.receiver.view === unit.xref) {
op.trackByFn = op.track.receiver;
} else {
op.trackByFn = importExpr(Identifiers.componentInstance).callFn([]).prop(op.track.receiver.name);
op.track = op.trackByFn;
}
} else {
op.track = transformExpressionsInExpression(op.track, (expr) => {
if (expr instanceof ContextExpr) {
op.usesComponentInstance = true;
return new TrackContextExpr(expr.view);
}
return expr;
}, VisitorContextFlag.None);
}
}
}
}
function isTrackByFunctionCall(rootView, expr) {
if (!(expr instanceof InvokeFunctionExpr) || expr.args.length === 0 || expr.args.length > 2) {
return false;
}
if (!(expr.receiver instanceof ReadPropExpr && expr.receiver.receiver instanceof ContextExpr) || expr.receiver.receiver.view !== rootView) {
return false;
}
const [arg0, arg1] = expr.args;
if (!(arg0 instanceof ReadVarExpr) || arg0.name !== "$index") {
return false;
} else if (expr.args.length === 1) {
return true;
}
if (!(arg1 instanceof ReadVarExpr) || arg1.name !== "$item") {
return false;
}
return true;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/track_variables.mjs
function generateTrackVariables(job) {
for (const unit of job.units) {
for (const op of unit.create) {
if (op.kind !== OpKind.RepeaterCreate) {
continue;
}
op.track = transformExpressionsInExpression(op.track, (expr) => {
if (expr instanceof LexicalReadExpr) {
if (op.varNames.$index.has(expr.name)) {
return variable("$index");
} else if (expr.name === op.varNames.$implicit) {
return variable("$item");
}
}
return expr;
}, VisitorContextFlag.None);
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/var_counting.mjs
function countVariables(job) {
for (const unit of job.units) {
let varCount = 0;
for (const op of unit.ops()) {
if (hasConsumesVarsTrait(op)) {
varCount += varsUsedByOp(op);
}
}
for (const op of unit.ops()) {
visitExpressionsInOp(op, (expr) => {
if (!isIrExpression(expr)) {
return;
}
if (job.compatibility === CompatibilityMode.TemplateDefinitionBuilder && expr instanceof PureFunctionExpr) {
return;
}
if (hasUsesVarOffsetTrait(expr)) {
expr.varOffset = varCount;
}
if (hasConsumesVarsTrait(expr)) {
varCount += varsUsedByIrExpression(expr);
}
});
}
if (job.compatibility === CompatibilityMode.TemplateDefinitionBuilder) {
for (const op of unit.ops()) {
visitExpressionsInOp(op, (expr) => {
if (!isIrExpression(expr) || !(expr instanceof PureFunctionExpr)) {
return;
}
if (hasUsesVarOffsetTrait(expr)) {
expr.varOffset = varCount;
}
if (hasConsumesVarsTrait(expr)) {
varCount += varsUsedByIrExpression(expr);
}
});
}
}
unit.vars = varCount;
}
if (job instanceof ComponentCompilationJob) {
for (const unit of job.units) {
for (const op of unit.create) {
if (op.kind !== OpKind.Template && op.kind !== OpKind.RepeaterCreate) {
continue;
}
const childView = job.views.get(op.xref);
op.vars = childView.vars;
}
}
}
}
function varsUsedByOp(op) {
let slots;
switch (op.kind) {
case OpKind.Property:
case OpKind.HostProperty:
case OpKind.Attribute:
slots = 1;
if (op.expression instanceof Interpolation2 && !isSingletonInterpolation(op.expression)) {
slots += op.expression.expressions.length;
}
return slots;
case OpKind.TwoWayProperty:
return 1;
case OpKind.StyleProp:
case OpKind.ClassProp:
case OpKind.StyleMap:
case OpKind.ClassMap:
slots = 2;
if (op.expression instanceof Interpolation2) {
slots += op.expression.expressions.length;
}
return slots;
case OpKind.InterpolateText:
return op.interpolation.expressions.length;
case OpKind.I18nExpression:
case OpKind.Conditional:
case OpKind.DeferWhen:
case OpKind.StoreLet:
return 1;
case OpKind.RepeaterCreate:
return op.emptyView ? 1 : 0;
default:
throw new Error(`Unhandled op: ${OpKind[op.kind]}`);
}
}
function varsUsedByIrExpression(expr) {
switch (expr.kind) {
case ExpressionKind.PureFunctionExpr:
return 1 + expr.args.length;
case ExpressionKind.PipeBinding:
return 1 + expr.args.length;
case ExpressionKind.PipeBindingVariadic:
return 1 + expr.numArgs;
case ExpressionKind.StoreLet:
return 1;
default:
throw new Error(`AssertionError: unhandled ConsumesVarsTrait expression ${expr.constructor.name}`);
}
}
function isSingletonInterpolation(expr) {
if (expr.expressions.length !== 1 || expr.strings.length !== 2) {
return false;
}
if (expr.strings[0] !== "" || expr.strings[1] !== "") {
return false;
}
return true;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/variable_optimization.mjs
function optimizeVariables(job) {
for (const unit of job.units) {
inlineAlwaysInlineVariables(unit.create);
inlineAlwaysInlineVariables(unit.update);
for (const op of unit.create) {
if (op.kind === OpKind.Listener || op.kind === OpKind.TwoWayListener) {
inlineAlwaysInlineVariables(op.handlerOps);
}
}
optimizeVariablesInOpList(unit.create, job.compatibility);
optimizeVariablesInOpList(unit.update, job.compatibility);
for (const op of unit.create) {
if (op.kind === OpKind.Listener || op.kind === OpKind.TwoWayListener) {
optimizeVariablesInOpList(op.handlerOps, job.compatibility);
}
}
}
}
var Fence;
(function(Fence2) {
Fence2[Fence2["None"] = 0] = "None";
Fence2[Fence2["ViewContextRead"] = 1] = "ViewContextRead";
Fence2[Fence2["ViewContextWrite"] = 2] = "ViewContextWrite";
Fence2[Fence2["SideEffectful"] = 4] = "SideEffectful";
})(Fence || (Fence = {}));
function inlineAlwaysInlineVariables(ops) {
const vars = /* @__PURE__ */ new Map();
for (const op of ops) {
if (op.kind === OpKind.Variable && op.flags & VariableFlags.AlwaysInline) {
visitExpressionsInOp(op, (expr) => {
if (isIrExpression(expr) && fencesForIrExpression(expr) !== Fence.None) {
throw new Error(`AssertionError: A context-sensitive variable was marked AlwaysInline`);
}
});
vars.set(op.xref, op);
}
transformExpressionsInOp(op, (expr) => {
if (expr instanceof ReadVariableExpr && vars.has(expr.xref)) {
const varOp = vars.get(expr.xref);
return varOp.initializer.clone();
}
return expr;
}, VisitorContextFlag.None);
}
for (const op of vars.values()) {
OpList.remove(op);
}
}
function optimizeVariablesInOpList(ops, compatibility) {
const varDecls = /* @__PURE__ */ new Map();
const varUsages = /* @__PURE__ */ new Map();
const varRemoteUsages = /* @__PURE__ */ new Set();
const opMap = /* @__PURE__ */ new Map();
for (const op of ops) {
if (op.kind === OpKind.Variable) {
if (varDecls.has(op.xref) || varUsages.has(op.xref)) {
throw new Error(`Should not see two declarations of the same variable: ${op.xref}`);
}
varDecls.set(op.xref, op);
varUsages.set(op.xref, 0);
}
opMap.set(op, collectOpInfo(op));
countVariableUsages(op, varUsages, varRemoteUsages);
}
let contextIsUsed = false;
for (const op of ops.reversed()) {
const opInfo = opMap.get(op);
if (op.kind === OpKind.Variable && varUsages.get(op.xref) === 0) {
if (contextIsUsed && opInfo.fences & Fence.ViewContextWrite || opInfo.fences & Fence.SideEffectful) {
const stmtOp = createStatementOp(op.initializer.toStmt());
opMap.set(stmtOp, opInfo);
OpList.replace(op, stmtOp);
} else {
uncountVariableUsages(op, varUsages);
OpList.remove(op);
}
opMap.delete(op);
varDecls.delete(op.xref);
varUsages.delete(op.xref);
continue;
}
if (opInfo.fences & Fence.ViewContextRead) {
contextIsUsed = true;
}
}
const toInline = [];
for (const [id, count] of varUsages) {
const decl = varDecls.get(id);
const isAlwaysInline = !!(decl.flags & VariableFlags.AlwaysInline);
if (count !== 1 || isAlwaysInline) {
continue;
}
if (varRemoteUsages.has(id)) {
continue;
}
toInline.push(id);
}
let candidate;
while (candidate = toInline.pop()) {
const decl = varDecls.get(candidate);
const varInfo = opMap.get(decl);
const isAlwaysInline = !!(decl.flags & VariableFlags.AlwaysInline);
if (isAlwaysInline) {
throw new Error(`AssertionError: Found an 'AlwaysInline' variable after the always inlining pass.`);
}
for (let targetOp = decl.next; targetOp.kind !== OpKind.ListEnd; targetOp = targetOp.next) {
const opInfo = opMap.get(targetOp);
if (opInfo.variablesUsed.has(candidate)) {
if (compatibility === CompatibilityMode.TemplateDefinitionBuilder && !allowConservativeInlining(decl, targetOp)) {
break;
}
if (tryInlineVariableInitializer(candidate, decl.initializer, targetOp, varInfo.fences)) {
opInfo.variablesUsed.delete(candidate);
for (const id of varInfo.variablesUsed) {
opInfo.variablesUsed.add(id);
}
opInfo.fences |= varInfo.fences;
varDecls.delete(candidate);
varUsages.delete(candidate);
opMap.delete(decl);
OpList.remove(decl);
}
break;
}
if (!safeToInlinePastFences(opInfo.fences, varInfo.fences)) {
break;
}
}
}
}
function fencesForIrExpression(expr) {
switch (expr.kind) {
case ExpressionKind.NextContext:
return Fence.ViewContextRead | Fence.ViewContextWrite;
case ExpressionKind.RestoreView:
return Fence.ViewContextRead | Fence.ViewContextWrite | Fence.SideEffectful;
case ExpressionKind.StoreLet:
return Fence.SideEffectful;
case ExpressionKind.Reference:
case ExpressionKind.ContextLetReference:
return Fence.ViewContextRead;
default:
return Fence.None;
}
}
function collectOpInfo(op) {
let fences = Fence.None;
const variablesUsed = /* @__PURE__ */ new Set();
visitExpressionsInOp(op, (expr) => {
if (!isIrExpression(expr)) {
return;
}
switch (expr.kind) {
case ExpressionKind.ReadVariable:
variablesUsed.add(expr.xref);
break;
default:
fences |= fencesForIrExpression(expr);
}
});
return { fences, variablesUsed };
}
function countVariableUsages(op, varUsages, varRemoteUsage) {
visitExpressionsInOp(op, (expr, flags) => {
if (!isIrExpression(expr)) {
return;
}
if (expr.kind !== ExpressionKind.ReadVariable) {
return;
}
const count = varUsages.get(expr.xref);
if (count === void 0) {
return;
}
varUsages.set(expr.xref, count + 1);
if (flags & VisitorContextFlag.InChildOperation) {
varRemoteUsage.add(expr.xref);
}
});
}
function uncountVariableUsages(op, varUsages) {
visitExpressionsInOp(op, (expr) => {
if (!isIrExpression(expr)) {
return;
}
if (expr.kind !== ExpressionKind.ReadVariable) {
return;
}
const count = varUsages.get(expr.xref);
if (count === void 0) {
return;
} else if (count === 0) {
throw new Error(`Inaccurate variable count: ${expr.xref} - found another read but count is already 0`);
}
varUsages.set(expr.xref, count - 1);
});
}
function safeToInlinePastFences(fences, declFences) {
if (fences & Fence.ViewContextWrite) {
if (declFences & Fence.ViewContextRead) {
return false;
}
} else if (fences & Fence.ViewContextRead) {
if (declFences & Fence.ViewContextWrite) {
return false;
}
}
return true;
}
function tryInlineVariableInitializer(id, initializer, target, declFences) {
let inlined = false;
let inliningAllowed = true;
transformExpressionsInOp(target, (expr, flags) => {
if (!isIrExpression(expr)) {
return expr;
}
if (inlined || !inliningAllowed) {
return expr;
} else if (flags & VisitorContextFlag.InChildOperation && declFences & Fence.ViewContextRead) {
return expr;
}
switch (expr.kind) {
case ExpressionKind.ReadVariable:
if (expr.xref === id) {
inlined = true;
return initializer;
}
break;
default:
const exprFences = fencesForIrExpression(expr);
inliningAllowed = inliningAllowed && safeToInlinePastFences(exprFences, declFences);
break;
}
return expr;
}, VisitorContextFlag.None);
return inlined;
}
function allowConservativeInlining(decl, target) {
switch (decl.variable.kind) {
case SemanticVariableKind.Identifier:
if (decl.initializer instanceof ReadVarExpr && decl.initializer.name === "ctx") {
return true;
}
return false;
case SemanticVariableKind.Context:
return target.kind === OpKind.Variable;
default:
return true;
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/wrap_icus.mjs
function wrapI18nIcus(job) {
for (const unit of job.units) {
let currentI18nOp = null;
let addedI18nId = null;
for (const op of unit.create) {
switch (op.kind) {
case OpKind.I18nStart:
currentI18nOp = op;
break;
case OpKind.I18nEnd:
currentI18nOp = null;
break;
case OpKind.IcuStart:
if (currentI18nOp === null) {
addedI18nId = job.allocateXrefId();
OpList.insertBefore(createI18nStartOp(addedI18nId, op.message, void 0, null), op);
}
break;
case OpKind.IcuEnd:
if (addedI18nId !== null) {
OpList.insertAfter(createI18nEndOp(addedI18nId, null), op);
addedI18nId = null;
}
break;
}
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/store_let_optimization.mjs
function optimizeStoreLet(job) {
const letUsedExternally = /* @__PURE__ */ new Set();
for (const unit of job.units) {
for (const op of unit.ops()) {
visitExpressionsInOp(op, (expr) => {
if (expr instanceof ContextLetReferenceExpr) {
letUsedExternally.add(expr.target);
}
});
}
}
for (const unit of job.units) {
for (const op of unit.update) {
transformExpressionsInOp(op, (expression) => expression instanceof StoreLetExpr && !letUsedExternally.has(expression.target) ? expression.value : expression, VisitorContextFlag.None);
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/remove_illegal_let_references.mjs
function removeIllegalLetReferences(job) {
for (const unit of job.units) {
for (const op of unit.update) {
if (op.kind !== OpKind.Variable || op.variable.kind !== SemanticVariableKind.Identifier || !(op.initializer instanceof StoreLetExpr)) {
continue;
}
const name = op.variable.identifier;
let current = op;
while (current && current.kind !== OpKind.ListEnd) {
transformExpressionsInOp(current, (expr) => expr instanceof LexicalReadExpr && expr.name === name ? literal(void 0) : expr, VisitorContextFlag.None);
current = current.prev;
}
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/phases/generate_local_let_references.mjs
function generateLocalLetReferences(job) {
for (const unit of job.units) {
for (const op of unit.update) {
if (op.kind !== OpKind.StoreLet) {
continue;
}
const variable2 = {
kind: SemanticVariableKind.Identifier,
name: null,
identifier: op.declaredName,
local: true
};
OpList.replace(op, createVariableOp(job.allocateXrefId(), variable2, new StoreLetExpr(op.target, op.value, op.sourceSpan), VariableFlags.None));
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/emit.mjs
var phases = [
{ kind: CompilationJobKind.Tmpl, fn: removeContentSelectors },
{ kind: CompilationJobKind.Host, fn: parseHostStyleProperties },
{ kind: CompilationJobKind.Tmpl, fn: emitNamespaceChanges },
{ kind: CompilationJobKind.Tmpl, fn: propagateI18nBlocks },
{ kind: CompilationJobKind.Tmpl, fn: wrapI18nIcus },
{ kind: CompilationJobKind.Both, fn: deduplicateTextBindings },
{ kind: CompilationJobKind.Both, fn: specializeStyleBindings },
{ kind: CompilationJobKind.Both, fn: specializeBindings },
{ kind: CompilationJobKind.Both, fn: extractAttributes },
{ kind: CompilationJobKind.Tmpl, fn: createI18nContexts },
{ kind: CompilationJobKind.Both, fn: parseExtractedStyles },
{ kind: CompilationJobKind.Tmpl, fn: removeEmptyBindings },
{ kind: CompilationJobKind.Both, fn: collapseSingletonInterpolations },
{ kind: CompilationJobKind.Both, fn: orderOps },
{ kind: CompilationJobKind.Tmpl, fn: generateConditionalExpressions },
{ kind: CompilationJobKind.Tmpl, fn: createPipes },
{ kind: CompilationJobKind.Tmpl, fn: configureDeferInstructions },
{ kind: CompilationJobKind.Tmpl, fn: convertI18nText },
{ kind: CompilationJobKind.Tmpl, fn: convertI18nBindings },
{ kind: CompilationJobKind.Tmpl, fn: removeUnusedI18nAttributesOps },
{ kind: CompilationJobKind.Tmpl, fn: assignI18nSlotDependencies },
{ kind: CompilationJobKind.Tmpl, fn: applyI18nExpressions },
{ kind: CompilationJobKind.Tmpl, fn: createVariadicPipes },
{ kind: CompilationJobKind.Both, fn: generatePureLiteralStructures },
{ kind: CompilationJobKind.Tmpl, fn: generateProjectionDefs },
{ kind: CompilationJobKind.Tmpl, fn: generateLocalLetReferences },
{ kind: CompilationJobKind.Tmpl, fn: generateVariables },
{ kind: CompilationJobKind.Tmpl, fn: saveAndRestoreView },
{ kind: CompilationJobKind.Both, fn: deleteAnyCasts },
{ kind: CompilationJobKind.Both, fn: resolveDollarEvent },
{ kind: CompilationJobKind.Tmpl, fn: generateTrackVariables },
{ kind: CompilationJobKind.Tmpl, fn: removeIllegalLetReferences },
{ kind: CompilationJobKind.Both, fn: resolveNames },
{ kind: CompilationJobKind.Tmpl, fn: resolveDeferTargetNames },
{ kind: CompilationJobKind.Tmpl, fn: transformTwoWayBindingSet },
{ kind: CompilationJobKind.Tmpl, fn: optimizeTrackFns },
{ kind: CompilationJobKind.Both, fn: resolveContexts },
{ kind: CompilationJobKind.Both, fn: resolveSanitizers },
{ kind: CompilationJobKind.Tmpl, fn: liftLocalRefs },
{ kind: CompilationJobKind.Both, fn: generateNullishCoalesceExpressions },
{ kind: CompilationJobKind.Both, fn: expandSafeReads },
{ kind: CompilationJobKind.Both, fn: generateTemporaryVariables },
{ kind: CompilationJobKind.Both, fn: optimizeVariables },
{ kind: CompilationJobKind.Both, fn: optimizeStoreLet },
{ kind: CompilationJobKind.Tmpl, fn: allocateSlots },
{ kind: CompilationJobKind.Tmpl, fn: resolveI18nElementPlaceholders },
{ kind: CompilationJobKind.Tmpl, fn: resolveI18nExpressionPlaceholders },
{ kind: CompilationJobKind.Tmpl, fn: extractI18nMessages },
{ kind: CompilationJobKind.Tmpl, fn: generateTrackFns },
{ kind: CompilationJobKind.Tmpl, fn: collectI18nConsts },
{ kind: CompilationJobKind.Tmpl, fn: collectConstExpressions },
{ kind: CompilationJobKind.Both, fn: collectElementConsts },
{ kind: CompilationJobKind.Tmpl, fn: removeI18nContexts },
{ kind: CompilationJobKind.Both, fn: countVariables },
{ kind: CompilationJobKind.Tmpl, fn: generateAdvance },
{ kind: CompilationJobKind.Both, fn: nameFunctionsAndVariables },
{ kind: CompilationJobKind.Tmpl, fn: resolveDeferDepsFns },
{ kind: CompilationJobKind.Tmpl, fn: mergeNextContextExpressions },
{ kind: CompilationJobKind.Tmpl, fn: generateNgContainerOps },
{ kind: CompilationJobKind.Tmpl, fn: collapseEmptyInstructions },
{ kind: CompilationJobKind.Tmpl, fn: disableBindings },
{ kind: CompilationJobKind.Both, fn: extractPureFunctions },
{ kind: CompilationJobKind.Both, fn: reify },
{ kind: CompilationJobKind.Both, fn: chain }
];
function transform(job, kind) {
for (const phase of phases) {
if (phase.kind === kind || phase.kind === CompilationJobKind.Both) {
phase.fn(job);
}
}
}
function emitTemplateFn(tpl, pool) {
const rootFn = emitView(tpl.root);
emitChildViews(tpl.root, pool);
return rootFn;
}
function emitChildViews(parent, pool) {
for (const unit of parent.job.units) {
if (unit.parent !== parent.xref) {
continue;
}
emitChildViews(unit, pool);
const viewFn = emitView(unit);
pool.statements.push(viewFn.toDeclStmt(viewFn.name));
}
}
function emitView(view) {
if (view.fnName === null) {
throw new Error(`AssertionError: view ${view.xref} is unnamed`);
}
const createStatements = [];
for (const op of view.create) {
if (op.kind !== OpKind.Statement) {
throw new Error(`AssertionError: expected all create ops to have been compiled, but got ${OpKind[op.kind]}`);
}
createStatements.push(op.statement);
}
const updateStatements = [];
for (const op of view.update) {
if (op.kind !== OpKind.Statement) {
throw new Error(`AssertionError: expected all update ops to have been compiled, but got ${OpKind[op.kind]}`);
}
updateStatements.push(op.statement);
}
const createCond = maybeGenerateRfBlock(1, createStatements);
const updateCond = maybeGenerateRfBlock(2, updateStatements);
return fn(
[new FnParam("rf"), new FnParam("ctx")],
[...createCond, ...updateCond],
void 0,
void 0,
view.fnName
);
}
function maybeGenerateRfBlock(flag, statements) {
if (statements.length === 0) {
return [];
}
return [
ifStmt(new BinaryOperatorExpr(BinaryOperator.BitwiseAnd, variable("rf"), literal(flag)), statements)
];
}
function emitHostBindingFunction(job) {
if (job.root.fnName === null) {
throw new Error(`AssertionError: host binding function is unnamed`);
}
const createStatements = [];
for (const op of job.root.create) {
if (op.kind !== OpKind.Statement) {
throw new Error(`AssertionError: expected all create ops to have been compiled, but got ${OpKind[op.kind]}`);
}
createStatements.push(op.statement);
}
const updateStatements = [];
for (const op of job.root.update) {
if (op.kind !== OpKind.Statement) {
throw new Error(`AssertionError: expected all update ops to have been compiled, but got ${OpKind[op.kind]}`);
}
updateStatements.push(op.statement);
}
if (createStatements.length === 0 && updateStatements.length === 0) {
return null;
}
const createCond = maybeGenerateRfBlock(1, createStatements);
const updateCond = maybeGenerateRfBlock(2, updateStatements);
return fn(
[new FnParam("rf"), new FnParam("ctx")],
[...createCond, ...updateCond],
void 0,
void 0,
job.root.fnName
);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template/pipeline/src/ingest.mjs
var compatibilityMode = CompatibilityMode.TemplateDefinitionBuilder;
var domSchema = new DomElementSchemaRegistry();
var NG_TEMPLATE_TAG_NAME = "ng-template";
function isI18nRootNode(meta) {
return meta instanceof Message;
}
function isSingleI18nIcu(meta) {
return isI18nRootNode(meta) && meta.nodes.length === 1 && meta.nodes[0] instanceof Icu2;
}
function ingestComponent(componentName, template2, constantPool, relativeContextFilePath, i18nUseExternalIds, deferMeta, allDeferrableDepsFn) {
const job = new ComponentCompilationJob(componentName, constantPool, compatibilityMode, relativeContextFilePath, i18nUseExternalIds, deferMeta, allDeferrableDepsFn);
ingestNodes(job.root, template2);
return job;
}
function ingestHostBinding(input, bindingParser, constantPool) {
var _a2, _b2, _c2;
const job = new HostBindingCompilationJob(input.componentName, constantPool, compatibilityMode);
for (const property2 of (_a2 = input.properties) != null ? _a2 : []) {
let bindingKind = BindingKind.Property;
if (property2.name.startsWith("attr.")) {
property2.name = property2.name.substring("attr.".length);
bindingKind = BindingKind.Attribute;
}
if (property2.isAnimation) {
bindingKind = BindingKind.Animation;
}
const securityContexts = bindingParser.calcPossibleSecurityContexts(input.componentSelector, property2.name, bindingKind === BindingKind.Attribute).filter((context) => context !== SecurityContext.NONE);
ingestHostProperty(job, property2, bindingKind, securityContexts);
}
for (const [name, expr] of (_b2 = Object.entries(input.attributes)) != null ? _b2 : []) {
const securityContexts = bindingParser.calcPossibleSecurityContexts(input.componentSelector, name, true).filter((context) => context !== SecurityContext.NONE);
ingestHostAttribute(job, name, expr, securityContexts);
}
for (const event of (_c2 = input.events) != null ? _c2 : []) {
ingestHostEvent(job, event);
}
return job;
}
function ingestHostProperty(job, property2, bindingKind, securityContexts) {
let expression;
const ast = property2.expression.ast;
if (ast instanceof Interpolation) {
expression = new Interpolation2(ast.strings, ast.expressions.map((expr) => convertAst(expr, job, property2.sourceSpan)), []);
} else {
expression = convertAst(ast, job, property2.sourceSpan);
}
job.root.update.push(createBindingOp(
job.root.xref,
bindingKind,
property2.name,
expression,
null,
securityContexts,
false,
false,
null,
null,
property2.sourceSpan
));
}
function ingestHostAttribute(job, name, value, securityContexts) {
const attrBinding = createBindingOp(
job.root.xref,
BindingKind.Attribute,
name,
value,
null,
securityContexts,
true,
false,
null,
null,
value.sourceSpan
);
job.root.update.push(attrBinding);
}
function ingestHostEvent(job, event) {
const [phase, target] = event.type !== ParsedEventType.Animation ? [null, event.targetOrPhase] : [event.targetOrPhase, null];
const eventBinding = createListenerOp(job.root.xref, new SlotHandle(), event.name, null, makeListenerHandlerOps(job.root, event.handler, event.handlerSpan), phase, target, true, event.sourceSpan);
job.root.create.push(eventBinding);
}
function ingestNodes(unit, template2) {
for (const node of template2) {
if (node instanceof Element) {
ingestElement(unit, node);
} else if (node instanceof Template) {
ingestTemplate(unit, node);
} else if (node instanceof Content) {
ingestContent(unit, node);
} else if (node instanceof Text) {
ingestText(unit, node, null);
} else if (node instanceof BoundText) {
ingestBoundText(unit, node, null);
} else if (node instanceof IfBlock) {
ingestIfBlock(unit, node);
} else if (node instanceof SwitchBlock) {
ingestSwitchBlock(unit, node);
} else if (node instanceof DeferredBlock) {
ingestDeferBlock(unit, node);
} else if (node instanceof Icu) {
ingestIcu(unit, node);
} else if (node instanceof ForLoopBlock) {
ingestForBlock(unit, node);
} else if (node instanceof LetDeclaration) {
ingestLetDeclaration(unit, node);
} else {
throw new Error(`Unsupported template node: ${node.constructor.name}`);
}
}
}
function ingestElement(unit, element2) {
var _a2, _b2;
if (element2.i18n !== void 0 && !(element2.i18n instanceof Message || element2.i18n instanceof TagPlaceholder)) {
throw Error(`Unhandled i18n metadata type for element: ${element2.i18n.constructor.name}`);
}
const id = unit.job.allocateXrefId();
const [namespaceKey, elementName] = splitNsName(element2.name);
const startOp = createElementStartOp(elementName, id, namespaceForKey(namespaceKey), element2.i18n instanceof TagPlaceholder ? element2.i18n : void 0, element2.startSourceSpan, element2.sourceSpan);
unit.create.push(startOp);
ingestElementBindings(unit, startOp, element2);
ingestReferences(startOp, element2);
let i18nBlockId = null;
if (element2.i18n instanceof Message) {
i18nBlockId = unit.job.allocateXrefId();
unit.create.push(createI18nStartOp(i18nBlockId, element2.i18n, void 0, element2.startSourceSpan));
}
ingestNodes(unit, element2.children);
const endOp = createElementEndOp(id, (_a2 = element2.endSourceSpan) != null ? _a2 : element2.startSourceSpan);
unit.create.push(endOp);
if (i18nBlockId !== null) {
OpList.insertBefore(createI18nEndOp(i18nBlockId, (_b2 = element2.endSourceSpan) != null ? _b2 : element2.startSourceSpan), endOp);
}
}
function ingestTemplate(unit, tmpl) {
var _a2;
if (tmpl.i18n !== void 0 && !(tmpl.i18n instanceof Message || tmpl.i18n instanceof TagPlaceholder)) {
throw Error(`Unhandled i18n metadata type for template: ${tmpl.i18n.constructor.name}`);
}
const childView = unit.job.allocateView(unit.xref);
let tagNameWithoutNamespace = tmpl.tagName;
let namespacePrefix = "";
if (tmpl.tagName) {
[namespacePrefix, tagNameWithoutNamespace] = splitNsName(tmpl.tagName);
}
const i18nPlaceholder = tmpl.i18n instanceof TagPlaceholder ? tmpl.i18n : void 0;
const namespace = namespaceForKey(namespacePrefix);
const functionNameSuffix = tagNameWithoutNamespace === null ? "" : prefixWithNamespace(tagNameWithoutNamespace, namespace);
const templateKind = isPlainTemplate(tmpl) ? TemplateKind.NgTemplate : TemplateKind.Structural;
const templateOp = createTemplateOp(childView.xref, templateKind, tagNameWithoutNamespace, functionNameSuffix, namespace, i18nPlaceholder, tmpl.startSourceSpan, tmpl.sourceSpan);
unit.create.push(templateOp);
ingestTemplateBindings(unit, templateOp, tmpl, templateKind);
ingestReferences(templateOp, tmpl);
ingestNodes(childView, tmpl.children);
for (const { name, value } of tmpl.variables) {
childView.contextVariables.set(name, value !== "" ? value : "$implicit");
}
if (templateKind === TemplateKind.NgTemplate && tmpl.i18n instanceof Message) {
const id = unit.job.allocateXrefId();
OpList.insertAfter(createI18nStartOp(id, tmpl.i18n, void 0, tmpl.startSourceSpan), childView.create.head);
OpList.insertBefore(createI18nEndOp(id, (_a2 = tmpl.endSourceSpan) != null ? _a2 : tmpl.startSourceSpan), childView.create.tail);
}
}
function ingestContent(unit, content) {
var _a2;
if (content.i18n !== void 0 && !(content.i18n instanceof TagPlaceholder)) {
throw Error(`Unhandled i18n metadata type for element: ${content.i18n.constructor.name}`);
}
let fallbackView = null;
if (content.children.some((child) => !(child instanceof Comment) && (!(child instanceof Text) || child.value.trim().length > 0))) {
fallbackView = unit.job.allocateView(unit.xref);
ingestNodes(fallbackView, content.children);
}
const id = unit.job.allocateXrefId();
const op = createProjectionOp(id, content.selector, content.i18n, (_a2 = fallbackView == null ? void 0 : fallbackView.xref) != null ? _a2 : null, content.sourceSpan);
for (const attr of content.attributes) {
const securityContext = domSchema.securityContext(content.name, attr.name, true);
unit.update.push(createBindingOp(op.xref, BindingKind.Attribute, attr.name, literal(attr.value), null, securityContext, true, false, null, asMessage(attr.i18n), attr.sourceSpan));
}
unit.create.push(op);
}
function ingestText(unit, text2, icuPlaceholder) {
unit.create.push(createTextOp(unit.job.allocateXrefId(), text2.value, icuPlaceholder, text2.sourceSpan));
}
function ingestBoundText(unit, text2, icuPlaceholder) {
var _a2;
let value = text2.value;
if (value instanceof ASTWithSource) {
value = value.ast;
}
if (!(value instanceof Interpolation)) {
throw new Error(`AssertionError: expected Interpolation for BoundText node, got ${value.constructor.name}`);
}
if (text2.i18n !== void 0 && !(text2.i18n instanceof Container)) {
throw Error(`Unhandled i18n metadata type for text interpolation: ${(_a2 = text2.i18n) == null ? void 0 : _a2.constructor.name}`);
}
const i18nPlaceholders = text2.i18n instanceof Container ? text2.i18n.children.filter((node) => node instanceof Placeholder).map((placeholder) => placeholder.name) : [];
if (i18nPlaceholders.length > 0 && i18nPlaceholders.length !== value.expressions.length) {
throw Error(`Unexpected number of i18n placeholders (${value.expressions.length}) for BoundText with ${value.expressions.length} expressions`);
}
const textXref = unit.job.allocateXrefId();
unit.create.push(createTextOp(textXref, "", icuPlaceholder, text2.sourceSpan));
const baseSourceSpan = unit.job.compatibility ? null : text2.sourceSpan;
unit.update.push(createInterpolateTextOp(textXref, new Interpolation2(value.strings, value.expressions.map((expr) => convertAst(expr, unit.job, baseSourceSpan)), i18nPlaceholders), text2.sourceSpan));
}
function ingestIfBlock(unit, ifBlock) {
var _a2;
let firstXref = null;
let conditions = [];
for (let i = 0; i < ifBlock.branches.length; i++) {
const ifCase = ifBlock.branches[i];
const cView = unit.job.allocateView(unit.xref);
const tagName = ingestControlFlowInsertionPoint(unit, cView.xref, ifCase);
if (ifCase.expressionAlias !== null) {
cView.contextVariables.set(ifCase.expressionAlias.name, CTX_REF);
}
let ifCaseI18nMeta = void 0;
if (ifCase.i18n !== void 0) {
if (!(ifCase.i18n instanceof BlockPlaceholder)) {
throw Error(`Unhandled i18n metadata type for if block: ${(_a2 = ifCase.i18n) == null ? void 0 : _a2.constructor.name}`);
}
ifCaseI18nMeta = ifCase.i18n;
}
const templateOp = createTemplateOp(cView.xref, TemplateKind.Block, tagName, "Conditional", Namespace.HTML, ifCaseI18nMeta, ifCase.startSourceSpan, ifCase.sourceSpan);
unit.create.push(templateOp);
if (firstXref === null) {
firstXref = cView.xref;
}
const caseExpr = ifCase.expression ? convertAst(ifCase.expression, unit.job, null) : null;
const conditionalCaseExpr = new ConditionalCaseExpr(caseExpr, templateOp.xref, templateOp.handle, ifCase.expressionAlias);
conditions.push(conditionalCaseExpr);
ingestNodes(cView, ifCase.children);
}
unit.update.push(createConditionalOp(firstXref, null, conditions, ifBlock.sourceSpan));
}
function ingestSwitchBlock(unit, switchBlock) {
var _a2;
if (switchBlock.cases.length === 0) {
return;
}
let firstXref = null;
let conditions = [];
for (const switchCase of switchBlock.cases) {
const cView = unit.job.allocateView(unit.xref);
const tagName = ingestControlFlowInsertionPoint(unit, cView.xref, switchCase);
let switchCaseI18nMeta = void 0;
if (switchCase.i18n !== void 0) {
if (!(switchCase.i18n instanceof BlockPlaceholder)) {
throw Error(`Unhandled i18n metadata type for switch block: ${(_a2 = switchCase.i18n) == null ? void 0 : _a2.constructor.name}`);
}
switchCaseI18nMeta = switchCase.i18n;
}
const templateOp = createTemplateOp(cView.xref, TemplateKind.Block, tagName, "Case", Namespace.HTML, switchCaseI18nMeta, switchCase.startSourceSpan, switchCase.sourceSpan);
unit.create.push(templateOp);
if (firstXref === null) {
firstXref = cView.xref;
}
const caseExpr = switchCase.expression ? convertAst(switchCase.expression, unit.job, switchBlock.startSourceSpan) : null;
const conditionalCaseExpr = new ConditionalCaseExpr(caseExpr, templateOp.xref, templateOp.handle);
conditions.push(conditionalCaseExpr);
ingestNodes(cView, switchCase.children);
}
unit.update.push(createConditionalOp(firstXref, convertAst(switchBlock.expression, unit.job, null), conditions, switchBlock.sourceSpan));
}
function ingestDeferView(unit, suffix, i18nMeta, children, sourceSpan) {
if (i18nMeta !== void 0 && !(i18nMeta instanceof BlockPlaceholder)) {
throw Error("Unhandled i18n metadata type for defer block");
}
if (children === void 0) {
return null;
}
const secondaryView = unit.job.allocateView(unit.xref);
ingestNodes(secondaryView, children);
const templateOp = createTemplateOp(secondaryView.xref, TemplateKind.Block, null, `Defer${suffix}`, Namespace.HTML, i18nMeta, sourceSpan, sourceSpan);
unit.create.push(templateOp);
return templateOp;
}
function ingestDeferBlock(unit, deferBlock) {
var _a2, _b2, _c2, _d2, _e2, _f2, _g2, _h2, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t;
let ownResolverFn = null;
if (unit.job.deferMeta.mode === 0) {
if (!unit.job.deferMeta.blocks.has(deferBlock)) {
throw new Error(`AssertionError: unable to find a dependency function for this deferred block`);
}
ownResolverFn = (_a2 = unit.job.deferMeta.blocks.get(deferBlock)) != null ? _a2 : null;
}
const main = ingestDeferView(unit, "", deferBlock.i18n, deferBlock.children, deferBlock.sourceSpan);
const loading = ingestDeferView(unit, "Loading", (_b2 = deferBlock.loading) == null ? void 0 : _b2.i18n, (_c2 = deferBlock.loading) == null ? void 0 : _c2.children, (_d2 = deferBlock.loading) == null ? void 0 : _d2.sourceSpan);
const placeholder = ingestDeferView(unit, "Placeholder", (_e2 = deferBlock.placeholder) == null ? void 0 : _e2.i18n, (_f2 = deferBlock.placeholder) == null ? void 0 : _f2.children, (_g2 = deferBlock.placeholder) == null ? void 0 : _g2.sourceSpan);
const error = ingestDeferView(unit, "Error", (_h2 = deferBlock.error) == null ? void 0 : _h2.i18n, (_i = deferBlock.error) == null ? void 0 : _i.children, (_j = deferBlock.error) == null ? void 0 : _j.sourceSpan);
const deferXref = unit.job.allocateXrefId();
const deferOp = createDeferOp(deferXref, main.xref, main.handle, ownResolverFn, unit.job.allDeferrableDepsFn, deferBlock.sourceSpan);
deferOp.placeholderView = (_k = placeholder == null ? void 0 : placeholder.xref) != null ? _k : null;
deferOp.placeholderSlot = (_l = placeholder == null ? void 0 : placeholder.handle) != null ? _l : null;
deferOp.loadingSlot = (_m = loading == null ? void 0 : loading.handle) != null ? _m : null;
deferOp.errorSlot = (_n = error == null ? void 0 : error.handle) != null ? _n : null;
deferOp.placeholderMinimumTime = (_p = (_o = deferBlock.placeholder) == null ? void 0 : _o.minimumTime) != null ? _p : null;
deferOp.loadingMinimumTime = (_r = (_q = deferBlock.loading) == null ? void 0 : _q.minimumTime) != null ? _r : null;
deferOp.loadingAfterTime = (_t = (_s = deferBlock.loading) == null ? void 0 : _s.afterTime) != null ? _t : null;
unit.create.push(deferOp);
let prefetch = false;
let deferOnOps = [];
let deferWhenOps = [];
for (const triggers of [deferBlock.triggers, deferBlock.prefetchTriggers]) {
if (triggers.idle !== void 0) {
const deferOnOp = createDeferOnOp(deferXref, { kind: DeferTriggerKind.Idle }, prefetch, triggers.idle.sourceSpan);
deferOnOps.push(deferOnOp);
}
if (triggers.immediate !== void 0) {
const deferOnOp = createDeferOnOp(deferXref, { kind: DeferTriggerKind.Immediate }, prefetch, triggers.immediate.sourceSpan);
deferOnOps.push(deferOnOp);
}
if (triggers.timer !== void 0) {
const deferOnOp = createDeferOnOp(deferXref, { kind: DeferTriggerKind.Timer, delay: triggers.timer.delay }, prefetch, triggers.timer.sourceSpan);
deferOnOps.push(deferOnOp);
}
if (triggers.hover !== void 0) {
const deferOnOp = createDeferOnOp(deferXref, {
kind: DeferTriggerKind.Hover,
targetName: triggers.hover.reference,
targetXref: null,
targetSlot: null,
targetView: null,
targetSlotViewSteps: null
}, prefetch, triggers.hover.sourceSpan);
deferOnOps.push(deferOnOp);
}
if (triggers.interaction !== void 0) {
const deferOnOp = createDeferOnOp(deferXref, {
kind: DeferTriggerKind.Interaction,
targetName: triggers.interaction.reference,
targetXref: null,
targetSlot: null,
targetView: null,
targetSlotViewSteps: null
}, prefetch, triggers.interaction.sourceSpan);
deferOnOps.push(deferOnOp);
}
if (triggers.viewport !== void 0) {
const deferOnOp = createDeferOnOp(deferXref, {
kind: DeferTriggerKind.Viewport,
targetName: triggers.viewport.reference,
targetXref: null,
targetSlot: null,
targetView: null,
targetSlotViewSteps: null
}, prefetch, triggers.viewport.sourceSpan);
deferOnOps.push(deferOnOp);
}
if (triggers.when !== void 0) {
if (triggers.when.value instanceof Interpolation) {
throw new Error(`Unexpected interpolation in defer block when trigger`);
}
const deferOnOp = createDeferWhenOp(deferXref, convertAst(triggers.when.value, unit.job, triggers.when.sourceSpan), prefetch, triggers.when.sourceSpan);
deferWhenOps.push(deferOnOp);
}
if (deferOnOps.length === 0 && deferWhenOps.length === 0) {
deferOnOps.push(createDeferOnOp(deferXref, { kind: DeferTriggerKind.Idle }, false, null));
}
prefetch = true;
}
unit.create.push(deferOnOps);
unit.update.push(deferWhenOps);
}
function ingestIcu(unit, icu) {
var _a2;
if (icu.i18n instanceof Message && isSingleI18nIcu(icu.i18n)) {
const xref = unit.job.allocateXrefId();
unit.create.push(createIcuStartOp(xref, icu.i18n, icuFromI18nMessage(icu.i18n).name, null));
for (const [placeholder, text2] of Object.entries(__spreadValues(__spreadValues({}, icu.vars), icu.placeholders))) {
if (text2 instanceof BoundText) {
ingestBoundText(unit, text2, placeholder);
} else {
ingestText(unit, text2, placeholder);
}
}
unit.create.push(createIcuEndOp(xref));
} else {
throw Error(`Unhandled i18n metadata type for ICU: ${(_a2 = icu.i18n) == null ? void 0 : _a2.constructor.name}`);
}
}
function ingestForBlock(unit, forBlock) {
var _a2, _b2, _c2;
const repeaterView = unit.job.allocateView(unit.xref);
const indexName = `\u0275$index_${repeaterView.xref}`;
const countName = `\u0275$count_${repeaterView.xref}`;
const indexVarNames = /* @__PURE__ */ new Set();
repeaterView.contextVariables.set(forBlock.item.name, forBlock.item.value);
for (const variable2 of forBlock.contextVariables) {
if (variable2.value === "$index") {
indexVarNames.add(variable2.name);
}
if (variable2.name === "$index") {
repeaterView.contextVariables.set("$index", variable2.value).set(indexName, variable2.value);
} else if (variable2.name === "$count") {
repeaterView.contextVariables.set("$count", variable2.value).set(countName, variable2.value);
} else {
repeaterView.aliases.add({
kind: SemanticVariableKind.Alias,
name: null,
identifier: variable2.name,
expression: getComputedForLoopVariableExpression(variable2, indexName, countName)
});
}
}
const sourceSpan = convertSourceSpan(forBlock.trackBy.span, forBlock.sourceSpan);
const track = convertAst(forBlock.trackBy, unit.job, sourceSpan);
ingestNodes(repeaterView, forBlock.children);
let emptyView = null;
let emptyTagName = null;
if (forBlock.empty !== null) {
emptyView = unit.job.allocateView(unit.xref);
ingestNodes(emptyView, forBlock.empty.children);
emptyTagName = ingestControlFlowInsertionPoint(unit, emptyView.xref, forBlock.empty);
}
const varNames = {
$index: indexVarNames,
$implicit: forBlock.item.name
};
if (forBlock.i18n !== void 0 && !(forBlock.i18n instanceof BlockPlaceholder)) {
throw Error("AssertionError: Unhandled i18n metadata type or @for");
}
if (((_a2 = forBlock.empty) == null ? void 0 : _a2.i18n) !== void 0 && !(forBlock.empty.i18n instanceof BlockPlaceholder)) {
throw Error("AssertionError: Unhandled i18n metadata type or @empty");
}
const i18nPlaceholder = forBlock.i18n;
const emptyI18nPlaceholder = (_b2 = forBlock.empty) == null ? void 0 : _b2.i18n;
const tagName = ingestControlFlowInsertionPoint(unit, repeaterView.xref, forBlock);
const repeaterCreate2 = createRepeaterCreateOp(repeaterView.xref, (_c2 = emptyView == null ? void 0 : emptyView.xref) != null ? _c2 : null, tagName, track, varNames, emptyTagName, i18nPlaceholder, emptyI18nPlaceholder, forBlock.startSourceSpan, forBlock.sourceSpan);
unit.create.push(repeaterCreate2);
const expression = convertAst(forBlock.expression, unit.job, convertSourceSpan(forBlock.expression.span, forBlock.sourceSpan));
const repeater2 = createRepeaterOp(repeaterCreate2.xref, repeaterCreate2.handle, expression, forBlock.sourceSpan);
unit.update.push(repeater2);
}
function getComputedForLoopVariableExpression(variable2, indexName, countName) {
switch (variable2.value) {
case "$index":
return new LexicalReadExpr(indexName);
case "$count":
return new LexicalReadExpr(countName);
case "$first":
return new LexicalReadExpr(indexName).identical(literal(0));
case "$last":
return new LexicalReadExpr(indexName).identical(new LexicalReadExpr(countName).minus(literal(1)));
case "$even":
return new LexicalReadExpr(indexName).modulo(literal(2)).identical(literal(0));
case "$odd":
return new LexicalReadExpr(indexName).modulo(literal(2)).notIdentical(literal(0));
default:
throw new Error(`AssertionError: unknown @for loop variable ${variable2.value}`);
}
}
function ingestLetDeclaration(unit, node) {
const target = unit.job.allocateXrefId();
unit.create.push(createDeclareLetOp(target, node.name, node.sourceSpan));
unit.update.push(createStoreLetOp(target, node.name, convertAst(node.value, unit.job, node.valueSpan), node.sourceSpan));
}
function convertAst(ast, job, baseSourceSpan) {
if (ast instanceof ASTWithSource) {
return convertAst(ast.ast, job, baseSourceSpan);
} else if (ast instanceof PropertyRead) {
const isThisReceiver = ast.receiver instanceof ThisReceiver;
const isImplicitReceiver = ast.receiver instanceof ImplicitReceiver && !(ast.receiver instanceof ThisReceiver);
const isSpecialNode = ast.name === "$any" || ast.name === "$event";
if (isImplicitReceiver || isThisReceiver && !isSpecialNode) {
return new LexicalReadExpr(ast.name);
} else {
return new ReadPropExpr(convertAst(ast.receiver, job, baseSourceSpan), ast.name, null, convertSourceSpan(ast.span, baseSourceSpan));
}
} else if (ast instanceof PropertyWrite) {
if (ast.receiver instanceof ImplicitReceiver) {
return new WritePropExpr(
new ContextExpr(job.root.xref),
ast.name,
convertAst(ast.value, job, baseSourceSpan),
null,
convertSourceSpan(ast.span, baseSourceSpan)
);
}
return new WritePropExpr(convertAst(ast.receiver, job, baseSourceSpan), ast.name, convertAst(ast.value, job, baseSourceSpan), void 0, convertSourceSpan(ast.span, baseSourceSpan));
} else if (ast instanceof KeyedWrite) {
return new WriteKeyExpr(convertAst(ast.receiver, job, baseSourceSpan), convertAst(ast.key, job, baseSourceSpan), convertAst(ast.value, job, baseSourceSpan), void 0, convertSourceSpan(ast.span, baseSourceSpan));
} else if (ast instanceof Call) {
if (ast.receiver instanceof ImplicitReceiver) {
throw new Error(`Unexpected ImplicitReceiver`);
} else {
return new InvokeFunctionExpr(convertAst(ast.receiver, job, baseSourceSpan), ast.args.map((arg) => convertAst(arg, job, baseSourceSpan)), void 0, convertSourceSpan(ast.span, baseSourceSpan));
}
} else if (ast instanceof LiteralPrimitive) {
return literal(ast.value, void 0, convertSourceSpan(ast.span, baseSourceSpan));
} else if (ast instanceof Unary) {
switch (ast.operator) {
case "+":
return new UnaryOperatorExpr(UnaryOperator.Plus, convertAst(ast.expr, job, baseSourceSpan), void 0, convertSourceSpan(ast.span, baseSourceSpan));
case "-":
return new UnaryOperatorExpr(UnaryOperator.Minus, convertAst(ast.expr, job, baseSourceSpan), void 0, convertSourceSpan(ast.span, baseSourceSpan));
default:
throw new Error(`AssertionError: unknown unary operator ${ast.operator}`);
}
} else if (ast instanceof Binary) {
const operator = BINARY_OPERATORS.get(ast.operation);
if (operator === void 0) {
throw new Error(`AssertionError: unknown binary operator ${ast.operation}`);
}
return new BinaryOperatorExpr(operator, convertAst(ast.left, job, baseSourceSpan), convertAst(ast.right, job, baseSourceSpan), void 0, convertSourceSpan(ast.span, baseSourceSpan));
} else if (ast instanceof ThisReceiver) {
return new ContextExpr(job.root.xref);
} else if (ast instanceof KeyedRead) {
return new ReadKeyExpr(convertAst(ast.receiver, job, baseSourceSpan), convertAst(ast.key, job, baseSourceSpan), void 0, convertSourceSpan(ast.span, baseSourceSpan));
} else if (ast instanceof Chain) {
throw new Error(`AssertionError: Chain in unknown context`);
} else if (ast instanceof LiteralMap) {
const entries = ast.keys.map((key, idx) => {
const value = ast.values[idx];
return new LiteralMapEntry(key.key, convertAst(value, job, baseSourceSpan), key.quoted);
});
return new LiteralMapExpr(entries, void 0, convertSourceSpan(ast.span, baseSourceSpan));
} else if (ast instanceof LiteralArray) {
return new LiteralArrayExpr(ast.expressions.map((expr) => convertAst(expr, job, baseSourceSpan)));
} else if (ast instanceof Conditional) {
return new ConditionalExpr(convertAst(ast.condition, job, baseSourceSpan), convertAst(ast.trueExp, job, baseSourceSpan), convertAst(ast.falseExp, job, baseSourceSpan), void 0, convertSourceSpan(ast.span, baseSourceSpan));
} else if (ast instanceof NonNullAssert) {
return convertAst(ast.expression, job, baseSourceSpan);
} else if (ast instanceof BindingPipe) {
return new PipeBindingExpr(job.allocateXrefId(), new SlotHandle(), ast.name, [
convertAst(ast.exp, job, baseSourceSpan),
...ast.args.map((arg) => convertAst(arg, job, baseSourceSpan))
]);
} else if (ast instanceof SafeKeyedRead) {
return new SafeKeyedReadExpr(convertAst(ast.receiver, job, baseSourceSpan), convertAst(ast.key, job, baseSourceSpan), convertSourceSpan(ast.span, baseSourceSpan));
} else if (ast instanceof SafePropertyRead) {
return new SafePropertyReadExpr(convertAst(ast.receiver, job, baseSourceSpan), ast.name);
} else if (ast instanceof SafeCall) {
return new SafeInvokeFunctionExpr(convertAst(ast.receiver, job, baseSourceSpan), ast.args.map((a) => convertAst(a, job, baseSourceSpan)));
} else if (ast instanceof EmptyExpr) {
return new EmptyExpr2(convertSourceSpan(ast.span, baseSourceSpan));
} else if (ast instanceof PrefixNot) {
return not(convertAst(ast.expression, job, baseSourceSpan), convertSourceSpan(ast.span, baseSourceSpan));
} else {
throw new Error(`Unhandled expression type "${ast.constructor.name}" in file "${baseSourceSpan == null ? void 0 : baseSourceSpan.start.file.url}"`);
}
}
function convertAstWithInterpolation(job, value, i18nMeta, sourceSpan) {
var _a2, _b2;
let expression;
if (value instanceof Interpolation) {
expression = new Interpolation2(value.strings, value.expressions.map((e) => convertAst(e, job, sourceSpan != null ? sourceSpan : null)), Object.keys((_b2 = (_a2 = asMessage(i18nMeta)) == null ? void 0 : _a2.placeholders) != null ? _b2 : {}));
} else if (value instanceof AST) {
expression = convertAst(value, job, sourceSpan != null ? sourceSpan : null);
} else {
expression = literal(value);
}
return expression;
}
var BINDING_KINDS = /* @__PURE__ */ new Map([
[BindingType.Property, BindingKind.Property],
[BindingType.TwoWay, BindingKind.TwoWayProperty],
[BindingType.Attribute, BindingKind.Attribute],
[BindingType.Class, BindingKind.ClassName],
[BindingType.Style, BindingKind.StyleProperty],
[BindingType.Animation, BindingKind.Animation]
]);
function isPlainTemplate(tmpl) {
var _a2;
return splitNsName((_a2 = tmpl.tagName) != null ? _a2 : "")[1] === NG_TEMPLATE_TAG_NAME;
}
function asMessage(i18nMeta) {
if (i18nMeta == null) {
return null;
}
if (!(i18nMeta instanceof Message)) {
throw Error(`Expected i18n meta to be a Message, but got: ${i18nMeta.constructor.name}`);
}
return i18nMeta;
}
function ingestElementBindings(unit, op, element2) {
var _a2;
let bindings = new Array();
let i18nAttributeBindingNames = /* @__PURE__ */ new Set();
for (const attr of element2.attributes) {
const securityContext = domSchema.securityContext(element2.name, attr.name, true);
bindings.push(createBindingOp(op.xref, BindingKind.Attribute, attr.name, convertAstWithInterpolation(unit.job, attr.value, attr.i18n), null, securityContext, true, false, null, asMessage(attr.i18n), attr.sourceSpan));
if (attr.i18n) {
i18nAttributeBindingNames.add(attr.name);
}
}
for (const input of element2.inputs) {
if (i18nAttributeBindingNames.has(input.name)) {
console.error(`On component ${unit.job.componentName}, the binding ${input.name} is both an i18n attribute and a property. You may want to remove the property binding. This will become a compilation error in future versions of Angular.`);
}
bindings.push(createBindingOp(op.xref, BINDING_KINDS.get(input.type), input.name, convertAstWithInterpolation(unit.job, astOf(input.value), input.i18n), input.unit, input.securityContext, false, false, null, (_a2 = asMessage(input.i18n)) != null ? _a2 : null, input.sourceSpan));
}
unit.create.push(bindings.filter((b) => (b == null ? void 0 : b.kind) === OpKind.ExtractedAttribute));
unit.update.push(bindings.filter((b) => (b == null ? void 0 : b.kind) === OpKind.Binding));
for (const output of element2.outputs) {
if (output.type === ParsedEventType.Animation && output.phase === null) {
throw Error("Animation listener should have a phase");
}
if (output.type === ParsedEventType.TwoWay) {
unit.create.push(createTwoWayListenerOp(op.xref, op.handle, output.name, op.tag, makeTwoWayListenerHandlerOps(unit, output.handler, output.handlerSpan), output.sourceSpan));
} else {
unit.create.push(createListenerOp(op.xref, op.handle, output.name, op.tag, makeListenerHandlerOps(unit, output.handler, output.handlerSpan), output.phase, output.target, false, output.sourceSpan));
}
}
if (bindings.some((b) => b == null ? void 0 : b.i18nMessage) !== null) {
unit.create.push(createI18nAttributesOp(unit.job.allocateXrefId(), new SlotHandle(), op.xref));
}
}
function ingestTemplateBindings(unit, op, template2, templateKind) {
let bindings = new Array();
for (const attr of template2.templateAttrs) {
if (attr instanceof TextAttribute) {
const securityContext = domSchema.securityContext(NG_TEMPLATE_TAG_NAME, attr.name, true);
bindings.push(createTemplateBinding(unit, op.xref, BindingType.Attribute, attr.name, attr.value, null, securityContext, true, templateKind, asMessage(attr.i18n), attr.sourceSpan));
} else {
bindings.push(createTemplateBinding(unit, op.xref, attr.type, attr.name, astOf(attr.value), attr.unit, attr.securityContext, true, templateKind, asMessage(attr.i18n), attr.sourceSpan));
}
}
for (const attr of template2.attributes) {
const securityContext = domSchema.securityContext(NG_TEMPLATE_TAG_NAME, attr.name, true);
bindings.push(createTemplateBinding(unit, op.xref, BindingType.Attribute, attr.name, attr.value, null, securityContext, false, templateKind, asMessage(attr.i18n), attr.sourceSpan));
}
for (const input of template2.inputs) {
bindings.push(createTemplateBinding(unit, op.xref, input.type, input.name, astOf(input.value), input.unit, input.securityContext, false, templateKind, asMessage(input.i18n), input.sourceSpan));
}
unit.create.push(bindings.filter((b) => (b == null ? void 0 : b.kind) === OpKind.ExtractedAttribute));
unit.update.push(bindings.filter((b) => (b == null ? void 0 : b.kind) === OpKind.Binding));
for (const output of template2.outputs) {
if (output.type === ParsedEventType.Animation && output.phase === null) {
throw Error("Animation listener should have a phase");
}
if (templateKind === TemplateKind.NgTemplate) {
if (output.type === ParsedEventType.TwoWay) {
unit.create.push(createTwoWayListenerOp(op.xref, op.handle, output.name, op.tag, makeTwoWayListenerHandlerOps(unit, output.handler, output.handlerSpan), output.sourceSpan));
} else {
unit.create.push(createListenerOp(op.xref, op.handle, output.name, op.tag, makeListenerHandlerOps(unit, output.handler, output.handlerSpan), output.phase, output.target, false, output.sourceSpan));
}
}
if (templateKind === TemplateKind.Structural && output.type !== ParsedEventType.Animation) {
const securityContext = domSchema.securityContext(NG_TEMPLATE_TAG_NAME, output.name, false);
unit.create.push(createExtractedAttributeOp(op.xref, BindingKind.Property, null, output.name, null, null, null, securityContext));
}
}
if (bindings.some((b) => b == null ? void 0 : b.i18nMessage) !== null) {
unit.create.push(createI18nAttributesOp(unit.job.allocateXrefId(), new SlotHandle(), op.xref));
}
}
function createTemplateBinding(view, xref, type, name, value, unit, securityContext, isStructuralTemplateAttribute, templateKind, i18nMessage, sourceSpan) {
const isTextBinding = typeof value === "string";
if (templateKind === TemplateKind.Structural) {
if (!isStructuralTemplateAttribute) {
switch (type) {
case BindingType.Property:
case BindingType.Class:
case BindingType.Style:
return createExtractedAttributeOp(xref, BindingKind.Property, null, name, null, null, i18nMessage, securityContext);
case BindingType.TwoWay:
return createExtractedAttributeOp(xref, BindingKind.TwoWayProperty, null, name, null, null, i18nMessage, securityContext);
}
}
if (!isTextBinding && (type === BindingType.Attribute || type === BindingType.Animation)) {
return null;
}
}
let bindingType = BINDING_KINDS.get(type);
if (templateKind === TemplateKind.NgTemplate) {
if (type === BindingType.Class || type === BindingType.Style || type === BindingType.Attribute && !isTextBinding) {
bindingType = BindingKind.Property;
}
}
return createBindingOp(xref, bindingType, name, convertAstWithInterpolation(view.job, value, i18nMessage), unit, securityContext, isTextBinding, isStructuralTemplateAttribute, templateKind, i18nMessage, sourceSpan);
}
function makeListenerHandlerOps(unit, handler, handlerSpan) {
handler = astOf(handler);
const handlerOps = new Array();
let handlerExprs = handler instanceof Chain ? handler.expressions : [handler];
if (handlerExprs.length === 0) {
throw new Error("Expected listener to have non-empty expression list.");
}
const expressions = handlerExprs.map((expr) => convertAst(expr, unit.job, handlerSpan));
const returnExpr = expressions.pop();
handlerOps.push(...expressions.map((e) => createStatementOp(new ExpressionStatement(e, e.sourceSpan))));
handlerOps.push(createStatementOp(new ReturnStatement(returnExpr, returnExpr.sourceSpan)));
return handlerOps;
}
function makeTwoWayListenerHandlerOps(unit, handler, handlerSpan) {
handler = astOf(handler);
const handlerOps = new Array();
if (handler instanceof Chain) {
if (handler.expressions.length === 1) {
handler = handler.expressions[0];
} else {
throw new Error("Expected two-way listener to have a single expression.");
}
}
const handlerExpr = convertAst(handler, unit.job, handlerSpan);
const eventReference = new LexicalReadExpr("$event");
const twoWaySetExpr = new TwoWayBindingSetExpr(handlerExpr, eventReference);
handlerOps.push(createStatementOp(new ExpressionStatement(twoWaySetExpr)));
handlerOps.push(createStatementOp(new ReturnStatement(eventReference)));
return handlerOps;
}
function astOf(ast) {
return ast instanceof ASTWithSource ? ast.ast : ast;
}
function ingestReferences(op, element2) {
assertIsArray(op.localRefs);
for (const { name, value } of element2.references) {
op.localRefs.push({
name,
target: value
});
}
}
function assertIsArray(value) {
if (!Array.isArray(value)) {
throw new Error(`AssertionError: expected an array`);
}
}
function convertSourceSpan(span, baseSourceSpan) {
if (baseSourceSpan === null) {
return null;
}
const start = baseSourceSpan.start.moveBy(span.start);
const end = baseSourceSpan.start.moveBy(span.end);
const fullStart = baseSourceSpan.fullStart.moveBy(span.start);
return new ParseSourceSpan(start, end, fullStart);
}
function ingestControlFlowInsertionPoint(unit, xref, node) {
let root = null;
for (const child of node.children) {
if (child instanceof Comment) {
continue;
}
if (root !== null) {
return null;
}
if (child instanceof Element || child instanceof Template && child.tagName !== null) {
root = child;
}
}
if (root !== null) {
for (const attr of root.attributes) {
const securityContext = domSchema.securityContext(NG_TEMPLATE_TAG_NAME, attr.name, true);
unit.update.push(createBindingOp(xref, BindingKind.Attribute, attr.name, literal(attr.value), null, securityContext, true, false, null, asMessage(attr.i18n), attr.sourceSpan));
}
for (const attr of root.inputs) {
if (attr.type !== BindingType.Animation && attr.type !== BindingType.Attribute) {
const securityContext = domSchema.securityContext(NG_TEMPLATE_TAG_NAME, attr.name, true);
unit.create.push(createExtractedAttributeOp(xref, BindingKind.Property, null, attr.name, null, null, null, securityContext));
}
}
const tagName = root instanceof Element ? root.name : root.tagName;
return tagName === NG_TEMPLATE_TAG_NAME ? null : tagName;
}
return null;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/view/query_generation.mjs
function renderFlagCheckIfStmt(flags, statements) {
return ifStmt(variable(RENDER_FLAGS).bitwiseAnd(literal(flags), null, false), statements);
}
function toQueryFlags(query) {
return (query.descendants ? 1 : 0) | (query.static ? 2 : 0) | (query.emitDistinctChangesOnly ? 4 : 0);
}
function getQueryPredicate(query, constantPool) {
if (Array.isArray(query.predicate)) {
let predicate = [];
query.predicate.forEach((selector) => {
const selectors = selector.split(",").map((token) => literal(token.trim()));
predicate.push(...selectors);
});
return constantPool.getConstLiteral(literalArr(predicate), true);
} else {
switch (query.predicate.forwardRef) {
case 0:
case 2:
return query.predicate.expression;
case 1:
return importExpr(Identifiers.resolveForwardRef).callFn([query.predicate.expression]);
}
}
}
function createQueryCreateCall(query, constantPool, queryTypeFns, prependParams) {
const parameters = [];
if (prependParams !== void 0) {
parameters.push(...prependParams);
}
if (query.isSignal) {
parameters.push(new ReadPropExpr(variable(CONTEXT_NAME), query.propertyName));
}
parameters.push(getQueryPredicate(query, constantPool), literal(toQueryFlags(query)));
if (query.read) {
parameters.push(query.read);
}
const queryCreateFn = query.isSignal ? queryTypeFns.signalBased : queryTypeFns.nonSignal;
return importExpr(queryCreateFn).callFn(parameters);
}
var queryAdvancePlaceholder = Symbol("queryAdvancePlaceholder");
function collapseAdvanceStatements(statements) {
const result = [];
let advanceCollapseCount = 0;
const flushAdvanceCount = () => {
if (advanceCollapseCount > 0) {
result.unshift(importExpr(Identifiers.queryAdvance).callFn(advanceCollapseCount === 1 ? [] : [literal(advanceCollapseCount)]).toStmt());
advanceCollapseCount = 0;
}
};
for (let i = statements.length - 1; i >= 0; i--) {
const st = statements[i];
if (st === queryAdvancePlaceholder) {
advanceCollapseCount++;
} else {
flushAdvanceCount();
result.unshift(st);
}
}
flushAdvanceCount();
return result;
}
function createViewQueriesFunction(viewQueries, constantPool, name) {
const createStatements = [];
const updateStatements = [];
const tempAllocator = temporaryAllocator((st) => updateStatements.push(st), TEMPORARY_NAME);
viewQueries.forEach((query) => {
const queryDefinitionCall = createQueryCreateCall(query, constantPool, {
signalBased: Identifiers.viewQuerySignal,
nonSignal: Identifiers.viewQuery
});
createStatements.push(queryDefinitionCall.toStmt());
if (query.isSignal) {
updateStatements.push(queryAdvancePlaceholder);
return;
}
const temporary = tempAllocator();
const getQueryList = importExpr(Identifiers.loadQuery).callFn([]);
const refresh = importExpr(Identifiers.queryRefresh).callFn([temporary.set(getQueryList)]);
const updateDirective = variable(CONTEXT_NAME).prop(query.propertyName).set(query.first ? temporary.prop("first") : temporary);
updateStatements.push(refresh.and(updateDirective).toStmt());
});
const viewQueryFnName = name ? `${name}_Query` : null;
return fn([new FnParam(RENDER_FLAGS, NUMBER_TYPE), new FnParam(CONTEXT_NAME, null)], [
renderFlagCheckIfStmt(1, createStatements),
renderFlagCheckIfStmt(2, collapseAdvanceStatements(updateStatements))
], INFERRED_TYPE, null, viewQueryFnName);
}
function createContentQueriesFunction(queries, constantPool, name) {
const createStatements = [];
const updateStatements = [];
const tempAllocator = temporaryAllocator((st) => updateStatements.push(st), TEMPORARY_NAME);
for (const query of queries) {
createStatements.push(createQueryCreateCall(
query,
constantPool,
{ nonSignal: Identifiers.contentQuery, signalBased: Identifiers.contentQuerySignal },
[variable("dirIndex")]
).toStmt());
if (query.isSignal) {
updateStatements.push(queryAdvancePlaceholder);
continue;
}
const temporary = tempAllocator();
const getQueryList = importExpr(Identifiers.loadQuery).callFn([]);
const refresh = importExpr(Identifiers.queryRefresh).callFn([temporary.set(getQueryList)]);
const updateDirective = variable(CONTEXT_NAME).prop(query.propertyName).set(query.first ? temporary.prop("first") : temporary);
updateStatements.push(refresh.and(updateDirective).toStmt());
}
const contentQueriesFnName = name ? `${name}_ContentQueries` : null;
return fn([
new FnParam(RENDER_FLAGS, NUMBER_TYPE),
new FnParam(CONTEXT_NAME, null),
new FnParam("dirIndex", null)
], [
renderFlagCheckIfStmt(1, createStatements),
renderFlagCheckIfStmt(2, collapseAdvanceStatements(updateStatements))
], INFERRED_TYPE, null, contentQueriesFnName);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/ml_parser/html_parser.mjs
var HtmlParser = class extends Parser {
constructor() {
super(getHtmlTagDefinition);
}
parse(source, url, options) {
return super.parse(source, url, options);
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template_parser/binding_parser.mjs
var PROPERTY_PARTS_SEPARATOR = ".";
var ATTRIBUTE_PREFIX = "attr";
var CLASS_PREFIX = "class";
var STYLE_PREFIX = "style";
var TEMPLATE_ATTR_PREFIX = "*";
var ANIMATE_PROP_PREFIX = "animate-";
var BindingParser = class {
constructor(_exprParser, _interpolationConfig, _schemaRegistry, errors, _allowInvalidAssignmentEvents = false) {
this._exprParser = _exprParser;
this._interpolationConfig = _interpolationConfig;
this._schemaRegistry = _schemaRegistry;
this.errors = errors;
this._allowInvalidAssignmentEvents = _allowInvalidAssignmentEvents;
}
get interpolationConfig() {
return this._interpolationConfig;
}
createBoundHostProperties(properties, sourceSpan) {
const boundProps = [];
for (const propName of Object.keys(properties)) {
const expression = properties[propName];
if (typeof expression === "string") {
this.parsePropertyBinding(
propName,
expression,
true,
false,
sourceSpan,
sourceSpan.start.offset,
void 0,
[],
boundProps,
sourceSpan
);
} 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;
}
createDirectiveHostEventAsts(hostListeners, sourceSpan) {
const targetEvents = [];
for (const propName of Object.keys(hostListeners)) {
const expression = hostListeners[propName];
if (typeof expression === "string") {
this.parseEvent(
propName,
expression,
false,
sourceSpan,
sourceSpan,
[],
targetEvents,
sourceSpan
);
} 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;
}
parseInterpolation(value, sourceSpan, interpolatedTokens) {
const sourceInfo = sourceSpan.start.toString();
const absoluteOffset = sourceSpan.fullStart.offset;
try {
const ast = this._exprParser.parseInterpolation(value, sourceInfo, absoluteOffset, interpolatedTokens, this._interpolationConfig);
if (ast)
this._reportExpressionParserErrors(ast.errors, sourceSpan);
return ast;
} catch (e) {
this._reportError(`${e}`, sourceSpan);
return this._exprParser.wrapLiteralPrimitive("ERROR", sourceInfo, absoluteOffset);
}
}
parseInterpolationExpression(expression, sourceSpan) {
const sourceInfo = sourceSpan.start.toString();
const absoluteOffset = sourceSpan.start.offset;
try {
const ast = this._exprParser.parseInterpolationExpression(expression, sourceInfo, absoluteOffset);
if (ast)
this._reportExpressionParserErrors(ast.errors, sourceSpan);
return ast;
} catch (e) {
this._reportError(`${e}`, sourceSpan);
return this._exprParser.wrapLiteralPrimitive("ERROR", sourceInfo, absoluteOffset);
}
}
parseInlineTemplateBinding(tplKey, tplValue, sourceSpan, absoluteValueOffset, targetMatchableAttrs, targetProps, targetVars, isIvyAst) {
const absoluteKeyOffset = sourceSpan.start.offset + TEMPLATE_ATTR_PREFIX.length;
const bindings = this._parseTemplateBindings(tplKey, tplValue, sourceSpan, absoluteKeyOffset, absoluteValueOffset);
for (const binding of bindings) {
const bindingSpan = moveParseSourceSpan(sourceSpan, binding.sourceSpan);
const key = binding.key.source;
const keySpan = moveParseSourceSpan(sourceSpan, binding.key.span);
if (binding instanceof VariableBinding) {
const value = binding.value ? binding.value.source : "$implicit";
const valueSpan = binding.value ? moveParseSourceSpan(sourceSpan, binding.value.span) : void 0;
targetVars.push(new ParsedVariable(key, value, bindingSpan, keySpan, valueSpan));
} else if (binding.value) {
const srcSpan = isIvyAst ? bindingSpan : sourceSpan;
const valueSpan = moveParseSourceSpan(sourceSpan, binding.value.ast.sourceSpan);
this._parsePropertyAst(key, binding.value, false, srcSpan, keySpan, valueSpan, targetMatchableAttrs, targetProps);
} else {
targetMatchableAttrs.push([key, ""]);
this.parseLiteralAttr(key, null, keySpan, absoluteValueOffset, void 0, targetMatchableAttrs, targetProps, keySpan);
}
}
}
_parseTemplateBindings(tplKey, tplValue, sourceSpan, absoluteKeyOffset, absoluteValueOffset) {
const sourceInfo = sourceSpan.start.toString();
try {
const bindingsResult = this._exprParser.parseTemplateBindings(tplKey, tplValue, sourceInfo, absoluteKeyOffset, absoluteValueOffset);
this._reportExpressionParserErrors(bindingsResult.errors, sourceSpan);
bindingsResult.warnings.forEach((warning) => {
this._reportError(warning, sourceSpan, ParseErrorLevel.WARNING);
});
return bindingsResult.templateBindings;
} catch (e) {
this._reportError(`${e}`, sourceSpan);
return [];
}
}
parseLiteralAttr(name, value, sourceSpan, absoluteOffset, valueSpan, targetMatchableAttrs, targetProps, keySpan) {
if (isAnimationLabel(name)) {
name = name.substring(1);
if (keySpan !== void 0) {
keySpan = moveParseSourceSpan(keySpan, new AbsoluteSourceSpan(keySpan.start.offset + 1, keySpan.end.offset));
}
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, keySpan, valueSpan, targetMatchableAttrs, targetProps);
} else {
targetProps.push(new ParsedProperty(name, this._exprParser.wrapLiteralPrimitive(value, "", absoluteOffset), ParsedPropertyType.LITERAL_ATTR, sourceSpan, keySpan, valueSpan));
}
}
parsePropertyBinding(name, expression, isHost, isPartOfAssignmentBinding, sourceSpan, absoluteOffset, valueSpan, targetMatchableAttrs, targetProps, keySpan) {
if (name.length === 0) {
this._reportError(`Property name is missing in binding`, sourceSpan);
}
let isAnimationProp = false;
if (name.startsWith(ANIMATE_PROP_PREFIX)) {
isAnimationProp = true;
name = name.substring(ANIMATE_PROP_PREFIX.length);
if (keySpan !== void 0) {
keySpan = moveParseSourceSpan(keySpan, new AbsoluteSourceSpan(keySpan.start.offset + ANIMATE_PROP_PREFIX.length, keySpan.end.offset));
}
} else if (isAnimationLabel(name)) {
isAnimationProp = true;
name = name.substring(1);
if (keySpan !== void 0) {
keySpan = moveParseSourceSpan(keySpan, new AbsoluteSourceSpan(keySpan.start.offset + 1, keySpan.end.offset));
}
}
if (isAnimationProp) {
this._parseAnimation(name, expression, sourceSpan, absoluteOffset, keySpan, valueSpan, targetMatchableAttrs, targetProps);
} else {
this._parsePropertyAst(name, this.parseBinding(expression, isHost, valueSpan || sourceSpan, absoluteOffset), isPartOfAssignmentBinding, sourceSpan, keySpan, valueSpan, targetMatchableAttrs, targetProps);
}
}
parsePropertyInterpolation(name, value, sourceSpan, valueSpan, targetMatchableAttrs, targetProps, keySpan, interpolatedTokens) {
const expr = this.parseInterpolation(value, valueSpan || sourceSpan, interpolatedTokens);
if (expr) {
this._parsePropertyAst(name, expr, false, sourceSpan, keySpan, valueSpan, targetMatchableAttrs, targetProps);
return true;
}
return false;
}
_parsePropertyAst(name, ast, isPartOfAssignmentBinding, sourceSpan, keySpan, valueSpan, targetMatchableAttrs, targetProps) {
targetMatchableAttrs.push([name, ast.source]);
targetProps.push(new ParsedProperty(name, ast, isPartOfAssignmentBinding ? ParsedPropertyType.TWO_WAY : ParsedPropertyType.DEFAULT, sourceSpan, keySpan, valueSpan));
}
_parseAnimation(name, expression, sourceSpan, absoluteOffset, keySpan, valueSpan, targetMatchableAttrs, targetProps) {
if (name.length === 0) {
this._reportError("Animation trigger is missing", sourceSpan);
}
const ast = this.parseBinding(expression || "undefined", false, valueSpan || sourceSpan, absoluteOffset);
targetMatchableAttrs.push([name, ast.source]);
targetProps.push(new ParsedProperty(name, ast, ParsedPropertyType.ANIMATION, sourceSpan, keySpan, valueSpan));
}
parseBinding(value, isHostBinding2, sourceSpan, absoluteOffset) {
const sourceInfo = (sourceSpan && sourceSpan.start || "(unknown)").toString();
try {
const ast = isHostBinding2 ? this._exprParser.parseSimpleBinding(value, sourceInfo, absoluteOffset, this._interpolationConfig) : this._exprParser.parseBinding(value, sourceInfo, absoluteOffset, this._interpolationConfig);
if (ast)
this._reportExpressionParserErrors(ast.errors, sourceSpan);
return ast;
} catch (e) {
this._reportError(`${e}`, sourceSpan);
return this._exprParser.wrapLiteralPrimitive("ERROR", sourceInfo, absoluteOffset);
}
}
createBoundElementProperty(elementSelector, boundProp, skipValidation = false, mapPropertyName = true) {
if (boundProp.isAnimation) {
return new BoundElementProperty(boundProp.name, BindingType.Animation, SecurityContext.NONE, boundProp.expression, null, boundProp.sourceSpan, boundProp.keySpan, boundProp.valueSpan);
}
let unit = null;
let bindingType = void 0;
let boundPropertyName = null;
const parts = boundProp.name.split(PROPERTY_PARTS_SEPARATOR);
let securityContexts = void 0;
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);
const nsSeparatorIdx = boundPropertyName.indexOf(":");
if (nsSeparatorIdx > -1) {
const ns = boundPropertyName.substring(0, nsSeparatorIdx);
const name = boundPropertyName.substring(nsSeparatorIdx + 1);
boundPropertyName = mergeNsAndName(ns, name);
}
bindingType = BindingType.Attribute;
} else if (parts[0] == CLASS_PREFIX) {
boundPropertyName = parts[1];
bindingType = BindingType.Class;
securityContexts = [SecurityContext.NONE];
} else if (parts[0] == STYLE_PREFIX) {
unit = parts.length > 2 ? parts[2] : null;
boundPropertyName = parts[1];
bindingType = BindingType.Style;
securityContexts = [SecurityContext.STYLE];
}
}
if (boundPropertyName === null) {
const mappedPropName = this._schemaRegistry.getMappedPropName(boundProp.name);
boundPropertyName = mapPropertyName ? mappedPropName : boundProp.name;
securityContexts = calcPossibleSecurityContexts(this._schemaRegistry, elementSelector, mappedPropName, false);
bindingType = boundProp.type === ParsedPropertyType.TWO_WAY ? BindingType.TwoWay : BindingType.Property;
if (!skipValidation) {
this._validatePropertyOrAttributeName(mappedPropName, boundProp.sourceSpan, false);
}
}
return new BoundElementProperty(boundPropertyName, bindingType, securityContexts[0], boundProp.expression, unit, boundProp.sourceSpan, boundProp.keySpan, boundProp.valueSpan);
}
parseEvent(name, expression, isAssignmentEvent, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents, keySpan) {
if (name.length === 0) {
this._reportError(`Event name is missing in binding`, sourceSpan);
}
if (isAnimationLabel(name)) {
name = name.slice(1);
if (keySpan !== void 0) {
keySpan = moveParseSourceSpan(keySpan, new AbsoluteSourceSpan(keySpan.start.offset + 1, keySpan.end.offset));
}
this._parseAnimationEvent(name, expression, sourceSpan, handlerSpan, targetEvents, keySpan);
} else {
this._parseRegularEvent(name, expression, isAssignmentEvent, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents, keySpan);
}
}
calcPossibleSecurityContexts(selector, propName, isAttribute) {
const prop = this._schemaRegistry.getMappedPropName(propName);
return calcPossibleSecurityContexts(this._schemaRegistry, selector, prop, isAttribute);
}
_parseAnimationEvent(name, expression, sourceSpan, handlerSpan, targetEvents, keySpan) {
const matches = splitAtPeriod(name, [name, ""]);
const eventName = matches[0];
const phase = matches[1].toLowerCase();
const ast = this._parseAction(expression, handlerSpan);
targetEvents.push(new ParsedEvent(eventName, phase, ParsedEventType.Animation, ast, sourceSpan, handlerSpan, keySpan));
if (eventName.length === 0) {
this._reportError(`Animation event name is missing in binding`, sourceSpan);
}
if (phase) {
if (phase !== "start" && phase !== "done") {
this._reportError(`The provided animation output phase value "${phase}" for "@${eventName}" is not supported (use start or done)`, sourceSpan);
}
} else {
this._reportError(`The animation trigger output event (@${eventName}) is missing its phase value name (start or done are currently supported)`, sourceSpan);
}
}
_parseRegularEvent(name, expression, isAssignmentEvent, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents, keySpan) {
const [target, eventName] = splitAtColon(name, [null, name]);
const prevErrorCount = this.errors.length;
const ast = this._parseAction(expression, handlerSpan);
const isValid = this.errors.length === prevErrorCount;
targetMatchableAttrs.push([name, ast.source]);
if (isAssignmentEvent && isValid && !this._isAllowedAssignmentEvent(ast)) {
this._reportError("Unsupported expression in a two-way binding", sourceSpan);
}
targetEvents.push(new ParsedEvent(eventName, target, isAssignmentEvent ? ParsedEventType.TwoWay : ParsedEventType.Regular, ast, sourceSpan, handlerSpan, keySpan));
}
_parseAction(value, sourceSpan) {
const sourceInfo = (sourceSpan && sourceSpan.start || "(unknown").toString();
const absoluteOffset = sourceSpan && sourceSpan.start ? sourceSpan.start.offset : 0;
try {
const 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);
}
return ast;
} catch (e) {
this._reportError(`${e}`, sourceSpan);
return this._exprParser.wrapLiteralPrimitive("ERROR", sourceInfo, absoluteOffset);
}
}
_reportError(message, sourceSpan, level = ParseErrorLevel.ERROR) {
this.errors.push(new ParseError(sourceSpan, message, level));
}
_reportExpressionParserErrors(errors, sourceSpan) {
for (const error of errors) {
this._reportError(error.message, sourceSpan);
}
}
_validatePropertyOrAttributeName(propName, sourceSpan, isAttr) {
const report = isAttr ? this._schemaRegistry.validateAttribute(propName) : this._schemaRegistry.validateProperty(propName);
if (report.error) {
this._reportError(report.msg, sourceSpan, ParseErrorLevel.ERROR);
}
}
_isAllowedAssignmentEvent(ast) {
if (ast instanceof ASTWithSource) {
return this._isAllowedAssignmentEvent(ast.ast);
}
if (ast instanceof NonNullAssert) {
return this._isAllowedAssignmentEvent(ast.expression);
}
if (ast instanceof PropertyRead || ast instanceof KeyedRead) {
return true;
}
if (!this._allowInvalidAssignmentEvents) {
return false;
}
if (ast instanceof Binary) {
return (ast.operation === "&&" || ast.operation === "||" || ast.operation === "??") && (ast.right instanceof PropertyRead || ast.right instanceof KeyedRead);
}
return ast instanceof Conditional || ast instanceof PrefixNot;
}
};
function isAnimationLabel(name) {
return name[0] == "@";
}
function calcPossibleSecurityContexts(registry, selector, propName, isAttribute) {
const ctxs = [];
CssSelector.parse(selector).forEach((selector2) => {
const elementNames = selector2.element ? [selector2.element] : registry.allKnownElementNames();
const notElementNames = new Set(selector2.notSelectors.filter((selector3) => selector3.isElementSelector()).map((selector3) => selector3.element));
const possibleElementNames = elementNames.filter((elementName) => !notElementNames.has(elementName));
ctxs.push(...possibleElementNames.map((elementName) => registry.securityContext(elementName, propName, isAttribute)));
});
return ctxs.length === 0 ? [SecurityContext.NONE] : Array.from(new Set(ctxs)).sort();
}
function moveParseSourceSpan(sourceSpan, absoluteSpan) {
const startDiff = absoluteSpan.start - sourceSpan.start.offset;
const endDiff = absoluteSpan.end - sourceSpan.end.offset;
return new ParseSourceSpan(sourceSpan.start.moveBy(startDiff), sourceSpan.end.moveBy(endDiff), sourceSpan.fullStart.moveBy(startDiff), sourceSpan.details);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/style_url_resolver.mjs
function isStyleUrlResolvable(url) {
if (url == null || url.length === 0 || url[0] == "/")
return false;
const schemeMatch = url.match(URL_WITH_SCHEMA_REGEXP);
return schemeMatch === null || schemeMatch[1] == "package" || schemeMatch[1] == "asset";
}
var URL_WITH_SCHEMA_REGEXP = /^([^:/?#]+):/;
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/template_parser/template_preparser.mjs
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) {
let selectAttr = null;
let hrefAttr = null;
let relAttr = null;
let nonBindable = false;
let projectAs = "";
ast.attrs.forEach((attr) => {
const 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);
const nodeName = ast.name.toLowerCase();
let 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(PreparsedElementType2) {
PreparsedElementType2[PreparsedElementType2["NG_CONTENT"] = 0] = "NG_CONTENT";
PreparsedElementType2[PreparsedElementType2["STYLE"] = 1] = "STYLE";
PreparsedElementType2[PreparsedElementType2["STYLESHEET"] = 2] = "STYLESHEET";
PreparsedElementType2[PreparsedElementType2["SCRIPT"] = 3] = "SCRIPT";
PreparsedElementType2[PreparsedElementType2["OTHER"] = 4] = "OTHER";
})(PreparsedElementType || (PreparsedElementType = {}));
var PreparsedElement = class {
constructor(type, selectAttr, hrefAttr, nonBindable, projectAs) {
this.type = type;
this.selectAttr = selectAttr;
this.hrefAttr = hrefAttr;
this.nonBindable = nonBindable;
this.projectAs = projectAs;
}
};
function normalizeNgContentSelect(selectAttr) {
if (selectAttr === null || selectAttr.length === 0) {
return "*";
}
return selectAttr;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/r3_control_flow.mjs
var FOR_LOOP_EXPRESSION_PATTERN = /^\s*([0-9A-Za-z_$]*)\s+of\s+([\S\s]*)/;
var FOR_LOOP_TRACK_PATTERN = /^track\s+([\S\s]*)/;
var CONDITIONAL_ALIAS_PATTERN = /^(as\s)+(.*)/;
var ELSE_IF_PATTERN = /^else[^\S\r\n]+if/;
var FOR_LOOP_LET_PATTERN = /^let\s+([\S\s]*)/;
var CHARACTERS_IN_SURROUNDING_WHITESPACE_PATTERN = /(\s*)(\S+)(\s*)/;
var ALLOWED_FOR_LOOP_LET_VARIABLES = /* @__PURE__ */ new Set([
"$index",
"$first",
"$last",
"$even",
"$odd",
"$count"
]);
function isConnectedForLoopBlock(name) {
return name === "empty";
}
function isConnectedIfLoopBlock(name) {
return name === "else" || ELSE_IF_PATTERN.test(name);
}
function createIfBlock(ast, connectedBlocks, visitor, bindingParser) {
const errors = validateIfConnectedBlocks(connectedBlocks);
const branches = [];
const mainBlockParams = parseConditionalBlockParameters(ast, errors, bindingParser);
if (mainBlockParams !== null) {
branches.push(new IfBlockBranch(mainBlockParams.expression, visitAll2(visitor, ast.children, ast.children), mainBlockParams.expressionAlias, ast.sourceSpan, ast.startSourceSpan, ast.endSourceSpan, ast.nameSpan, ast.i18n));
}
for (const block of connectedBlocks) {
if (ELSE_IF_PATTERN.test(block.name)) {
const params = parseConditionalBlockParameters(block, errors, bindingParser);
if (params !== null) {
const children = visitAll2(visitor, block.children, block.children);
branches.push(new IfBlockBranch(params.expression, children, params.expressionAlias, block.sourceSpan, block.startSourceSpan, block.endSourceSpan, block.nameSpan, block.i18n));
}
} else if (block.name === "else") {
const children = visitAll2(visitor, block.children, block.children);
branches.push(new IfBlockBranch(null, children, null, block.sourceSpan, block.startSourceSpan, block.endSourceSpan, block.nameSpan, block.i18n));
}
}
const ifBlockStartSourceSpan = branches.length > 0 ? branches[0].startSourceSpan : ast.startSourceSpan;
const ifBlockEndSourceSpan = branches.length > 0 ? branches[branches.length - 1].endSourceSpan : ast.endSourceSpan;
let wholeSourceSpan = ast.sourceSpan;
const lastBranch = branches[branches.length - 1];
if (lastBranch !== void 0) {
wholeSourceSpan = new ParseSourceSpan(ifBlockStartSourceSpan.start, lastBranch.sourceSpan.end);
}
return {
node: new IfBlock(branches, wholeSourceSpan, ast.startSourceSpan, ifBlockEndSourceSpan, ast.nameSpan),
errors
};
}
function createForLoop(ast, connectedBlocks, visitor, bindingParser) {
var _a2, _b2;
const errors = [];
const params = parseForLoopParameters(ast, errors, bindingParser);
let node = null;
let empty = null;
for (const block of connectedBlocks) {
if (block.name === "empty") {
if (empty !== null) {
errors.push(new ParseError(block.sourceSpan, "@for loop can only have one @empty block"));
} else if (block.parameters.length > 0) {
errors.push(new ParseError(block.sourceSpan, "@empty block cannot have parameters"));
} else {
empty = new ForLoopBlockEmpty(visitAll2(visitor, block.children, block.children), block.sourceSpan, block.startSourceSpan, block.endSourceSpan, block.nameSpan, block.i18n);
}
} else {
errors.push(new ParseError(block.sourceSpan, `Unrecognized @for loop block "${block.name}"`));
}
}
if (params !== null) {
if (params.trackBy === null) {
errors.push(new ParseError(ast.startSourceSpan, '@for loop must have a "track" expression'));
} else {
const endSpan = (_a2 = empty == null ? void 0 : empty.endSourceSpan) != null ? _a2 : ast.endSourceSpan;
const sourceSpan = new ParseSourceSpan(ast.sourceSpan.start, (_b2 = endSpan == null ? void 0 : endSpan.end) != null ? _b2 : ast.sourceSpan.end);
node = new ForLoopBlock(params.itemName, params.expression, params.trackBy.expression, params.trackBy.keywordSpan, params.context, visitAll2(visitor, ast.children, ast.children), empty, sourceSpan, ast.sourceSpan, ast.startSourceSpan, endSpan, ast.nameSpan, ast.i18n);
}
}
return { node, errors };
}
function createSwitchBlock(ast, visitor, bindingParser) {
const errors = validateSwitchBlock(ast);
const primaryExpression = ast.parameters.length > 0 ? parseBlockParameterToBinding(ast.parameters[0], bindingParser) : bindingParser.parseBinding("", false, ast.sourceSpan, 0);
const cases = [];
const unknownBlocks = [];
let defaultCase = null;
for (const node of ast.children) {
if (!(node instanceof Block)) {
continue;
}
if ((node.name !== "case" || node.parameters.length === 0) && node.name !== "default") {
unknownBlocks.push(new UnknownBlock(node.name, node.sourceSpan, node.nameSpan));
continue;
}
const expression = node.name === "case" ? parseBlockParameterToBinding(node.parameters[0], bindingParser) : null;
const ast2 = new SwitchBlockCase(expression, visitAll2(visitor, node.children, node.children), node.sourceSpan, node.startSourceSpan, node.endSourceSpan, node.nameSpan, node.i18n);
if (expression === null) {
defaultCase = ast2;
} else {
cases.push(ast2);
}
}
if (defaultCase !== null) {
cases.push(defaultCase);
}
return {
node: new SwitchBlock(primaryExpression, cases, unknownBlocks, ast.sourceSpan, ast.startSourceSpan, ast.endSourceSpan, ast.nameSpan),
errors
};
}
function parseForLoopParameters(block, errors, bindingParser) {
var _a2;
if (block.parameters.length === 0) {
errors.push(new ParseError(block.startSourceSpan, "@for loop does not have an expression"));
return null;
}
const [expressionParam, ...secondaryParams] = block.parameters;
const match = (_a2 = stripOptionalParentheses(expressionParam, errors)) == null ? void 0 : _a2.match(FOR_LOOP_EXPRESSION_PATTERN);
if (!match || match[2].trim().length === 0) {
errors.push(new ParseError(expressionParam.sourceSpan, 'Cannot parse expression. @for loop expression must match the pattern " of "'));
return null;
}
const [, itemName, rawExpression] = match;
if (ALLOWED_FOR_LOOP_LET_VARIABLES.has(itemName)) {
errors.push(new ParseError(expressionParam.sourceSpan, `@for loop item name cannot be one of ${Array.from(ALLOWED_FOR_LOOP_LET_VARIABLES).join(", ")}.`));
}
const variableName = expressionParam.expression.split(" ")[0];
const variableSpan = new ParseSourceSpan(expressionParam.sourceSpan.start, expressionParam.sourceSpan.start.moveBy(variableName.length));
const result = {
itemName: new Variable(itemName, "$implicit", variableSpan, variableSpan),
trackBy: null,
expression: parseBlockParameterToBinding(expressionParam, bindingParser, rawExpression),
context: Array.from(ALLOWED_FOR_LOOP_LET_VARIABLES, (variableName2) => {
const emptySpanAfterForBlockStart = new ParseSourceSpan(block.startSourceSpan.end, block.startSourceSpan.end);
return new Variable(variableName2, variableName2, emptySpanAfterForBlockStart, emptySpanAfterForBlockStart);
})
};
for (const param of secondaryParams) {
const letMatch = param.expression.match(FOR_LOOP_LET_PATTERN);
if (letMatch !== null) {
const variablesSpan = new ParseSourceSpan(param.sourceSpan.start.moveBy(letMatch[0].length - letMatch[1].length), param.sourceSpan.end);
parseLetParameter(param.sourceSpan, letMatch[1], variablesSpan, itemName, result.context, errors);
continue;
}
const trackMatch = param.expression.match(FOR_LOOP_TRACK_PATTERN);
if (trackMatch !== null) {
if (result.trackBy !== null) {
errors.push(new ParseError(param.sourceSpan, '@for loop can only have one "track" expression'));
} else {
const expression = parseBlockParameterToBinding(param, bindingParser, trackMatch[1]);
if (expression.ast instanceof EmptyExpr) {
errors.push(new ParseError(block.startSourceSpan, '@for loop must have a "track" expression'));
}
const keywordSpan = new ParseSourceSpan(param.sourceSpan.start, param.sourceSpan.start.moveBy("track".length));
result.trackBy = { expression, keywordSpan };
}
continue;
}
errors.push(new ParseError(param.sourceSpan, `Unrecognized @for loop paramater "${param.expression}"`));
}
return result;
}
function parseLetParameter(sourceSpan, expression, span, loopItemName, context, errors) {
var _a2, _b2, _c2;
const parts = expression.split(",");
let startSpan = span.start;
for (const part of parts) {
const expressionParts = part.split("=");
const name = expressionParts.length === 2 ? expressionParts[0].trim() : "";
const variableName = expressionParts.length === 2 ? expressionParts[1].trim() : "";
if (name.length === 0 || variableName.length === 0) {
errors.push(new ParseError(sourceSpan, `Invalid @for loop "let" parameter. Parameter should match the pattern " = "`));
} else if (!ALLOWED_FOR_LOOP_LET_VARIABLES.has(variableName)) {
errors.push(new ParseError(sourceSpan, `Unknown "let" parameter variable "${variableName}". The allowed variables are: ${Array.from(ALLOWED_FOR_LOOP_LET_VARIABLES).join(", ")}`));
} else if (name === loopItemName) {
errors.push(new ParseError(sourceSpan, `Invalid @for loop "let" parameter. Variable cannot be called "${loopItemName}"`));
} else if (context.some((v) => v.name === name)) {
errors.push(new ParseError(sourceSpan, `Duplicate "let" parameter variable "${variableName}"`));
} else {
const [, keyLeadingWhitespace, keyName] = (_a2 = expressionParts[0].match(CHARACTERS_IN_SURROUNDING_WHITESPACE_PATTERN)) != null ? _a2 : [];
const keySpan = keyLeadingWhitespace !== void 0 && expressionParts.length === 2 ? new ParseSourceSpan(
startSpan.moveBy(keyLeadingWhitespace.length),
startSpan.moveBy(keyLeadingWhitespace.length + keyName.length)
) : span;
let valueSpan = void 0;
if (expressionParts.length === 2) {
const [, valueLeadingWhitespace, implicit] = (_b2 = expressionParts[1].match(CHARACTERS_IN_SURROUNDING_WHITESPACE_PATTERN)) != null ? _b2 : [];
valueSpan = valueLeadingWhitespace !== void 0 ? new ParseSourceSpan(startSpan.moveBy(expressionParts[0].length + 1 + valueLeadingWhitespace.length), startSpan.moveBy(expressionParts[0].length + 1 + valueLeadingWhitespace.length + implicit.length)) : void 0;
}
const sourceSpan2 = new ParseSourceSpan(keySpan.start, (_c2 = valueSpan == null ? void 0 : valueSpan.end) != null ? _c2 : keySpan.end);
context.push(new Variable(name, variableName, sourceSpan2, keySpan, valueSpan));
}
startSpan = startSpan.moveBy(part.length + 1);
}
}
function validateIfConnectedBlocks(connectedBlocks) {
const errors = [];
let hasElse = false;
for (let i = 0; i < connectedBlocks.length; i++) {
const block = connectedBlocks[i];
if (block.name === "else") {
if (hasElse) {
errors.push(new ParseError(block.startSourceSpan, "Conditional can only have one @else block"));
} else if (connectedBlocks.length > 1 && i < connectedBlocks.length - 1) {
errors.push(new ParseError(block.startSourceSpan, "@else block must be last inside the conditional"));
} else if (block.parameters.length > 0) {
errors.push(new ParseError(block.startSourceSpan, "@else block cannot have parameters"));
}
hasElse = true;
} else if (!ELSE_IF_PATTERN.test(block.name)) {
errors.push(new ParseError(block.startSourceSpan, `Unrecognized conditional block @${block.name}`));
}
}
return errors;
}
function validateSwitchBlock(ast) {
const errors = [];
let hasDefault = false;
if (ast.parameters.length !== 1) {
errors.push(new ParseError(ast.startSourceSpan, "@switch block must have exactly one parameter"));
return errors;
}
for (const node of ast.children) {
if (node instanceof Comment2 || node instanceof Text4 && node.value.trim().length === 0) {
continue;
}
if (!(node instanceof Block) || node.name !== "case" && node.name !== "default") {
errors.push(new ParseError(node.sourceSpan, "@switch block can only contain @case and @default blocks"));
continue;
}
if (node.name === "default") {
if (hasDefault) {
errors.push(new ParseError(node.startSourceSpan, "@switch block can only have one @default block"));
} else if (node.parameters.length > 0) {
errors.push(new ParseError(node.startSourceSpan, "@default block cannot have parameters"));
}
hasDefault = true;
} else if (node.name === "case" && node.parameters.length !== 1) {
errors.push(new ParseError(node.startSourceSpan, "@case block must have exactly one parameter"));
}
}
return errors;
}
function parseBlockParameterToBinding(ast, bindingParser, part) {
let start;
let end;
if (typeof part === "string") {
start = Math.max(0, ast.expression.lastIndexOf(part));
end = start + part.length;
} else {
start = 0;
end = ast.expression.length;
}
return bindingParser.parseBinding(ast.expression.slice(start, end), false, ast.sourceSpan, ast.sourceSpan.start.offset + start);
}
function parseConditionalBlockParameters(block, errors, bindingParser) {
if (block.parameters.length === 0) {
errors.push(new ParseError(block.startSourceSpan, "Conditional block does not have an expression"));
return null;
}
const expression = parseBlockParameterToBinding(block.parameters[0], bindingParser);
let expressionAlias = null;
for (let i = 1; i < block.parameters.length; i++) {
const param = block.parameters[i];
const aliasMatch = param.expression.match(CONDITIONAL_ALIAS_PATTERN);
if (aliasMatch === null) {
errors.push(new ParseError(param.sourceSpan, `Unrecognized conditional paramater "${param.expression}"`));
} else if (block.name !== "if") {
errors.push(new ParseError(param.sourceSpan, '"as" expression is only allowed on the primary @if block'));
} else if (expressionAlias !== null) {
errors.push(new ParseError(param.sourceSpan, 'Conditional can only have one "as" expression'));
} else {
const name = aliasMatch[2].trim();
const variableStart = param.sourceSpan.start.moveBy(aliasMatch[1].length);
const variableSpan = new ParseSourceSpan(variableStart, variableStart.moveBy(name.length));
expressionAlias = new Variable(name, name, variableSpan, variableSpan);
}
}
return { expression, expressionAlias };
}
function stripOptionalParentheses(param, errors) {
const expression = param.expression;
const spaceRegex = /^\s$/;
let openParens = 0;
let start = 0;
let end = expression.length - 1;
for (let i = 0; i < expression.length; i++) {
const char = expression[i];
if (char === "(") {
start = i + 1;
openParens++;
} else if (spaceRegex.test(char)) {
continue;
} else {
break;
}
}
if (openParens === 0) {
return expression;
}
for (let i = expression.length - 1; i > -1; i--) {
const char = expression[i];
if (char === ")") {
end = i;
openParens--;
if (openParens === 0) {
break;
}
} else if (spaceRegex.test(char)) {
continue;
} else {
break;
}
}
if (openParens !== 0) {
errors.push(new ParseError(param.sourceSpan, "Unclosed parentheses in expression"));
return null;
}
return expression.slice(start, end);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/r3_deferred_triggers.mjs
var TIME_PATTERN = /^\d+\.?\d*(ms|s)?$/;
var SEPARATOR_PATTERN = /^\s$/;
var COMMA_DELIMITED_SYNTAX = /* @__PURE__ */ new Map([
[$LBRACE, $RBRACE],
[$LBRACKET, $RBRACKET],
[$LPAREN, $RPAREN]
]);
var OnTriggerType;
(function(OnTriggerType2) {
OnTriggerType2["IDLE"] = "idle";
OnTriggerType2["TIMER"] = "timer";
OnTriggerType2["INTERACTION"] = "interaction";
OnTriggerType2["IMMEDIATE"] = "immediate";
OnTriggerType2["HOVER"] = "hover";
OnTriggerType2["VIEWPORT"] = "viewport";
})(OnTriggerType || (OnTriggerType = {}));
function parseWhenTrigger({ expression, sourceSpan }, bindingParser, triggers, errors) {
const whenIndex = expression.indexOf("when");
const whenSourceSpan = new ParseSourceSpan(sourceSpan.start.moveBy(whenIndex), sourceSpan.start.moveBy(whenIndex + "when".length));
const prefetchSpan = getPrefetchSpan(expression, sourceSpan);
if (whenIndex === -1) {
errors.push(new ParseError(sourceSpan, `Could not find "when" keyword in expression`));
} else {
const start = getTriggerParametersStart(expression, whenIndex + 1);
const parsed = bindingParser.parseBinding(expression.slice(start), false, sourceSpan, sourceSpan.start.offset + start);
trackTrigger("when", triggers, errors, new BoundDeferredTrigger(parsed, sourceSpan, prefetchSpan, whenSourceSpan));
}
}
function parseOnTrigger({ expression, sourceSpan }, triggers, errors, placeholder) {
const onIndex = expression.indexOf("on");
const onSourceSpan = new ParseSourceSpan(sourceSpan.start.moveBy(onIndex), sourceSpan.start.moveBy(onIndex + "on".length));
const prefetchSpan = getPrefetchSpan(expression, sourceSpan);
if (onIndex === -1) {
errors.push(new ParseError(sourceSpan, `Could not find "on" keyword in expression`));
} else {
const start = getTriggerParametersStart(expression, onIndex + 1);
const parser = new OnTriggerParser(expression, start, sourceSpan, triggers, errors, placeholder, prefetchSpan, onSourceSpan);
parser.parse();
}
}
function getPrefetchSpan(expression, sourceSpan) {
if (!expression.startsWith("prefetch")) {
return null;
}
return new ParseSourceSpan(sourceSpan.start, sourceSpan.start.moveBy("prefetch".length));
}
var OnTriggerParser = class {
constructor(expression, start, span, triggers, errors, placeholder, prefetchSpan, onSourceSpan) {
this.expression = expression;
this.start = start;
this.span = span;
this.triggers = triggers;
this.errors = errors;
this.placeholder = placeholder;
this.prefetchSpan = prefetchSpan;
this.onSourceSpan = onSourceSpan;
this.index = 0;
this.tokens = new Lexer().tokenize(expression.slice(start));
}
parse() {
while (this.tokens.length > 0 && this.index < this.tokens.length) {
const token = this.token();
if (!token.isIdentifier()) {
this.unexpectedToken(token);
break;
}
if (this.isFollowedByOrLast($COMMA)) {
this.consumeTrigger(token, []);
this.advance();
} else if (this.isFollowedByOrLast($LPAREN)) {
this.advance();
const prevErrors = this.errors.length;
const parameters = this.consumeParameters();
if (this.errors.length !== prevErrors) {
break;
}
this.consumeTrigger(token, parameters);
this.advance();
} else if (this.index < this.tokens.length - 1) {
this.unexpectedToken(this.tokens[this.index + 1]);
}
this.advance();
}
}
advance() {
this.index++;
}
isFollowedByOrLast(char) {
if (this.index === this.tokens.length - 1) {
return true;
}
return this.tokens[this.index + 1].isCharacter(char);
}
token() {
return this.tokens[Math.min(this.index, this.tokens.length - 1)];
}
consumeTrigger(identifier, parameters) {
const triggerNameStartSpan = this.span.start.moveBy(this.start + identifier.index - this.tokens[0].index);
const nameSpan = new ParseSourceSpan(triggerNameStartSpan, triggerNameStartSpan.moveBy(identifier.strValue.length));
const endSpan = triggerNameStartSpan.moveBy(this.token().end - identifier.index);
const isFirstTrigger = identifier.index === 0;
const onSourceSpan = isFirstTrigger ? this.onSourceSpan : null;
const prefetchSourceSpan = isFirstTrigger ? this.prefetchSpan : null;
const sourceSpan = new ParseSourceSpan(isFirstTrigger ? this.span.start : triggerNameStartSpan, endSpan);
try {
switch (identifier.toString()) {
case OnTriggerType.IDLE:
this.trackTrigger("idle", createIdleTrigger(parameters, nameSpan, sourceSpan, prefetchSourceSpan, onSourceSpan));
break;
case OnTriggerType.TIMER:
this.trackTrigger("timer", createTimerTrigger(parameters, nameSpan, sourceSpan, this.prefetchSpan, this.onSourceSpan));
break;
case OnTriggerType.INTERACTION:
this.trackTrigger("interaction", createInteractionTrigger(parameters, nameSpan, sourceSpan, this.prefetchSpan, this.onSourceSpan, this.placeholder));
break;
case OnTriggerType.IMMEDIATE:
this.trackTrigger("immediate", createImmediateTrigger(parameters, nameSpan, sourceSpan, this.prefetchSpan, this.onSourceSpan));
break;
case OnTriggerType.HOVER:
this.trackTrigger("hover", createHoverTrigger(parameters, nameSpan, sourceSpan, this.prefetchSpan, this.onSourceSpan, this.placeholder));
break;
case OnTriggerType.VIEWPORT:
this.trackTrigger("viewport", createViewportTrigger(parameters, nameSpan, sourceSpan, this.prefetchSpan, this.onSourceSpan, this.placeholder));
break;
default:
throw new Error(`Unrecognized trigger type "${identifier}"`);
}
} catch (e) {
this.error(identifier, e.message);
}
}
consumeParameters() {
const parameters = [];
if (!this.token().isCharacter($LPAREN)) {
this.unexpectedToken(this.token());
return parameters;
}
this.advance();
const commaDelimStack = [];
let current = "";
while (this.index < this.tokens.length) {
const token = this.token();
if (token.isCharacter($RPAREN) && commaDelimStack.length === 0) {
if (current.length) {
parameters.push(current);
}
break;
}
if (token.type === TokenType.Character && COMMA_DELIMITED_SYNTAX.has(token.numValue)) {
commaDelimStack.push(COMMA_DELIMITED_SYNTAX.get(token.numValue));
}
if (commaDelimStack.length > 0 && token.isCharacter(commaDelimStack[commaDelimStack.length - 1])) {
commaDelimStack.pop();
}
if (commaDelimStack.length === 0 && token.isCharacter($COMMA) && current.length > 0) {
parameters.push(current);
current = "";
this.advance();
continue;
}
current += this.tokenText();
this.advance();
}
if (!this.token().isCharacter($RPAREN) || commaDelimStack.length > 0) {
this.error(this.token(), "Unexpected end of expression");
}
if (this.index < this.tokens.length - 1 && !this.tokens[this.index + 1].isCharacter($COMMA)) {
this.unexpectedToken(this.tokens[this.index + 1]);
}
return parameters;
}
tokenText() {
return this.expression.slice(this.start + this.token().index, this.start + this.token().end);
}
trackTrigger(name, trigger) {
trackTrigger(name, this.triggers, this.errors, trigger);
}
error(token, message) {
const newStart = this.span.start.moveBy(this.start + token.index);
const newEnd = newStart.moveBy(token.end - token.index);
this.errors.push(new ParseError(new ParseSourceSpan(newStart, newEnd), message));
}
unexpectedToken(token) {
this.error(token, `Unexpected token "${token}"`);
}
};
function trackTrigger(name, allTriggers, errors, trigger) {
if (allTriggers[name]) {
errors.push(new ParseError(trigger.sourceSpan, `Duplicate "${name}" trigger is not allowed`));
} else {
allTriggers[name] = trigger;
}
}
function createIdleTrigger(parameters, nameSpan, sourceSpan, prefetchSpan, onSourceSpan) {
if (parameters.length > 0) {
throw new Error(`"${OnTriggerType.IDLE}" trigger cannot have parameters`);
}
return new IdleDeferredTrigger(nameSpan, sourceSpan, prefetchSpan, onSourceSpan);
}
function createTimerTrigger(parameters, nameSpan, sourceSpan, prefetchSpan, onSourceSpan) {
if (parameters.length !== 1) {
throw new Error(`"${OnTriggerType.TIMER}" trigger must have exactly one parameter`);
}
const delay = parseDeferredTime(parameters[0]);
if (delay === null) {
throw new Error(`Could not parse time value of trigger "${OnTriggerType.TIMER}"`);
}
return new TimerDeferredTrigger(delay, nameSpan, sourceSpan, prefetchSpan, onSourceSpan);
}
function createImmediateTrigger(parameters, nameSpan, sourceSpan, prefetchSpan, onSourceSpan) {
if (parameters.length > 0) {
throw new Error(`"${OnTriggerType.IMMEDIATE}" trigger cannot have parameters`);
}
return new ImmediateDeferredTrigger(nameSpan, sourceSpan, prefetchSpan, onSourceSpan);
}
function createHoverTrigger(parameters, nameSpan, sourceSpan, prefetchSpan, onSourceSpan, placeholder) {
var _a2;
validateReferenceBasedTrigger(OnTriggerType.HOVER, parameters, placeholder);
return new HoverDeferredTrigger((_a2 = parameters[0]) != null ? _a2 : null, nameSpan, sourceSpan, prefetchSpan, onSourceSpan);
}
function createInteractionTrigger(parameters, nameSpan, sourceSpan, prefetchSpan, onSourceSpan, placeholder) {
var _a2;
validateReferenceBasedTrigger(OnTriggerType.INTERACTION, parameters, placeholder);
return new InteractionDeferredTrigger((_a2 = parameters[0]) != null ? _a2 : null, nameSpan, sourceSpan, prefetchSpan, onSourceSpan);
}
function createViewportTrigger(parameters, nameSpan, sourceSpan, prefetchSpan, onSourceSpan, placeholder) {
var _a2;
validateReferenceBasedTrigger(OnTriggerType.VIEWPORT, parameters, placeholder);
return new ViewportDeferredTrigger((_a2 = parameters[0]) != null ? _a2 : null, nameSpan, sourceSpan, prefetchSpan, onSourceSpan);
}
function validateReferenceBasedTrigger(type, parameters, placeholder) {
if (parameters.length > 1) {
throw new Error(`"${type}" trigger can only have zero or one parameters`);
}
if (parameters.length === 0) {
if (placeholder === null) {
throw new Error(`"${type}" trigger with no parameters can only be placed on an @defer that has a @placeholder block`);
}
if (placeholder.children.length !== 1 || !(placeholder.children[0] instanceof Element)) {
throw new Error(`"${type}" trigger with no parameters can only be placed on an @defer that has a @placeholder block with exactly one root element node`);
}
}
}
function getTriggerParametersStart(value, startPosition = 0) {
let hasFoundSeparator = false;
for (let i = startPosition; i < value.length; i++) {
if (SEPARATOR_PATTERN.test(value[i])) {
hasFoundSeparator = true;
} else if (hasFoundSeparator) {
return i;
}
}
return -1;
}
function parseDeferredTime(value) {
const match = value.match(TIME_PATTERN);
if (!match) {
return null;
}
const [time, units] = match;
return parseFloat(time) * (units === "s" ? 1e3 : 1);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/r3_deferred_blocks.mjs
var PREFETCH_WHEN_PATTERN = /^prefetch\s+when\s/;
var PREFETCH_ON_PATTERN = /^prefetch\s+on\s/;
var MINIMUM_PARAMETER_PATTERN = /^minimum\s/;
var AFTER_PARAMETER_PATTERN = /^after\s/;
var WHEN_PARAMETER_PATTERN = /^when\s/;
var ON_PARAMETER_PATTERN = /^on\s/;
function isConnectedDeferLoopBlock(name) {
return name === "placeholder" || name === "loading" || name === "error";
}
function createDeferredBlock(ast, connectedBlocks, visitor, bindingParser) {
const errors = [];
const { placeholder, loading, error } = parseConnectedBlocks(connectedBlocks, errors, visitor);
const { triggers, prefetchTriggers } = parsePrimaryTriggers(ast.parameters, bindingParser, errors, placeholder);
let lastEndSourceSpan = ast.endSourceSpan;
let endOfLastSourceSpan = ast.sourceSpan.end;
if (connectedBlocks.length > 0) {
const lastConnectedBlock = connectedBlocks[connectedBlocks.length - 1];
lastEndSourceSpan = lastConnectedBlock.endSourceSpan;
endOfLastSourceSpan = lastConnectedBlock.sourceSpan.end;
}
const sourceSpanWithConnectedBlocks = new ParseSourceSpan(ast.sourceSpan.start, endOfLastSourceSpan);
const node = new DeferredBlock(visitAll2(visitor, ast.children, ast.children), triggers, prefetchTriggers, placeholder, loading, error, ast.nameSpan, sourceSpanWithConnectedBlocks, ast.sourceSpan, ast.startSourceSpan, lastEndSourceSpan, ast.i18n);
return { node, errors };
}
function parseConnectedBlocks(connectedBlocks, errors, visitor) {
let placeholder = null;
let loading = null;
let error = null;
for (const block of connectedBlocks) {
try {
if (!isConnectedDeferLoopBlock(block.name)) {
errors.push(new ParseError(block.startSourceSpan, `Unrecognized block "@${block.name}"`));
break;
}
switch (block.name) {
case "placeholder":
if (placeholder !== null) {
errors.push(new ParseError(block.startSourceSpan, `@defer block can only have one @placeholder block`));
} else {
placeholder = parsePlaceholderBlock(block, visitor);
}
break;
case "loading":
if (loading !== null) {
errors.push(new ParseError(block.startSourceSpan, `@defer block can only have one @loading block`));
} else {
loading = parseLoadingBlock(block, visitor);
}
break;
case "error":
if (error !== null) {
errors.push(new ParseError(block.startSourceSpan, `@defer block can only have one @error block`));
} else {
error = parseErrorBlock(block, visitor);
}
break;
}
} catch (e) {
errors.push(new ParseError(block.startSourceSpan, e.message));
}
}
return { placeholder, loading, error };
}
function parsePlaceholderBlock(ast, visitor) {
let minimumTime = null;
for (const param of ast.parameters) {
if (MINIMUM_PARAMETER_PATTERN.test(param.expression)) {
if (minimumTime != null) {
throw new Error(`@placeholder block can only have one "minimum" parameter`);
}
const parsedTime = parseDeferredTime(param.expression.slice(getTriggerParametersStart(param.expression)));
if (parsedTime === null) {
throw new Error(`Could not parse time value of parameter "minimum"`);
}
minimumTime = parsedTime;
} else {
throw new Error(`Unrecognized parameter in @placeholder block: "${param.expression}"`);
}
}
return new DeferredBlockPlaceholder(visitAll2(visitor, ast.children, ast.children), minimumTime, ast.nameSpan, ast.sourceSpan, ast.startSourceSpan, ast.endSourceSpan, ast.i18n);
}
function parseLoadingBlock(ast, visitor) {
let afterTime = null;
let minimumTime = null;
for (const param of ast.parameters) {
if (AFTER_PARAMETER_PATTERN.test(param.expression)) {
if (afterTime != null) {
throw new Error(`@loading block can only have one "after" parameter`);
}
const parsedTime = parseDeferredTime(param.expression.slice(getTriggerParametersStart(param.expression)));
if (parsedTime === null) {
throw new Error(`Could not parse time value of parameter "after"`);
}
afterTime = parsedTime;
} else if (MINIMUM_PARAMETER_PATTERN.test(param.expression)) {
if (minimumTime != null) {
throw new Error(`@loading block can only have one "minimum" parameter`);
}
const parsedTime = parseDeferredTime(param.expression.slice(getTriggerParametersStart(param.expression)));
if (parsedTime === null) {
throw new Error(`Could not parse time value of parameter "minimum"`);
}
minimumTime = parsedTime;
} else {
throw new Error(`Unrecognized parameter in @loading block: "${param.expression}"`);
}
}
return new DeferredBlockLoading(visitAll2(visitor, ast.children, ast.children), afterTime, minimumTime, ast.nameSpan, ast.sourceSpan, ast.startSourceSpan, ast.endSourceSpan, ast.i18n);
}
function parseErrorBlock(ast, visitor) {
if (ast.parameters.length > 0) {
throw new Error(`@error block cannot have parameters`);
}
return new DeferredBlockError(visitAll2(visitor, ast.children, ast.children), ast.nameSpan, ast.sourceSpan, ast.startSourceSpan, ast.endSourceSpan, ast.i18n);
}
function parsePrimaryTriggers(params, bindingParser, errors, placeholder) {
const triggers = {};
const prefetchTriggers = {};
for (const param of params) {
if (WHEN_PARAMETER_PATTERN.test(param.expression)) {
parseWhenTrigger(param, bindingParser, triggers, errors);
} else if (ON_PARAMETER_PATTERN.test(param.expression)) {
parseOnTrigger(param, triggers, errors, placeholder);
} else if (PREFETCH_WHEN_PATTERN.test(param.expression)) {
parseWhenTrigger(param, bindingParser, prefetchTriggers, errors);
} else if (PREFETCH_ON_PATTERN.test(param.expression)) {
parseOnTrigger(param, prefetchTriggers, errors, placeholder);
} else {
errors.push(new ParseError(param.sourceSpan, "Unrecognized trigger"));
}
}
return { triggers, prefetchTriggers };
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/r3_template_transform.mjs
var BIND_NAME_REGEXP = /^(?:(bind-)|(let-)|(ref-|#)|(on-)|(bindon-)|(@))(.*)$/;
var KW_BIND_IDX = 1;
var KW_LET_IDX = 2;
var KW_REF_IDX = 3;
var KW_ON_IDX = 4;
var KW_BINDON_IDX = 5;
var KW_AT_IDX = 6;
var IDENT_KW_IDX = 7;
var BINDING_DELIMS = {
BANANA_BOX: { start: "[(", end: ")]" },
PROPERTY: { start: "[", end: "]" },
EVENT: { start: "(", end: ")" }
};
var TEMPLATE_ATTR_PREFIX2 = "*";
function htmlAstToRender3Ast(htmlNodes, bindingParser, options) {
const transformer = new HtmlAstToIvyAst(bindingParser, options);
const ivyNodes = visitAll2(transformer, htmlNodes, htmlNodes);
const allErrors = bindingParser.errors.concat(transformer.errors);
const result = {
nodes: ivyNodes,
errors: allErrors,
styleUrls: transformer.styleUrls,
styles: transformer.styles,
ngContentSelectors: transformer.ngContentSelectors
};
if (options.collectCommentNodes) {
result.commentNodes = transformer.commentNodes;
}
return result;
}
var HtmlAstToIvyAst = class {
constructor(bindingParser, options) {
this.bindingParser = bindingParser;
this.options = options;
this.errors = [];
this.styles = [];
this.styleUrls = [];
this.ngContentSelectors = [];
this.commentNodes = [];
this.inI18nBlock = false;
this.processedNodes = /* @__PURE__ */ new Set();
}
visitElement(element2) {
const isI18nRootElement = isI18nRootNode(element2.i18n);
if (isI18nRootElement) {
if (this.inI18nBlock) {
this.reportError("Cannot mark an element as translatable inside of a translatable section. Please remove the nested i18n marker.", element2.sourceSpan);
}
this.inI18nBlock = true;
}
const preparsedElement = preparseElement(element2);
if (preparsedElement.type === PreparsedElementType.SCRIPT) {
return null;
} else if (preparsedElement.type === PreparsedElementType.STYLE) {
const contents = textContents(element2);
if (contents !== null) {
this.styles.push(contents);
}
return null;
} else if (preparsedElement.type === PreparsedElementType.STYLESHEET && isStyleUrlResolvable(preparsedElement.hrefAttr)) {
this.styleUrls.push(preparsedElement.hrefAttr);
return null;
}
const isTemplateElement = isNgTemplate(element2.name);
const parsedProperties = [];
const boundEvents = [];
const variables = [];
const references = [];
const attributes = [];
const i18nAttrsMeta = {};
const templateParsedProperties = [];
const templateVariables = [];
let elementHasInlineTemplate = false;
for (const attribute2 of element2.attrs) {
let hasBinding = false;
const normalizedName = normalizeAttributeName(attribute2.name);
let isTemplateBinding = false;
if (attribute2.i18n) {
i18nAttrsMeta[attribute2.name] = attribute2.i18n;
}
if (normalizedName.startsWith(TEMPLATE_ATTR_PREFIX2)) {
if (elementHasInlineTemplate) {
this.reportError(`Can't have multiple template bindings on one element. Use only one attribute prefixed with *`, attribute2.sourceSpan);
}
isTemplateBinding = true;
elementHasInlineTemplate = true;
const templateValue = attribute2.value;
const templateKey = normalizedName.substring(TEMPLATE_ATTR_PREFIX2.length);
const parsedVariables = [];
const absoluteValueOffset = attribute2.valueSpan ? attribute2.valueSpan.start.offset : attribute2.sourceSpan.start.offset + attribute2.name.length;
this.bindingParser.parseInlineTemplateBinding(templateKey, templateValue, attribute2.sourceSpan, absoluteValueOffset, [], templateParsedProperties, parsedVariables, true);
templateVariables.push(...parsedVariables.map((v) => new Variable(v.name, v.value, v.sourceSpan, v.keySpan, v.valueSpan)));
} else {
hasBinding = this.parseAttribute(isTemplateElement, attribute2, [], parsedProperties, boundEvents, variables, references);
}
if (!hasBinding && !isTemplateBinding) {
attributes.push(this.visitAttribute(attribute2));
}
}
let children;
if (preparsedElement.nonBindable) {
children = visitAll2(NON_BINDABLE_VISITOR, element2.children).flat(Infinity);
} else {
children = visitAll2(this, element2.children, element2.children);
}
let parsedElement;
if (preparsedElement.type === PreparsedElementType.NG_CONTENT) {
const selector = preparsedElement.selectAttr;
const attrs = element2.attrs.map((attr) => this.visitAttribute(attr));
parsedElement = new Content(selector, attrs, children, element2.sourceSpan, element2.i18n);
this.ngContentSelectors.push(selector);
} else if (isTemplateElement) {
const attrs = this.extractAttributes(element2.name, parsedProperties, i18nAttrsMeta);
parsedElement = new Template(element2.name, attributes, attrs.bound, boundEvents, [], children, references, variables, element2.sourceSpan, element2.startSourceSpan, element2.endSourceSpan, element2.i18n);
} else {
const attrs = this.extractAttributes(element2.name, parsedProperties, i18nAttrsMeta);
parsedElement = new Element(element2.name, attributes, attrs.bound, boundEvents, children, references, element2.sourceSpan, element2.startSourceSpan, element2.endSourceSpan, element2.i18n);
}
if (elementHasInlineTemplate) {
const attrs = this.extractAttributes("ng-template", templateParsedProperties, i18nAttrsMeta);
const templateAttrs = [];
attrs.literal.forEach((attr) => templateAttrs.push(attr));
attrs.bound.forEach((attr) => templateAttrs.push(attr));
const hoistedAttrs = parsedElement instanceof Element ? {
attributes: parsedElement.attributes,
inputs: parsedElement.inputs,
outputs: parsedElement.outputs
} : { attributes: [], inputs: [], outputs: [] };
const i18n2 = isTemplateElement && isI18nRootElement ? void 0 : element2.i18n;
const name = parsedElement instanceof Template ? null : parsedElement.name;
parsedElement = new Template(name, hoistedAttrs.attributes, hoistedAttrs.inputs, hoistedAttrs.outputs, templateAttrs, [parsedElement], [], templateVariables, element2.sourceSpan, element2.startSourceSpan, element2.endSourceSpan, i18n2);
}
if (isI18nRootElement) {
this.inI18nBlock = false;
}
return parsedElement;
}
visitAttribute(attribute2) {
return new TextAttribute(attribute2.name, attribute2.value, attribute2.sourceSpan, attribute2.keySpan, attribute2.valueSpan, attribute2.i18n);
}
visitText(text2) {
return this.processedNodes.has(text2) ? null : this._visitTextWithInterpolation(text2.value, text2.sourceSpan, text2.tokens, text2.i18n);
}
visitExpansion(expansion) {
if (!expansion.i18n) {
return null;
}
if (!isI18nRootNode(expansion.i18n)) {
throw new Error(`Invalid type "${expansion.i18n.constructor}" for "i18n" property of ${expansion.sourceSpan.toString()}. Expected a "Message"`);
}
const message = expansion.i18n;
const vars = {};
const placeholders = {};
Object.keys(message.placeholders).forEach((key) => {
const value = message.placeholders[key];
if (key.startsWith(I18N_ICU_VAR_PREFIX)) {
const formattedKey = key.trim();
const ast = this.bindingParser.parseInterpolationExpression(value.text, value.sourceSpan);
vars[formattedKey] = new BoundText(ast, value.sourceSpan);
} else {
placeholders[key] = this._visitTextWithInterpolation(value.text, value.sourceSpan, null);
}
});
return new Icu(vars, placeholders, expansion.sourceSpan, message);
}
visitExpansionCase(expansionCase) {
return null;
}
visitComment(comment) {
if (this.options.collectCommentNodes) {
this.commentNodes.push(new Comment(comment.value || "", comment.sourceSpan));
}
return null;
}
visitLetDeclaration(decl, context) {
const value = this.bindingParser.parseBinding(decl.value, false, decl.valueSpan, decl.valueSpan.start.offset);
if (value.errors.length === 0 && value.ast instanceof EmptyExpr) {
this.reportError("@let declaration value cannot be empty", decl.valueSpan);
}
return new LetDeclaration(decl.name, value, decl.sourceSpan, decl.nameSpan, decl.valueSpan);
}
visitBlockParameter() {
return null;
}
visitBlock(block, context) {
const index = Array.isArray(context) ? context.indexOf(block) : -1;
if (index === -1) {
throw new Error("Visitor invoked incorrectly. Expecting visitBlock to be invoked siblings array as its context");
}
if (this.processedNodes.has(block)) {
return null;
}
let result = null;
switch (block.name) {
case "defer":
result = createDeferredBlock(block, this.findConnectedBlocks(index, context, isConnectedDeferLoopBlock), this, this.bindingParser);
break;
case "switch":
result = createSwitchBlock(block, this, this.bindingParser);
break;
case "for":
result = createForLoop(block, this.findConnectedBlocks(index, context, isConnectedForLoopBlock), this, this.bindingParser);
break;
case "if":
result = createIfBlock(block, this.findConnectedBlocks(index, context, isConnectedIfLoopBlock), this, this.bindingParser);
break;
default:
let errorMessage;
if (isConnectedDeferLoopBlock(block.name)) {
errorMessage = `@${block.name} block can only be used after an @defer block.`;
this.processedNodes.add(block);
} else if (isConnectedForLoopBlock(block.name)) {
errorMessage = `@${block.name} block can only be used after an @for block.`;
this.processedNodes.add(block);
} else if (isConnectedIfLoopBlock(block.name)) {
errorMessage = `@${block.name} block can only be used after an @if or @else if block.`;
this.processedNodes.add(block);
} else {
errorMessage = `Unrecognized block @${block.name}.`;
}
result = {
node: new UnknownBlock(block.name, block.sourceSpan, block.nameSpan),
errors: [new ParseError(block.sourceSpan, errorMessage)]
};
break;
}
this.errors.push(...result.errors);
return result.node;
}
findConnectedBlocks(primaryBlockIndex, siblings, predicate) {
const relatedBlocks = [];
for (let i = primaryBlockIndex + 1; i < siblings.length; i++) {
const node = siblings[i];
if (node instanceof Comment2) {
continue;
}
if (node instanceof Text4 && node.value.trim().length === 0) {
this.processedNodes.add(node);
continue;
}
if (!(node instanceof Block) || !predicate(node.name)) {
break;
}
relatedBlocks.push(node);
this.processedNodes.add(node);
}
return relatedBlocks;
}
extractAttributes(elementName, properties, i18nPropsMeta) {
const bound = [];
const literal3 = [];
properties.forEach((prop) => {
const i18n2 = i18nPropsMeta[prop.name];
if (prop.isLiteral) {
literal3.push(new TextAttribute(prop.name, prop.expression.source || "", prop.sourceSpan, prop.keySpan, prop.valueSpan, i18n2));
} else {
const bep = this.bindingParser.createBoundElementProperty(
elementName,
prop,
true,
false
);
bound.push(BoundAttribute.fromBoundElementProperty(bep, i18n2));
}
});
return { bound, literal: literal3 };
}
parseAttribute(isTemplateElement, attribute2, matchableAttributes, parsedProperties, boundEvents, variables, references) {
var _a2;
const name = normalizeAttributeName(attribute2.name);
const value = attribute2.value;
const srcSpan = attribute2.sourceSpan;
const absoluteOffset = attribute2.valueSpan ? attribute2.valueSpan.start.offset : srcSpan.start.offset;
function createKeySpan(srcSpan2, prefix, identifier) {
const normalizationAdjustment = attribute2.name.length - name.length;
const keySpanStart = srcSpan2.start.moveBy(prefix.length + normalizationAdjustment);
const keySpanEnd = keySpanStart.moveBy(identifier.length);
return new ParseSourceSpan(keySpanStart, keySpanEnd, keySpanStart, identifier);
}
const bindParts = name.match(BIND_NAME_REGEXP);
if (bindParts) {
if (bindParts[KW_BIND_IDX] != null) {
const identifier = bindParts[IDENT_KW_IDX];
const keySpan2 = createKeySpan(srcSpan, bindParts[KW_BIND_IDX], identifier);
this.bindingParser.parsePropertyBinding(identifier, value, false, false, srcSpan, absoluteOffset, attribute2.valueSpan, matchableAttributes, parsedProperties, keySpan2);
} else if (bindParts[KW_LET_IDX]) {
if (isTemplateElement) {
const identifier = bindParts[IDENT_KW_IDX];
const keySpan2 = createKeySpan(srcSpan, bindParts[KW_LET_IDX], identifier);
this.parseVariable(identifier, value, srcSpan, keySpan2, attribute2.valueSpan, variables);
} else {
this.reportError(`"let-" is only supported on ng-template elements.`, srcSpan);
}
} else if (bindParts[KW_REF_IDX]) {
const identifier = bindParts[IDENT_KW_IDX];
const keySpan2 = createKeySpan(srcSpan, bindParts[KW_REF_IDX], identifier);
this.parseReference(identifier, value, srcSpan, keySpan2, attribute2.valueSpan, references);
} else if (bindParts[KW_ON_IDX]) {
const events = [];
const identifier = bindParts[IDENT_KW_IDX];
const keySpan2 = createKeySpan(srcSpan, bindParts[KW_ON_IDX], identifier);
this.bindingParser.parseEvent(
identifier,
value,
false,
srcSpan,
attribute2.valueSpan || srcSpan,
matchableAttributes,
events,
keySpan2
);
addEvents(events, boundEvents);
} else if (bindParts[KW_BINDON_IDX]) {
const identifier = bindParts[IDENT_KW_IDX];
const keySpan2 = createKeySpan(srcSpan, bindParts[KW_BINDON_IDX], identifier);
this.bindingParser.parsePropertyBinding(identifier, value, false, true, srcSpan, absoluteOffset, attribute2.valueSpan, matchableAttributes, parsedProperties, keySpan2);
this.parseAssignmentEvent(identifier, value, srcSpan, attribute2.valueSpan, matchableAttributes, boundEvents, keySpan2);
} else if (bindParts[KW_AT_IDX]) {
const keySpan2 = createKeySpan(srcSpan, "", name);
this.bindingParser.parseLiteralAttr(name, value, srcSpan, absoluteOffset, attribute2.valueSpan, matchableAttributes, parsedProperties, keySpan2);
}
return true;
}
let delims = null;
if (name.startsWith(BINDING_DELIMS.BANANA_BOX.start)) {
delims = BINDING_DELIMS.BANANA_BOX;
} else if (name.startsWith(BINDING_DELIMS.PROPERTY.start)) {
delims = BINDING_DELIMS.PROPERTY;
} else if (name.startsWith(BINDING_DELIMS.EVENT.start)) {
delims = BINDING_DELIMS.EVENT;
}
if (delims !== null && name.endsWith(delims.end) && name.length > delims.start.length + delims.end.length) {
const identifier = name.substring(delims.start.length, name.length - delims.end.length);
const keySpan2 = createKeySpan(srcSpan, delims.start, identifier);
if (delims.start === BINDING_DELIMS.BANANA_BOX.start) {
this.bindingParser.parsePropertyBinding(identifier, value, false, true, srcSpan, absoluteOffset, attribute2.valueSpan, matchableAttributes, parsedProperties, keySpan2);
this.parseAssignmentEvent(identifier, value, srcSpan, attribute2.valueSpan, matchableAttributes, boundEvents, keySpan2);
} else if (delims.start === BINDING_DELIMS.PROPERTY.start) {
this.bindingParser.parsePropertyBinding(identifier, value, false, false, srcSpan, absoluteOffset, attribute2.valueSpan, matchableAttributes, parsedProperties, keySpan2);
} else {
const events = [];
this.bindingParser.parseEvent(
identifier,
value,
false,
srcSpan,
attribute2.valueSpan || srcSpan,
matchableAttributes,
events,
keySpan2
);
addEvents(events, boundEvents);
}
return true;
}
const keySpan = createKeySpan(srcSpan, "", name);
const hasBinding = this.bindingParser.parsePropertyInterpolation(name, value, srcSpan, attribute2.valueSpan, matchableAttributes, parsedProperties, keySpan, (_a2 = attribute2.valueTokens) != null ? _a2 : null);
return hasBinding;
}
_visitTextWithInterpolation(value, sourceSpan, interpolatedTokens, i18n2) {
const valueNoNgsp = replaceNgsp(value);
const expr = this.bindingParser.parseInterpolation(valueNoNgsp, sourceSpan, interpolatedTokens);
return expr ? new BoundText(expr, sourceSpan, i18n2) : new Text(valueNoNgsp, sourceSpan);
}
parseVariable(identifier, value, sourceSpan, keySpan, valueSpan, variables) {
if (identifier.indexOf("-") > -1) {
this.reportError(`"-" is not allowed in variable names`, sourceSpan);
} else if (identifier.length === 0) {
this.reportError(`Variable does not have a name`, sourceSpan);
}
variables.push(new Variable(identifier, value, sourceSpan, keySpan, valueSpan));
}
parseReference(identifier, value, sourceSpan, keySpan, valueSpan, references) {
if (identifier.indexOf("-") > -1) {
this.reportError(`"-" is not allowed in reference names`, sourceSpan);
} else if (identifier.length === 0) {
this.reportError(`Reference does not have a name`, sourceSpan);
} else if (references.some((reference2) => reference2.name === identifier)) {
this.reportError(`Reference "#${identifier}" is defined more than once`, sourceSpan);
}
references.push(new Reference(identifier, value, sourceSpan, keySpan, valueSpan));
}
parseAssignmentEvent(name, expression, sourceSpan, valueSpan, targetMatchableAttrs, boundEvents, keySpan) {
const events = [];
this.bindingParser.parseEvent(
`${name}Change`,
expression,
true,
sourceSpan,
valueSpan || sourceSpan,
targetMatchableAttrs,
events,
keySpan
);
addEvents(events, boundEvents);
}
reportError(message, sourceSpan, level = ParseErrorLevel.ERROR) {
this.errors.push(new ParseError(sourceSpan, message, level));
}
};
var NonBindableVisitor = class {
visitElement(ast) {
const preparsedElement = preparseElement(ast);
if (preparsedElement.type === PreparsedElementType.SCRIPT || preparsedElement.type === PreparsedElementType.STYLE || preparsedElement.type === PreparsedElementType.STYLESHEET) {
return null;
}
const children = visitAll2(this, ast.children, null);
return new Element(
ast.name,
visitAll2(this, ast.attrs),
[],
[],
children,
[],
ast.sourceSpan,
ast.startSourceSpan,
ast.endSourceSpan
);
}
visitComment(comment) {
return null;
}
visitAttribute(attribute2) {
return new TextAttribute(attribute2.name, attribute2.value, attribute2.sourceSpan, attribute2.keySpan, attribute2.valueSpan, attribute2.i18n);
}
visitText(text2) {
return new Text(text2.value, text2.sourceSpan);
}
visitExpansion(expansion) {
return null;
}
visitExpansionCase(expansionCase) {
return null;
}
visitBlock(block, context) {
const nodes = [
new Text(block.startSourceSpan.toString(), block.startSourceSpan),
...visitAll2(this, block.children)
];
if (block.endSourceSpan !== null) {
nodes.push(new Text(block.endSourceSpan.toString(), block.endSourceSpan));
}
return nodes;
}
visitBlockParameter(parameter, context) {
return null;
}
visitLetDeclaration(decl, context) {
return new Text(`@let ${decl.name} = ${decl.value};`, decl.sourceSpan);
}
};
var NON_BINDABLE_VISITOR = new NonBindableVisitor();
function normalizeAttributeName(attrName) {
return /^data-/i.test(attrName) ? attrName.substring(5) : attrName;
}
function addEvents(events, boundEvents) {
boundEvents.push(...events.map((e) => BoundEvent.fromParsedEvent(e)));
}
function textContents(node) {
if (node.children.length !== 1 || !(node.children[0] instanceof Text4)) {
return null;
} else {
return node.children[0].value;
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/view/template.mjs
var LEADING_TRIVIA_CHARS = [" ", "\n", "\r", " "];
function parseTemplate(template2, templateUrl, options = {}) {
var _a2, _b2, _c2;
const { interpolationConfig, preserveWhitespaces, enableI18nLegacyMessageIdFormat, allowInvalidAssignmentEvents } = options;
const bindingParser = makeBindingParser(interpolationConfig, allowInvalidAssignmentEvents);
const htmlParser = new HtmlParser();
const parseResult = htmlParser.parse(template2, templateUrl, __spreadProps(__spreadValues({
leadingTriviaChars: LEADING_TRIVIA_CHARS
}, options), {
tokenizeExpansionForms: true,
tokenizeBlocks: (_a2 = options.enableBlockSyntax) != null ? _a2 : true,
tokenizeLet: (_b2 = options.enableLetSyntax) != null ? _b2 : true
}));
if (!options.alwaysAttemptHtmlToR3AstConversion && parseResult.errors && parseResult.errors.length > 0) {
const parsedTemplate2 = {
interpolationConfig,
preserveWhitespaces,
errors: parseResult.errors,
nodes: [],
styleUrls: [],
styles: [],
ngContentSelectors: []
};
if (options.collectCommentNodes) {
parsedTemplate2.commentNodes = [];
}
return parsedTemplate2;
}
let rootNodes = parseResult.rootNodes;
const retainEmptyTokens = !((_c2 = options.preserveSignificantWhitespace) != null ? _c2 : true);
const i18nMetaVisitor = new I18nMetaVisitor(
interpolationConfig,
!preserveWhitespaces,
enableI18nLegacyMessageIdFormat,
void 0,
options.preserveSignificantWhitespace,
retainEmptyTokens
);
const i18nMetaResult = i18nMetaVisitor.visitAllWithErrors(rootNodes);
if (!options.alwaysAttemptHtmlToR3AstConversion && i18nMetaResult.errors && i18nMetaResult.errors.length > 0) {
const parsedTemplate2 = {
interpolationConfig,
preserveWhitespaces,
errors: i18nMetaResult.errors,
nodes: [],
styleUrls: [],
styles: [],
ngContentSelectors: []
};
if (options.collectCommentNodes) {
parsedTemplate2.commentNodes = [];
}
return parsedTemplate2;
}
rootNodes = i18nMetaResult.rootNodes;
if (!preserveWhitespaces) {
rootNodes = visitAll2(new WhitespaceVisitor(
true,
void 0,
false
), rootNodes);
if (i18nMetaVisitor.hasI18nMeta) {
rootNodes = visitAll2(new I18nMetaVisitor(
interpolationConfig,
false,
void 0,
void 0,
true,
retainEmptyTokens
), rootNodes);
}
}
const { nodes, errors, styleUrls, styles, ngContentSelectors, commentNodes } = htmlAstToRender3Ast(rootNodes, bindingParser, { collectCommentNodes: !!options.collectCommentNodes });
errors.push(...parseResult.errors, ...i18nMetaResult.errors);
const parsedTemplate = {
interpolationConfig,
preserveWhitespaces,
errors: errors.length > 0 ? errors : null,
nodes,
styleUrls,
styles,
ngContentSelectors
};
if (options.collectCommentNodes) {
parsedTemplate.commentNodes = commentNodes;
}
return parsedTemplate;
}
var elementRegistry = new DomElementSchemaRegistry();
function makeBindingParser(interpolationConfig = DEFAULT_INTERPOLATION_CONFIG, allowInvalidAssignmentEvents = false) {
return new BindingParser(new Parser2(new Lexer()), interpolationConfig, elementRegistry, [], allowInvalidAssignmentEvents);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/view/compiler.mjs
var COMPONENT_VARIABLE = "%COMP%";
var HOST_ATTR = `_nghost-${COMPONENT_VARIABLE}`;
var CONTENT_ATTR = `_ngcontent-${COMPONENT_VARIABLE}`;
function baseDirectiveFields(meta, constantPool, bindingParser) {
const definitionMap = new DefinitionMap();
const selectors = parseSelectorToR3Selector(meta.selector);
definitionMap.set("type", meta.type.value);
if (selectors.length > 0) {
definitionMap.set("selectors", asLiteral(selectors));
}
if (meta.queries.length > 0) {
definitionMap.set("contentQueries", createContentQueriesFunction(meta.queries, constantPool, meta.name));
}
if (meta.viewQueries.length) {
definitionMap.set("viewQuery", createViewQueriesFunction(meta.viewQueries, constantPool, meta.name));
}
definitionMap.set("hostBindings", createHostBindingsFunction(meta.host, meta.typeSourceSpan, bindingParser, constantPool, meta.selector || "", meta.name, definitionMap));
definitionMap.set("inputs", conditionallyCreateDirectiveBindingLiteral(meta.inputs, true));
definitionMap.set("outputs", conditionallyCreateDirectiveBindingLiteral(meta.outputs));
if (meta.exportAs !== null) {
definitionMap.set("exportAs", literalArr(meta.exportAs.map((e) => literal(e))));
}
if (meta.isStandalone) {
definitionMap.set("standalone", literal(true));
}
if (meta.isSignal) {
definitionMap.set("signals", literal(true));
}
return definitionMap;
}
function addFeatures(definitionMap, meta) {
var _a2;
const features = [];
const providers = meta.providers;
const viewProviders = meta.viewProviders;
const inputKeys = Object.keys(meta.inputs);
if (providers || viewProviders) {
const args = [providers || new LiteralArrayExpr([])];
if (viewProviders) {
args.push(viewProviders);
}
features.push(importExpr(Identifiers.ProvidersFeature).callFn(args));
}
for (const key of inputKeys) {
if (meta.inputs[key].transformFunction !== null) {
features.push(importExpr(Identifiers.InputTransformsFeatureFeature));
break;
}
}
if ((_a2 = meta.hostDirectives) == null ? void 0 : _a2.length) {
features.push(importExpr(Identifiers.HostDirectivesFeature).callFn([createHostDirectivesFeatureArg(meta.hostDirectives)]));
}
if (meta.usesInheritance) {
features.push(importExpr(Identifiers.InheritDefinitionFeature));
}
if (meta.fullInheritance) {
features.push(importExpr(Identifiers.CopyDefinitionFeature));
}
if (meta.lifecycle.usesOnChanges) {
features.push(importExpr(Identifiers.NgOnChangesFeature));
}
if (meta.hasOwnProperty("template") && meta.isStandalone) {
features.push(importExpr(Identifiers.StandaloneFeature));
}
if (features.length) {
definitionMap.set("features", literalArr(features));
}
}
function compileDirectiveFromMetadata(meta, constantPool, bindingParser) {
const definitionMap = baseDirectiveFields(meta, constantPool, bindingParser);
addFeatures(definitionMap, meta);
const expression = importExpr(Identifiers.defineDirective).callFn([definitionMap.toLiteralMap()], void 0, true);
const type = createDirectiveType(meta);
return { expression, type, statements: [] };
}
function compileComponentFromMetadata(meta, constantPool, bindingParser) {
const definitionMap = baseDirectiveFields(meta, constantPool, bindingParser);
addFeatures(definitionMap, meta);
const selector = meta.selector && CssSelector.parse(meta.selector);
const firstSelector = selector && selector[0];
if (firstSelector) {
const selectorAttributes = firstSelector.getAttrs();
if (selectorAttributes.length) {
definitionMap.set("attrs", constantPool.getConstLiteral(
literalArr(selectorAttributes.map((value) => value != null ? literal(value) : literal(void 0))),
true
));
}
}
const templateTypeName = meta.name;
let allDeferrableDepsFn = null;
if (meta.defer.mode === 1 && meta.defer.dependenciesFn !== null) {
const fnName = `${templateTypeName}_DeferFn`;
constantPool.statements.push(new DeclareVarStmt(fnName, meta.defer.dependenciesFn, void 0, StmtModifier.Final));
allDeferrableDepsFn = variable(fnName);
}
const tpl = ingestComponent(meta.name, meta.template.nodes, constantPool, meta.relativeContextFilePath, meta.i18nUseExternalIds, meta.defer, allDeferrableDepsFn);
transform(tpl, CompilationJobKind.Tmpl);
const templateFn = emitTemplateFn(tpl, constantPool);
if (tpl.contentSelectors !== null) {
definitionMap.set("ngContentSelectors", tpl.contentSelectors);
}
definitionMap.set("decls", literal(tpl.root.decls));
definitionMap.set("vars", literal(tpl.root.vars));
if (tpl.consts.length > 0) {
if (tpl.constsInitializers.length > 0) {
definitionMap.set("consts", arrowFn([], [...tpl.constsInitializers, new ReturnStatement(literalArr(tpl.consts))]));
} else {
definitionMap.set("consts", literalArr(tpl.consts));
}
}
definitionMap.set("template", templateFn);
if (meta.declarationListEmitMode !== 3 && meta.declarations.length > 0) {
definitionMap.set("dependencies", compileDeclarationList(literalArr(meta.declarations.map((decl) => decl.type)), meta.declarationListEmitMode));
} else if (meta.declarationListEmitMode === 3) {
const args = [meta.type.value];
if (meta.rawImports) {
args.push(meta.rawImports);
}
definitionMap.set("dependencies", importExpr(Identifiers.getComponentDepsFactory).callFn(args));
}
if (meta.encapsulation === null) {
meta.encapsulation = ViewEncapsulation.Emulated;
}
if (meta.styles && meta.styles.length) {
const styleValues = meta.encapsulation == ViewEncapsulation.Emulated ? compileStyles(meta.styles, CONTENT_ATTR, HOST_ATTR) : meta.styles;
const styleNodes = styleValues.reduce((result, style) => {
if (style.trim().length > 0) {
result.push(constantPool.getConstLiteral(literal(style)));
}
return result;
}, []);
if (styleNodes.length > 0) {
definitionMap.set("styles", literalArr(styleNodes));
}
} else if (meta.encapsulation === ViewEncapsulation.Emulated) {
meta.encapsulation = ViewEncapsulation.None;
}
if (meta.encapsulation !== ViewEncapsulation.Emulated) {
definitionMap.set("encapsulation", literal(meta.encapsulation));
}
if (meta.animations !== null) {
definitionMap.set("data", literalMap([{ key: "animation", value: meta.animations, quoted: false }]));
}
if (meta.changeDetection !== null) {
if (typeof meta.changeDetection === "number" && meta.changeDetection !== ChangeDetectionStrategy.Default) {
definitionMap.set("changeDetection", literal(meta.changeDetection));
} else if (typeof meta.changeDetection === "object") {
definitionMap.set("changeDetection", meta.changeDetection);
}
}
const expression = importExpr(Identifiers.defineComponent).callFn([definitionMap.toLiteralMap()], void 0, true);
const type = createComponentType(meta);
return { expression, type, statements: [] };
}
function createComponentType(meta) {
const typeParams = createBaseDirectiveTypeParams(meta);
typeParams.push(stringArrayAsType(meta.template.ngContentSelectors));
typeParams.push(expressionType(literal(meta.isStandalone)));
typeParams.push(createHostDirectivesType(meta));
if (meta.isSignal) {
typeParams.push(expressionType(literal(meta.isSignal)));
}
return expressionType(importExpr(Identifiers.ComponentDeclaration, typeParams));
}
function compileDeclarationList(list, mode) {
switch (mode) {
case 0:
return list;
case 1:
return arrowFn([], list);
case 2:
const resolvedList = list.prop("map").callFn([importExpr(Identifiers.resolveForwardRef)]);
return arrowFn([], resolvedList);
case 3:
throw new Error(`Unsupported with an array of pre-resolved dependencies`);
}
}
function stringAsType(str) {
return expressionType(literal(str));
}
function stringMapAsLiteralExpression(map) {
const mapValues = Object.keys(map).map((key) => {
const value = Array.isArray(map[key]) ? map[key][0] : map[key];
return {
key,
value: literal(value),
quoted: true
};
});
return literalMap(mapValues);
}
function stringArrayAsType(arr) {
return arr.length > 0 ? expressionType(literalArr(arr.map((value) => literal(value)))) : NONE_TYPE;
}
function createBaseDirectiveTypeParams(meta) {
const selectorForType = meta.selector !== null ? meta.selector.replace(/\n/g, "") : null;
return [
typeWithParameters(meta.type.type, meta.typeArgumentCount),
selectorForType !== null ? stringAsType(selectorForType) : NONE_TYPE,
meta.exportAs !== null ? stringArrayAsType(meta.exportAs) : NONE_TYPE,
expressionType(getInputsTypeExpression(meta)),
expressionType(stringMapAsLiteralExpression(meta.outputs)),
stringArrayAsType(meta.queries.map((q) => q.propertyName))
];
}
function getInputsTypeExpression(meta) {
return literalMap(Object.keys(meta.inputs).map((key) => {
const value = meta.inputs[key];
const values = [
{ key: "alias", value: literal(value.bindingPropertyName), quoted: true },
{ key: "required", value: literal(value.required), quoted: true }
];
if (value.isSignal) {
values.push({ key: "isSignal", value: literal(value.isSignal), quoted: true });
}
return { key, value: literalMap(values), quoted: true };
}));
}
function createDirectiveType(meta) {
const typeParams = createBaseDirectiveTypeParams(meta);
typeParams.push(NONE_TYPE);
typeParams.push(expressionType(literal(meta.isStandalone)));
typeParams.push(createHostDirectivesType(meta));
if (meta.isSignal) {
typeParams.push(expressionType(literal(meta.isSignal)));
}
return expressionType(importExpr(Identifiers.DirectiveDeclaration, typeParams));
}
function createHostBindingsFunction(hostBindingsMetadata, typeSourceSpan, bindingParser, constantPool, selector, name, definitionMap) {
const bindings = bindingParser.createBoundHostProperties(hostBindingsMetadata.properties, typeSourceSpan);
const eventBindings = bindingParser.createDirectiveHostEventAsts(hostBindingsMetadata.listeners, typeSourceSpan);
if (hostBindingsMetadata.specialAttributes.styleAttr) {
hostBindingsMetadata.attributes["style"] = literal(hostBindingsMetadata.specialAttributes.styleAttr);
}
if (hostBindingsMetadata.specialAttributes.classAttr) {
hostBindingsMetadata.attributes["class"] = literal(hostBindingsMetadata.specialAttributes.classAttr);
}
const hostJob = ingestHostBinding({
componentName: name,
componentSelector: selector,
properties: bindings,
events: eventBindings,
attributes: hostBindingsMetadata.attributes
}, bindingParser, constantPool);
transform(hostJob, CompilationJobKind.Host);
definitionMap.set("hostAttrs", hostJob.root.attributes);
const varCount = hostJob.root.vars;
if (varCount !== null && varCount > 0) {
definitionMap.set("hostVars", literal(varCount));
}
return emitHostBindingFunction(hostJob);
}
var HOST_REG_EXP = /^(?:\[([^\]]+)\])|(?:\(([^\)]+)\))$/;
function parseHostBindings(host) {
const attributes = {};
const listeners = {};
const properties = {};
const specialAttributes = {};
for (const key of Object.keys(host)) {
const value = host[key];
const matches = key.match(HOST_REG_EXP);
if (matches === null) {
switch (key) {
case "class":
if (typeof value !== "string") {
throw new Error(`Class binding must be string`);
}
specialAttributes.classAttr = value;
break;
case "style":
if (typeof value !== "string") {
throw new Error(`Style binding must be string`);
}
specialAttributes.styleAttr = value;
break;
default:
if (typeof value === "string") {
attributes[key] = literal(value);
} else {
attributes[key] = value;
}
}
} else if (matches[1] != null) {
if (typeof value !== "string") {
throw new Error(`Property binding must be string`);
}
properties[matches[1]] = value;
} else if (matches[2] != null) {
if (typeof value !== "string") {
throw new Error(`Event binding must be string`);
}
listeners[matches[2]] = value;
}
}
return { attributes, listeners, properties, specialAttributes };
}
function verifyHostBindings(bindings, sourceSpan) {
const bindingParser = makeBindingParser();
bindingParser.createDirectiveHostEventAsts(bindings.listeners, sourceSpan);
bindingParser.createBoundHostProperties(bindings.properties, sourceSpan);
return bindingParser.errors;
}
function compileStyles(styles, selector, hostSelector) {
const shadowCss = new ShadowCss();
return styles.map((style) => {
return shadowCss.shimCssText(style, selector, hostSelector);
});
}
function createHostDirectivesType(meta) {
var _a2;
if (!((_a2 = meta.hostDirectives) == null ? void 0 : _a2.length)) {
return NONE_TYPE;
}
return expressionType(literalArr(meta.hostDirectives.map((hostMeta) => literalMap([
{ key: "directive", value: typeofExpr(hostMeta.directive.type), quoted: false },
{
key: "inputs",
value: stringMapAsLiteralExpression(hostMeta.inputs || {}),
quoted: false
},
{
key: "outputs",
value: stringMapAsLiteralExpression(hostMeta.outputs || {}),
quoted: false
}
]))));
}
function createHostDirectivesFeatureArg(hostDirectives) {
const expressions = [];
let hasForwardRef = false;
for (const current of hostDirectives) {
if (!current.inputs && !current.outputs) {
expressions.push(current.directive.type);
} else {
const keys = [{ key: "directive", value: current.directive.type, quoted: false }];
if (current.inputs) {
const inputsLiteral = createHostDirectivesMappingArray(current.inputs);
if (inputsLiteral) {
keys.push({ key: "inputs", value: inputsLiteral, quoted: false });
}
}
if (current.outputs) {
const outputsLiteral = createHostDirectivesMappingArray(current.outputs);
if (outputsLiteral) {
keys.push({ key: "outputs", value: outputsLiteral, quoted: false });
}
}
expressions.push(literalMap(keys));
}
if (current.isForwardReference) {
hasForwardRef = true;
}
}
return hasForwardRef ? new FunctionExpr([], [new ReturnStatement(literalArr(expressions))]) : literalArr(expressions);
}
function createHostDirectivesMappingArray(mapping) {
const elements = [];
for (const publicName in mapping) {
if (mapping.hasOwnProperty(publicName)) {
elements.push(literal(publicName), literal(mapping[publicName]));
}
}
return elements.length > 0 ? literalArr(elements) : null;
}
function compileDeferResolverFunction(meta) {
const depExpressions = [];
if (meta.mode === 0) {
for (const dep of meta.dependencies) {
if (dep.isDeferrable) {
const innerFn = arrowFn(
[new FnParam("m", DYNAMIC_TYPE)],
variable("m").prop(dep.isDefaultImport ? "default" : dep.symbolName)
);
const importExpr2 = new DynamicImportExpr(dep.importPath).prop("then").callFn([innerFn]);
depExpressions.push(importExpr2);
} else {
depExpressions.push(dep.typeReference);
}
}
} else {
for (const { symbolName, importPath, isDefaultImport: isDefaultImport2 } of meta.dependencies) {
const innerFn = arrowFn([new FnParam("m", DYNAMIC_TYPE)], variable("m").prop(isDefaultImport2 ? "default" : symbolName));
const importExpr2 = new DynamicImportExpr(importPath).prop("then").callFn([innerFn]);
depExpressions.push(importExpr2);
}
}
return arrowFn([], literalArr(depExpressions));
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/view/t2_binder.mjs
var R3TargetBinder = class {
constructor(directiveMatcher) {
this.directiveMatcher = directiveMatcher;
}
bind(target) {
if (!target.template) {
throw new Error("Binding without a template not yet supported");
}
const scope = Scope2.apply(target.template);
const scopedNodeEntities = extractScopedNodeEntities(scope);
const { directives, eagerDirectives, bindings, references } = DirectiveBinder.apply(target.template, this.directiveMatcher);
const { expressions, symbols, nestingLevel, usedPipes, eagerPipes, deferBlocks } = TemplateBinder.applyWithScope(target.template, scope);
return new R3BoundTarget(target, directives, eagerDirectives, bindings, references, expressions, symbols, nestingLevel, scopedNodeEntities, usedPipes, eagerPipes, deferBlocks);
}
};
var Scope2 = class {
constructor(parentScope, rootNode) {
this.parentScope = parentScope;
this.rootNode = rootNode;
this.namedEntities = /* @__PURE__ */ new Map();
this.elementsInScope = /* @__PURE__ */ new Set();
this.childScopes = /* @__PURE__ */ new Map();
this.isDeferred = parentScope !== null && parentScope.isDeferred ? true : rootNode instanceof DeferredBlock;
}
static newRootScope() {
return new Scope2(null, null);
}
static apply(template2) {
const scope = Scope2.newRootScope();
scope.ingest(template2);
return scope;
}
ingest(nodeOrNodes) {
if (nodeOrNodes instanceof Template) {
nodeOrNodes.variables.forEach((node) => this.visitVariable(node));
nodeOrNodes.children.forEach((node) => node.visit(this));
} else if (nodeOrNodes instanceof IfBlockBranch) {
if (nodeOrNodes.expressionAlias !== null) {
this.visitVariable(nodeOrNodes.expressionAlias);
}
nodeOrNodes.children.forEach((node) => node.visit(this));
} else if (nodeOrNodes instanceof ForLoopBlock) {
this.visitVariable(nodeOrNodes.item);
nodeOrNodes.contextVariables.forEach((v) => this.visitVariable(v));
nodeOrNodes.children.forEach((node) => node.visit(this));
} else if (nodeOrNodes instanceof SwitchBlockCase || nodeOrNodes instanceof ForLoopBlockEmpty || nodeOrNodes instanceof DeferredBlock || nodeOrNodes instanceof DeferredBlockError || nodeOrNodes instanceof DeferredBlockPlaceholder || nodeOrNodes instanceof DeferredBlockLoading || nodeOrNodes instanceof Content) {
nodeOrNodes.children.forEach((node) => node.visit(this));
} else {
nodeOrNodes.forEach((node) => node.visit(this));
}
}
visitElement(element2) {
element2.references.forEach((node) => this.visitReference(node));
element2.children.forEach((node) => node.visit(this));
this.elementsInScope.add(element2);
}
visitTemplate(template2) {
template2.references.forEach((node) => this.visitReference(node));
this.ingestScopedNode(template2);
}
visitVariable(variable2) {
this.maybeDeclare(variable2);
}
visitReference(reference2) {
this.maybeDeclare(reference2);
}
visitDeferredBlock(deferred) {
var _a2, _b2, _c2;
this.ingestScopedNode(deferred);
(_a2 = deferred.placeholder) == null ? void 0 : _a2.visit(this);
(_b2 = deferred.loading) == null ? void 0 : _b2.visit(this);
(_c2 = deferred.error) == null ? void 0 : _c2.visit(this);
}
visitDeferredBlockPlaceholder(block) {
this.ingestScopedNode(block);
}
visitDeferredBlockError(block) {
this.ingestScopedNode(block);
}
visitDeferredBlockLoading(block) {
this.ingestScopedNode(block);
}
visitSwitchBlock(block) {
block.cases.forEach((node) => node.visit(this));
}
visitSwitchBlockCase(block) {
this.ingestScopedNode(block);
}
visitForLoopBlock(block) {
var _a2;
this.ingestScopedNode(block);
(_a2 = block.empty) == null ? void 0 : _a2.visit(this);
}
visitForLoopBlockEmpty(block) {
this.ingestScopedNode(block);
}
visitIfBlock(block) {
block.branches.forEach((node) => node.visit(this));
}
visitIfBlockBranch(block) {
this.ingestScopedNode(block);
}
visitContent(content) {
this.ingestScopedNode(content);
}
visitLetDeclaration(decl) {
this.maybeDeclare(decl);
}
visitBoundAttribute(attr) {
}
visitBoundEvent(event) {
}
visitBoundText(text2) {
}
visitText(text2) {
}
visitTextAttribute(attr) {
}
visitIcu(icu) {
}
visitDeferredTrigger(trigger) {
}
visitUnknownBlock(block) {
}
maybeDeclare(thing) {
if (!this.namedEntities.has(thing.name)) {
this.namedEntities.set(thing.name, thing);
}
}
lookup(name) {
if (this.namedEntities.has(name)) {
return this.namedEntities.get(name);
} else if (this.parentScope !== null) {
return this.parentScope.lookup(name);
} else {
return null;
}
}
getChildScope(node) {
const res = this.childScopes.get(node);
if (res === void 0) {
throw new Error(`Assertion error: child scope for ${node} not found`);
}
return res;
}
ingestScopedNode(node) {
const scope = new Scope2(this, node);
scope.ingest(node);
this.childScopes.set(node, scope);
}
};
var DirectiveBinder = class {
constructor(matcher, directives, eagerDirectives, bindings, references) {
this.matcher = matcher;
this.directives = directives;
this.eagerDirectives = eagerDirectives;
this.bindings = bindings;
this.references = references;
this.isInDeferBlock = false;
}
static apply(template2, selectorMatcher) {
const directives = /* @__PURE__ */ new Map();
const bindings = /* @__PURE__ */ new Map();
const references = /* @__PURE__ */ new Map();
const eagerDirectives = [];
const matcher = new DirectiveBinder(selectorMatcher, directives, eagerDirectives, bindings, references);
matcher.ingest(template2);
return { directives, eagerDirectives, bindings, references };
}
ingest(template2) {
template2.forEach((node) => node.visit(this));
}
visitElement(element2) {
this.visitElementOrTemplate(element2);
}
visitTemplate(template2) {
this.visitElementOrTemplate(template2);
}
visitElementOrTemplate(node) {
const cssSelector = createCssSelectorFromNode(node);
const directives = [];
this.matcher.match(cssSelector, (_selector, results) => directives.push(...results));
if (directives.length > 0) {
this.directives.set(node, directives);
if (!this.isInDeferBlock) {
this.eagerDirectives.push(...directives);
}
}
node.references.forEach((ref) => {
let dirTarget = null;
if (ref.value.trim() === "") {
dirTarget = directives.find((dir) => dir.isComponent) || null;
} else {
dirTarget = directives.find((dir) => dir.exportAs !== null && dir.exportAs.some((value) => value === ref.value)) || null;
if (dirTarget === null) {
return;
}
}
if (dirTarget !== null) {
this.references.set(ref, { directive: dirTarget, node });
} else {
this.references.set(ref, node);
}
});
const setAttributeBinding = (attribute2, ioType) => {
const dir = directives.find((dir2) => dir2[ioType].hasBindingPropertyName(attribute2.name));
const binding = dir !== void 0 ? dir : node;
this.bindings.set(attribute2, binding);
};
node.inputs.forEach((input) => setAttributeBinding(input, "inputs"));
node.attributes.forEach((attr) => setAttributeBinding(attr, "inputs"));
if (node instanceof Template) {
node.templateAttrs.forEach((attr) => setAttributeBinding(attr, "inputs"));
}
node.outputs.forEach((output) => setAttributeBinding(output, "outputs"));
node.children.forEach((child) => child.visit(this));
}
visitDeferredBlock(deferred) {
var _a2, _b2, _c2;
const wasInDeferBlock = this.isInDeferBlock;
this.isInDeferBlock = true;
deferred.children.forEach((child) => child.visit(this));
this.isInDeferBlock = wasInDeferBlock;
(_a2 = deferred.placeholder) == null ? void 0 : _a2.visit(this);
(_b2 = deferred.loading) == null ? void 0 : _b2.visit(this);
(_c2 = deferred.error) == null ? void 0 : _c2.visit(this);
}
visitDeferredBlockPlaceholder(block) {
block.children.forEach((child) => child.visit(this));
}
visitDeferredBlockError(block) {
block.children.forEach((child) => child.visit(this));
}
visitDeferredBlockLoading(block) {
block.children.forEach((child) => child.visit(this));
}
visitSwitchBlock(block) {
block.cases.forEach((node) => node.visit(this));
}
visitSwitchBlockCase(block) {
block.children.forEach((node) => node.visit(this));
}
visitForLoopBlock(block) {
var _a2;
block.item.visit(this);
block.contextVariables.forEach((v) => v.visit(this));
block.children.forEach((node) => node.visit(this));
(_a2 = block.empty) == null ? void 0 : _a2.visit(this);
}
visitForLoopBlockEmpty(block) {
block.children.forEach((node) => node.visit(this));
}
visitIfBlock(block) {
block.branches.forEach((node) => node.visit(this));
}
visitIfBlockBranch(block) {
var _a2;
(_a2 = block.expressionAlias) == null ? void 0 : _a2.visit(this);
block.children.forEach((node) => node.visit(this));
}
visitContent(content) {
content.children.forEach((child) => child.visit(this));
}
visitVariable(variable2) {
}
visitReference(reference2) {
}
visitTextAttribute(attribute2) {
}
visitBoundAttribute(attribute2) {
}
visitBoundEvent(attribute2) {
}
visitBoundAttributeOrEvent(node) {
}
visitText(text2) {
}
visitBoundText(text2) {
}
visitIcu(icu) {
}
visitDeferredTrigger(trigger) {
}
visitUnknownBlock(block) {
}
visitLetDeclaration(decl) {
}
};
var TemplateBinder = class extends RecursiveAstVisitor2 {
constructor(bindings, symbols, usedPipes, eagerPipes, deferBlocks, nestingLevel, scope, rootNode, level) {
super();
this.bindings = bindings;
this.symbols = symbols;
this.usedPipes = usedPipes;
this.eagerPipes = eagerPipes;
this.deferBlocks = deferBlocks;
this.nestingLevel = nestingLevel;
this.scope = scope;
this.rootNode = rootNode;
this.level = level;
this.visitNode = (node) => node.visit(this);
}
visit(node, context) {
if (node instanceof AST) {
node.visit(this, context);
} else {
node.visit(this);
}
}
static applyWithScope(nodes, scope) {
const expressions = /* @__PURE__ */ new Map();
const symbols = /* @__PURE__ */ new Map();
const nestingLevel = /* @__PURE__ */ new Map();
const usedPipes = /* @__PURE__ */ new Set();
const eagerPipes = /* @__PURE__ */ new Set();
const template2 = nodes instanceof Template ? nodes : null;
const deferBlocks = [];
const binder = new TemplateBinder(expressions, symbols, usedPipes, eagerPipes, deferBlocks, nestingLevel, scope, template2, 0);
binder.ingest(nodes);
return { expressions, symbols, nestingLevel, usedPipes, eagerPipes, deferBlocks };
}
ingest(nodeOrNodes) {
if (nodeOrNodes instanceof Template) {
nodeOrNodes.variables.forEach(this.visitNode);
nodeOrNodes.children.forEach(this.visitNode);
this.nestingLevel.set(nodeOrNodes, this.level);
} else if (nodeOrNodes instanceof IfBlockBranch) {
if (nodeOrNodes.expressionAlias !== null) {
this.visitNode(nodeOrNodes.expressionAlias);
}
nodeOrNodes.children.forEach(this.visitNode);
this.nestingLevel.set(nodeOrNodes, this.level);
} else if (nodeOrNodes instanceof ForLoopBlock) {
this.visitNode(nodeOrNodes.item);
nodeOrNodes.contextVariables.forEach((v) => this.visitNode(v));
nodeOrNodes.trackBy.visit(this);
nodeOrNodes.children.forEach(this.visitNode);
this.nestingLevel.set(nodeOrNodes, this.level);
} else if (nodeOrNodes instanceof DeferredBlock) {
if (this.scope.rootNode !== nodeOrNodes) {
throw new Error(`Assertion error: resolved incorrect scope for deferred block ${nodeOrNodes}`);
}
this.deferBlocks.push([nodeOrNodes, this.scope]);
nodeOrNodes.children.forEach((node) => node.visit(this));
this.nestingLevel.set(nodeOrNodes, this.level);
} else if (nodeOrNodes instanceof SwitchBlockCase || nodeOrNodes instanceof ForLoopBlockEmpty || nodeOrNodes instanceof DeferredBlockError || nodeOrNodes instanceof DeferredBlockPlaceholder || nodeOrNodes instanceof DeferredBlockLoading || nodeOrNodes instanceof Content) {
nodeOrNodes.children.forEach((node) => node.visit(this));
this.nestingLevel.set(nodeOrNodes, this.level);
} else {
nodeOrNodes.forEach(this.visitNode);
}
}
visitElement(element2) {
element2.inputs.forEach(this.visitNode);
element2.outputs.forEach(this.visitNode);
element2.children.forEach(this.visitNode);
element2.references.forEach(this.visitNode);
}
visitTemplate(template2) {
template2.inputs.forEach(this.visitNode);
template2.outputs.forEach(this.visitNode);
template2.templateAttrs.forEach(this.visitNode);
template2.references.forEach(this.visitNode);
this.ingestScopedNode(template2);
}
visitVariable(variable2) {
if (this.rootNode !== null) {
this.symbols.set(variable2, this.rootNode);
}
}
visitReference(reference2) {
if (this.rootNode !== null) {
this.symbols.set(reference2, this.rootNode);
}
}
visitText(text2) {
}
visitTextAttribute(attribute2) {
}
visitUnknownBlock(block) {
}
visitDeferredTrigger() {
}
visitIcu(icu) {
Object.keys(icu.vars).forEach((key) => icu.vars[key].visit(this));
Object.keys(icu.placeholders).forEach((key) => icu.placeholders[key].visit(this));
}
visitBoundAttribute(attribute2) {
attribute2.value.visit(this);
}
visitBoundEvent(event) {
event.handler.visit(this);
}
visitDeferredBlock(deferred) {
var _a2, _b2;
this.ingestScopedNode(deferred);
(_a2 = deferred.triggers.when) == null ? void 0 : _a2.value.visit(this);
(_b2 = deferred.prefetchTriggers.when) == null ? void 0 : _b2.value.visit(this);
deferred.placeholder && this.visitNode(deferred.placeholder);
deferred.loading && this.visitNode(deferred.loading);
deferred.error && this.visitNode(deferred.error);
}
visitDeferredBlockPlaceholder(block) {
this.ingestScopedNode(block);
}
visitDeferredBlockError(block) {
this.ingestScopedNode(block);
}
visitDeferredBlockLoading(block) {
this.ingestScopedNode(block);
}
visitSwitchBlock(block) {
block.expression.visit(this);
block.cases.forEach(this.visitNode);
}
visitSwitchBlockCase(block) {
var _a2;
(_a2 = block.expression) == null ? void 0 : _a2.visit(this);
this.ingestScopedNode(block);
}
visitForLoopBlock(block) {
var _a2;
block.expression.visit(this);
this.ingestScopedNode(block);
(_a2 = block.empty) == null ? void 0 : _a2.visit(this);
}
visitForLoopBlockEmpty(block) {
this.ingestScopedNode(block);
}
visitIfBlock(block) {
block.branches.forEach((node) => node.visit(this));
}
visitIfBlockBranch(block) {
var _a2;
(_a2 = block.expression) == null ? void 0 : _a2.visit(this);
this.ingestScopedNode(block);
}
visitContent(content) {
this.ingestScopedNode(content);
}
visitBoundText(text2) {
text2.value.visit(this);
}
visitLetDeclaration(decl) {
decl.value.visit(this);
if (this.rootNode !== null) {
this.symbols.set(decl, this.rootNode);
}
}
visitPipe(ast, context) {
this.usedPipes.add(ast.name);
if (!this.scope.isDeferred) {
this.eagerPipes.add(ast.name);
}
return super.visitPipe(ast, context);
}
visitPropertyRead(ast, context) {
this.maybeMap(ast, ast.name);
return super.visitPropertyRead(ast, context);
}
visitSafePropertyRead(ast, context) {
this.maybeMap(ast, ast.name);
return super.visitSafePropertyRead(ast, context);
}
visitPropertyWrite(ast, context) {
this.maybeMap(ast, ast.name);
return super.visitPropertyWrite(ast, context);
}
ingestScopedNode(node) {
const childScope = this.scope.getChildScope(node);
const binder = new TemplateBinder(this.bindings, this.symbols, this.usedPipes, this.eagerPipes, this.deferBlocks, this.nestingLevel, childScope, node, this.level + 1);
binder.ingest(node);
}
maybeMap(ast, name) {
if (!(ast.receiver instanceof ImplicitReceiver)) {
return;
}
const target = this.scope.lookup(name);
if (target instanceof LetDeclaration && ast.receiver instanceof ThisReceiver) {
return;
}
if (target !== null) {
this.bindings.set(ast, target);
}
}
};
var R3BoundTarget = class {
constructor(target, directives, eagerDirectives, bindings, references, exprTargets, symbols, nestingLevel, scopedNodeEntities, usedPipes, eagerPipes, rawDeferred) {
this.target = target;
this.directives = directives;
this.eagerDirectives = eagerDirectives;
this.bindings = bindings;
this.references = references;
this.exprTargets = exprTargets;
this.symbols = symbols;
this.nestingLevel = nestingLevel;
this.scopedNodeEntities = scopedNodeEntities;
this.usedPipes = usedPipes;
this.eagerPipes = eagerPipes;
this.deferredBlocks = rawDeferred.map((current) => current[0]);
this.deferredScopes = new Map(rawDeferred);
}
getEntitiesInScope(node) {
var _a2;
return (_a2 = this.scopedNodeEntities.get(node)) != null ? _a2 : /* @__PURE__ */ new Set();
}
getDirectivesOfNode(node) {
return this.directives.get(node) || null;
}
getReferenceTarget(ref) {
return this.references.get(ref) || null;
}
getConsumerOfBinding(binding) {
return this.bindings.get(binding) || null;
}
getExpressionTarget(expr) {
return this.exprTargets.get(expr) || null;
}
getDefinitionNodeOfSymbol(symbol) {
return this.symbols.get(symbol) || null;
}
getNestingLevel(node) {
return this.nestingLevel.get(node) || 0;
}
getUsedDirectives() {
const set = /* @__PURE__ */ new Set();
this.directives.forEach((dirs) => dirs.forEach((dir) => set.add(dir)));
return Array.from(set.values());
}
getEagerlyUsedDirectives() {
const set = new Set(this.eagerDirectives);
return Array.from(set.values());
}
getUsedPipes() {
return Array.from(this.usedPipes);
}
getEagerlyUsedPipes() {
return Array.from(this.eagerPipes);
}
getDeferBlocks() {
return this.deferredBlocks;
}
getDeferredTriggerTarget(block, trigger) {
if (!(trigger instanceof InteractionDeferredTrigger) && !(trigger instanceof ViewportDeferredTrigger) && !(trigger instanceof HoverDeferredTrigger)) {
return null;
}
const name = trigger.reference;
if (name === null) {
let trigger2 = null;
if (block.placeholder !== null) {
for (const child of block.placeholder.children) {
if (child instanceof Comment) {
continue;
}
if (trigger2 !== null) {
return null;
}
if (child instanceof Element) {
trigger2 = child;
}
}
}
return trigger2;
}
const outsideRef = this.findEntityInScope(block, name);
if (outsideRef instanceof Reference && this.getDefinitionNodeOfSymbol(outsideRef) !== block) {
const target = this.getReferenceTarget(outsideRef);
if (target !== null) {
return this.referenceTargetToElement(target);
}
}
if (block.placeholder !== null) {
const refInPlaceholder = this.findEntityInScope(block.placeholder, name);
const targetInPlaceholder = refInPlaceholder instanceof Reference ? this.getReferenceTarget(refInPlaceholder) : null;
if (targetInPlaceholder !== null) {
return this.referenceTargetToElement(targetInPlaceholder);
}
}
return null;
}
isDeferred(element2) {
for (const block of this.deferredBlocks) {
if (!this.deferredScopes.has(block)) {
continue;
}
const stack = [this.deferredScopes.get(block)];
while (stack.length > 0) {
const current = stack.pop();
if (current.elementsInScope.has(element2)) {
return true;
}
stack.push(...current.childScopes.values());
}
}
return false;
}
findEntityInScope(rootNode, name) {
const entities = this.getEntitiesInScope(rootNode);
for (const entity of entities) {
if (entity.name === name) {
return entity;
}
}
return null;
}
referenceTargetToElement(target) {
if (target instanceof Element) {
return target;
}
if (target instanceof Template) {
return null;
}
return this.referenceTargetToElement(target.node);
}
};
function extractScopedNodeEntities(rootScope) {
const entityMap = /* @__PURE__ */ new Map();
function extractScopeEntities(scope) {
if (entityMap.has(scope.rootNode)) {
return entityMap.get(scope.rootNode);
}
const currentEntities = scope.namedEntities;
let entities;
if (scope.parentScope !== null) {
entities = new Map([...extractScopeEntities(scope.parentScope), ...currentEntities]);
} else {
entities = new Map(currentEntities);
}
entityMap.set(scope.rootNode, entities);
return entities;
}
const scopesToProcess = [rootScope];
while (scopesToProcess.length > 0) {
const scope = scopesToProcess.pop();
for (const childScope of scope.childScopes.values()) {
scopesToProcess.push(childScope);
}
extractScopeEntities(scope);
}
const templateEntities = /* @__PURE__ */ new Map();
for (const [template2, entities] of entityMap) {
templateEntities.set(template2, new Set(entities.values()));
}
return templateEntities;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/resource_loader.mjs
var ResourceLoader = class {
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/jit_compiler_facade.mjs
var CompilerFacadeImpl = class {
constructor(jitEvaluator = new JitEvaluator()) {
this.jitEvaluator = jitEvaluator;
this.FactoryTarget = FactoryTarget;
this.ResourceLoader = ResourceLoader;
this.elementSchemaRegistry = new DomElementSchemaRegistry();
}
compilePipe(angularCoreEnv, sourceMapUrl, facade) {
const metadata = {
name: facade.name,
type: wrapReference(facade.type),
typeArgumentCount: 0,
deps: null,
pipeName: facade.pipeName,
pure: facade.pure,
isStandalone: facade.isStandalone
};
const res = compilePipeFromMetadata(metadata);
return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, []);
}
compilePipeDeclaration(angularCoreEnv, sourceMapUrl, declaration) {
const meta = convertDeclarePipeFacadeToMetadata(declaration);
const res = compilePipeFromMetadata(meta);
return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, []);
}
compileInjectable(angularCoreEnv, sourceMapUrl, facade) {
var _a2;
const { expression, statements } = compileInjectable(
{
name: facade.name,
type: wrapReference(facade.type),
typeArgumentCount: facade.typeArgumentCount,
providedIn: computeProvidedIn(facade.providedIn),
useClass: convertToProviderExpression(facade, "useClass"),
useFactory: wrapExpression(facade, "useFactory"),
useValue: convertToProviderExpression(facade, "useValue"),
useExisting: convertToProviderExpression(facade, "useExisting"),
deps: (_a2 = facade.deps) == null ? void 0 : _a2.map(convertR3DependencyMetadata)
},
true
);
return this.jitExpression(expression, angularCoreEnv, sourceMapUrl, statements);
}
compileInjectableDeclaration(angularCoreEnv, sourceMapUrl, facade) {
var _a2;
const { expression, statements } = compileInjectable(
{
name: facade.type.name,
type: wrapReference(facade.type),
typeArgumentCount: 0,
providedIn: computeProvidedIn(facade.providedIn),
useClass: convertToProviderExpression(facade, "useClass"),
useFactory: wrapExpression(facade, "useFactory"),
useValue: convertToProviderExpression(facade, "useValue"),
useExisting: convertToProviderExpression(facade, "useExisting"),
deps: (_a2 = facade.deps) == null ? void 0 : _a2.map(convertR3DeclareDependencyMetadata)
},
true
);
return this.jitExpression(expression, angularCoreEnv, sourceMapUrl, statements);
}
compileInjector(angularCoreEnv, sourceMapUrl, facade) {
const meta = {
name: facade.name,
type: wrapReference(facade.type),
providers: facade.providers && facade.providers.length > 0 ? new WrappedNodeExpr(facade.providers) : null,
imports: facade.imports.map((i) => new WrappedNodeExpr(i))
};
const res = compileInjector(meta);
return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, []);
}
compileInjectorDeclaration(angularCoreEnv, sourceMapUrl, declaration) {
const meta = convertDeclareInjectorFacadeToMetadata(declaration);
const res = compileInjector(meta);
return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, []);
}
compileNgModule(angularCoreEnv, sourceMapUrl, facade) {
const meta = {
kind: R3NgModuleMetadataKind.Global,
type: wrapReference(facade.type),
bootstrap: facade.bootstrap.map(wrapReference),
declarations: facade.declarations.map(wrapReference),
publicDeclarationTypes: null,
imports: facade.imports.map(wrapReference),
includeImportTypes: true,
exports: facade.exports.map(wrapReference),
selectorScopeMode: R3SelectorScopeMode.Inline,
containsForwardDecls: false,
schemas: facade.schemas ? facade.schemas.map(wrapReference) : null,
id: facade.id ? new WrappedNodeExpr(facade.id) : null
};
const res = compileNgModule(meta);
return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, []);
}
compileNgModuleDeclaration(angularCoreEnv, sourceMapUrl, declaration) {
const expression = compileNgModuleDeclarationExpression(declaration);
return this.jitExpression(expression, angularCoreEnv, sourceMapUrl, []);
}
compileDirective(angularCoreEnv, sourceMapUrl, facade) {
const meta = convertDirectiveFacadeToMetadata(facade);
return this.compileDirectiveFromMeta(angularCoreEnv, sourceMapUrl, meta);
}
compileDirectiveDeclaration(angularCoreEnv, sourceMapUrl, declaration) {
const typeSourceSpan = this.createParseSourceSpan("Directive", declaration.type.name, sourceMapUrl);
const meta = convertDeclareDirectiveFacadeToMetadata(declaration, typeSourceSpan);
return this.compileDirectiveFromMeta(angularCoreEnv, sourceMapUrl, meta);
}
compileDirectiveFromMeta(angularCoreEnv, sourceMapUrl, meta) {
const constantPool = new ConstantPool();
const bindingParser = makeBindingParser();
const res = compileDirectiveFromMetadata(meta, constantPool, bindingParser);
return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, constantPool.statements);
}
compileComponent(angularCoreEnv, sourceMapUrl, facade) {
var _a2;
const { template: template2, interpolation, defer: defer2 } = parseJitTemplate(facade.template, facade.name, sourceMapUrl, facade.preserveWhitespaces, facade.interpolation, void 0);
const meta = __spreadProps(__spreadValues(__spreadValues({}, facade), convertDirectiveFacadeToMetadata(facade)), {
selector: facade.selector || this.elementSchemaRegistry.getDefaultComponentElementName(),
template: template2,
declarations: facade.declarations.map(convertDeclarationFacadeToMetadata),
declarationListEmitMode: 0,
defer: defer2,
styles: [...facade.styles, ...template2.styles],
encapsulation: facade.encapsulation,
interpolation,
changeDetection: (_a2 = facade.changeDetection) != null ? _a2 : null,
animations: facade.animations != null ? new WrappedNodeExpr(facade.animations) : null,
viewProviders: facade.viewProviders != null ? new WrappedNodeExpr(facade.viewProviders) : null,
relativeContextFilePath: "",
i18nUseExternalIds: true
});
const jitExpressionSourceMap = `ng:///${facade.name}.js`;
return this.compileComponentFromMeta(angularCoreEnv, jitExpressionSourceMap, meta);
}
compileComponentDeclaration(angularCoreEnv, sourceMapUrl, declaration) {
const typeSourceSpan = this.createParseSourceSpan("Component", declaration.type.name, sourceMapUrl);
const meta = convertDeclareComponentFacadeToMetadata(declaration, typeSourceSpan, sourceMapUrl);
return this.compileComponentFromMeta(angularCoreEnv, sourceMapUrl, meta);
}
compileComponentFromMeta(angularCoreEnv, sourceMapUrl, meta) {
const constantPool = new ConstantPool();
const bindingParser = makeBindingParser(meta.interpolation);
const res = compileComponentFromMetadata(meta, constantPool, bindingParser);
return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, constantPool.statements);
}
compileFactory(angularCoreEnv, sourceMapUrl, meta) {
const factoryRes = compileFactoryFunction({
name: meta.name,
type: wrapReference(meta.type),
typeArgumentCount: meta.typeArgumentCount,
deps: convertR3DependencyMetadataArray(meta.deps),
target: meta.target
});
return this.jitExpression(factoryRes.expression, angularCoreEnv, sourceMapUrl, factoryRes.statements);
}
compileFactoryDeclaration(angularCoreEnv, sourceMapUrl, meta) {
const factoryRes = compileFactoryFunction({
name: meta.type.name,
type: wrapReference(meta.type),
typeArgumentCount: 0,
deps: Array.isArray(meta.deps) ? meta.deps.map(convertR3DeclareDependencyMetadata) : meta.deps,
target: meta.target
});
return this.jitExpression(factoryRes.expression, angularCoreEnv, sourceMapUrl, factoryRes.statements);
}
createParseSourceSpan(kind, typeName, sourceUrl) {
return r3JitTypeSourceSpan(kind, typeName, sourceUrl);
}
jitExpression(def, context, sourceUrl, preStatements) {
const statements = [
...preStatements,
new DeclareVarStmt("$def", def, void 0, StmtModifier.Exported)
];
const res = this.jitEvaluator.evaluateStatements(
sourceUrl,
statements,
new R3JitReflector(context),
true
);
return res["$def"];
}
};
function convertToR3QueryMetadata(facade) {
return __spreadProps(__spreadValues({}, facade), {
isSignal: facade.isSignal,
predicate: convertQueryPredicate(facade.predicate),
read: facade.read ? new WrappedNodeExpr(facade.read) : null,
static: facade.static,
emitDistinctChangesOnly: facade.emitDistinctChangesOnly
});
}
function convertQueryDeclarationToMetadata(declaration) {
var _a2, _b2, _c2, _d2;
return {
propertyName: declaration.propertyName,
first: (_a2 = declaration.first) != null ? _a2 : false,
predicate: convertQueryPredicate(declaration.predicate),
descendants: (_b2 = declaration.descendants) != null ? _b2 : false,
read: declaration.read ? new WrappedNodeExpr(declaration.read) : null,
static: (_c2 = declaration.static) != null ? _c2 : false,
emitDistinctChangesOnly: (_d2 = declaration.emitDistinctChangesOnly) != null ? _d2 : true,
isSignal: !!declaration.isSignal
};
}
function convertQueryPredicate(predicate) {
return Array.isArray(predicate) ? predicate : createMayBeForwardRefExpression(new WrappedNodeExpr(predicate), 1);
}
function convertDirectiveFacadeToMetadata(facade) {
var _a2;
const inputsFromMetadata = parseInputsArray(facade.inputs || []);
const outputsFromMetadata = parseMappingStringArray(facade.outputs || []);
const propMetadata = facade.propMetadata;
const inputsFromType = {};
const outputsFromType = {};
for (const field in propMetadata) {
if (propMetadata.hasOwnProperty(field)) {
propMetadata[field].forEach((ann) => {
if (isInput(ann)) {
inputsFromType[field] = {
bindingPropertyName: ann.alias || field,
classPropertyName: field,
required: ann.required || false,
isSignal: !!ann.isSignal,
transformFunction: ann.transform != null ? new WrappedNodeExpr(ann.transform) : null
};
} else if (isOutput(ann)) {
outputsFromType[field] = ann.alias || field;
}
});
}
}
const hostDirectives = ((_a2 = facade.hostDirectives) == null ? void 0 : _a2.length) ? facade.hostDirectives.map((hostDirective) => {
return typeof hostDirective === "function" ? {
directive: wrapReference(hostDirective),
inputs: null,
outputs: null,
isForwardReference: false
} : {
directive: wrapReference(hostDirective.directive),
isForwardReference: false,
inputs: hostDirective.inputs ? parseMappingStringArray(hostDirective.inputs) : null,
outputs: hostDirective.outputs ? parseMappingStringArray(hostDirective.outputs) : null
};
}) : null;
return __spreadProps(__spreadValues({}, facade), {
typeArgumentCount: 0,
typeSourceSpan: facade.typeSourceSpan,
type: wrapReference(facade.type),
deps: null,
host: __spreadValues({}, extractHostBindings(facade.propMetadata, facade.typeSourceSpan, facade.host)),
inputs: __spreadValues(__spreadValues({}, inputsFromMetadata), inputsFromType),
outputs: __spreadValues(__spreadValues({}, outputsFromMetadata), outputsFromType),
queries: facade.queries.map(convertToR3QueryMetadata),
providers: facade.providers != null ? new WrappedNodeExpr(facade.providers) : null,
viewQueries: facade.viewQueries.map(convertToR3QueryMetadata),
fullInheritance: false,
hostDirectives
});
}
function convertDeclareDirectiveFacadeToMetadata(declaration, typeSourceSpan) {
var _a2, _b2, _c2, _d2, _e2, _f2, _g2, _h2, _i, _j;
const hostDirectives = ((_a2 = declaration.hostDirectives) == null ? void 0 : _a2.length) ? declaration.hostDirectives.map((dir) => ({
directive: wrapReference(dir.directive),
isForwardReference: false,
inputs: dir.inputs ? getHostDirectiveBindingMapping(dir.inputs) : null,
outputs: dir.outputs ? getHostDirectiveBindingMapping(dir.outputs) : null
})) : null;
return {
name: declaration.type.name,
type: wrapReference(declaration.type),
typeSourceSpan,
selector: (_b2 = declaration.selector) != null ? _b2 : null,
inputs: declaration.inputs ? inputsPartialMetadataToInputMetadata(declaration.inputs) : {},
outputs: (_c2 = declaration.outputs) != null ? _c2 : {},
host: convertHostDeclarationToMetadata(declaration.host),
queries: ((_d2 = declaration.queries) != null ? _d2 : []).map(convertQueryDeclarationToMetadata),
viewQueries: ((_e2 = declaration.viewQueries) != null ? _e2 : []).map(convertQueryDeclarationToMetadata),
providers: declaration.providers !== void 0 ? new WrappedNodeExpr(declaration.providers) : null,
exportAs: (_f2 = declaration.exportAs) != null ? _f2 : null,
usesInheritance: (_g2 = declaration.usesInheritance) != null ? _g2 : false,
lifecycle: { usesOnChanges: (_h2 = declaration.usesOnChanges) != null ? _h2 : false },
deps: null,
typeArgumentCount: 0,
fullInheritance: false,
isStandalone: (_i = declaration.isStandalone) != null ? _i : false,
isSignal: (_j = declaration.isSignal) != null ? _j : false,
hostDirectives
};
}
function convertHostDeclarationToMetadata(host = {}) {
var _a2, _b2, _c2;
return {
attributes: convertOpaqueValuesToExpressions((_a2 = host.attributes) != null ? _a2 : {}),
listeners: (_b2 = host.listeners) != null ? _b2 : {},
properties: (_c2 = host.properties) != null ? _c2 : {},
specialAttributes: {
classAttr: host.classAttribute,
styleAttr: host.styleAttribute
}
};
}
function getHostDirectiveBindingMapping(array) {
let result = null;
for (let i = 1; i < array.length; i += 2) {
result = result || {};
result[array[i - 1]] = array[i];
}
return result;
}
function convertOpaqueValuesToExpressions(obj) {
const result = {};
for (const key of Object.keys(obj)) {
result[key] = new WrappedNodeExpr(obj[key]);
}
return result;
}
function convertDeclareComponentFacadeToMetadata(decl, typeSourceSpan, sourceMapUrl) {
var _a2, _b2, _c2, _d2;
const { template: template2, interpolation, defer: defer2 } = parseJitTemplate(decl.template, decl.type.name, sourceMapUrl, (_a2 = decl.preserveWhitespaces) != null ? _a2 : false, decl.interpolation, decl.deferBlockDependencies);
const declarations = [];
if (decl.dependencies) {
for (const innerDep of decl.dependencies) {
switch (innerDep.kind) {
case "directive":
case "component":
declarations.push(convertDirectiveDeclarationToMetadata(innerDep));
break;
case "pipe":
declarations.push(convertPipeDeclarationToMetadata(innerDep));
break;
}
}
} else if (decl.components || decl.directives || decl.pipes) {
decl.components && declarations.push(...decl.components.map((dir) => convertDirectiveDeclarationToMetadata(dir, true)));
decl.directives && declarations.push(...decl.directives.map((dir) => convertDirectiveDeclarationToMetadata(dir)));
decl.pipes && declarations.push(...convertPipeMapToMetadata(decl.pipes));
}
return __spreadProps(__spreadValues({}, convertDeclareDirectiveFacadeToMetadata(decl, typeSourceSpan)), {
template: template2,
styles: (_b2 = decl.styles) != null ? _b2 : [],
declarations,
viewProviders: decl.viewProviders !== void 0 ? new WrappedNodeExpr(decl.viewProviders) : null,
animations: decl.animations !== void 0 ? new WrappedNodeExpr(decl.animations) : null,
defer: defer2,
changeDetection: (_c2 = decl.changeDetection) != null ? _c2 : ChangeDetectionStrategy.Default,
encapsulation: (_d2 = decl.encapsulation) != null ? _d2 : ViewEncapsulation.Emulated,
interpolation,
declarationListEmitMode: 2,
relativeContextFilePath: "",
i18nUseExternalIds: true
});
}
function convertDeclarationFacadeToMetadata(declaration) {
return __spreadProps(__spreadValues({}, declaration), {
type: new WrappedNodeExpr(declaration.type)
});
}
function convertDirectiveDeclarationToMetadata(declaration, isComponent = null) {
var _a2, _b2, _c2;
return {
kind: R3TemplateDependencyKind.Directive,
isComponent: isComponent || declaration.kind === "component",
selector: declaration.selector,
type: new WrappedNodeExpr(declaration.type),
inputs: (_a2 = declaration.inputs) != null ? _a2 : [],
outputs: (_b2 = declaration.outputs) != null ? _b2 : [],
exportAs: (_c2 = declaration.exportAs) != null ? _c2 : null
};
}
function convertPipeMapToMetadata(pipes) {
if (!pipes) {
return [];
}
return Object.keys(pipes).map((name) => {
return {
kind: R3TemplateDependencyKind.Pipe,
name,
type: new WrappedNodeExpr(pipes[name])
};
});
}
function convertPipeDeclarationToMetadata(pipe2) {
return {
kind: R3TemplateDependencyKind.Pipe,
name: pipe2.name,
type: new WrappedNodeExpr(pipe2.type)
};
}
function parseJitTemplate(template2, typeName, sourceMapUrl, preserveWhitespaces, interpolation, deferBlockDependencies) {
const interpolationConfig = interpolation ? InterpolationConfig.fromArray(interpolation) : DEFAULT_INTERPOLATION_CONFIG;
const parsed = parseTemplate(template2, sourceMapUrl, {
preserveWhitespaces,
interpolationConfig
});
if (parsed.errors !== null) {
const errors = parsed.errors.map((err) => err.toString()).join(", ");
throw new Error(`Errors during JIT compilation of template for ${typeName}: ${errors}`);
}
const binder = new R3TargetBinder(new SelectorMatcher());
const boundTarget = binder.bind({ template: parsed.nodes });
return {
template: parsed,
interpolation: interpolationConfig,
defer: createR3ComponentDeferMetadata(boundTarget, deferBlockDependencies)
};
}
function convertToProviderExpression(obj, property2) {
if (obj.hasOwnProperty(property2)) {
return createMayBeForwardRefExpression(new WrappedNodeExpr(obj[property2]), 0);
} else {
return void 0;
}
}
function wrapExpression(obj, property2) {
if (obj.hasOwnProperty(property2)) {
return new WrappedNodeExpr(obj[property2]);
} else {
return void 0;
}
}
function computeProvidedIn(providedIn) {
const expression = typeof providedIn === "function" ? new WrappedNodeExpr(providedIn) : new LiteralExpr(providedIn != null ? providedIn : null);
return createMayBeForwardRefExpression(expression, 0);
}
function convertR3DependencyMetadataArray(facades) {
return facades == null ? null : facades.map(convertR3DependencyMetadata);
}
function convertR3DependencyMetadata(facade) {
const isAttributeDep = facade.attribute != null;
const rawToken = facade.token === null ? null : new WrappedNodeExpr(facade.token);
const token = isAttributeDep ? new WrappedNodeExpr(facade.attribute) : rawToken;
return createR3DependencyMetadata(token, isAttributeDep, facade.host, facade.optional, facade.self, facade.skipSelf);
}
function convertR3DeclareDependencyMetadata(facade) {
var _a2, _b2, _c2, _d2, _e2;
const isAttributeDep = (_a2 = facade.attribute) != null ? _a2 : false;
const token = facade.token === null ? null : new WrappedNodeExpr(facade.token);
return createR3DependencyMetadata(token, isAttributeDep, (_b2 = facade.host) != null ? _b2 : false, (_c2 = facade.optional) != null ? _c2 : false, (_d2 = facade.self) != null ? _d2 : false, (_e2 = facade.skipSelf) != null ? _e2 : false);
}
function createR3DependencyMetadata(token, isAttributeDep, host, optional, self, skipSelf) {
const attributeNameType = isAttributeDep ? literal("unknown") : null;
return { token, attributeNameType, host, optional, self, skipSelf };
}
function createR3ComponentDeferMetadata(boundTarget, deferBlockDependencies) {
const deferredBlocks = boundTarget.getDeferBlocks();
const blocks = /* @__PURE__ */ new Map();
for (let i = 0; i < deferredBlocks.length; i++) {
const dependencyFn = deferBlockDependencies == null ? void 0 : deferBlockDependencies[i];
blocks.set(deferredBlocks[i], dependencyFn ? new WrappedNodeExpr(dependencyFn) : null);
}
return { mode: 0, blocks };
}
function extractHostBindings(propMetadata, sourceSpan, host) {
const bindings = parseHostBindings(host || {});
const errors = verifyHostBindings(bindings, sourceSpan);
if (errors.length) {
throw new Error(errors.map((error) => error.msg).join("\n"));
}
for (const field in propMetadata) {
if (propMetadata.hasOwnProperty(field)) {
propMetadata[field].forEach((ann) => {
if (isHostBinding(ann)) {
bindings.properties[ann.hostPropertyName || field] = getSafePropertyAccessString("this", field);
} else if (isHostListener(ann)) {
bindings.listeners[ann.eventName || field] = `${field}(${(ann.args || []).join(",")})`;
}
});
}
}
return bindings;
}
function isHostBinding(value) {
return value.ngMetadataName === "HostBinding";
}
function isHostListener(value) {
return value.ngMetadataName === "HostListener";
}
function isInput(value) {
return value.ngMetadataName === "Input";
}
function isOutput(value) {
return value.ngMetadataName === "Output";
}
function inputsPartialMetadataToInputMetadata(inputs) {
return Object.keys(inputs).reduce((result, minifiedClassName) => {
const value = inputs[minifiedClassName];
if (typeof value === "string" || Array.isArray(value)) {
result[minifiedClassName] = parseLegacyInputPartialOutput(value);
} else {
result[minifiedClassName] = {
bindingPropertyName: value.publicName,
classPropertyName: minifiedClassName,
transformFunction: value.transformFunction !== null ? new WrappedNodeExpr(value.transformFunction) : null,
required: value.isRequired,
isSignal: value.isSignal
};
}
return result;
}, {});
}
function parseLegacyInputPartialOutput(value) {
if (typeof value === "string") {
return {
bindingPropertyName: value,
classPropertyName: value,
transformFunction: null,
required: false,
isSignal: false
};
}
return {
bindingPropertyName: value[0],
classPropertyName: value[1],
transformFunction: value[2] ? new WrappedNodeExpr(value[2]) : null,
required: false,
isSignal: false
};
}
function parseInputsArray(values) {
return values.reduce((results, value) => {
if (typeof value === "string") {
const [bindingPropertyName, classPropertyName] = parseMappingString(value);
results[classPropertyName] = {
bindingPropertyName,
classPropertyName,
required: false,
isSignal: false,
transformFunction: null
};
} else {
results[value.name] = {
bindingPropertyName: value.alias || value.name,
classPropertyName: value.name,
required: value.required || false,
isSignal: false,
transformFunction: value.transform != null ? new WrappedNodeExpr(value.transform) : null
};
}
return results;
}, {});
}
function parseMappingStringArray(values) {
return values.reduce((results, value) => {
const [alias, fieldName] = parseMappingString(value);
results[fieldName] = alias;
return results;
}, {});
}
function parseMappingString(value) {
const [fieldName, bindingPropertyName] = value.split(":", 2).map((str) => str.trim());
return [bindingPropertyName != null ? bindingPropertyName : fieldName, fieldName];
}
function convertDeclarePipeFacadeToMetadata(declaration) {
var _a2, _b2;
return {
name: declaration.type.name,
type: wrapReference(declaration.type),
typeArgumentCount: 0,
pipeName: declaration.name,
deps: null,
pure: (_a2 = declaration.pure) != null ? _a2 : true,
isStandalone: (_b2 = declaration.isStandalone) != null ? _b2 : false
};
}
function convertDeclareInjectorFacadeToMetadata(declaration) {
return {
name: declaration.type.name,
type: wrapReference(declaration.type),
providers: declaration.providers !== void 0 && declaration.providers.length > 0 ? new WrappedNodeExpr(declaration.providers) : null,
imports: declaration.imports !== void 0 ? declaration.imports.map((i) => new WrappedNodeExpr(i)) : []
};
}
function publishFacade(global) {
const ng = global.ng || (global.ng = {});
ng.\u0275compilerFacade = new CompilerFacadeImpl();
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/version.mjs
var VERSION2 = new Version("18.2.6");
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/i18n/extractor_merger.mjs
var _I18N_ATTR = "i18n";
var _I18N_ATTR_PREFIX = "i18n-";
var _I18N_COMMENT_PREFIX_REGEXP = /^i18n:?/;
var MEANING_SEPARATOR2 = "|";
var ID_SEPARATOR2 = "@@";
var i18nCommentsWarned = false;
function extractMessages(nodes, interpolationConfig, implicitTags, implicitAttrs, preserveSignificantWhitespace) {
const visitor = new _Visitor3(implicitTags, implicitAttrs, preserveSignificantWhitespace);
return visitor.extract(nodes, interpolationConfig);
}
var ExtractionResult = class {
constructor(messages, errors) {
this.messages = messages;
this.errors = errors;
}
};
var _VisitorMode;
(function(_VisitorMode2) {
_VisitorMode2[_VisitorMode2["Extract"] = 0] = "Extract";
_VisitorMode2[_VisitorMode2["Merge"] = 1] = "Merge";
})(_VisitorMode || (_VisitorMode = {}));
var _Visitor3 = class {
constructor(_implicitTags, _implicitAttrs, _preserveSignificantWhitespace = true) {
this._implicitTags = _implicitTags;
this._implicitAttrs = _implicitAttrs;
this._preserveSignificantWhitespace = _preserveSignificantWhitespace;
}
extract(nodes, interpolationConfig) {
this._init(_VisitorMode.Extract, interpolationConfig);
nodes.forEach((node) => node.visit(this, null));
if (this._inI18nBlock) {
this._reportError(nodes[nodes.length - 1], "Unclosed block");
}
return new ExtractionResult(this._messages, this._errors);
}
merge(nodes, translations, interpolationConfig) {
this._init(_VisitorMode.Merge, interpolationConfig);
this._translations = translations;
const wrapper = new Element2("wrapper", [], nodes, void 0, void 0, void 0);
const translatedNode = wrapper.visit(this, null);
if (this._inI18nBlock) {
this._reportError(nodes[nodes.length - 1], "Unclosed block");
}
return new ParseTreeResult(translatedNode.children, this._errors);
}
visitExpansionCase(icuCase, context) {
const expression = visitAll2(this, icuCase.expression, context);
if (this._mode === _VisitorMode.Merge) {
return new ExpansionCase(icuCase.value, expression, icuCase.sourceSpan, icuCase.valueSourceSpan, icuCase.expSourceSpan);
}
}
visitExpansion(icu, context) {
this._mayBeAddBlockChildren(icu);
const wasInIcu = this._inIcu;
if (!this._inIcu) {
if (this._isInTranslatableSection) {
this._addMessage([icu]);
}
this._inIcu = true;
}
const cases = visitAll2(this, icu.cases, context);
if (this._mode === _VisitorMode.Merge) {
icu = new Expansion(icu.switchValue, icu.type, cases, icu.sourceSpan, icu.switchValueSourceSpan);
}
this._inIcu = wasInIcu;
return icu;
}
visitComment(comment, context) {
const isOpening = _isOpeningComment(comment);
if (isOpening && this._isInTranslatableSection) {
this._reportError(comment, "Could not start a block inside a translatable section");
return;
}
const isClosing = _isClosingComment(comment);
if (isClosing && !this._inI18nBlock) {
this._reportError(comment, "Trying to close an unopened block");
return;
}
if (!this._inI18nNode && !this._inIcu) {
if (!this._inI18nBlock) {
if (isOpening) {
if (!i18nCommentsWarned && console && console.warn) {
i18nCommentsWarned = true;
const details = comment.sourceSpan.details ? `, ${comment.sourceSpan.details}` : "";
console.warn(`I18n comments are deprecated, use an element instead (${comment.sourceSpan.start}${details})`);
}
this._inI18nBlock = true;
this._blockStartDepth = this._depth;
this._blockChildren = [];
this._blockMeaningAndDesc = comment.value.replace(_I18N_COMMENT_PREFIX_REGEXP, "").trim();
this._openTranslatableSection(comment);
}
} else {
if (isClosing) {
if (this._depth == this._blockStartDepth) {
this._closeTranslatableSection(comment, this._blockChildren);
this._inI18nBlock = false;
const message = this._addMessage(this._blockChildren, this._blockMeaningAndDesc);
const nodes = this._translateMessage(comment, message);
return visitAll2(this, nodes);
} else {
this._reportError(comment, "I18N blocks should not cross element boundaries");
return;
}
}
}
}
}
visitText(text2, context) {
if (this._isInTranslatableSection) {
this._mayBeAddBlockChildren(text2);
}
return text2;
}
visitElement(el, context) {
this._mayBeAddBlockChildren(el);
this._depth++;
const wasInI18nNode = this._inI18nNode;
const wasInImplicitNode = this._inImplicitNode;
let childNodes = [];
let translatedChildNodes = void 0;
const i18nAttr = _getI18nAttr(el);
const i18nMeta = i18nAttr ? i18nAttr.value : "";
const isImplicit = this._implicitTags.some((tag) => el.name === tag) && !this._inIcu && !this._isInTranslatableSection;
const isTopLevelImplicit = !wasInImplicitNode && isImplicit;
this._inImplicitNode = wasInImplicitNode || isImplicit;
if (!this._isInTranslatableSection && !this._inIcu) {
if (i18nAttr || isTopLevelImplicit) {
this._inI18nNode = true;
const message = this._addMessage(el.children, i18nMeta);
translatedChildNodes = this._translateMessage(el, message);
}
if (this._mode == _VisitorMode.Extract) {
const isTranslatable = i18nAttr || isTopLevelImplicit;
if (isTranslatable)
this._openTranslatableSection(el);
visitAll2(this, el.children);
if (isTranslatable)
this._closeTranslatableSection(el, el.children);
}
} else {
if (i18nAttr || isTopLevelImplicit) {
this._reportError(el, "Could not mark an element as translatable inside a translatable section");
}
if (this._mode == _VisitorMode.Extract) {
visitAll2(this, el.children);
}
}
if (this._mode === _VisitorMode.Merge) {
const visitNodes = translatedChildNodes || el.children;
visitNodes.forEach((child) => {
const visited = child.visit(this, context);
if (visited && !this._isInTranslatableSection) {
childNodes = childNodes.concat(visited);
}
});
}
this._visitAttributesOf(el);
this._depth--;
this._inI18nNode = wasInI18nNode;
this._inImplicitNode = wasInImplicitNode;
if (this._mode === _VisitorMode.Merge) {
const translatedAttrs = this._translateAttributes(el);
return new Element2(el.name, translatedAttrs, childNodes, el.sourceSpan, el.startSourceSpan, el.endSourceSpan);
}
return null;
}
visitAttribute(attribute2, context) {
throw new Error("unreachable code");
}
visitBlock(block, context) {
visitAll2(this, block.children, context);
}
visitBlockParameter(parameter, context) {
}
visitLetDeclaration(decl, context) {
}
_init(mode, interpolationConfig) {
this._mode = mode;
this._inI18nBlock = false;
this._inI18nNode = false;
this._depth = 0;
this._inIcu = false;
this._msgCountAtSectionStart = void 0;
this._errors = [];
this._messages = [];
this._inImplicitNode = false;
this._createI18nMessage = createI18nMessageFactory(
interpolationConfig,
DEFAULT_CONTAINER_BLOCKS,
!this._preserveSignificantWhitespace
);
}
_visitAttributesOf(el) {
const explicitAttrNameToValue = {};
const implicitAttrNames = this._implicitAttrs[el.name] || [];
el.attrs.filter((attr) => attr.name.startsWith(_I18N_ATTR_PREFIX)).forEach((attr) => explicitAttrNameToValue[attr.name.slice(_I18N_ATTR_PREFIX.length)] = attr.value);
el.attrs.forEach((attr) => {
if (attr.name in explicitAttrNameToValue) {
this._addMessage([attr], explicitAttrNameToValue[attr.name]);
} else if (implicitAttrNames.some((name) => attr.name === name)) {
this._addMessage([attr]);
}
});
}
_addMessage(ast, msgMeta) {
if (ast.length == 0 || ast.length == 1 && ast[0] instanceof Attribute && !ast[0].value) {
return null;
}
const { meaning, description, id } = _parseMessageMeta(msgMeta);
const message = this._createI18nMessage(ast, meaning, description, id);
this._messages.push(message);
return message;
}
_translateMessage(el, message) {
if (message && this._mode === _VisitorMode.Merge) {
const nodes = this._translations.get(message);
if (nodes) {
return nodes;
}
this._reportError(el, `Translation unavailable for message id="${this._translations.digest(message)}"`);
}
return [];
}
_translateAttributes(el) {
const attributes = el.attrs;
const i18nParsedMessageMeta = {};
attributes.forEach((attr) => {
if (attr.name.startsWith(_I18N_ATTR_PREFIX)) {
i18nParsedMessageMeta[attr.name.slice(_I18N_ATTR_PREFIX.length)] = _parseMessageMeta(attr.value);
}
});
const translatedAttributes = [];
attributes.forEach((attr) => {
if (attr.name === _I18N_ATTR || attr.name.startsWith(_I18N_ATTR_PREFIX)) {
return;
}
if (attr.value && attr.value != "" && i18nParsedMessageMeta.hasOwnProperty(attr.name)) {
const { meaning, description, id } = i18nParsedMessageMeta[attr.name];
const message = this._createI18nMessage([attr], meaning, description, id);
const nodes = this._translations.get(message);
if (nodes) {
if (nodes.length == 0) {
translatedAttributes.push(new Attribute(attr.name, "", attr.sourceSpan, void 0, void 0, void 0, void 0));
} else if (nodes[0] instanceof Text4) {
const value = nodes[0].value;
translatedAttributes.push(new Attribute(attr.name, value, attr.sourceSpan, void 0, void 0, void 0, void 0));
} else {
this._reportError(el, `Unexpected translation for attribute "${attr.name}" (id="${id || this._translations.digest(message)}")`);
}
} else {
this._reportError(el, `Translation unavailable for attribute "${attr.name}" (id="${id || this._translations.digest(message)}")`);
}
} else {
translatedAttributes.push(attr);
}
});
return translatedAttributes;
}
_mayBeAddBlockChildren(node) {
if (this._inI18nBlock && !this._inIcu && this._depth == this._blockStartDepth) {
this._blockChildren.push(node);
}
}
_openTranslatableSection(node) {
if (this._isInTranslatableSection) {
this._reportError(node, "Unexpected section start");
} else {
this._msgCountAtSectionStart = this._messages.length;
}
}
get _isInTranslatableSection() {
return this._msgCountAtSectionStart !== void 0;
}
_closeTranslatableSection(node, directChildren) {
if (!this._isInTranslatableSection) {
this._reportError(node, "Unexpected section end");
return;
}
const startIndex = this._msgCountAtSectionStart;
const significantChildren = directChildren.reduce((count, node2) => count + (node2 instanceof Comment2 ? 0 : 1), 0);
if (significantChildren == 1) {
for (let i = this._messages.length - 1; i >= startIndex; i--) {
const ast = this._messages[i].nodes;
if (!(ast.length == 1 && ast[0] instanceof Text2)) {
this._messages.splice(i, 1);
break;
}
}
}
this._msgCountAtSectionStart = void 0;
}
_reportError(node, msg) {
this._errors.push(new I18nError(node.sourceSpan, msg));
}
};
function _isOpeningComment(n2) {
return !!(n2 instanceof Comment2 && n2.value && n2.value.startsWith("i18n"));
}
function _isClosingComment(n2) {
return !!(n2 instanceof Comment2 && n2.value && n2.value === "/i18n");
}
function _getI18nAttr(p2) {
return p2.attrs.find((attr) => attr.name === _I18N_ATTR) || null;
}
function _parseMessageMeta(i18n2) {
if (!i18n2)
return { meaning: "", description: "", id: "" };
const idIndex = i18n2.indexOf(ID_SEPARATOR2);
const descIndex = i18n2.indexOf(MEANING_SEPARATOR2);
const [meaningAndDesc, id] = idIndex > -1 ? [i18n2.slice(0, idIndex), i18n2.slice(idIndex + 2)] : [i18n2, ""];
const [meaning, description] = descIndex > -1 ? [meaningAndDesc.slice(0, descIndex), meaningAndDesc.slice(descIndex + 1)] : ["", meaningAndDesc];
return { meaning, description, id: id.trim() };
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/ml_parser/xml_tags.mjs
var XmlTagDefinition = class {
constructor() {
this.closedByParent = false;
this.implicitNamespacePrefix = null;
this.isVoid = false;
this.ignoreFirstLf = false;
this.canSelfClose = true;
this.preventNamespaceInheritance = false;
}
requireExtraParent(currentParent) {
return false;
}
isClosedByChild(name) {
return false;
}
getContentType() {
return TagContentType.PARSABLE_DATA;
}
};
var _TAG_DEFINITION = new XmlTagDefinition();
function getXmlTagDefinition(tagName) {
return _TAG_DEFINITION;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/ml_parser/xml_parser.mjs
var XmlParser = class extends Parser {
constructor() {
super(getXmlTagDefinition);
}
parse(source, url, options = {}) {
return super.parse(source, url, __spreadProps(__spreadValues({}, options), { tokenizeBlocks: false, tokenizeLet: false }));
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/i18n/serializers/xliff.mjs
var _VERSION = "1.2";
var _XMLNS = "urn:oasis:names:tc:xliff:document:1.2";
var _DEFAULT_SOURCE_LANG = "en";
var _PLACEHOLDER_TAG2 = "x";
var _MARKER_TAG = "mrk";
var _FILE_TAG = "file";
var _SOURCE_TAG2 = "source";
var _SEGMENT_SOURCE_TAG = "seg-source";
var _ALT_TRANS_TAG = "alt-trans";
var _TARGET_TAG = "target";
var _UNIT_TAG = "trans-unit";
var _CONTEXT_GROUP_TAG = "context-group";
var _CONTEXT_TAG = "context";
var Xliff = class extends Serializer {
write(messages, locale) {
const visitor = new _WriteVisitor();
const transUnits = [];
messages.forEach((message) => {
let contextTags = [];
message.sources.forEach((source) => {
let contextGroupTag = new Tag(_CONTEXT_GROUP_TAG, { purpose: "location" });
contextGroupTag.children.push(new CR(10), new Tag(_CONTEXT_TAG, { "context-type": "sourcefile" }, [
new Text3(source.filePath)
]), new CR(10), new Tag(_CONTEXT_TAG, { "context-type": "linenumber" }, [
new Text3(`${source.startLine}`)
]), new CR(8));
contextTags.push(new CR(8), contextGroupTag);
});
const transUnit = new Tag(_UNIT_TAG, { id: message.id, datatype: "html" });
transUnit.children.push(new CR(8), new Tag(_SOURCE_TAG2, {}, visitor.serialize(message.nodes)), ...contextTags);
if (message.description) {
transUnit.children.push(new CR(8), new Tag("note", { priority: "1", from: "description" }, [
new Text3(message.description)
]));
}
if (message.meaning) {
transUnit.children.push(new CR(8), new Tag("note", { priority: "1", from: "meaning" }, [new Text3(message.meaning)]));
}
transUnit.children.push(new CR(6));
transUnits.push(new CR(6), transUnit);
});
const body = new Tag("body", {}, [...transUnits, new CR(4)]);
const file = new Tag("file", {
"source-language": locale || _DEFAULT_SOURCE_LANG,
datatype: "plaintext",
original: "ng2.template"
}, [new CR(4), body, new CR(2)]);
const xliff = new Tag("xliff", { version: _VERSION, xmlns: _XMLNS }, [
new CR(2),
file,
new CR()
]);
return serialize([
new Declaration({ version: "1.0", encoding: "UTF-8" }),
new CR(),
xliff,
new CR()
]);
}
load(content, url) {
const xliffParser = new XliffParser();
const { locale, msgIdToHtml, errors } = xliffParser.parse(content, url);
const i18nNodesByMsgId = {};
const converter = new XmlToI18n();
Object.keys(msgIdToHtml).forEach((msgId) => {
const { i18nNodes, errors: e } = converter.convert(msgIdToHtml[msgId], url);
errors.push(...e);
i18nNodesByMsgId[msgId] = i18nNodes;
});
if (errors.length) {
throw new Error(`xliff parse errors:
${errors.join("\n")}`);
}
return { locale, i18nNodesByMsgId };
}
digest(message) {
return digest(message);
}
};
var _WriteVisitor = class {
visitText(text2, context) {
return [new Text3(text2.value)];
}
visitContainer(container, context) {
const nodes = [];
container.children.forEach((node) => nodes.push(...node.visit(this)));
return nodes;
}
visitIcu(icu, context) {
const nodes = [new Text3(`{${icu.expressionPlaceholder}, ${icu.type}, `)];
Object.keys(icu.cases).forEach((c) => {
nodes.push(new Text3(`${c} {`), ...icu.cases[c].visit(this), new Text3(`} `));
});
nodes.push(new Text3(`}`));
return nodes;
}
visitTagPlaceholder(ph, context) {
const ctype = getCtypeForTag(ph.tag);
if (ph.isVoid) {
return [
new Tag(_PLACEHOLDER_TAG2, { id: ph.startName, ctype, "equiv-text": `<${ph.tag}/>` })
];
}
const startTagPh = new Tag(_PLACEHOLDER_TAG2, {
id: ph.startName,
ctype,
"equiv-text": `<${ph.tag}>`
});
const closeTagPh = new Tag(_PLACEHOLDER_TAG2, {
id: ph.closeName,
ctype,
"equiv-text": `${ph.tag}>`
});
return [startTagPh, ...this.serialize(ph.children), closeTagPh];
}
visitPlaceholder(ph, context) {
return [new Tag(_PLACEHOLDER_TAG2, { id: ph.name, "equiv-text": `{{${ph.value}}}` })];
}
visitBlockPlaceholder(ph, context) {
const ctype = `x-${ph.name.toLowerCase().replace(/[^a-z0-9]/g, "-")}`;
const startTagPh = new Tag(_PLACEHOLDER_TAG2, {
id: ph.startName,
ctype,
"equiv-text": `@${ph.name}`
});
const closeTagPh = new Tag(_PLACEHOLDER_TAG2, { id: ph.closeName, ctype, "equiv-text": `}` });
return [startTagPh, ...this.serialize(ph.children), closeTagPh];
}
visitIcuPlaceholder(ph, context) {
const equivText = `{${ph.value.expression}, ${ph.value.type}, ${Object.keys(ph.value.cases).map((value) => value + " {...}").join(" ")}}`;
return [new Tag(_PLACEHOLDER_TAG2, { id: ph.name, "equiv-text": equivText })];
}
serialize(nodes) {
return [].concat(...nodes.map((node) => node.visit(this)));
}
};
var XliffParser = class {
constructor() {
this._locale = null;
}
parse(xliff, url) {
this._unitMlString = null;
this._msgIdToHtml = {};
const xml = new XmlParser().parse(xliff, url);
this._errors = xml.errors;
visitAll2(this, xml.rootNodes, null);
return {
msgIdToHtml: this._msgIdToHtml,
errors: this._errors,
locale: this._locale
};
}
visitElement(element2, context) {
switch (element2.name) {
case _UNIT_TAG:
this._unitMlString = null;
const idAttr = element2.attrs.find((attr) => attr.name === "id");
if (!idAttr) {
this._addError(element2, `<${_UNIT_TAG}> misses the "id" attribute`);
} else {
const id = idAttr.value;
if (this._msgIdToHtml.hasOwnProperty(id)) {
this._addError(element2, `Duplicated translations for msg ${id}`);
} else {
visitAll2(this, element2.children, null);
if (typeof this._unitMlString === "string") {
this._msgIdToHtml[id] = this._unitMlString;
} else {
this._addError(element2, `Message ${id} misses a translation`);
}
}
}
break;
case _SOURCE_TAG2:
case _SEGMENT_SOURCE_TAG:
case _ALT_TRANS_TAG:
break;
case _TARGET_TAG:
const innerTextStart = element2.startSourceSpan.end.offset;
const innerTextEnd = element2.endSourceSpan.start.offset;
const content = element2.startSourceSpan.start.file.content;
const innerText = content.slice(innerTextStart, innerTextEnd);
this._unitMlString = innerText;
break;
case _FILE_TAG:
const localeAttr = element2.attrs.find((attr) => attr.name === "target-language");
if (localeAttr) {
this._locale = localeAttr.value;
}
visitAll2(this, element2.children, null);
break;
default:
visitAll2(this, element2.children, null);
}
}
visitAttribute(attribute2, context) {
}
visitText(text2, context) {
}
visitComment(comment, context) {
}
visitExpansion(expansion, context) {
}
visitExpansionCase(expansionCase, context) {
}
visitBlock(block, context) {
}
visitBlockParameter(parameter, context) {
}
visitLetDeclaration(decl, context) {
}
_addError(node, message) {
this._errors.push(new I18nError(node.sourceSpan, message));
}
};
var XmlToI18n = class {
convert(message, url) {
const xmlIcu = new XmlParser().parse(message, url, { tokenizeExpansionForms: true });
this._errors = xmlIcu.errors;
const i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ? [] : [].concat(...visitAll2(this, xmlIcu.rootNodes));
return {
i18nNodes,
errors: this._errors
};
}
visitText(text2, context) {
return new Text2(text2.value, text2.sourceSpan);
}
visitElement(el, context) {
if (el.name === _PLACEHOLDER_TAG2) {
const nameAttr = el.attrs.find((attr) => attr.name === "id");
if (nameAttr) {
return new Placeholder("", nameAttr.value, el.sourceSpan);
}
this._addError(el, `<${_PLACEHOLDER_TAG2}> misses the "id" attribute`);
return null;
}
if (el.name === _MARKER_TAG) {
return [].concat(...visitAll2(this, el.children));
}
this._addError(el, `Unexpected tag`);
return null;
}
visitExpansion(icu, context) {
const caseMap = {};
visitAll2(this, icu.cases).forEach((c) => {
caseMap[c.value] = new Container(c.nodes, icu.sourceSpan);
});
return new Icu2(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
}
visitExpansionCase(icuCase, context) {
return {
value: icuCase.value,
nodes: visitAll2(this, icuCase.expression)
};
}
visitComment(comment, context) {
}
visitAttribute(attribute2, context) {
}
visitBlock(block, context) {
}
visitBlockParameter(parameter, context) {
}
visitLetDeclaration(decl, context) {
}
_addError(node, message) {
this._errors.push(new I18nError(node.sourceSpan, message));
}
};
function getCtypeForTag(tag) {
switch (tag.toLowerCase()) {
case "br":
return "lb";
case "img":
return "image";
default:
return `x-${tag}`;
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/i18n/serializers/xliff2.mjs
var _VERSION2 = "2.0";
var _XMLNS2 = "urn:oasis:names:tc:xliff:document:2.0";
var _DEFAULT_SOURCE_LANG2 = "en";
var _PLACEHOLDER_TAG3 = "ph";
var _PLACEHOLDER_SPANNING_TAG = "pc";
var _MARKER_TAG2 = "mrk";
var _XLIFF_TAG = "xliff";
var _SOURCE_TAG3 = "source";
var _TARGET_TAG2 = "target";
var _UNIT_TAG2 = "unit";
var Xliff2 = class extends Serializer {
write(messages, locale) {
const visitor = new _WriteVisitor2();
const units = [];
messages.forEach((message) => {
const unit = new Tag(_UNIT_TAG2, { id: message.id });
const notes = new Tag("notes");
if (message.description || message.meaning) {
if (message.description) {
notes.children.push(new CR(8), new Tag("note", { category: "description" }, [new Text3(message.description)]));
}
if (message.meaning) {
notes.children.push(new CR(8), new Tag("note", { category: "meaning" }, [new Text3(message.meaning)]));
}
}
message.sources.forEach((source) => {
notes.children.push(new CR(8), new Tag("note", { category: "location" }, [
new Text3(`${source.filePath}:${source.startLine}${source.endLine !== source.startLine ? "," + source.endLine : ""}`)
]));
});
notes.children.push(new CR(6));
unit.children.push(new CR(6), notes);
const segment = new Tag("segment");
segment.children.push(new CR(8), new Tag(_SOURCE_TAG3, {}, visitor.serialize(message.nodes)), new CR(6));
unit.children.push(new CR(6), segment, new CR(4));
units.push(new CR(4), unit);
});
const file = new Tag("file", { "original": "ng.template", id: "ngi18n" }, [
...units,
new CR(2)
]);
const xliff = new Tag(_XLIFF_TAG, { version: _VERSION2, xmlns: _XMLNS2, srcLang: locale || _DEFAULT_SOURCE_LANG2 }, [new CR(2), file, new CR()]);
return serialize([
new Declaration({ version: "1.0", encoding: "UTF-8" }),
new CR(),
xliff,
new CR()
]);
}
load(content, url) {
const xliff2Parser = new Xliff2Parser();
const { locale, msgIdToHtml, errors } = xliff2Parser.parse(content, url);
const i18nNodesByMsgId = {};
const converter = new XmlToI18n2();
Object.keys(msgIdToHtml).forEach((msgId) => {
const { i18nNodes, errors: e } = converter.convert(msgIdToHtml[msgId], url);
errors.push(...e);
i18nNodesByMsgId[msgId] = i18nNodes;
});
if (errors.length) {
throw new Error(`xliff2 parse errors:
${errors.join("\n")}`);
}
return { locale, i18nNodesByMsgId };
}
digest(message) {
return decimalDigest(message, true);
}
};
var _WriteVisitor2 = class {
constructor() {
this._nextPlaceholderId = 0;
}
visitText(text2, context) {
return [new Text3(text2.value)];
}
visitContainer(container, context) {
const nodes = [];
container.children.forEach((node) => nodes.push(...node.visit(this)));
return nodes;
}
visitIcu(icu, context) {
const nodes = [new Text3(`{${icu.expressionPlaceholder}, ${icu.type}, `)];
Object.keys(icu.cases).forEach((c) => {
nodes.push(new Text3(`${c} {`), ...icu.cases[c].visit(this), new Text3(`} `));
});
nodes.push(new Text3(`}`));
return nodes;
}
visitTagPlaceholder(ph, context) {
const type = getTypeForTag(ph.tag);
if (ph.isVoid) {
const tagPh = new Tag(_PLACEHOLDER_TAG3, {
id: (this._nextPlaceholderId++).toString(),
equiv: ph.startName,
type,
disp: `<${ph.tag}/>`
});
return [tagPh];
}
const tagPc = new Tag(_PLACEHOLDER_SPANNING_TAG, {
id: (this._nextPlaceholderId++).toString(),
equivStart: ph.startName,
equivEnd: ph.closeName,
type,
dispStart: `<${ph.tag}>`,
dispEnd: `${ph.tag}>`
});
const nodes = [].concat(...ph.children.map((node) => node.visit(this)));
if (nodes.length) {
nodes.forEach((node) => tagPc.children.push(node));
} else {
tagPc.children.push(new Text3(""));
}
return [tagPc];
}
visitPlaceholder(ph, context) {
const idStr = (this._nextPlaceholderId++).toString();
return [
new Tag(_PLACEHOLDER_TAG3, {
id: idStr,
equiv: ph.name,
disp: `{{${ph.value}}}`
})
];
}
visitBlockPlaceholder(ph, context) {
const tagPc = new Tag(_PLACEHOLDER_SPANNING_TAG, {
id: (this._nextPlaceholderId++).toString(),
equivStart: ph.startName,
equivEnd: ph.closeName,
type: "other",
dispStart: `@${ph.name}`,
dispEnd: `}`
});
const nodes = [].concat(...ph.children.map((node) => node.visit(this)));
if (nodes.length) {
nodes.forEach((node) => tagPc.children.push(node));
} else {
tagPc.children.push(new Text3(""));
}
return [tagPc];
}
visitIcuPlaceholder(ph, context) {
const cases = Object.keys(ph.value.cases).map((value) => value + " {...}").join(" ");
const idStr = (this._nextPlaceholderId++).toString();
return [
new Tag(_PLACEHOLDER_TAG3, {
id: idStr,
equiv: ph.name,
disp: `{${ph.value.expression}, ${ph.value.type}, ${cases}}`
})
];
}
serialize(nodes) {
this._nextPlaceholderId = 0;
return [].concat(...nodes.map((node) => node.visit(this)));
}
};
var Xliff2Parser = class {
constructor() {
this._locale = null;
}
parse(xliff, url) {
this._unitMlString = null;
this._msgIdToHtml = {};
const xml = new XmlParser().parse(xliff, url);
this._errors = xml.errors;
visitAll2(this, xml.rootNodes, null);
return {
msgIdToHtml: this._msgIdToHtml,
errors: this._errors,
locale: this._locale
};
}
visitElement(element2, context) {
switch (element2.name) {
case _UNIT_TAG2:
this._unitMlString = null;
const idAttr = element2.attrs.find((attr) => attr.name === "id");
if (!idAttr) {
this._addError(element2, `<${_UNIT_TAG2}> misses the "id" attribute`);
} else {
const id = idAttr.value;
if (this._msgIdToHtml.hasOwnProperty(id)) {
this._addError(element2, `Duplicated translations for msg ${id}`);
} else {
visitAll2(this, element2.children, null);
if (typeof this._unitMlString === "string") {
this._msgIdToHtml[id] = this._unitMlString;
} else {
this._addError(element2, `Message ${id} misses a translation`);
}
}
}
break;
case _SOURCE_TAG3:
break;
case _TARGET_TAG2:
const innerTextStart = element2.startSourceSpan.end.offset;
const innerTextEnd = element2.endSourceSpan.start.offset;
const content = element2.startSourceSpan.start.file.content;
const innerText = content.slice(innerTextStart, innerTextEnd);
this._unitMlString = innerText;
break;
case _XLIFF_TAG:
const localeAttr = element2.attrs.find((attr) => attr.name === "trgLang");
if (localeAttr) {
this._locale = localeAttr.value;
}
const versionAttr = element2.attrs.find((attr) => attr.name === "version");
if (versionAttr) {
const version = versionAttr.value;
if (version !== "2.0") {
this._addError(element2, `The XLIFF file version ${version} is not compatible with XLIFF 2.0 serializer`);
} else {
visitAll2(this, element2.children, null);
}
}
break;
default:
visitAll2(this, element2.children, null);
}
}
visitAttribute(attribute2, context) {
}
visitText(text2, context) {
}
visitComment(comment, context) {
}
visitExpansion(expansion, context) {
}
visitExpansionCase(expansionCase, context) {
}
visitBlock(block, context) {
}
visitBlockParameter(parameter, context) {
}
visitLetDeclaration(decl, context) {
}
_addError(node, message) {
this._errors.push(new I18nError(node.sourceSpan, message));
}
};
var XmlToI18n2 = class {
convert(message, url) {
const xmlIcu = new XmlParser().parse(message, url, { tokenizeExpansionForms: true });
this._errors = xmlIcu.errors;
const i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ? [] : [].concat(...visitAll2(this, xmlIcu.rootNodes));
return {
i18nNodes,
errors: this._errors
};
}
visitText(text2, context) {
return new Text2(text2.value, text2.sourceSpan);
}
visitElement(el, context) {
switch (el.name) {
case _PLACEHOLDER_TAG3:
const nameAttr = el.attrs.find((attr) => attr.name === "equiv");
if (nameAttr) {
return [new Placeholder("", nameAttr.value, el.sourceSpan)];
}
this._addError(el, `<${_PLACEHOLDER_TAG3}> misses the "equiv" attribute`);
break;
case _PLACEHOLDER_SPANNING_TAG:
const startAttr = el.attrs.find((attr) => attr.name === "equivStart");
const endAttr = el.attrs.find((attr) => attr.name === "equivEnd");
if (!startAttr) {
this._addError(el, `<${_PLACEHOLDER_TAG3}> misses the "equivStart" attribute`);
} else if (!endAttr) {
this._addError(el, `<${_PLACEHOLDER_TAG3}> misses the "equivEnd" attribute`);
} else {
const startId = startAttr.value;
const endId = endAttr.value;
const nodes = [];
return nodes.concat(new Placeholder("", startId, el.sourceSpan), ...el.children.map((node) => node.visit(this, null)), new Placeholder("", endId, el.sourceSpan));
}
break;
case _MARKER_TAG2:
return [].concat(...visitAll2(this, el.children));
default:
this._addError(el, `Unexpected tag`);
}
return null;
}
visitExpansion(icu, context) {
const caseMap = {};
visitAll2(this, icu.cases).forEach((c) => {
caseMap[c.value] = new Container(c.nodes, icu.sourceSpan);
});
return new Icu2(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
}
visitExpansionCase(icuCase, context) {
return {
value: icuCase.value,
nodes: [].concat(...visitAll2(this, icuCase.expression))
};
}
visitComment(comment, context) {
}
visitAttribute(attribute2, context) {
}
visitBlock(block, context) {
}
visitBlockParameter(parameter, context) {
}
visitLetDeclaration(decl, context) {
}
_addError(node, message) {
this._errors.push(new I18nError(node.sourceSpan, message));
}
};
function getTypeForTag(tag) {
switch (tag.toLowerCase()) {
case "br":
case "b":
case "i":
case "u":
return "fmt";
case "img":
return "image";
case "a":
return "link";
default:
return "other";
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/i18n/message_bundle.mjs
var MessageBundle = class {
constructor(_htmlParser, _implicitTags, _implicitAttrs, _locale = null, _preserveWhitespace = true) {
this._htmlParser = _htmlParser;
this._implicitTags = _implicitTags;
this._implicitAttrs = _implicitAttrs;
this._locale = _locale;
this._preserveWhitespace = _preserveWhitespace;
this._messages = [];
}
updateFromTemplate(source, url, interpolationConfig) {
const htmlParserResult = this._htmlParser.parse(source, url, {
tokenizeExpansionForms: true,
interpolationConfig
});
if (htmlParserResult.errors.length) {
return htmlParserResult.errors;
}
const rootNodes = this._preserveWhitespace ? htmlParserResult.rootNodes : visitAllWithSiblings(new WhitespaceVisitor(false), htmlParserResult.rootNodes);
const i18nParserResult = extractMessages(
rootNodes,
interpolationConfig,
this._implicitTags,
this._implicitAttrs,
this._preserveWhitespace
);
if (i18nParserResult.errors.length) {
return i18nParserResult.errors;
}
this._messages.push(...i18nParserResult.messages);
return [];
}
getMessages() {
return this._messages;
}
write(serializer2, filterSources) {
const messages = {};
const mapperVisitor = new MapPlaceholderNames();
this._messages.forEach((message) => {
const id = serializer2.digest(message);
if (!messages.hasOwnProperty(id)) {
messages[id] = message;
} else {
messages[id].sources.push(...message.sources);
}
});
const msgList = Object.keys(messages).map((id) => {
const mapper = serializer2.createNameMapper(messages[id]);
const src = messages[id];
const nodes = mapper ? mapperVisitor.convert(src.nodes, mapper) : src.nodes;
let transformedMessage = new Message(nodes, {}, {}, src.meaning, src.description, id);
transformedMessage.sources = src.sources;
if (filterSources) {
transformedMessage.sources.forEach((source) => source.filePath = filterSources(source.filePath));
}
return transformedMessage;
});
return serializer2.write(msgList, this._locale);
}
};
var MapPlaceholderNames = class extends CloneVisitor {
convert(nodes, mapper) {
return mapper ? nodes.map((n2) => n2.visit(this, mapper)) : nodes;
}
visitTagPlaceholder(ph, mapper) {
const startName = mapper.toPublicName(ph.startName);
const closeName = ph.closeName ? mapper.toPublicName(ph.closeName) : ph.closeName;
const children = ph.children.map((n2) => n2.visit(this, mapper));
return new TagPlaceholder(ph.tag, ph.attrs, startName, closeName, children, ph.isVoid, ph.sourceSpan, ph.startSourceSpan, ph.endSourceSpan);
}
visitBlockPlaceholder(ph, mapper) {
const startName = mapper.toPublicName(ph.startName);
const closeName = ph.closeName ? mapper.toPublicName(ph.closeName) : ph.closeName;
const children = ph.children.map((n2) => n2.visit(this, mapper));
return new BlockPlaceholder(ph.name, ph.parameters, startName, closeName, children, ph.sourceSpan, ph.startSourceSpan, ph.endSourceSpan);
}
visitPlaceholder(ph, mapper) {
return new Placeholder(ph.value, mapper.toPublicName(ph.name), ph.sourceSpan);
}
visitIcuPlaceholder(ph, mapper) {
return new IcuPlaceholder(ph.value, mapper.toPublicName(ph.name), ph.sourceSpan);
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/partial/api.mjs
var FactoryTarget2;
(function(FactoryTarget3) {
FactoryTarget3[FactoryTarget3["Directive"] = 0] = "Directive";
FactoryTarget3[FactoryTarget3["Component"] = 1] = "Component";
FactoryTarget3[FactoryTarget3["Injectable"] = 2] = "Injectable";
FactoryTarget3[FactoryTarget3["Pipe"] = 3] = "Pipe";
FactoryTarget3[FactoryTarget3["NgModule"] = 4] = "NgModule";
})(FactoryTarget2 || (FactoryTarget2 = {}));
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/r3_class_metadata_compiler.mjs
function compileClassMetadata(metadata) {
const fnCall = internalCompileClassMetadata(metadata);
return arrowFn([], [devOnlyGuardedExpression(fnCall).toStmt()]).callFn([]);
}
function internalCompileClassMetadata(metadata) {
var _a2, _b2;
return importExpr(Identifiers.setClassMetadata).callFn([
metadata.type,
metadata.decorators,
(_a2 = metadata.ctorParameters) != null ? _a2 : literal(null),
(_b2 = metadata.propDecorators) != null ? _b2 : literal(null)
]);
}
function compileComponentClassMetadata(metadata, dependencies) {
if (dependencies === null || dependencies.length === 0) {
return compileClassMetadata(metadata);
}
return internalCompileSetClassMetadataAsync(metadata, dependencies.map((dep) => new FnParam(dep.symbolName, DYNAMIC_TYPE)), compileComponentMetadataAsyncResolver(dependencies));
}
function internalCompileSetClassMetadataAsync(metadata, wrapperParams, dependencyResolverFn) {
const setClassMetadataCall = internalCompileClassMetadata(metadata);
const setClassMetaWrapper = arrowFn(wrapperParams, [setClassMetadataCall.toStmt()]);
const setClassMetaAsync = importExpr(Identifiers.setClassMetadataAsync).callFn([metadata.type, dependencyResolverFn, setClassMetaWrapper]);
return arrowFn([], [devOnlyGuardedExpression(setClassMetaAsync).toStmt()]).callFn([]);
}
function compileComponentMetadataAsyncResolver(dependencies) {
const dynamicImports = dependencies.map(({ symbolName, importPath, isDefaultImport: isDefaultImport2 }) => {
const innerFn = arrowFn([new FnParam("m", DYNAMIC_TYPE)], variable("m").prop(isDefaultImport2 ? "default" : symbolName));
return new DynamicImportExpr(importPath).prop("then").callFn([innerFn]);
});
return arrowFn([], literalArr(dynamicImports));
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/r3_class_debug_info_compiler.mjs
function compileClassDebugInfo(debugInfo) {
const debugInfoObject = {
className: debugInfo.className
};
if (debugInfo.filePath) {
debugInfoObject.filePath = debugInfo.filePath;
debugInfoObject.lineNumber = debugInfo.lineNumber;
}
if (debugInfo.forbidOrphanRendering) {
debugInfoObject.forbidOrphanRendering = literal(true);
}
const fnCall = importExpr(Identifiers.setClassDebugInfo).callFn([debugInfo.type, mapLiteral(debugInfoObject)]);
const iife = arrowFn([], [devOnlyGuardedExpression(fnCall).toStmt()]);
return iife.callFn([]);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/partial/class_metadata.mjs
var MINIMUM_PARTIAL_LINKER_VERSION = "12.0.0";
var MINIMUM_PARTIAL_LINKER_DEFER_SUPPORT_VERSION = "18.0.0";
function compileDeclareClassMetadata(metadata) {
const definitionMap = new DefinitionMap();
definitionMap.set("minVersion", literal(MINIMUM_PARTIAL_LINKER_VERSION));
definitionMap.set("version", literal("18.2.6"));
definitionMap.set("ngImport", importExpr(Identifiers.core));
definitionMap.set("type", metadata.type);
definitionMap.set("decorators", metadata.decorators);
definitionMap.set("ctorParameters", metadata.ctorParameters);
definitionMap.set("propDecorators", metadata.propDecorators);
return importExpr(Identifiers.declareClassMetadata).callFn([definitionMap.toLiteralMap()]);
}
function compileComponentDeclareClassMetadata(metadata, dependencies) {
var _a2, _b2;
if (dependencies === null || dependencies.length === 0) {
return compileDeclareClassMetadata(metadata);
}
const definitionMap = new DefinitionMap();
const callbackReturnDefinitionMap = new DefinitionMap();
callbackReturnDefinitionMap.set("decorators", metadata.decorators);
callbackReturnDefinitionMap.set("ctorParameters", (_a2 = metadata.ctorParameters) != null ? _a2 : literal(null));
callbackReturnDefinitionMap.set("propDecorators", (_b2 = metadata.propDecorators) != null ? _b2 : literal(null));
definitionMap.set("minVersion", literal(MINIMUM_PARTIAL_LINKER_DEFER_SUPPORT_VERSION));
definitionMap.set("version", literal("18.2.6"));
definitionMap.set("ngImport", importExpr(Identifiers.core));
definitionMap.set("type", metadata.type);
definitionMap.set("resolveDeferredDeps", compileComponentMetadataAsyncResolver(dependencies));
definitionMap.set("resolveMetadata", arrowFn(dependencies.map((dep) => new FnParam(dep.symbolName, DYNAMIC_TYPE)), callbackReturnDefinitionMap.toLiteralMap()));
return importExpr(Identifiers.declareClassMetadataAsync).callFn([definitionMap.toLiteralMap()]);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/partial/util.mjs
function toOptionalLiteralArray(values, mapper) {
if (values === null || values.length === 0) {
return null;
}
return literalArr(values.map((value) => mapper(value)));
}
function toOptionalLiteralMap(object, mapper) {
const entries = Object.keys(object).map((key) => {
const value = object[key];
return { key, value: mapper(value), quoted: true };
});
if (entries.length > 0) {
return literalMap(entries);
} else {
return null;
}
}
function compileDependencies(deps) {
if (deps === "invalid") {
return literal("invalid");
} else if (deps === null) {
return literal(null);
} else {
return literalArr(deps.map(compileDependency));
}
}
function compileDependency(dep) {
const depMeta = new DefinitionMap();
depMeta.set("token", dep.token);
if (dep.attributeNameType !== null) {
depMeta.set("attribute", literal(true));
}
if (dep.host) {
depMeta.set("host", literal(true));
}
if (dep.optional) {
depMeta.set("optional", literal(true));
}
if (dep.self) {
depMeta.set("self", literal(true));
}
if (dep.skipSelf) {
depMeta.set("skipSelf", literal(true));
}
return depMeta.toLiteralMap();
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/partial/directive.mjs
function compileDeclareDirectiveFromMetadata(meta) {
const definitionMap = createDirectiveDefinitionMap(meta);
const expression = importExpr(Identifiers.declareDirective).callFn([definitionMap.toLiteralMap()]);
const type = createDirectiveType(meta);
return { expression, type, statements: [] };
}
function createDirectiveDefinitionMap(meta) {
var _a2;
const definitionMap = new DefinitionMap();
const minVersion = getMinimumVersionForPartialOutput(meta);
definitionMap.set("minVersion", literal(minVersion));
definitionMap.set("version", literal("18.2.6"));
definitionMap.set("type", meta.type.value);
if (meta.isStandalone) {
definitionMap.set("isStandalone", literal(meta.isStandalone));
}
if (meta.isSignal) {
definitionMap.set("isSignal", literal(meta.isSignal));
}
if (meta.selector !== null) {
definitionMap.set("selector", literal(meta.selector));
}
definitionMap.set("inputs", needsNewInputPartialOutput(meta) ? createInputsPartialMetadata(meta.inputs) : legacyInputsPartialMetadata(meta.inputs));
definitionMap.set("outputs", conditionallyCreateDirectiveBindingLiteral(meta.outputs));
definitionMap.set("host", compileHostMetadata(meta.host));
definitionMap.set("providers", meta.providers);
if (meta.queries.length > 0) {
definitionMap.set("queries", literalArr(meta.queries.map(compileQuery)));
}
if (meta.viewQueries.length > 0) {
definitionMap.set("viewQueries", literalArr(meta.viewQueries.map(compileQuery)));
}
if (meta.exportAs !== null) {
definitionMap.set("exportAs", asLiteral(meta.exportAs));
}
if (meta.usesInheritance) {
definitionMap.set("usesInheritance", literal(true));
}
if (meta.lifecycle.usesOnChanges) {
definitionMap.set("usesOnChanges", literal(true));
}
if ((_a2 = meta.hostDirectives) == null ? void 0 : _a2.length) {
definitionMap.set("hostDirectives", createHostDirectives(meta.hostDirectives));
}
definitionMap.set("ngImport", importExpr(Identifiers.core));
return definitionMap;
}
function getMinimumVersionForPartialOutput(meta) {
let minVersion = "14.0.0";
const hasDecoratorTransformFunctions = Object.values(meta.inputs).some((input) => input.transformFunction !== null);
if (hasDecoratorTransformFunctions) {
minVersion = "16.1.0";
}
if (needsNewInputPartialOutput(meta)) {
minVersion = "17.1.0";
}
if (meta.queries.some((q) => q.isSignal) || meta.viewQueries.some((q) => q.isSignal)) {
minVersion = "17.2.0";
}
return minVersion;
}
function needsNewInputPartialOutput(meta) {
return Object.values(meta.inputs).some((input) => input.isSignal);
}
function compileQuery(query) {
const meta = new DefinitionMap();
meta.set("propertyName", literal(query.propertyName));
if (query.first) {
meta.set("first", literal(true));
}
meta.set("predicate", Array.isArray(query.predicate) ? asLiteral(query.predicate) : convertFromMaybeForwardRefExpression(query.predicate));
if (!query.emitDistinctChangesOnly) {
meta.set("emitDistinctChangesOnly", literal(false));
} else {
}
if (query.descendants) {
meta.set("descendants", literal(true));
}
meta.set("read", query.read);
if (query.static) {
meta.set("static", literal(true));
}
if (query.isSignal) {
meta.set("isSignal", literal(true));
}
return meta.toLiteralMap();
}
function compileHostMetadata(meta) {
const hostMetadata = new DefinitionMap();
hostMetadata.set("attributes", toOptionalLiteralMap(meta.attributes, (expression) => expression));
hostMetadata.set("listeners", toOptionalLiteralMap(meta.listeners, literal));
hostMetadata.set("properties", toOptionalLiteralMap(meta.properties, literal));
if (meta.specialAttributes.styleAttr) {
hostMetadata.set("styleAttribute", literal(meta.specialAttributes.styleAttr));
}
if (meta.specialAttributes.classAttr) {
hostMetadata.set("classAttribute", literal(meta.specialAttributes.classAttr));
}
if (hostMetadata.values.length > 0) {
return hostMetadata.toLiteralMap();
} else {
return null;
}
}
function createHostDirectives(hostDirectives) {
const expressions = hostDirectives.map((current) => {
const keys = [
{
key: "directive",
value: current.isForwardReference ? generateForwardRef(current.directive.type) : current.directive.type,
quoted: false
}
];
const inputsLiteral = current.inputs ? createHostDirectivesMappingArray(current.inputs) : null;
const outputsLiteral = current.outputs ? createHostDirectivesMappingArray(current.outputs) : null;
if (inputsLiteral) {
keys.push({ key: "inputs", value: inputsLiteral, quoted: false });
}
if (outputsLiteral) {
keys.push({ key: "outputs", value: outputsLiteral, quoted: false });
}
return literalMap(keys);
});
return literalArr(expressions);
}
function createInputsPartialMetadata(inputs) {
const keys = Object.getOwnPropertyNames(inputs);
if (keys.length === 0) {
return null;
}
return literalMap(keys.map((declaredName) => {
var _a2;
const value = inputs[declaredName];
return {
key: declaredName,
quoted: UNSAFE_OBJECT_KEY_NAME_REGEXP.test(declaredName),
value: literalMap([
{ key: "classPropertyName", quoted: false, value: asLiteral(value.classPropertyName) },
{ key: "publicName", quoted: false, value: asLiteral(value.bindingPropertyName) },
{ key: "isSignal", quoted: false, value: asLiteral(value.isSignal) },
{ key: "isRequired", quoted: false, value: asLiteral(value.required) },
{ key: "transformFunction", quoted: false, value: (_a2 = value.transformFunction) != null ? _a2 : NULL_EXPR }
])
};
}));
}
function legacyInputsPartialMetadata(inputs) {
const keys = Object.getOwnPropertyNames(inputs);
if (keys.length === 0) {
return null;
}
return literalMap(keys.map((declaredName) => {
const value = inputs[declaredName];
const publicName = value.bindingPropertyName;
const differentDeclaringName = publicName !== declaredName;
let result;
if (differentDeclaringName || value.transformFunction !== null) {
const values = [asLiteral(publicName), asLiteral(declaredName)];
if (value.transformFunction !== null) {
values.push(value.transformFunction);
}
result = literalArr(values);
} else {
result = asLiteral(publicName);
}
return {
key: declaredName,
quoted: UNSAFE_OBJECT_KEY_NAME_REGEXP.test(declaredName),
value: result
};
}));
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/partial/component.mjs
function compileDeclareComponentFromMetadata(meta, template2, additionalTemplateInfo) {
const definitionMap = createComponentDefinitionMap(meta, template2, additionalTemplateInfo);
const expression = importExpr(Identifiers.declareComponent).callFn([definitionMap.toLiteralMap()]);
const type = createComponentType(meta);
return { expression, type, statements: [] };
}
function createComponentDefinitionMap(meta, template2, templateInfo) {
const definitionMap = createDirectiveDefinitionMap(meta);
const blockVisitor = new BlockPresenceVisitor();
visitAll(blockVisitor, template2.nodes);
definitionMap.set("template", getTemplateExpression(template2, templateInfo));
if (templateInfo.isInline) {
definitionMap.set("isInline", literal(true));
}
if (blockVisitor.hasBlocks) {
definitionMap.set("minVersion", literal("17.0.0"));
}
definitionMap.set("styles", toOptionalLiteralArray(meta.styles, literal));
definitionMap.set("dependencies", compileUsedDependenciesMetadata(meta));
definitionMap.set("viewProviders", meta.viewProviders);
definitionMap.set("animations", meta.animations);
if (meta.changeDetection !== null) {
if (typeof meta.changeDetection === "object") {
throw new Error("Impossible state! Change detection flag is not resolved!");
}
definitionMap.set("changeDetection", importExpr(Identifiers.ChangeDetectionStrategy).prop(ChangeDetectionStrategy[meta.changeDetection]));
}
if (meta.encapsulation !== ViewEncapsulation.Emulated) {
definitionMap.set("encapsulation", importExpr(Identifiers.ViewEncapsulation).prop(ViewEncapsulation[meta.encapsulation]));
}
if (meta.interpolation !== DEFAULT_INTERPOLATION_CONFIG) {
definitionMap.set("interpolation", literalArr([literal(meta.interpolation.start), literal(meta.interpolation.end)]));
}
if (template2.preserveWhitespaces === true) {
definitionMap.set("preserveWhitespaces", literal(true));
}
if (meta.defer.mode === 0) {
const resolvers = [];
let hasResolvers = false;
for (const deps of meta.defer.blocks.values()) {
if (deps === null) {
resolvers.push(literal(null));
} else {
resolvers.push(deps);
hasResolvers = true;
}
}
if (hasResolvers) {
definitionMap.set("deferBlockDependencies", literalArr(resolvers));
}
} else {
throw new Error("Unsupported defer function emit mode in partial compilation");
}
return definitionMap;
}
function getTemplateExpression(template2, templateInfo) {
if (templateInfo.inlineTemplateLiteralExpression !== null) {
return templateInfo.inlineTemplateLiteralExpression;
}
if (templateInfo.isInline) {
return literal(templateInfo.content, null, null);
}
const contents = templateInfo.content;
const file = new ParseSourceFile(contents, templateInfo.sourceUrl);
const start = new ParseLocation(file, 0, 0, 0);
const end = computeEndLocation(file, contents);
const span = new ParseSourceSpan(start, end);
return literal(contents, null, span);
}
function computeEndLocation(file, contents) {
const length = contents.length;
let lineStart = 0;
let lastLineStart = 0;
let line = 0;
do {
lineStart = contents.indexOf("\n", lastLineStart);
if (lineStart !== -1) {
lastLineStart = lineStart + 1;
line++;
}
} while (lineStart !== -1);
return new ParseLocation(file, length, line, length - lastLineStart);
}
function compileUsedDependenciesMetadata(meta) {
const wrapType = meta.declarationListEmitMode !== 0 ? generateForwardRef : (expr) => expr;
if (meta.declarationListEmitMode === 3) {
throw new Error(`Unsupported emit mode`);
}
return toOptionalLiteralArray(meta.declarations, (decl) => {
switch (decl.kind) {
case R3TemplateDependencyKind.Directive:
const dirMeta = new DefinitionMap();
dirMeta.set("kind", literal(decl.isComponent ? "component" : "directive"));
dirMeta.set("type", wrapType(decl.type));
dirMeta.set("selector", literal(decl.selector));
dirMeta.set("inputs", toOptionalLiteralArray(decl.inputs, literal));
dirMeta.set("outputs", toOptionalLiteralArray(decl.outputs, literal));
dirMeta.set("exportAs", toOptionalLiteralArray(decl.exportAs, literal));
return dirMeta.toLiteralMap();
case R3TemplateDependencyKind.Pipe:
const pipeMeta = new DefinitionMap();
pipeMeta.set("kind", literal("pipe"));
pipeMeta.set("type", wrapType(decl.type));
pipeMeta.set("name", literal(decl.name));
return pipeMeta.toLiteralMap();
case R3TemplateDependencyKind.NgModule:
const ngModuleMeta = new DefinitionMap();
ngModuleMeta.set("kind", literal("ngmodule"));
ngModuleMeta.set("type", wrapType(decl.type));
return ngModuleMeta.toLiteralMap();
}
});
}
var BlockPresenceVisitor = class extends RecursiveVisitor {
constructor() {
super(...arguments);
this.hasBlocks = false;
}
visitDeferredBlock() {
this.hasBlocks = true;
}
visitDeferredBlockPlaceholder() {
this.hasBlocks = true;
}
visitDeferredBlockLoading() {
this.hasBlocks = true;
}
visitDeferredBlockError() {
this.hasBlocks = true;
}
visitIfBlock() {
this.hasBlocks = true;
}
visitIfBlockBranch() {
this.hasBlocks = true;
}
visitForLoopBlock() {
this.hasBlocks = true;
}
visitForLoopBlockEmpty() {
this.hasBlocks = true;
}
visitSwitchBlock() {
this.hasBlocks = true;
}
visitSwitchBlockCase() {
this.hasBlocks = true;
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/partial/factory.mjs
var MINIMUM_PARTIAL_LINKER_VERSION2 = "12.0.0";
function compileDeclareFactoryFunction(meta) {
const definitionMap = new DefinitionMap();
definitionMap.set("minVersion", literal(MINIMUM_PARTIAL_LINKER_VERSION2));
definitionMap.set("version", literal("18.2.6"));
definitionMap.set("ngImport", importExpr(Identifiers.core));
definitionMap.set("type", meta.type.value);
definitionMap.set("deps", compileDependencies(meta.deps));
definitionMap.set("target", importExpr(Identifiers.FactoryTarget).prop(FactoryTarget[meta.target]));
return {
expression: importExpr(Identifiers.declareFactory).callFn([definitionMap.toLiteralMap()]),
statements: [],
type: createFactoryType(meta)
};
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/partial/injectable.mjs
var MINIMUM_PARTIAL_LINKER_VERSION3 = "12.0.0";
function compileDeclareInjectableFromMetadata(meta) {
const definitionMap = createInjectableDefinitionMap(meta);
const expression = importExpr(Identifiers.declareInjectable).callFn([definitionMap.toLiteralMap()]);
const type = createInjectableType(meta);
return { expression, type, statements: [] };
}
function createInjectableDefinitionMap(meta) {
const definitionMap = new DefinitionMap();
definitionMap.set("minVersion", literal(MINIMUM_PARTIAL_LINKER_VERSION3));
definitionMap.set("version", literal("18.2.6"));
definitionMap.set("ngImport", importExpr(Identifiers.core));
definitionMap.set("type", meta.type.value);
if (meta.providedIn !== void 0) {
const providedIn = convertFromMaybeForwardRefExpression(meta.providedIn);
if (providedIn.value !== null) {
definitionMap.set("providedIn", providedIn);
}
}
if (meta.useClass !== void 0) {
definitionMap.set("useClass", convertFromMaybeForwardRefExpression(meta.useClass));
}
if (meta.useExisting !== void 0) {
definitionMap.set("useExisting", convertFromMaybeForwardRefExpression(meta.useExisting));
}
if (meta.useValue !== void 0) {
definitionMap.set("useValue", convertFromMaybeForwardRefExpression(meta.useValue));
}
if (meta.useFactory !== void 0) {
definitionMap.set("useFactory", meta.useFactory);
}
if (meta.deps !== void 0) {
definitionMap.set("deps", literalArr(meta.deps.map(compileDependency)));
}
return definitionMap;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/partial/injector.mjs
var MINIMUM_PARTIAL_LINKER_VERSION4 = "12.0.0";
function compileDeclareInjectorFromMetadata(meta) {
const definitionMap = createInjectorDefinitionMap(meta);
const expression = importExpr(Identifiers.declareInjector).callFn([definitionMap.toLiteralMap()]);
const type = createInjectorType(meta);
return { expression, type, statements: [] };
}
function createInjectorDefinitionMap(meta) {
const definitionMap = new DefinitionMap();
definitionMap.set("minVersion", literal(MINIMUM_PARTIAL_LINKER_VERSION4));
definitionMap.set("version", literal("18.2.6"));
definitionMap.set("ngImport", importExpr(Identifiers.core));
definitionMap.set("type", meta.type.value);
definitionMap.set("providers", meta.providers);
if (meta.imports.length > 0) {
definitionMap.set("imports", literalArr(meta.imports));
}
return definitionMap;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/partial/ng_module.mjs
var MINIMUM_PARTIAL_LINKER_VERSION5 = "14.0.0";
function compileDeclareNgModuleFromMetadata(meta) {
const definitionMap = createNgModuleDefinitionMap(meta);
const expression = importExpr(Identifiers.declareNgModule).callFn([definitionMap.toLiteralMap()]);
const type = createNgModuleType(meta);
return { expression, type, statements: [] };
}
function createNgModuleDefinitionMap(meta) {
const definitionMap = new DefinitionMap();
if (meta.kind === R3NgModuleMetadataKind.Local) {
throw new Error("Invalid path! Local compilation mode should not get into the partial compilation path");
}
definitionMap.set("minVersion", literal(MINIMUM_PARTIAL_LINKER_VERSION5));
definitionMap.set("version", literal("18.2.6"));
definitionMap.set("ngImport", importExpr(Identifiers.core));
definitionMap.set("type", meta.type.value);
if (meta.bootstrap.length > 0) {
definitionMap.set("bootstrap", refsToArray(meta.bootstrap, meta.containsForwardDecls));
}
if (meta.declarations.length > 0) {
definitionMap.set("declarations", refsToArray(meta.declarations, meta.containsForwardDecls));
}
if (meta.imports.length > 0) {
definitionMap.set("imports", refsToArray(meta.imports, meta.containsForwardDecls));
}
if (meta.exports.length > 0) {
definitionMap.set("exports", refsToArray(meta.exports, meta.containsForwardDecls));
}
if (meta.schemas !== null && meta.schemas.length > 0) {
definitionMap.set("schemas", literalArr(meta.schemas.map((ref) => ref.value)));
}
if (meta.id !== null) {
definitionMap.set("id", meta.id);
}
return definitionMap;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/render3/partial/pipe.mjs
var MINIMUM_PARTIAL_LINKER_VERSION6 = "14.0.0";
function compileDeclarePipeFromMetadata(meta) {
const definitionMap = createPipeDefinitionMap(meta);
const expression = importExpr(Identifiers.declarePipe).callFn([definitionMap.toLiteralMap()]);
const type = createPipeType(meta);
return { expression, type, statements: [] };
}
function createPipeDefinitionMap(meta) {
const definitionMap = new DefinitionMap();
definitionMap.set("minVersion", literal(MINIMUM_PARTIAL_LINKER_VERSION6));
definitionMap.set("version", literal("18.2.6"));
definitionMap.set("ngImport", importExpr(Identifiers.core));
definitionMap.set("type", meta.type.value);
if (meta.isStandalone) {
definitionMap.set("isStandalone", literal(meta.isStandalone));
}
definitionMap.set("name", literal(meta.pipeName));
if (meta.pure === false) {
definitionMap.set("pure", literal(meta.pure));
}
return definitionMap;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler/src/compiler.mjs
publishFacade(_global);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/version.mjs
var VERSION3 = new Version("18.2.6");
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/imports/src/emitter.mjs
var import_typescript5 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/diagnostics/src/error_code.mjs
var ErrorCode;
(function(ErrorCode2) {
ErrorCode2[ErrorCode2["DECORATOR_ARG_NOT_LITERAL"] = 1001] = "DECORATOR_ARG_NOT_LITERAL";
ErrorCode2[ErrorCode2["DECORATOR_ARITY_WRONG"] = 1002] = "DECORATOR_ARITY_WRONG";
ErrorCode2[ErrorCode2["DECORATOR_NOT_CALLED"] = 1003] = "DECORATOR_NOT_CALLED";
ErrorCode2[ErrorCode2["DECORATOR_UNEXPECTED"] = 1005] = "DECORATOR_UNEXPECTED";
ErrorCode2[ErrorCode2["DECORATOR_COLLISION"] = 1006] = "DECORATOR_COLLISION";
ErrorCode2[ErrorCode2["VALUE_HAS_WRONG_TYPE"] = 1010] = "VALUE_HAS_WRONG_TYPE";
ErrorCode2[ErrorCode2["VALUE_NOT_LITERAL"] = 1011] = "VALUE_NOT_LITERAL";
ErrorCode2[ErrorCode2["INITIALIZER_API_WITH_DISALLOWED_DECORATOR"] = 1050] = "INITIALIZER_API_WITH_DISALLOWED_DECORATOR";
ErrorCode2[ErrorCode2["INITIALIZER_API_DECORATOR_METADATA_COLLISION"] = 1051] = "INITIALIZER_API_DECORATOR_METADATA_COLLISION";
ErrorCode2[ErrorCode2["INITIALIZER_API_NO_REQUIRED_FUNCTION"] = 1052] = "INITIALIZER_API_NO_REQUIRED_FUNCTION";
ErrorCode2[ErrorCode2["INITIALIZER_API_DISALLOWED_MEMBER_VISIBILITY"] = 1053] = "INITIALIZER_API_DISALLOWED_MEMBER_VISIBILITY";
ErrorCode2[ErrorCode2["INCORRECTLY_DECLARED_ON_STATIC_MEMBER"] = 1100] = "INCORRECTLY_DECLARED_ON_STATIC_MEMBER";
ErrorCode2[ErrorCode2["COMPONENT_MISSING_TEMPLATE"] = 2001] = "COMPONENT_MISSING_TEMPLATE";
ErrorCode2[ErrorCode2["PIPE_MISSING_NAME"] = 2002] = "PIPE_MISSING_NAME";
ErrorCode2[ErrorCode2["PARAM_MISSING_TOKEN"] = 2003] = "PARAM_MISSING_TOKEN";
ErrorCode2[ErrorCode2["DIRECTIVE_MISSING_SELECTOR"] = 2004] = "DIRECTIVE_MISSING_SELECTOR";
ErrorCode2[ErrorCode2["UNDECORATED_PROVIDER"] = 2005] = "UNDECORATED_PROVIDER";
ErrorCode2[ErrorCode2["DIRECTIVE_INHERITS_UNDECORATED_CTOR"] = 2006] = "DIRECTIVE_INHERITS_UNDECORATED_CTOR";
ErrorCode2[ErrorCode2["UNDECORATED_CLASS_USING_ANGULAR_FEATURES"] = 2007] = "UNDECORATED_CLASS_USING_ANGULAR_FEATURES";
ErrorCode2[ErrorCode2["COMPONENT_RESOURCE_NOT_FOUND"] = 2008] = "COMPONENT_RESOURCE_NOT_FOUND";
ErrorCode2[ErrorCode2["COMPONENT_INVALID_SHADOW_DOM_SELECTOR"] = 2009] = "COMPONENT_INVALID_SHADOW_DOM_SELECTOR";
ErrorCode2[ErrorCode2["COMPONENT_NOT_STANDALONE"] = 2010] = "COMPONENT_NOT_STANDALONE";
ErrorCode2[ErrorCode2["COMPONENT_IMPORT_NOT_STANDALONE"] = 2011] = "COMPONENT_IMPORT_NOT_STANDALONE";
ErrorCode2[ErrorCode2["COMPONENT_UNKNOWN_IMPORT"] = 2012] = "COMPONENT_UNKNOWN_IMPORT";
ErrorCode2[ErrorCode2["HOST_DIRECTIVE_INVALID"] = 2013] = "HOST_DIRECTIVE_INVALID";
ErrorCode2[ErrorCode2["HOST_DIRECTIVE_NOT_STANDALONE"] = 2014] = "HOST_DIRECTIVE_NOT_STANDALONE";
ErrorCode2[ErrorCode2["HOST_DIRECTIVE_COMPONENT"] = 2015] = "HOST_DIRECTIVE_COMPONENT";
ErrorCode2[ErrorCode2["INJECTABLE_INHERITS_INVALID_CONSTRUCTOR"] = 2016] = "INJECTABLE_INHERITS_INVALID_CONSTRUCTOR";
ErrorCode2[ErrorCode2["HOST_DIRECTIVE_UNDEFINED_BINDING"] = 2017] = "HOST_DIRECTIVE_UNDEFINED_BINDING";
ErrorCode2[ErrorCode2["HOST_DIRECTIVE_CONFLICTING_ALIAS"] = 2018] = "HOST_DIRECTIVE_CONFLICTING_ALIAS";
ErrorCode2[ErrorCode2["HOST_DIRECTIVE_MISSING_REQUIRED_BINDING"] = 2019] = "HOST_DIRECTIVE_MISSING_REQUIRED_BINDING";
ErrorCode2[ErrorCode2["CONFLICTING_INPUT_TRANSFORM"] = 2020] = "CONFLICTING_INPUT_TRANSFORM";
ErrorCode2[ErrorCode2["COMPONENT_INVALID_STYLE_URLS"] = 2021] = "COMPONENT_INVALID_STYLE_URLS";
ErrorCode2[ErrorCode2["COMPONENT_UNKNOWN_DEFERRED_IMPORT"] = 2022] = "COMPONENT_UNKNOWN_DEFERRED_IMPORT";
ErrorCode2[ErrorCode2["SYMBOL_NOT_EXPORTED"] = 3001] = "SYMBOL_NOT_EXPORTED";
ErrorCode2[ErrorCode2["IMPORT_CYCLE_DETECTED"] = 3003] = "IMPORT_CYCLE_DETECTED";
ErrorCode2[ErrorCode2["IMPORT_GENERATION_FAILURE"] = 3004] = "IMPORT_GENERATION_FAILURE";
ErrorCode2[ErrorCode2["CONFIG_FLAT_MODULE_NO_INDEX"] = 4001] = "CONFIG_FLAT_MODULE_NO_INDEX";
ErrorCode2[ErrorCode2["CONFIG_STRICT_TEMPLATES_IMPLIES_FULL_TEMPLATE_TYPECHECK"] = 4002] = "CONFIG_STRICT_TEMPLATES_IMPLIES_FULL_TEMPLATE_TYPECHECK";
ErrorCode2[ErrorCode2["CONFIG_EXTENDED_DIAGNOSTICS_IMPLIES_STRICT_TEMPLATES"] = 4003] = "CONFIG_EXTENDED_DIAGNOSTICS_IMPLIES_STRICT_TEMPLATES";
ErrorCode2[ErrorCode2["CONFIG_EXTENDED_DIAGNOSTICS_UNKNOWN_CATEGORY_LABEL"] = 4004] = "CONFIG_EXTENDED_DIAGNOSTICS_UNKNOWN_CATEGORY_LABEL";
ErrorCode2[ErrorCode2["CONFIG_EXTENDED_DIAGNOSTICS_UNKNOWN_CHECK"] = 4005] = "CONFIG_EXTENDED_DIAGNOSTICS_UNKNOWN_CHECK";
ErrorCode2[ErrorCode2["HOST_BINDING_PARSE_ERROR"] = 5001] = "HOST_BINDING_PARSE_ERROR";
ErrorCode2[ErrorCode2["TEMPLATE_PARSE_ERROR"] = 5002] = "TEMPLATE_PARSE_ERROR";
ErrorCode2[ErrorCode2["NGMODULE_INVALID_DECLARATION"] = 6001] = "NGMODULE_INVALID_DECLARATION";
ErrorCode2[ErrorCode2["NGMODULE_INVALID_IMPORT"] = 6002] = "NGMODULE_INVALID_IMPORT";
ErrorCode2[ErrorCode2["NGMODULE_INVALID_EXPORT"] = 6003] = "NGMODULE_INVALID_EXPORT";
ErrorCode2[ErrorCode2["NGMODULE_INVALID_REEXPORT"] = 6004] = "NGMODULE_INVALID_REEXPORT";
ErrorCode2[ErrorCode2["NGMODULE_MODULE_WITH_PROVIDERS_MISSING_GENERIC"] = 6005] = "NGMODULE_MODULE_WITH_PROVIDERS_MISSING_GENERIC";
ErrorCode2[ErrorCode2["NGMODULE_REEXPORT_NAME_COLLISION"] = 6006] = "NGMODULE_REEXPORT_NAME_COLLISION";
ErrorCode2[ErrorCode2["NGMODULE_DECLARATION_NOT_UNIQUE"] = 6007] = "NGMODULE_DECLARATION_NOT_UNIQUE";
ErrorCode2[ErrorCode2["NGMODULE_DECLARATION_IS_STANDALONE"] = 6008] = "NGMODULE_DECLARATION_IS_STANDALONE";
ErrorCode2[ErrorCode2["NGMODULE_BOOTSTRAP_IS_STANDALONE"] = 6009] = "NGMODULE_BOOTSTRAP_IS_STANDALONE";
ErrorCode2[ErrorCode2["WARN_NGMODULE_ID_UNNECESSARY"] = 6100] = "WARN_NGMODULE_ID_UNNECESSARY";
ErrorCode2[ErrorCode2["SCHEMA_INVALID_ELEMENT"] = 8001] = "SCHEMA_INVALID_ELEMENT";
ErrorCode2[ErrorCode2["SCHEMA_INVALID_ATTRIBUTE"] = 8002] = "SCHEMA_INVALID_ATTRIBUTE";
ErrorCode2[ErrorCode2["MISSING_REFERENCE_TARGET"] = 8003] = "MISSING_REFERENCE_TARGET";
ErrorCode2[ErrorCode2["MISSING_PIPE"] = 8004] = "MISSING_PIPE";
ErrorCode2[ErrorCode2["WRITE_TO_READ_ONLY_VARIABLE"] = 8005] = "WRITE_TO_READ_ONLY_VARIABLE";
ErrorCode2[ErrorCode2["DUPLICATE_VARIABLE_DECLARATION"] = 8006] = "DUPLICATE_VARIABLE_DECLARATION";
ErrorCode2[ErrorCode2["SPLIT_TWO_WAY_BINDING"] = 8007] = "SPLIT_TWO_WAY_BINDING";
ErrorCode2[ErrorCode2["MISSING_REQUIRED_INPUTS"] = 8008] = "MISSING_REQUIRED_INPUTS";
ErrorCode2[ErrorCode2["ILLEGAL_FOR_LOOP_TRACK_ACCESS"] = 8009] = "ILLEGAL_FOR_LOOP_TRACK_ACCESS";
ErrorCode2[ErrorCode2["INACCESSIBLE_DEFERRED_TRIGGER_ELEMENT"] = 8010] = "INACCESSIBLE_DEFERRED_TRIGGER_ELEMENT";
ErrorCode2[ErrorCode2["CONTROL_FLOW_PREVENTING_CONTENT_PROJECTION"] = 8011] = "CONTROL_FLOW_PREVENTING_CONTENT_PROJECTION";
ErrorCode2[ErrorCode2["DEFERRED_PIPE_USED_EAGERLY"] = 8012] = "DEFERRED_PIPE_USED_EAGERLY";
ErrorCode2[ErrorCode2["DEFERRED_DIRECTIVE_USED_EAGERLY"] = 8013] = "DEFERRED_DIRECTIVE_USED_EAGERLY";
ErrorCode2[ErrorCode2["DEFERRED_DEPENDENCY_IMPORTED_EAGERLY"] = 8014] = "DEFERRED_DEPENDENCY_IMPORTED_EAGERLY";
ErrorCode2[ErrorCode2["ILLEGAL_LET_WRITE"] = 8015] = "ILLEGAL_LET_WRITE";
ErrorCode2[ErrorCode2["LET_USED_BEFORE_DEFINITION"] = 8016] = "LET_USED_BEFORE_DEFINITION";
ErrorCode2[ErrorCode2["CONFLICTING_LET_DECLARATION"] = 8017] = "CONFLICTING_LET_DECLARATION";
ErrorCode2[ErrorCode2["INVALID_BANANA_IN_BOX"] = 8101] = "INVALID_BANANA_IN_BOX";
ErrorCode2[ErrorCode2["NULLISH_COALESCING_NOT_NULLABLE"] = 8102] = "NULLISH_COALESCING_NOT_NULLABLE";
ErrorCode2[ErrorCode2["MISSING_CONTROL_FLOW_DIRECTIVE"] = 8103] = "MISSING_CONTROL_FLOW_DIRECTIVE";
ErrorCode2[ErrorCode2["TEXT_ATTRIBUTE_NOT_BINDING"] = 8104] = "TEXT_ATTRIBUTE_NOT_BINDING";
ErrorCode2[ErrorCode2["MISSING_NGFOROF_LET"] = 8105] = "MISSING_NGFOROF_LET";
ErrorCode2[ErrorCode2["SUFFIX_NOT_SUPPORTED"] = 8106] = "SUFFIX_NOT_SUPPORTED";
ErrorCode2[ErrorCode2["OPTIONAL_CHAIN_NOT_NULLABLE"] = 8107] = "OPTIONAL_CHAIN_NOT_NULLABLE";
ErrorCode2[ErrorCode2["SKIP_HYDRATION_NOT_STATIC"] = 8108] = "SKIP_HYDRATION_NOT_STATIC";
ErrorCode2[ErrorCode2["INTERPOLATED_SIGNAL_NOT_INVOKED"] = 8109] = "INTERPOLATED_SIGNAL_NOT_INVOKED";
ErrorCode2[ErrorCode2["UNSUPPORTED_INITIALIZER_API_USAGE"] = 8110] = "UNSUPPORTED_INITIALIZER_API_USAGE";
ErrorCode2[ErrorCode2["UNINVOKED_FUNCTION_IN_EVENT_BINDING"] = 8111] = "UNINVOKED_FUNCTION_IN_EVENT_BINDING";
ErrorCode2[ErrorCode2["UNUSED_LET_DECLARATION"] = 8112] = "UNUSED_LET_DECLARATION";
ErrorCode2[ErrorCode2["INLINE_TCB_REQUIRED"] = 8900] = "INLINE_TCB_REQUIRED";
ErrorCode2[ErrorCode2["INLINE_TYPE_CTOR_REQUIRED"] = 8901] = "INLINE_TYPE_CTOR_REQUIRED";
ErrorCode2[ErrorCode2["INJECTABLE_DUPLICATE_PROV"] = 9001] = "INJECTABLE_DUPLICATE_PROV";
ErrorCode2[ErrorCode2["SUGGEST_STRICT_TEMPLATES"] = 10001] = "SUGGEST_STRICT_TEMPLATES";
ErrorCode2[ErrorCode2["SUGGEST_SUBOPTIMAL_TYPE_INFERENCE"] = 10002] = "SUGGEST_SUBOPTIMAL_TYPE_INFERENCE";
ErrorCode2[ErrorCode2["LOCAL_COMPILATION_UNRESOLVED_CONST"] = 11001] = "LOCAL_COMPILATION_UNRESOLVED_CONST";
ErrorCode2[ErrorCode2["LOCAL_COMPILATION_UNSUPPORTED_EXPRESSION"] = 11003] = "LOCAL_COMPILATION_UNSUPPORTED_EXPRESSION";
})(ErrorCode || (ErrorCode = {}));
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/diagnostics/src/docs.mjs
var COMPILER_ERRORS_WITH_GUIDES = /* @__PURE__ */ new Set([
ErrorCode.DECORATOR_ARG_NOT_LITERAL,
ErrorCode.IMPORT_CYCLE_DETECTED,
ErrorCode.PARAM_MISSING_TOKEN,
ErrorCode.SCHEMA_INVALID_ELEMENT,
ErrorCode.SCHEMA_INVALID_ATTRIBUTE,
ErrorCode.MISSING_REFERENCE_TARGET,
ErrorCode.COMPONENT_INVALID_SHADOW_DOM_SELECTOR,
ErrorCode.WARN_NGMODULE_ID_UNNECESSARY
]);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/diagnostics/src/error.mjs
var import_typescript2 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/diagnostics/src/util.mjs
function ngErrorCode(code) {
return parseInt("-99" + code);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/diagnostics/src/error.mjs
var FatalDiagnosticError = class extends Error {
constructor(code, node, diagnosticMessage, relatedInformation) {
super(`FatalDiagnosticError: Code: ${code}, Message: ${import_typescript2.default.flattenDiagnosticMessageText(diagnosticMessage, "\n")}`);
this.code = code;
this.node = node;
this.diagnosticMessage = diagnosticMessage;
this.relatedInformation = relatedInformation;
this._isFatalDiagnosticError = true;
Object.setPrototypeOf(this, new.target.prototype);
}
toDiagnostic() {
return makeDiagnostic(this.code, this.node, this.diagnosticMessage, this.relatedInformation);
}
};
function makeDiagnostic(code, node, messageText, relatedInformation) {
node = import_typescript2.default.getOriginalNode(node);
return {
category: import_typescript2.default.DiagnosticCategory.Error,
code: ngErrorCode(code),
file: import_typescript2.default.getOriginalNode(node).getSourceFile(),
start: node.getStart(void 0, false),
length: node.getWidth(),
messageText,
relatedInformation
};
}
function makeDiagnosticChain(messageText, next) {
return {
category: import_typescript2.default.DiagnosticCategory.Message,
code: 0,
messageText,
next
};
}
function makeRelatedInformation(node, messageText) {
node = import_typescript2.default.getOriginalNode(node);
return {
category: import_typescript2.default.DiagnosticCategory.Message,
code: 0,
file: node.getSourceFile(),
start: node.getStart(),
length: node.getWidth(),
messageText
};
}
function addDiagnosticChain(messageText, add) {
if (typeof messageText === "string") {
return makeDiagnosticChain(messageText, add);
}
if (messageText.next === void 0) {
messageText.next = add;
} else {
messageText.next.push(...add);
}
return messageText;
}
function isFatalDiagnosticError(err) {
return err._isFatalDiagnosticError === true;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/diagnostics/src/error_details_base_url.mjs
var ERROR_DETAILS_PAGE_BASE_URL = "https://angular.dev/errors";
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/diagnostics/src/extended_template_diagnostic_name.mjs
var ExtendedTemplateDiagnosticName;
(function(ExtendedTemplateDiagnosticName2) {
ExtendedTemplateDiagnosticName2["INVALID_BANANA_IN_BOX"] = "invalidBananaInBox";
ExtendedTemplateDiagnosticName2["NULLISH_COALESCING_NOT_NULLABLE"] = "nullishCoalescingNotNullable";
ExtendedTemplateDiagnosticName2["OPTIONAL_CHAIN_NOT_NULLABLE"] = "optionalChainNotNullable";
ExtendedTemplateDiagnosticName2["MISSING_CONTROL_FLOW_DIRECTIVE"] = "missingControlFlowDirective";
ExtendedTemplateDiagnosticName2["TEXT_ATTRIBUTE_NOT_BINDING"] = "textAttributeNotBinding";
ExtendedTemplateDiagnosticName2["UNINVOKED_FUNCTION_IN_EVENT_BINDING"] = "uninvokedFunctionInEventBinding";
ExtendedTemplateDiagnosticName2["MISSING_NGFOROF_LET"] = "missingNgForOfLet";
ExtendedTemplateDiagnosticName2["SUFFIX_NOT_SUPPORTED"] = "suffixNotSupported";
ExtendedTemplateDiagnosticName2["SKIP_HYDRATION_NOT_STATIC"] = "skipHydrationNotStatic";
ExtendedTemplateDiagnosticName2["INTERPOLATED_SIGNAL_NOT_INVOKED"] = "interpolatedSignalNotInvoked";
ExtendedTemplateDiagnosticName2["CONTROL_FLOW_PREVENTING_CONTENT_PROJECTION"] = "controlFlowPreventingContentProjection";
ExtendedTemplateDiagnosticName2["UNUSED_LET_DECLARATION"] = "unusedLetDeclaration";
})(ExtendedTemplateDiagnosticName || (ExtendedTemplateDiagnosticName = {}));
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/util/src/typescript.mjs
var import_typescript3 = __toESM(require("typescript"), 1);
var TS = /\.tsx?$/i;
var D_TS = /\.d\.ts$/i;
function isSymbolWithValueDeclaration(symbol) {
return symbol != null && symbol.valueDeclaration !== void 0 && symbol.declarations !== void 0;
}
function isDtsPath(filePath) {
return D_TS.test(filePath);
}
function isNonDeclarationTsPath(filePath) {
return TS.test(filePath) && !D_TS.test(filePath);
}
function isFromDtsFile(node) {
let sf = node.getSourceFile();
if (sf === void 0) {
sf = import_typescript3.default.getOriginalNode(node).getSourceFile();
}
return sf !== void 0 && sf.isDeclarationFile;
}
function nodeNameForError(node) {
if (node.name !== void 0 && import_typescript3.default.isIdentifier(node.name)) {
return node.name.text;
} else {
const kind = import_typescript3.default.SyntaxKind[node.kind];
const { line, character } = import_typescript3.default.getLineAndCharacterOfPosition(node.getSourceFile(), node.getStart());
return `${kind}@${line}:${character}`;
}
}
function getSourceFile(node) {
const directSf = node.getSourceFile();
return directSf !== void 0 ? directSf : import_typescript3.default.getOriginalNode(node).getSourceFile();
}
function getSourceFileOrNull(program, fileName) {
return program.getSourceFile(fileName) || null;
}
function getTokenAtPosition(sf, pos) {
return import_typescript3.default.getTokenAtPosition(sf, pos);
}
function identifierOfNode(decl) {
if (decl.name !== void 0 && import_typescript3.default.isIdentifier(decl.name)) {
return decl.name;
} else {
return null;
}
}
function isDeclaration(node) {
return isValueDeclaration(node) || isTypeDeclaration(node);
}
function isValueDeclaration(node) {
return import_typescript3.default.isClassDeclaration(node) || import_typescript3.default.isFunctionDeclaration(node) || import_typescript3.default.isVariableDeclaration(node);
}
function isTypeDeclaration(node) {
return import_typescript3.default.isEnumDeclaration(node) || import_typescript3.default.isTypeAliasDeclaration(node) || import_typescript3.default.isInterfaceDeclaration(node);
}
function isNamedDeclaration(node) {
const namedNode = node;
return namedNode.name !== void 0 && import_typescript3.default.isIdentifier(namedNode.name);
}
function getRootDirs(host, options) {
const rootDirs = [];
const cwd = host.getCurrentDirectory();
const fs3 = getFileSystem();
if (options.rootDirs !== void 0) {
rootDirs.push(...options.rootDirs);
} else if (options.rootDir !== void 0) {
rootDirs.push(options.rootDir);
} else {
rootDirs.push(cwd);
}
return rootDirs.map((rootDir) => fs3.resolve(cwd, host.getCanonicalFileName(rootDir)));
}
function nodeDebugInfo(node) {
const sf = getSourceFile(node);
const { line, character } = import_typescript3.default.getLineAndCharacterOfPosition(sf, node.pos);
return `[${sf.fileName}: ${import_typescript3.default.SyntaxKind[node.kind]} @ ${line}:${character}]`;
}
function resolveModuleName(moduleName, containingFile, compilerOptions, compilerHost, moduleResolutionCache) {
if (compilerHost.resolveModuleNames) {
return compilerHost.resolveModuleNames(
[moduleName],
containingFile,
void 0,
void 0,
compilerOptions
)[0];
} else {
return import_typescript3.default.resolveModuleName(moduleName, containingFile, compilerOptions, compilerHost, moduleResolutionCache !== null ? moduleResolutionCache : void 0).resolvedModule;
}
}
function isAssignment(node) {
return import_typescript3.default.isBinaryExpression(node) && node.operatorToken.kind === import_typescript3.default.SyntaxKind.EqualsToken;
}
function toUnredirectedSourceFile(sf) {
const redirectInfo = sf.redirectInfo;
if (redirectInfo === void 0) {
return sf;
}
return redirectInfo.unredirected;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/imports/src/find_export.mjs
function findExportedNameOfNode(target, file, reflector) {
const exports = reflector.getExportsOfModule(file);
if (exports === null) {
return null;
}
const declaredName = isNamedDeclaration(target) ? target.name.text : null;
let foundExportName = null;
for (const [exportName, declaration] of exports) {
if (declaration.node !== target) {
continue;
}
if (exportName === declaredName) {
return exportName;
}
foundExportName = exportName;
}
return foundExportName;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/imports/src/emitter.mjs
var ImportFlags;
(function(ImportFlags2) {
ImportFlags2[ImportFlags2["None"] = 0] = "None";
ImportFlags2[ImportFlags2["ForceNewImport"] = 1] = "ForceNewImport";
ImportFlags2[ImportFlags2["NoAliasing"] = 2] = "NoAliasing";
ImportFlags2[ImportFlags2["AllowTypeImports"] = 4] = "AllowTypeImports";
ImportFlags2[ImportFlags2["AllowRelativeDtsImports"] = 8] = "AllowRelativeDtsImports";
ImportFlags2[ImportFlags2["AllowAmbientReferences"] = 16] = "AllowAmbientReferences";
})(ImportFlags || (ImportFlags = {}));
function assertSuccessfulReferenceEmit(result, origin, typeKind) {
if (result.kind === 0) {
return;
}
const message = makeDiagnosticChain(`Unable to import ${typeKind} ${nodeNameForError(result.ref.node)}.`, [makeDiagnosticChain(result.reason)]);
throw new FatalDiagnosticError(ErrorCode.IMPORT_GENERATION_FAILURE, origin, message, [
makeRelatedInformation(result.ref.node, `The ${typeKind} is declared here.`)
]);
}
var ReferenceEmitter = class {
constructor(strategies) {
this.strategies = strategies;
}
emit(ref, context, importFlags = ImportFlags.None) {
for (const strategy of this.strategies) {
const emitted = strategy.emit(ref, context, importFlags);
if (emitted !== null) {
return emitted;
}
}
return {
kind: 1,
ref,
context,
reason: `Unable to write a reference to ${nodeNameForError(ref.node)}.`
};
}
};
var LocalIdentifierStrategy = class {
emit(ref, context, importFlags) {
const refSf = getSourceFile(ref.node);
if (importFlags & ImportFlags.ForceNewImport && refSf !== context) {
return null;
}
if (!isDeclaration(ref.node) && refSf === context) {
return {
kind: 0,
expression: new WrappedNodeExpr(ref.node),
importedFile: null
};
}
if (ref.isAmbient && importFlags & ImportFlags.AllowAmbientReferences) {
const identifier2 = identifierOfNode(ref.node);
if (identifier2 !== null) {
return {
kind: 0,
expression: new WrappedNodeExpr(identifier2),
importedFile: null
};
} else {
return null;
}
}
const identifier = ref.getIdentityIn(context);
if (identifier !== null) {
return {
kind: 0,
expression: new WrappedNodeExpr(identifier),
importedFile: null
};
} else {
return null;
}
}
};
var AbsoluteModuleStrategy = class {
constructor(program, checker, moduleResolver, reflectionHost) {
this.program = program;
this.checker = checker;
this.moduleResolver = moduleResolver;
this.reflectionHost = reflectionHost;
this.moduleExportsCache = /* @__PURE__ */ new Map();
}
emit(ref, context, importFlags) {
if (ref.bestGuessOwningModule === null) {
return null;
} else if (!isDeclaration(ref.node)) {
throw new Error(`Debug assert: unable to import a Reference to non-declaration of type ${import_typescript5.default.SyntaxKind[ref.node.kind]}.`);
} else if ((importFlags & ImportFlags.AllowTypeImports) === 0 && isTypeDeclaration(ref.node)) {
throw new Error(`Importing a type-only declaration of type ${import_typescript5.default.SyntaxKind[ref.node.kind]} in a value position is not allowed.`);
}
const { specifier, resolutionContext } = ref.bestGuessOwningModule;
const exports = this.getExportsOfModule(specifier, resolutionContext);
if (exports.module === null) {
return {
kind: 1,
ref,
context,
reason: `The module '${specifier}' could not be found.`
};
} else if (exports.exportMap === null || !exports.exportMap.has(ref.node)) {
return {
kind: 1,
ref,
context,
reason: `The symbol is not exported from ${exports.module.fileName} (module '${specifier}').`
};
}
const symbolName = exports.exportMap.get(ref.node);
return {
kind: 0,
expression: new ExternalExpr(new ExternalReference(specifier, symbolName)),
importedFile: exports.module
};
}
getExportsOfModule(moduleName, fromFile) {
if (!this.moduleExportsCache.has(moduleName)) {
this.moduleExportsCache.set(moduleName, this.enumerateExportsOfModule(moduleName, fromFile));
}
return this.moduleExportsCache.get(moduleName);
}
enumerateExportsOfModule(specifier, fromFile) {
const entryPointFile = this.moduleResolver.resolveModule(specifier, fromFile);
if (entryPointFile === null) {
return { module: null, exportMap: null };
}
const exports = this.reflectionHost.getExportsOfModule(entryPointFile);
if (exports === null) {
return { module: entryPointFile, exportMap: null };
}
const exportMap = /* @__PURE__ */ new Map();
for (const [name, declaration] of exports) {
if (exportMap.has(declaration.node)) {
const existingExport = exportMap.get(declaration.node);
if (isNamedDeclaration(declaration.node) && declaration.node.name.text === existingExport) {
continue;
}
}
exportMap.set(declaration.node, name);
}
return { module: entryPointFile, exportMap };
}
};
var LogicalProjectStrategy = class {
constructor(reflector, logicalFs) {
this.reflector = reflector;
this.logicalFs = logicalFs;
this.relativePathStrategy = new RelativePathStrategy(this.reflector);
}
emit(ref, context, importFlags) {
const destSf = getSourceFile(ref.node);
const destPath = this.logicalFs.logicalPathOfSf(destSf);
if (destPath === null) {
if (destSf.isDeclarationFile && importFlags & ImportFlags.AllowRelativeDtsImports) {
return this.relativePathStrategy.emit(ref, context);
}
return {
kind: 1,
ref,
context,
reason: `The file ${destSf.fileName} is outside of the configured 'rootDir'.`
};
}
const originPath = this.logicalFs.logicalPathOfSf(context);
if (originPath === null) {
throw new Error(`Debug assert: attempt to import from ${context.fileName} but it's outside the program?`);
}
if (destPath === originPath) {
return null;
}
const name = findExportedNameOfNode(ref.node, destSf, this.reflector);
if (name === null) {
return {
kind: 1,
ref,
context,
reason: `The symbol is not exported from ${destSf.fileName}.`
};
}
const moduleName = LogicalProjectPath.relativePathBetween(originPath, destPath);
return {
kind: 0,
expression: new ExternalExpr({ moduleName, name }),
importedFile: destSf
};
}
};
var RelativePathStrategy = class {
constructor(reflector) {
this.reflector = reflector;
}
emit(ref, context) {
const destSf = getSourceFile(ref.node);
const relativePath = relative(dirname(absoluteFromSourceFile(context)), absoluteFromSourceFile(destSf));
const moduleName = toRelativeImport(stripExtension(relativePath));
const name = findExportedNameOfNode(ref.node, destSf, this.reflector);
if (name === null) {
return {
kind: 1,
ref,
context,
reason: `The symbol is not exported from ${destSf.fileName}.`
};
}
return {
kind: 0,
expression: new ExternalExpr({ moduleName, name }),
importedFile: destSf
};
}
};
var UnifiedModulesStrategy = class {
constructor(reflector, unifiedModulesHost) {
this.reflector = reflector;
this.unifiedModulesHost = unifiedModulesHost;
}
emit(ref, context) {
const destSf = getSourceFile(ref.node);
const name = findExportedNameOfNode(ref.node, destSf, this.reflector);
if (name === null) {
return null;
}
const moduleName = this.unifiedModulesHost.fileNameToModuleName(destSf.fileName, context.fileName);
return {
kind: 0,
expression: new ExternalExpr({ moduleName, name }),
importedFile: destSf
};
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/imports/src/alias.mjs
var CHARS_TO_ESCAPE = /[^a-zA-Z0-9/_]/g;
var UnifiedModulesAliasingHost = class {
constructor(unifiedModulesHost) {
this.unifiedModulesHost = unifiedModulesHost;
this.aliasExportsInDts = false;
}
maybeAliasSymbolAs(ref, context, ngModuleName, isReExport) {
if (!isReExport) {
return null;
}
return this.aliasName(ref.node, context);
}
getAliasIn(decl, via, isReExport) {
if (!isReExport) {
return null;
}
const moduleName = this.unifiedModulesHost.fileNameToModuleName(via.fileName, via.fileName);
return new ExternalExpr({ moduleName, name: this.aliasName(decl, via) });
}
aliasName(decl, context) {
const declModule = this.unifiedModulesHost.fileNameToModuleName(decl.getSourceFile().fileName, context.fileName);
const replaced = declModule.replace(CHARS_TO_ESCAPE, "_").replace(/\//g, "$");
return "\u0275ng$" + replaced + "$$" + decl.name.text;
}
};
var PrivateExportAliasingHost = class {
constructor(host) {
this.host = host;
this.aliasExportsInDts = true;
}
maybeAliasSymbolAs(ref, context, ngModuleName) {
if (ref.hasOwningModuleGuess) {
return null;
}
const exports = this.host.getExportsOfModule(context);
if (exports === null) {
throw new Error(`Could not determine the exports of: ${context.fileName}`);
}
let found = false;
exports.forEach((value) => {
if (value.node === ref.node) {
found = true;
}
});
if (found) {
return null;
}
return `\u0275ngExport\u0275${ngModuleName}\u0275${ref.node.name.text}`;
}
getAliasIn() {
return null;
}
};
var AliasStrategy = class {
emit(ref, context, importMode) {
if (importMode & ImportFlags.NoAliasing || ref.alias === null) {
return null;
}
return {
kind: 0,
expression: ref.alias,
importedFile: "unknown"
};
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/util/src/path.mjs
function relativePathBetween(from, to) {
const relativePath = stripExtension(relative(dirname(resolve(from)), resolve(to)));
return relativePath !== "" ? toRelativeImport(relativePath) : null;
}
function normalizeSeparators2(path4) {
return path4.replace(/\\/g, "/");
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/imports/src/core.mjs
var NoopImportRewriter = class {
rewriteSymbol(symbol, specifier) {
return symbol;
}
rewriteSpecifier(specifier, inContextOfFile) {
return specifier;
}
};
var CORE_SUPPORTED_SYMBOLS = /* @__PURE__ */ new Map([
["\u0275\u0275defineInjectable", "\u0275\u0275defineInjectable"],
["\u0275\u0275defineInjector", "\u0275\u0275defineInjector"],
["\u0275\u0275defineNgModule", "\u0275\u0275defineNgModule"],
["\u0275\u0275setNgModuleScope", "\u0275\u0275setNgModuleScope"],
["\u0275\u0275inject", "\u0275\u0275inject"],
["\u0275\u0275FactoryDeclaration", "\u0275\u0275FactoryDeclaration"],
["\u0275setClassMetadata", "setClassMetadata"],
["\u0275setClassMetadataAsync", "setClassMetadataAsync"],
["\u0275\u0275InjectableDeclaration", "\u0275\u0275InjectableDeclaration"],
["\u0275\u0275InjectorDeclaration", "\u0275\u0275InjectorDeclaration"],
["\u0275\u0275NgModuleDeclaration", "\u0275\u0275NgModuleDeclaration"],
["\u0275NgModuleFactory", "NgModuleFactory"],
["\u0275noSideEffects", "\u0275noSideEffects"]
]);
var CORE_MODULE = "@angular/core";
var R3SymbolsImportRewriter = class {
constructor(r3SymbolsPath) {
this.r3SymbolsPath = r3SymbolsPath;
}
rewriteSymbol(symbol, specifier) {
if (specifier !== CORE_MODULE) {
return symbol;
}
return validateAndRewriteCoreSymbol(symbol);
}
rewriteSpecifier(specifier, inContextOfFile) {
if (specifier !== CORE_MODULE) {
return specifier;
}
const relativePathToR3Symbols = relativePathBetween(inContextOfFile, this.r3SymbolsPath);
if (relativePathToR3Symbols === null) {
throw new Error(`Failed to rewrite import inside ${CORE_MODULE}: ${inContextOfFile} -> ${this.r3SymbolsPath}`);
}
return relativePathToR3Symbols;
}
};
function validateAndRewriteCoreSymbol(name) {
if (!CORE_SUPPORTED_SYMBOLS.has(name)) {
throw new Error(`Importing unexpected symbol ${name} while compiling ${CORE_MODULE}`);
}
return CORE_SUPPORTED_SYMBOLS.get(name);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/imports/src/patch_alias_reference_resolution.mjs
var import_typescript7 = __toESM(require("typescript"), 1);
var patchedReferencedAliasesSymbol = Symbol("patchedReferencedAliases");
function loadIsReferencedAliasDeclarationPatch(context) {
if (!isTransformationContextWithEmitResolver(context)) {
throwIncompatibleTransformationContextError();
}
const emitResolver = context.getEmitResolver();
const existingReferencedAliases = emitResolver[patchedReferencedAliasesSymbol];
if (existingReferencedAliases !== void 0) {
return existingReferencedAliases;
}
const originalIsReferencedAliasDeclaration = emitResolver.isReferencedAliasDeclaration;
if (originalIsReferencedAliasDeclaration === void 0) {
throwIncompatibleTransformationContextError();
}
const referencedAliases = /* @__PURE__ */ new Set();
emitResolver.isReferencedAliasDeclaration = function(node, ...args) {
if (isAliasImportDeclaration(node) && referencedAliases.has(node)) {
return true;
}
return originalIsReferencedAliasDeclaration.call(emitResolver, node, ...args);
};
return emitResolver[patchedReferencedAliasesSymbol] = referencedAliases;
}
function isAliasImportDeclaration(node) {
return import_typescript7.default.isImportSpecifier(node) || import_typescript7.default.isNamespaceImport(node) || import_typescript7.default.isImportClause(node);
}
function isTransformationContextWithEmitResolver(context) {
return context.getEmitResolver !== void 0;
}
function throwIncompatibleTransformationContextError() {
throw Error("Angular compiler is incompatible with this version of the TypeScript compiler.\n\nIf you recently updated TypeScript and this issue surfaces now, consider downgrading.\n\nPlease report an issue on the Angular repositories when this issue surfaces and you are using a supposedly compatible TypeScript version.");
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/imports/src/default.mjs
var DefaultImportDeclaration = Symbol("DefaultImportDeclaration");
function attachDefaultImportDeclaration(expr, importDecl) {
expr[DefaultImportDeclaration] = importDecl;
}
function getDefaultImportDeclaration(expr) {
var _a2;
return (_a2 = expr[DefaultImportDeclaration]) != null ? _a2 : null;
}
var DefaultImportTracker = class {
constructor() {
this.sourceFileToUsedImports = /* @__PURE__ */ new Map();
}
recordUsedImport(importDecl) {
if (importDecl.importClause) {
const sf = getSourceFile(importDecl);
if (!this.sourceFileToUsedImports.has(sf.fileName)) {
this.sourceFileToUsedImports.set(sf.fileName, /* @__PURE__ */ new Set());
}
this.sourceFileToUsedImports.get(sf.fileName).add(importDecl.importClause);
}
}
importPreservingTransformer() {
return (context) => {
let clausesToPreserve = null;
return (sourceFile) => {
const clausesForFile = this.sourceFileToUsedImports.get(sourceFile.fileName);
if (clausesForFile !== void 0) {
for (const clause of clausesForFile) {
if (clausesToPreserve === null) {
clausesToPreserve = loadIsReferencedAliasDeclarationPatch(context);
}
clausesToPreserve.add(clause);
}
}
return sourceFile;
};
};
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/imports/src/deferred_symbol_tracker.mjs
var import_typescript13 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/reflection/src/typescript.mjs
var import_typescript12 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/reflection/src/host.mjs
var import_typescript9 = __toESM(require("typescript"), 1);
function isDecoratorIdentifier(exp) {
return import_typescript9.default.isIdentifier(exp) || import_typescript9.default.isPropertyAccessExpression(exp) && import_typescript9.default.isIdentifier(exp.expression) && import_typescript9.default.isIdentifier(exp.name);
}
var ClassMemberKind;
(function(ClassMemberKind2) {
ClassMemberKind2[ClassMemberKind2["Constructor"] = 0] = "Constructor";
ClassMemberKind2[ClassMemberKind2["Getter"] = 1] = "Getter";
ClassMemberKind2[ClassMemberKind2["Setter"] = 2] = "Setter";
ClassMemberKind2[ClassMemberKind2["Property"] = 3] = "Property";
ClassMemberKind2[ClassMemberKind2["Method"] = 4] = "Method";
})(ClassMemberKind || (ClassMemberKind = {}));
var ClassMemberAccessLevel;
(function(ClassMemberAccessLevel2) {
ClassMemberAccessLevel2[ClassMemberAccessLevel2["PublicWritable"] = 0] = "PublicWritable";
ClassMemberAccessLevel2[ClassMemberAccessLevel2["PublicReadonly"] = 1] = "PublicReadonly";
ClassMemberAccessLevel2[ClassMemberAccessLevel2["Protected"] = 2] = "Protected";
ClassMemberAccessLevel2[ClassMemberAccessLevel2["Private"] = 3] = "Private";
ClassMemberAccessLevel2[ClassMemberAccessLevel2["EcmaScriptPrivate"] = 4] = "EcmaScriptPrivate";
})(ClassMemberAccessLevel || (ClassMemberAccessLevel = {}));
var AmbientImport = {};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/reflection/src/type_to_value.mjs
var import_typescript10 = __toESM(require("typescript"), 1);
function typeToValue(typeNode, checker, isLocalCompilation) {
var _a2, _b2;
if (typeNode === null) {
return missingType();
}
if (!import_typescript10.default.isTypeReferenceNode(typeNode)) {
return unsupportedType(typeNode);
}
const symbols = resolveTypeSymbols(typeNode, checker);
if (symbols === null) {
return unknownReference(typeNode);
}
const { local, decl } = symbols;
if (decl.valueDeclaration === void 0 || decl.flags & import_typescript10.default.SymbolFlags.ConstEnum) {
let typeOnlyDecl = null;
if (decl.declarations !== void 0 && decl.declarations.length > 0) {
typeOnlyDecl = decl.declarations[0];
}
if (!isLocalCompilation || typeOnlyDecl && [
import_typescript10.default.SyntaxKind.TypeParameter,
import_typescript10.default.SyntaxKind.TypeAliasDeclaration,
import_typescript10.default.SyntaxKind.InterfaceDeclaration
].includes(typeOnlyDecl.kind)) {
return noValueDeclaration(typeNode, typeOnlyDecl);
}
}
const firstDecl = local.declarations && local.declarations[0];
if (firstDecl !== void 0) {
if (import_typescript10.default.isImportClause(firstDecl) && firstDecl.name !== void 0) {
if (firstDecl.isTypeOnly) {
return typeOnlyImport(typeNode, firstDecl);
}
if (!import_typescript10.default.isImportDeclaration(firstDecl.parent)) {
return unsupportedType(typeNode);
}
return {
kind: 0,
expression: firstDecl.name,
defaultImportStatement: firstDecl.parent
};
} else if (import_typescript10.default.isImportSpecifier(firstDecl)) {
if (firstDecl.isTypeOnly) {
return typeOnlyImport(typeNode, firstDecl);
}
if (firstDecl.parent.parent.isTypeOnly) {
return typeOnlyImport(typeNode, firstDecl.parent.parent);
}
const importedName = (firstDecl.propertyName || firstDecl.name).text;
const [_localName, ...nestedPath] = symbols.symbolNames;
const importDeclaration = firstDecl.parent.parent.parent;
if (!import_typescript10.default.isImportDeclaration(importDeclaration)) {
return unsupportedType(typeNode);
}
const moduleName = extractModuleName(importDeclaration);
return {
kind: 1,
valueDeclaration: (_a2 = decl.valueDeclaration) != null ? _a2 : null,
moduleName,
importedName,
nestedPath
};
} else if (import_typescript10.default.isNamespaceImport(firstDecl)) {
if (firstDecl.parent.isTypeOnly) {
return typeOnlyImport(typeNode, firstDecl.parent);
}
if (symbols.symbolNames.length === 1) {
return namespaceImport(typeNode, firstDecl.parent);
}
const [_ns, importedName, ...nestedPath] = symbols.symbolNames;
const importDeclaration = firstDecl.parent.parent;
if (!import_typescript10.default.isImportDeclaration(importDeclaration)) {
return unsupportedType(typeNode);
}
const moduleName = extractModuleName(importDeclaration);
return {
kind: 1,
valueDeclaration: (_b2 = decl.valueDeclaration) != null ? _b2 : null,
moduleName,
importedName,
nestedPath
};
}
}
const expression = typeNodeToValueExpr(typeNode);
if (expression !== null) {
return {
kind: 0,
expression,
defaultImportStatement: null
};
} else {
return unsupportedType(typeNode);
}
}
function unsupportedType(typeNode) {
return {
kind: 2,
reason: { kind: 5, typeNode }
};
}
function noValueDeclaration(typeNode, decl) {
return {
kind: 2,
reason: { kind: 1, typeNode, decl }
};
}
function typeOnlyImport(typeNode, node) {
return {
kind: 2,
reason: { kind: 2, typeNode, node }
};
}
function unknownReference(typeNode) {
return {
kind: 2,
reason: { kind: 3, typeNode }
};
}
function namespaceImport(typeNode, importClause) {
return {
kind: 2,
reason: { kind: 4, typeNode, importClause }
};
}
function missingType() {
return {
kind: 2,
reason: { kind: 0 }
};
}
function typeNodeToValueExpr(node) {
if (import_typescript10.default.isTypeReferenceNode(node)) {
return entityNameToValue(node.typeName);
} else {
return null;
}
}
function resolveTypeSymbols(typeRef, checker) {
const typeName = typeRef.typeName;
const typeRefSymbol = checker.getSymbolAtLocation(typeName);
if (typeRefSymbol === void 0) {
return null;
}
let local = typeRefSymbol;
let leftMost = typeName;
const symbolNames = [];
while (import_typescript10.default.isQualifiedName(leftMost)) {
symbolNames.unshift(leftMost.right.text);
leftMost = leftMost.left;
}
symbolNames.unshift(leftMost.text);
if (leftMost !== typeName) {
const localTmp = checker.getSymbolAtLocation(leftMost);
if (localTmp !== void 0) {
local = localTmp;
}
}
let decl = typeRefSymbol;
if (typeRefSymbol.flags & import_typescript10.default.SymbolFlags.Alias) {
decl = checker.getAliasedSymbol(typeRefSymbol);
}
return { local, decl, symbolNames };
}
function entityNameToValue(node) {
if (import_typescript10.default.isQualifiedName(node)) {
const left = entityNameToValue(node.left);
return left !== null ? import_typescript10.default.factory.createPropertyAccessExpression(left, node.right) : null;
} else if (import_typescript10.default.isIdentifier(node)) {
const clone = import_typescript10.default.setOriginalNode(import_typescript10.default.factory.createIdentifier(node.text), node);
clone.parent = node.parent;
return clone;
} else {
return null;
}
}
function extractModuleName(node) {
if (!import_typescript10.default.isStringLiteral(node.moduleSpecifier)) {
throw new Error("not a module specifier");
}
return node.moduleSpecifier.text;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/reflection/src/util.mjs
var import_typescript11 = __toESM(require("typescript"), 1);
function isNamedClassDeclaration(node) {
return import_typescript11.default.isClassDeclaration(node) && isIdentifier(node.name);
}
function isIdentifier(node) {
return node !== void 0 && import_typescript11.default.isIdentifier(node);
}
function classMemberAccessLevelToString(level) {
switch (level) {
case ClassMemberAccessLevel.EcmaScriptPrivate:
return "ES private";
case ClassMemberAccessLevel.Private:
return "private";
case ClassMemberAccessLevel.Protected:
return "protected";
case ClassMemberAccessLevel.PublicReadonly:
return "public readonly";
case ClassMemberAccessLevel.PublicWritable:
default:
return "public";
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/reflection/src/typescript.mjs
var TypeScriptReflectionHost = class {
constructor(checker, isLocalCompilation = false) {
this.checker = checker;
this.isLocalCompilation = isLocalCompilation;
}
getDecoratorsOfDeclaration(declaration) {
const decorators = import_typescript12.default.canHaveDecorators(declaration) ? import_typescript12.default.getDecorators(declaration) : void 0;
return decorators !== void 0 && decorators.length ? decorators.map((decorator) => this._reflectDecorator(decorator)).filter((dec) => dec !== null) : null;
}
getMembersOfClass(clazz) {
const tsClazz = castDeclarationToClassOrDie(clazz);
return tsClazz.members.map((member) => {
const result = reflectClassMember(member);
if (result === null) {
return null;
}
return __spreadProps(__spreadValues({}, result), {
decorators: this.getDecoratorsOfDeclaration(member)
});
}).filter((member) => member !== null);
}
getConstructorParameters(clazz) {
const tsClazz = castDeclarationToClassOrDie(clazz);
const isDeclaration2 = tsClazz.getSourceFile().isDeclarationFile;
const ctor = tsClazz.members.find((member) => import_typescript12.default.isConstructorDeclaration(member) && (isDeclaration2 || member.body !== void 0));
if (ctor === void 0) {
return null;
}
return ctor.parameters.map((node) => {
const name = parameterName(node.name);
const decorators = this.getDecoratorsOfDeclaration(node);
let originalTypeNode = node.type || null;
let typeNode = originalTypeNode;
if (typeNode && import_typescript12.default.isUnionTypeNode(typeNode)) {
let childTypeNodes = typeNode.types.filter((childTypeNode) => !(import_typescript12.default.isLiteralTypeNode(childTypeNode) && childTypeNode.literal.kind === import_typescript12.default.SyntaxKind.NullKeyword));
if (childTypeNodes.length === 1) {
typeNode = childTypeNodes[0];
}
}
const typeValueReference = typeToValue(typeNode, this.checker, this.isLocalCompilation);
return {
name,
nameNode: node.name,
typeValueReference,
typeNode: originalTypeNode,
decorators
};
});
}
getImportOfIdentifier(id) {
const directImport = this.getDirectImportOfIdentifier(id);
if (directImport !== null) {
return directImport;
} else if (import_typescript12.default.isQualifiedName(id.parent) && id.parent.right === id) {
return this.getImportOfNamespacedIdentifier(id, getQualifiedNameRoot(id.parent));
} else if (import_typescript12.default.isPropertyAccessExpression(id.parent) && id.parent.name === id) {
return this.getImportOfNamespacedIdentifier(id, getFarLeftIdentifier(id.parent));
} else {
return null;
}
}
getExportsOfModule(node) {
if (!import_typescript12.default.isSourceFile(node)) {
throw new Error(`getExportsOfModule() called on non-SourceFile in TS code`);
}
const symbol = this.checker.getSymbolAtLocation(node);
if (symbol === void 0) {
return null;
}
const map = /* @__PURE__ */ new Map();
this.checker.getExportsOfModule(symbol).forEach((exportSymbol) => {
const decl = this.getDeclarationOfSymbol(exportSymbol, null);
if (decl !== null) {
map.set(exportSymbol.name, decl);
}
});
return map;
}
isClass(node) {
return isNamedClassDeclaration(node);
}
hasBaseClass(clazz) {
return this.getBaseClassExpression(clazz) !== null;
}
getBaseClassExpression(clazz) {
if (!(import_typescript12.default.isClassDeclaration(clazz) || import_typescript12.default.isClassExpression(clazz)) || clazz.heritageClauses === void 0) {
return null;
}
const extendsClause = clazz.heritageClauses.find((clause) => clause.token === import_typescript12.default.SyntaxKind.ExtendsKeyword);
if (extendsClause === void 0) {
return null;
}
const extendsType = extendsClause.types[0];
if (extendsType === void 0) {
return null;
}
return extendsType.expression;
}
getDeclarationOfIdentifier(id) {
let symbol = this.checker.getSymbolAtLocation(id);
if (symbol === void 0) {
return null;
}
return this.getDeclarationOfSymbol(symbol, id);
}
getDefinitionOfFunction(node) {
if (!import_typescript12.default.isFunctionDeclaration(node) && !import_typescript12.default.isMethodDeclaration(node) && !import_typescript12.default.isFunctionExpression(node) && !import_typescript12.default.isArrowFunction(node)) {
return null;
}
let body = null;
if (node.body !== void 0) {
body = import_typescript12.default.isBlock(node.body) ? Array.from(node.body.statements) : [import_typescript12.default.factory.createReturnStatement(node.body)];
}
const type = this.checker.getTypeAtLocation(node);
const signatures = this.checker.getSignaturesOfType(type, import_typescript12.default.SignatureKind.Call);
return {
node,
body,
signatureCount: signatures.length,
typeParameters: node.typeParameters === void 0 ? null : Array.from(node.typeParameters),
parameters: node.parameters.map((param) => {
const name = parameterName(param.name);
const initializer = param.initializer || null;
return { name, node: param, initializer, type: param.type || null };
})
};
}
getGenericArityOfClass(clazz) {
if (!import_typescript12.default.isClassDeclaration(clazz)) {
return null;
}
return clazz.typeParameters !== void 0 ? clazz.typeParameters.length : 0;
}
getVariableValue(declaration) {
return declaration.initializer || null;
}
isStaticallyExported(decl) {
let topLevel = decl;
if (import_typescript12.default.isVariableDeclaration(decl) && import_typescript12.default.isVariableDeclarationList(decl.parent)) {
topLevel = decl.parent.parent;
}
const modifiers = import_typescript12.default.canHaveModifiers(topLevel) ? import_typescript12.default.getModifiers(topLevel) : void 0;
if (modifiers !== void 0 && modifiers.some((modifier) => modifier.kind === import_typescript12.default.SyntaxKind.ExportKeyword)) {
return true;
}
if (topLevel.parent === void 0 || !import_typescript12.default.isSourceFile(topLevel.parent)) {
return false;
}
const localExports = this.getLocalExportedDeclarationsOfSourceFile(decl.getSourceFile());
return localExports.has(decl);
}
getDirectImportOfIdentifier(id) {
const symbol = this.checker.getSymbolAtLocation(id);
if (symbol === void 0 || symbol.declarations === void 0 || symbol.declarations.length !== 1) {
return null;
}
const decl = symbol.declarations[0];
const importDecl = getContainingImportDeclaration(decl);
if (importDecl === null) {
return null;
}
if (!import_typescript12.default.isStringLiteral(importDecl.moduleSpecifier)) {
return null;
}
return {
from: importDecl.moduleSpecifier.text,
name: getExportedName(decl, id),
node: importDecl
};
}
getImportOfNamespacedIdentifier(id, namespaceIdentifier) {
if (namespaceIdentifier === null) {
return null;
}
const namespaceSymbol = this.checker.getSymbolAtLocation(namespaceIdentifier);
if (!namespaceSymbol || namespaceSymbol.declarations === void 0) {
return null;
}
const declaration = namespaceSymbol.declarations.length === 1 ? namespaceSymbol.declarations[0] : null;
if (!declaration) {
return null;
}
const namespaceDeclaration = import_typescript12.default.isNamespaceImport(declaration) ? declaration : null;
if (!namespaceDeclaration) {
return null;
}
const importDeclaration = namespaceDeclaration.parent.parent;
if (!import_typescript12.default.isImportDeclaration(importDeclaration) || !import_typescript12.default.isStringLiteral(importDeclaration.moduleSpecifier)) {
return null;
}
return {
from: importDeclaration.moduleSpecifier.text,
name: id.text,
node: importDeclaration
};
}
getDeclarationOfSymbol(symbol, originalId) {
let valueDeclaration = void 0;
if (symbol.valueDeclaration !== void 0) {
valueDeclaration = symbol.valueDeclaration;
} else if (symbol.declarations !== void 0 && symbol.declarations.length > 0) {
valueDeclaration = symbol.declarations[0];
}
if (valueDeclaration !== void 0 && import_typescript12.default.isShorthandPropertyAssignment(valueDeclaration)) {
const shorthandSymbol = this.checker.getShorthandAssignmentValueSymbol(valueDeclaration);
if (shorthandSymbol === void 0) {
return null;
}
return this.getDeclarationOfSymbol(shorthandSymbol, originalId);
} else if (valueDeclaration !== void 0 && import_typescript12.default.isExportSpecifier(valueDeclaration)) {
const targetSymbol = this.checker.getExportSpecifierLocalTargetSymbol(valueDeclaration);
if (targetSymbol === void 0) {
return null;
}
return this.getDeclarationOfSymbol(targetSymbol, originalId);
}
const importInfo = originalId && this.getImportOfIdentifier(originalId);
while (symbol.flags & import_typescript12.default.SymbolFlags.Alias) {
symbol = this.checker.getAliasedSymbol(symbol);
}
if (symbol.valueDeclaration !== void 0) {
return {
node: symbol.valueDeclaration,
viaModule: this._viaModule(symbol.valueDeclaration, originalId, importInfo)
};
} else if (symbol.declarations !== void 0 && symbol.declarations.length > 0) {
return {
node: symbol.declarations[0],
viaModule: this._viaModule(symbol.declarations[0], originalId, importInfo)
};
} else {
return null;
}
}
_reflectDecorator(node) {
let decoratorExpr = node.expression;
let args = null;
if (import_typescript12.default.isCallExpression(decoratorExpr)) {
args = Array.from(decoratorExpr.arguments);
decoratorExpr = decoratorExpr.expression;
}
if (!isDecoratorIdentifier(decoratorExpr)) {
return null;
}
const decoratorIdentifier = import_typescript12.default.isIdentifier(decoratorExpr) ? decoratorExpr : decoratorExpr.name;
const importDecl = this.getImportOfIdentifier(decoratorIdentifier);
return {
name: decoratorIdentifier.text,
identifier: decoratorExpr,
import: importDecl,
node,
args
};
}
getLocalExportedDeclarationsOfSourceFile(file) {
const cacheSf = file;
if (cacheSf[LocalExportedDeclarations] !== void 0) {
return cacheSf[LocalExportedDeclarations];
}
const exportSet = /* @__PURE__ */ new Set();
cacheSf[LocalExportedDeclarations] = exportSet;
const sfSymbol = this.checker.getSymbolAtLocation(cacheSf);
if (sfSymbol === void 0 || sfSymbol.exports === void 0) {
return exportSet;
}
const iter = sfSymbol.exports.values();
let item = iter.next();
while (item.done !== true) {
let exportedSymbol = item.value;
if (exportedSymbol.flags & import_typescript12.default.SymbolFlags.Alias) {
exportedSymbol = this.checker.getAliasedSymbol(exportedSymbol);
}
if (exportedSymbol.valueDeclaration !== void 0 && exportedSymbol.valueDeclaration.getSourceFile() === file) {
exportSet.add(exportedSymbol.valueDeclaration);
}
item = iter.next();
}
return exportSet;
}
_viaModule(declaration, originalId, importInfo) {
if (importInfo === null && originalId !== null && declaration.getSourceFile() !== originalId.getSourceFile()) {
return AmbientImport;
}
return importInfo !== null && importInfo.from !== null && !importInfo.from.startsWith(".") ? importInfo.from : null;
}
};
function reflectTypeEntityToDeclaration(type, checker) {
let realSymbol = checker.getSymbolAtLocation(type);
if (realSymbol === void 0) {
throw new Error(`Cannot resolve type entity ${type.getText()} to symbol`);
}
while (realSymbol.flags & import_typescript12.default.SymbolFlags.Alias) {
realSymbol = checker.getAliasedSymbol(realSymbol);
}
let node = null;
if (realSymbol.valueDeclaration !== void 0) {
node = realSymbol.valueDeclaration;
} else if (realSymbol.declarations !== void 0 && realSymbol.declarations.length === 1) {
node = realSymbol.declarations[0];
} else {
throw new Error(`Cannot resolve type entity symbol to declaration`);
}
if (import_typescript12.default.isQualifiedName(type)) {
if (!import_typescript12.default.isIdentifier(type.left)) {
throw new Error(`Cannot handle qualified name with non-identifier lhs`);
}
const symbol = checker.getSymbolAtLocation(type.left);
if (symbol === void 0 || symbol.declarations === void 0 || symbol.declarations.length !== 1) {
throw new Error(`Cannot resolve qualified type entity lhs to symbol`);
}
const decl = symbol.declarations[0];
if (import_typescript12.default.isNamespaceImport(decl)) {
const clause = decl.parent;
const importDecl = clause.parent;
if (!import_typescript12.default.isStringLiteral(importDecl.moduleSpecifier)) {
throw new Error(`Module specifier is not a string`);
}
return { node, from: importDecl.moduleSpecifier.text };
} else if (import_typescript12.default.isModuleDeclaration(decl)) {
return { node, from: null };
} else {
throw new Error(`Unknown import type?`);
}
} else {
return { node, from: null };
}
}
function filterToMembersWithDecorator(members, name, module2) {
return members.filter((member) => !member.isStatic).map((member) => {
if (member.decorators === null) {
return null;
}
const decorators = member.decorators.filter((dec) => {
if (dec.import !== null) {
return dec.import.name === name && (module2 === void 0 || dec.import.from === module2);
} else {
return dec.name === name && module2 === void 0;
}
});
if (decorators.length === 0) {
return null;
}
return { member, decorators };
}).filter((value) => value !== null);
}
function extractModifiersOfMember(node) {
const modifiers = import_typescript12.default.getModifiers(node);
let isStatic = false;
let isReadonly = false;
let accessLevel = ClassMemberAccessLevel.PublicWritable;
if (modifiers !== void 0) {
for (const modifier of modifiers) {
switch (modifier.kind) {
case import_typescript12.default.SyntaxKind.StaticKeyword:
isStatic = true;
break;
case import_typescript12.default.SyntaxKind.PrivateKeyword:
accessLevel = ClassMemberAccessLevel.Private;
break;
case import_typescript12.default.SyntaxKind.ProtectedKeyword:
accessLevel = ClassMemberAccessLevel.Protected;
break;
case import_typescript12.default.SyntaxKind.ReadonlyKeyword:
isReadonly = true;
break;
}
}
}
if (isReadonly && accessLevel === ClassMemberAccessLevel.PublicWritable) {
accessLevel = ClassMemberAccessLevel.PublicReadonly;
}
if (node.name !== void 0 && import_typescript12.default.isPrivateIdentifier(node.name)) {
accessLevel = ClassMemberAccessLevel.EcmaScriptPrivate;
}
return { accessLevel, isStatic };
}
function reflectClassMember(node) {
let kind = null;
let value = null;
let name = null;
let nameNode = null;
if (import_typescript12.default.isPropertyDeclaration(node)) {
kind = ClassMemberKind.Property;
value = node.initializer || null;
} else if (import_typescript12.default.isGetAccessorDeclaration(node)) {
kind = ClassMemberKind.Getter;
} else if (import_typescript12.default.isSetAccessorDeclaration(node)) {
kind = ClassMemberKind.Setter;
} else if (import_typescript12.default.isMethodDeclaration(node)) {
kind = ClassMemberKind.Method;
} else if (import_typescript12.default.isConstructorDeclaration(node)) {
kind = ClassMemberKind.Constructor;
} else {
return null;
}
if (import_typescript12.default.isConstructorDeclaration(node)) {
name = "constructor";
} else if (import_typescript12.default.isIdentifier(node.name)) {
name = node.name.text;
nameNode = node.name;
} else if (import_typescript12.default.isStringLiteral(node.name)) {
name = node.name.text;
nameNode = node.name;
} else if (import_typescript12.default.isPrivateIdentifier(node.name)) {
name = node.name.text;
nameNode = node.name;
} else {
return null;
}
const { accessLevel, isStatic } = extractModifiersOfMember(node);
return {
node,
implementation: node,
kind,
type: node.type || null,
accessLevel,
name,
nameNode,
value,
isStatic
};
}
function reflectObjectLiteral(node) {
const map = /* @__PURE__ */ new Map();
node.properties.forEach((prop) => {
if (import_typescript12.default.isPropertyAssignment(prop)) {
const name = propertyNameToString(prop.name);
if (name === null) {
return;
}
map.set(name, prop.initializer);
} else if (import_typescript12.default.isShorthandPropertyAssignment(prop)) {
map.set(prop.name.text, prop.name);
} else {
return;
}
});
return map;
}
function castDeclarationToClassOrDie(declaration) {
if (!import_typescript12.default.isClassDeclaration(declaration)) {
throw new Error(`Reflecting on a ${import_typescript12.default.SyntaxKind[declaration.kind]} instead of a ClassDeclaration.`);
}
return declaration;
}
function parameterName(name) {
if (import_typescript12.default.isIdentifier(name)) {
return name.text;
} else {
return null;
}
}
function propertyNameToString(node) {
if (import_typescript12.default.isIdentifier(node) || import_typescript12.default.isStringLiteral(node) || import_typescript12.default.isNumericLiteral(node)) {
return node.text;
} else {
return null;
}
}
function getQualifiedNameRoot(qualifiedName) {
while (import_typescript12.default.isQualifiedName(qualifiedName.left)) {
qualifiedName = qualifiedName.left;
}
return import_typescript12.default.isIdentifier(qualifiedName.left) ? qualifiedName.left : null;
}
function getFarLeftIdentifier(propertyAccess) {
while (import_typescript12.default.isPropertyAccessExpression(propertyAccess.expression)) {
propertyAccess = propertyAccess.expression;
}
return import_typescript12.default.isIdentifier(propertyAccess.expression) ? propertyAccess.expression : null;
}
function getContainingImportDeclaration(node) {
let parent = node.parent;
while (parent && !import_typescript12.default.isSourceFile(parent)) {
if (import_typescript12.default.isImportDeclaration(parent)) {
return parent;
}
parent = parent.parent;
}
return null;
}
function getExportedName(decl, originalId) {
return import_typescript12.default.isImportSpecifier(decl) ? (decl.propertyName !== void 0 ? decl.propertyName : decl.name).text : originalId.text;
}
var LocalExportedDeclarations = Symbol("LocalExportedDeclarations");
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/imports/src/deferred_symbol_tracker.mjs
var AssumeEager = "AssumeEager";
var DeferredSymbolTracker = class {
constructor(typeChecker, onlyExplicitDeferDependencyImports) {
this.typeChecker = typeChecker;
this.onlyExplicitDeferDependencyImports = onlyExplicitDeferDependencyImports;
this.imports = /* @__PURE__ */ new Map();
this.explicitlyDeferredImports = /* @__PURE__ */ new Map();
}
extractImportedSymbols(importDecl) {
const symbolMap = /* @__PURE__ */ new Map();
if (importDecl.importClause === void 0) {
throw new Error(`Provided import declaration doesn't have any symbols.`);
}
if (importDecl.importClause.isTypeOnly) {
return symbolMap;
}
if (importDecl.importClause.namedBindings !== void 0) {
const bindings = importDecl.importClause.namedBindings;
if (import_typescript13.default.isNamedImports(bindings)) {
for (const element2 of bindings.elements) {
if (!element2.isTypeOnly) {
symbolMap.set(element2.name.text, AssumeEager);
}
}
} else {
symbolMap.set(bindings.name.text, AssumeEager);
}
} else if (importDecl.importClause.name !== void 0) {
symbolMap.set(importDecl.importClause.name.text, AssumeEager);
} else {
throw new Error("Unrecognized import structure.");
}
return symbolMap;
}
getNonRemovableDeferredImports(sourceFile, classDecl) {
var _a2;
const affectedImports = [];
const importDecls = (_a2 = this.explicitlyDeferredImports.get(classDecl)) != null ? _a2 : [];
for (const importDecl of importDecls) {
if (importDecl.getSourceFile() === sourceFile && !this.canDefer(importDecl)) {
affectedImports.push(importDecl);
}
}
return affectedImports;
}
markAsDeferrableCandidate(identifier, importDecl, componentClassDecl, isExplicitlyDeferred) {
if (this.onlyExplicitDeferDependencyImports && !isExplicitlyDeferred) {
return;
}
if (isExplicitlyDeferred) {
if (this.explicitlyDeferredImports.has(componentClassDecl)) {
this.explicitlyDeferredImports.get(componentClassDecl).push(importDecl);
} else {
this.explicitlyDeferredImports.set(componentClassDecl, [importDecl]);
}
}
let symbolMap = this.imports.get(importDecl);
if (!symbolMap) {
symbolMap = this.extractImportedSymbols(importDecl);
this.imports.set(importDecl, symbolMap);
}
if (!symbolMap.has(identifier.text)) {
throw new Error(`The '${identifier.text}' identifier doesn't belong to the provided import declaration.`);
}
if (symbolMap.get(identifier.text) === AssumeEager) {
symbolMap.set(identifier.text, this.lookupIdentifiersInSourceFile(identifier.text, importDecl));
}
const identifiers = symbolMap.get(identifier.text);
identifiers.delete(identifier);
}
canDefer(importDecl) {
if (!this.imports.has(importDecl)) {
return false;
}
const symbolsMap = this.imports.get(importDecl);
for (const [symbol, refs] of symbolsMap) {
if (refs === AssumeEager || refs.size > 0) {
return false;
}
}
return true;
}
getDeferrableImportDecls() {
const deferrableDecls = /* @__PURE__ */ new Set();
for (const [importDecl] of this.imports) {
if (this.canDefer(importDecl)) {
deferrableDecls.add(importDecl);
}
}
return deferrableDecls;
}
lookupIdentifiersInSourceFile(name, importDecl) {
const results = /* @__PURE__ */ new Set();
const visit2 = (node) => {
if (node === importDecl) {
return;
}
if (import_typescript13.default.isIdentifier(node) && node.text === name) {
const sym = this.typeChecker.getSymbolAtLocation(node);
if (sym === void 0) {
return;
}
if (sym.declarations === void 0 || sym.declarations.length === 0) {
return;
}
const importClause = sym.declarations[0];
const decl = getContainingImportDeclaration(importClause);
if (decl !== importDecl) {
return;
}
results.add(node);
}
import_typescript13.default.forEachChild(node, visit2);
};
visit2(importDecl.getSourceFile());
return results;
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/imports/src/imported_symbols_tracker.mjs
var import_typescript15 = __toESM(require("typescript"), 1);
var ImportedSymbolsTracker = class {
constructor() {
this.fileToNamedImports = /* @__PURE__ */ new WeakMap();
this.fileToNamespaceImports = /* @__PURE__ */ new WeakMap();
}
isPotentialReferenceToNamedImport(node, exportedName, moduleName) {
const sourceFile = node.getSourceFile();
this.scanImports(sourceFile);
const fileImports = this.fileToNamedImports.get(sourceFile);
const moduleImports = fileImports.get(moduleName);
const symbolImports = moduleImports == null ? void 0 : moduleImports.get(exportedName);
return symbolImports !== void 0 && symbolImports.has(node.text);
}
isPotentialReferenceToNamespaceImport(node, moduleName) {
var _a2, _b2;
const sourceFile = node.getSourceFile();
this.scanImports(sourceFile);
const namespaces = this.fileToNamespaceImports.get(sourceFile);
return (_b2 = (_a2 = namespaces.get(moduleName)) == null ? void 0 : _a2.has(node.text)) != null ? _b2 : false;
}
hasNamedImport(sourceFile, exportedName, moduleName) {
this.scanImports(sourceFile);
const fileImports = this.fileToNamedImports.get(sourceFile);
const moduleImports = fileImports.get(moduleName);
return moduleImports !== void 0 && moduleImports.has(exportedName);
}
hasNamespaceImport(sourceFile, moduleName) {
this.scanImports(sourceFile);
const namespaces = this.fileToNamespaceImports.get(sourceFile);
return namespaces.has(moduleName);
}
scanImports(sourceFile) {
var _a2, _b2;
if (this.fileToNamedImports.has(sourceFile) && this.fileToNamespaceImports.has(sourceFile)) {
return;
}
const namedImports = /* @__PURE__ */ new Map();
const namespaceImports = /* @__PURE__ */ new Map();
this.fileToNamedImports.set(sourceFile, namedImports);
this.fileToNamespaceImports.set(sourceFile, namespaceImports);
for (const stmt of sourceFile.statements) {
if (!import_typescript15.default.isImportDeclaration(stmt) || !import_typescript15.default.isStringLiteralLike(stmt.moduleSpecifier) || ((_a2 = stmt.importClause) == null ? void 0 : _a2.namedBindings) === void 0) {
continue;
}
const moduleName = stmt.moduleSpecifier.text;
if (import_typescript15.default.isNamespaceImport(stmt.importClause.namedBindings)) {
if (!namespaceImports.has(moduleName)) {
namespaceImports.set(moduleName, /* @__PURE__ */ new Set());
}
namespaceImports.get(moduleName).add(stmt.importClause.namedBindings.name.text);
} else {
for (const element2 of stmt.importClause.namedBindings.elements) {
const localName = element2.name.text;
const exportedName = element2.propertyName === void 0 ? localName : element2.propertyName.text;
if (!namedImports.has(moduleName)) {
namedImports.set(moduleName, /* @__PURE__ */ new Map());
}
const localNames = namedImports.get(moduleName);
if (!localNames.has(exportedName)) {
localNames.set(exportedName, /* @__PURE__ */ new Set());
}
(_b2 = localNames.get(exportedName)) == null ? void 0 : _b2.add(localName);
}
}
}
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/imports/src/local_compilation_extra_imports_tracker.mjs
var import_typescript16 = __toESM(require("typescript"), 1);
var LocalCompilationExtraImportsTracker = class {
constructor(typeChecker) {
this.typeChecker = typeChecker;
this.localImportsMap = /* @__PURE__ */ new Map();
this.globalImportsSet = /* @__PURE__ */ new Set();
this.markedFilesSet = /* @__PURE__ */ new Set();
}
markFileForExtraImportGeneration(sf) {
this.markedFilesSet.add(sf.fileName);
}
addImportForFile(sf, moduleName) {
if (!this.localImportsMap.has(sf.fileName)) {
this.localImportsMap.set(sf.fileName, /* @__PURE__ */ new Set());
}
this.localImportsMap.get(sf.fileName).add(moduleName);
}
addGlobalImportFromIdentifier(node) {
var _a2;
let identifier = null;
if (import_typescript16.default.isIdentifier(node)) {
identifier = node;
} else if (import_typescript16.default.isPropertyAccessExpression(node) && import_typescript16.default.isIdentifier(node.expression)) {
identifier = node.expression;
}
if (identifier === null) {
return;
}
const sym = this.typeChecker.getSymbolAtLocation(identifier);
if (!((_a2 = sym == null ? void 0 : sym.declarations) == null ? void 0 : _a2.length)) {
return;
}
const importClause = sym.declarations[0];
const decl = getContainingImportDeclaration(importClause);
if (decl !== null) {
this.globalImportsSet.add(removeQuotations(decl.moduleSpecifier.getText()));
}
}
getImportsForFile(sf) {
var _a2;
if (!this.markedFilesSet.has(sf.fileName)) {
return [];
}
return [...this.globalImportsSet, ...(_a2 = this.localImportsMap.get(sf.fileName)) != null ? _a2 : []];
}
};
function removeQuotations(s) {
return s.substring(1, s.length - 1).trim();
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/imports/src/references.mjs
var Reference2 = class {
constructor(node, bestGuessOwningModule = null) {
this.node = node;
this.identifiers = [];
this.synthetic = false;
this._alias = null;
if (bestGuessOwningModule === AmbientImport) {
this.isAmbient = true;
this.bestGuessOwningModule = null;
} else {
this.isAmbient = false;
this.bestGuessOwningModule = bestGuessOwningModule;
}
const id = identifierOfNode(node);
if (id !== null) {
this.identifiers.push(id);
}
}
get ownedByModuleGuess() {
if (this.bestGuessOwningModule !== null) {
return this.bestGuessOwningModule.specifier;
} else {
return null;
}
}
get hasOwningModuleGuess() {
return this.bestGuessOwningModule !== null;
}
get debugName() {
const id = identifierOfNode(this.node);
return id !== null ? id.text : null;
}
get alias() {
return this._alias;
}
addIdentifier(identifier) {
this.identifiers.push(identifier);
}
getIdentityIn(context) {
return this.identifiers.find((id) => id.getSourceFile() === context) || null;
}
getIdentityInExpression(expr) {
const sf = expr.getSourceFile();
return this.identifiers.find((id) => {
if (id.getSourceFile() !== sf) {
return false;
}
return id.pos >= expr.pos && id.end <= expr.end;
}) || null;
}
getOriginForDiagnostics(container, fallback = container) {
const id = this.getIdentityInExpression(container);
return id !== null ? id : fallback;
}
cloneWithAlias(alias) {
const ref = new Reference2(this.node, this.isAmbient ? AmbientImport : this.bestGuessOwningModule);
ref.identifiers = [...this.identifiers];
ref._alias = alias;
return ref;
}
cloneWithNoIdentifiers() {
const ref = new Reference2(this.node, this.isAmbient ? AmbientImport : this.bestGuessOwningModule);
ref._alias = this._alias;
ref.identifiers = [];
return ref;
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/imports/src/resolver.mjs
var ModuleResolver = class {
constructor(program, compilerOptions, host, moduleResolutionCache) {
this.program = program;
this.compilerOptions = compilerOptions;
this.host = host;
this.moduleResolutionCache = moduleResolutionCache;
}
resolveModule(moduleName, containingFile) {
const resolved = resolveModuleName(moduleName, containingFile, this.compilerOptions, this.host, this.moduleResolutionCache);
if (resolved === void 0) {
return null;
}
return getSourceFileOrNull(this.program, absoluteFrom(resolved.resolvedFileName));
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/transform/jit/src/downlevel_decorators_transform.mjs
var import_typescript21 = __toESM(require("typescript"), 1);
function isAngularDecorator(decorator, isCore) {
return isCore || decorator.import !== null && decorator.import.from === "@angular/core";
}
var DECORATOR_INVOCATION_JSDOC_TYPE = "!Array<{type: !Function, args: (undefined|!Array>)}>";
function extractMetadataFromSingleDecorator(decorator, diagnostics) {
const metadataProperties = [];
const expr = decorator.expression;
switch (expr.kind) {
case import_typescript21.default.SyntaxKind.Identifier:
metadataProperties.push(import_typescript21.default.factory.createPropertyAssignment("type", expr));
break;
case import_typescript21.default.SyntaxKind.CallExpression:
const call2 = expr;
metadataProperties.push(import_typescript21.default.factory.createPropertyAssignment("type", call2.expression));
if (call2.arguments.length) {
const args = [];
for (const arg of call2.arguments) {
args.push(arg);
}
const argsArrayLiteral = import_typescript21.default.factory.createArrayLiteralExpression(import_typescript21.default.factory.createNodeArray(args, true));
metadataProperties.push(import_typescript21.default.factory.createPropertyAssignment("args", argsArrayLiteral));
}
break;
default:
diagnostics.push({
file: decorator.getSourceFile(),
start: decorator.getStart(),
length: decorator.getEnd() - decorator.getStart(),
messageText: `${import_typescript21.default.SyntaxKind[decorator.kind]} not implemented in gathering decorator metadata.`,
category: import_typescript21.default.DiagnosticCategory.Error,
code: 0
});
break;
}
return import_typescript21.default.factory.createObjectLiteralExpression(metadataProperties);
}
function createCtorParametersClassProperty(diagnostics, entityNameToExpression, ctorParameters, isClosureCompilerEnabled) {
const params = [];
for (const ctorParam of ctorParameters) {
if (!ctorParam.type && ctorParam.decorators.length === 0) {
params.push(import_typescript21.default.factory.createNull());
continue;
}
const paramType = ctorParam.type ? typeReferenceToExpression(entityNameToExpression, ctorParam.type) : void 0;
const members = [
import_typescript21.default.factory.createPropertyAssignment("type", paramType || import_typescript21.default.factory.createIdentifier("undefined"))
];
const decorators = [];
for (const deco of ctorParam.decorators) {
decorators.push(extractMetadataFromSingleDecorator(deco, diagnostics));
}
if (decorators.length) {
members.push(import_typescript21.default.factory.createPropertyAssignment("decorators", import_typescript21.default.factory.createArrayLiteralExpression(decorators)));
}
params.push(import_typescript21.default.factory.createObjectLiteralExpression(members));
}
const initializer = import_typescript21.default.factory.createArrowFunction(void 0, void 0, [], void 0, import_typescript21.default.factory.createToken(import_typescript21.default.SyntaxKind.EqualsGreaterThanToken), import_typescript21.default.factory.createArrayLiteralExpression(params, true));
const ctorProp = import_typescript21.default.factory.createPropertyDeclaration([import_typescript21.default.factory.createToken(import_typescript21.default.SyntaxKind.StaticKeyword)], "ctorParameters", void 0, void 0, initializer);
if (isClosureCompilerEnabled) {
import_typescript21.default.setSyntheticLeadingComments(ctorProp, [
{
kind: import_typescript21.default.SyntaxKind.MultiLineCommentTrivia,
text: [
`*`,
` * @type {function(): !Array<(null|{`,
` * type: ?,`,
` * decorators: (undefined|${DECORATOR_INVOCATION_JSDOC_TYPE}),`,
` * })>}`,
` * @nocollapse`,
` `
].join("\n"),
pos: -1,
end: -1,
hasTrailingNewLine: true
}
]);
}
return ctorProp;
}
function typeReferenceToExpression(entityNameToExpression, node) {
let kind = node.kind;
if (import_typescript21.default.isLiteralTypeNode(node)) {
kind = node.literal.kind;
}
switch (kind) {
case import_typescript21.default.SyntaxKind.FunctionType:
case import_typescript21.default.SyntaxKind.ConstructorType:
return import_typescript21.default.factory.createIdentifier("Function");
case import_typescript21.default.SyntaxKind.ArrayType:
case import_typescript21.default.SyntaxKind.TupleType:
return import_typescript21.default.factory.createIdentifier("Array");
case import_typescript21.default.SyntaxKind.TypePredicate:
case import_typescript21.default.SyntaxKind.TrueKeyword:
case import_typescript21.default.SyntaxKind.FalseKeyword:
case import_typescript21.default.SyntaxKind.BooleanKeyword:
return import_typescript21.default.factory.createIdentifier("Boolean");
case import_typescript21.default.SyntaxKind.StringLiteral:
case import_typescript21.default.SyntaxKind.StringKeyword:
return import_typescript21.default.factory.createIdentifier("String");
case import_typescript21.default.SyntaxKind.ObjectKeyword:
return import_typescript21.default.factory.createIdentifier("Object");
case import_typescript21.default.SyntaxKind.NumberKeyword:
case import_typescript21.default.SyntaxKind.NumericLiteral:
return import_typescript21.default.factory.createIdentifier("Number");
case import_typescript21.default.SyntaxKind.TypeReference:
const typeRef = node;
return entityNameToExpression(typeRef.typeName);
case import_typescript21.default.SyntaxKind.UnionType:
const childTypeNodes = node.types.filter((t) => !(import_typescript21.default.isLiteralTypeNode(t) && t.literal.kind === import_typescript21.default.SyntaxKind.NullKeyword));
return childTypeNodes.length === 1 ? typeReferenceToExpression(entityNameToExpression, childTypeNodes[0]) : void 0;
default:
return void 0;
}
}
function symbolIsRuntimeValue(typeChecker, symbol) {
if (symbol.flags & import_typescript21.default.SymbolFlags.Alias) {
symbol = typeChecker.getAliasedSymbol(symbol);
}
return (symbol.flags & import_typescript21.default.SymbolFlags.Value & import_typescript21.default.SymbolFlags.ConstEnumExcludes) !== 0;
}
function getDownlevelDecoratorsTransform(typeChecker, host, diagnostics, isCore, isClosureCompilerEnabled, shouldTransformClass) {
function addJSDocTypeAnnotation(node, jsdocType) {
if (!isClosureCompilerEnabled) {
return;
}
import_typescript21.default.setSyntheticLeadingComments(node, [
{
kind: import_typescript21.default.SyntaxKind.MultiLineCommentTrivia,
text: `* @type {${jsdocType}} `,
pos: -1,
end: -1,
hasTrailingNewLine: true
}
]);
}
function createPropDecoratorsClassProperty(diagnostics2, properties) {
const entries = [];
for (const [name, decorators] of properties.entries()) {
entries.push(import_typescript21.default.factory.createPropertyAssignment(name, import_typescript21.default.factory.createArrayLiteralExpression(decorators.map((deco) => extractMetadataFromSingleDecorator(deco, diagnostics2)))));
}
const initializer = import_typescript21.default.factory.createObjectLiteralExpression(entries, true);
const prop = import_typescript21.default.factory.createPropertyDeclaration([import_typescript21.default.factory.createToken(import_typescript21.default.SyntaxKind.StaticKeyword)], "propDecorators", void 0, void 0, initializer);
addJSDocTypeAnnotation(prop, `!Object`);
return prop;
}
return (context) => {
const referencedParameterTypes = loadIsReferencedAliasDeclarationPatch(context);
function entityNameToExpression(name) {
const symbol = typeChecker.getSymbolAtLocation(name);
if (!symbol || !symbolIsRuntimeValue(typeChecker, symbol) || !symbol.declarations || symbol.declarations.length === 0) {
return void 0;
}
if (import_typescript21.default.isQualifiedName(name)) {
const containerExpr = entityNameToExpression(name.left);
if (containerExpr === void 0) {
return void 0;
}
return import_typescript21.default.factory.createPropertyAccessExpression(containerExpr, name.right);
}
const decl = symbol.declarations[0];
if (isAliasImportDeclaration(decl)) {
referencedParameterTypes.add(decl);
if (decl.name !== void 0) {
return import_typescript21.default.setOriginalNode(import_typescript21.default.factory.createIdentifier(decl.name.text), decl.name);
}
}
return import_typescript21.default.setOriginalNode(import_typescript21.default.factory.createIdentifier(name.text), name);
}
function transformClassElement(element2) {
element2 = import_typescript21.default.visitEachChild(element2, decoratorDownlevelVisitor, context);
const decoratorsToKeep = [];
const toLower = [];
const decorators = host.getDecoratorsOfDeclaration(element2) || [];
for (const decorator of decorators) {
const decoratorNode = decorator.node;
if (!isAngularDecorator(decorator, isCore)) {
decoratorsToKeep.push(decoratorNode);
continue;
}
toLower.push(decoratorNode);
}
if (!toLower.length)
return [void 0, element2, []];
if (!element2.name || !import_typescript21.default.isIdentifier(element2.name)) {
diagnostics.push({
file: element2.getSourceFile(),
start: element2.getStart(),
length: element2.getEnd() - element2.getStart(),
messageText: `Cannot process decorators for class element with non-analyzable name.`,
category: import_typescript21.default.DiagnosticCategory.Error,
code: 0
});
return [void 0, element2, []];
}
const elementModifiers = import_typescript21.default.canHaveModifiers(element2) ? import_typescript21.default.getModifiers(element2) : void 0;
let modifiers;
if (decoratorsToKeep.length || (elementModifiers == null ? void 0 : elementModifiers.length)) {
modifiers = import_typescript21.default.setTextRange(import_typescript21.default.factory.createNodeArray([...decoratorsToKeep, ...elementModifiers || []]), element2.modifiers);
}
return [element2.name.text, cloneClassElementWithModifiers(element2, modifiers), toLower];
}
function transformConstructor(ctor) {
ctor = import_typescript21.default.visitEachChild(ctor, decoratorDownlevelVisitor, context);
const newParameters = [];
const oldParameters = ctor.parameters;
const parametersInfo = [];
for (const param of oldParameters) {
const decoratorsToKeep = [];
const paramInfo = { decorators: [], type: null };
const decorators = host.getDecoratorsOfDeclaration(param) || [];
for (const decorator of decorators) {
const decoratorNode = decorator.node;
if (!isAngularDecorator(decorator, isCore)) {
decoratorsToKeep.push(decoratorNode);
continue;
}
paramInfo.decorators.push(decoratorNode);
}
if (param.type) {
paramInfo.type = param.type;
}
parametersInfo.push(paramInfo);
let modifiers;
const paramModifiers = import_typescript21.default.getModifiers(param);
if (decoratorsToKeep.length || (paramModifiers == null ? void 0 : paramModifiers.length)) {
modifiers = [...decoratorsToKeep, ...paramModifiers || []];
}
const newParam = import_typescript21.default.factory.updateParameterDeclaration(param, modifiers, param.dotDotDotToken, param.name, param.questionToken, param.type, param.initializer);
newParameters.push(newParam);
}
const updated = import_typescript21.default.factory.updateConstructorDeclaration(ctor, import_typescript21.default.getModifiers(ctor), newParameters, ctor.body);
return [updated, parametersInfo];
}
function transformClassDeclaration(classDecl) {
const newMembers = [];
const decoratedProperties = /* @__PURE__ */ new Map();
let classParameters = null;
for (const member of classDecl.members) {
switch (member.kind) {
case import_typescript21.default.SyntaxKind.PropertyDeclaration:
case import_typescript21.default.SyntaxKind.GetAccessor:
case import_typescript21.default.SyntaxKind.SetAccessor:
case import_typescript21.default.SyntaxKind.MethodDeclaration: {
const [name, newMember, decorators] = transformClassElement(member);
newMembers.push(newMember);
if (name)
decoratedProperties.set(name, decorators);
continue;
}
case import_typescript21.default.SyntaxKind.Constructor: {
const ctor = member;
if (!ctor.body)
break;
const [newMember, parametersInfo] = transformConstructor(member);
classParameters = parametersInfo;
newMembers.push(newMember);
continue;
}
default:
break;
}
newMembers.push(import_typescript21.default.visitEachChild(member, decoratorDownlevelVisitor, context));
}
const possibleAngularDecorators = host.getDecoratorsOfDeclaration(classDecl) || [];
const hasAngularDecorator = possibleAngularDecorators.some((d) => isAngularDecorator(d, isCore));
if (classParameters) {
if (hasAngularDecorator || classParameters.some((p2) => !!p2.decorators.length)) {
newMembers.push(createCtorParametersClassProperty(diagnostics, entityNameToExpression, classParameters, isClosureCompilerEnabled));
}
}
if (decoratedProperties.size) {
newMembers.push(createPropDecoratorsClassProperty(diagnostics, decoratedProperties));
}
const members = import_typescript21.default.setTextRange(import_typescript21.default.factory.createNodeArray(newMembers, classDecl.members.hasTrailingComma), classDecl.members);
return import_typescript21.default.factory.updateClassDeclaration(classDecl, classDecl.modifiers, classDecl.name, classDecl.typeParameters, classDecl.heritageClauses, members);
}
function decoratorDownlevelVisitor(node) {
if (import_typescript21.default.isClassDeclaration(node) && (shouldTransformClass === void 0 || shouldTransformClass(node))) {
return transformClassDeclaration(node);
}
return import_typescript21.default.visitEachChild(node, decoratorDownlevelVisitor, context);
}
return (sf) => {
return import_typescript21.default.visitEachChild(sf, decoratorDownlevelVisitor, context);
};
};
}
function cloneClassElementWithModifiers(node, modifiers) {
let clone;
if (import_typescript21.default.isMethodDeclaration(node)) {
clone = import_typescript21.default.factory.createMethodDeclaration(modifiers, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body);
} else if (import_typescript21.default.isPropertyDeclaration(node)) {
clone = import_typescript21.default.factory.createPropertyDeclaration(modifiers, node.name, node.questionToken, node.type, node.initializer);
} else if (import_typescript21.default.isGetAccessor(node)) {
clone = import_typescript21.default.factory.createGetAccessorDeclaration(modifiers, node.name, node.parameters, node.type, node.body);
} else if (import_typescript21.default.isSetAccessor(node)) {
clone = import_typescript21.default.factory.createSetAccessorDeclaration(modifiers, node.name, node.parameters, node.body);
} else {
throw new Error(`Unsupported decorated member with kind ${import_typescript21.default.SyntaxKind[node.kind]}`);
}
return import_typescript21.default.setOriginalNode(clone, node);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/transform/jit/src/initializer_api_transforms/transform.mjs
var import_typescript94 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/common/src/di.mjs
var import_typescript23 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/common/src/util.mjs
var import_typescript22 = __toESM(require("typescript"), 1);
var CORE_MODULE2 = "@angular/core";
function valueReferenceToExpression(valueRef) {
if (valueRef.kind === 2) {
return null;
} else if (valueRef.kind === 0) {
const expr = new WrappedNodeExpr(valueRef.expression);
if (valueRef.defaultImportStatement !== null) {
attachDefaultImportDeclaration(expr, valueRef.defaultImportStatement);
}
return expr;
} else {
let importExpr2 = new ExternalExpr({
moduleName: valueRef.moduleName,
name: valueRef.importedName
});
if (valueRef.nestedPath !== null) {
for (const property2 of valueRef.nestedPath) {
importExpr2 = new ReadPropExpr(importExpr2, property2);
}
}
return importExpr2;
}
}
function toR3Reference(origin, ref, context, refEmitter) {
const emittedValueRef = refEmitter.emit(ref, context);
assertSuccessfulReferenceEmit(emittedValueRef, origin, "class");
const emittedTypeRef = refEmitter.emit(ref, context, ImportFlags.ForceNewImport | ImportFlags.AllowTypeImports);
assertSuccessfulReferenceEmit(emittedTypeRef, origin, "class");
return {
value: emittedValueRef.expression,
type: emittedTypeRef.expression
};
}
function isAngularCore(decorator) {
return decorator.import !== null && decorator.import.from === CORE_MODULE2;
}
function isAngularCoreReference(reference2, symbolName) {
return reference2.ownedByModuleGuess === CORE_MODULE2 && reference2.debugName === symbolName;
}
function findAngularDecorator(decorators, name, isCore) {
return decorators.find((decorator) => isAngularDecorator2(decorator, name, isCore));
}
function isAngularDecorator2(decorator, name, isCore) {
if (isCore) {
return decorator.name === name;
} else if (isAngularCore(decorator)) {
return decorator.import.name === name;
}
return false;
}
function getAngularDecorators(decorators, names, isCore) {
return decorators.filter((decorator) => {
var _a2;
const name = isCore ? decorator.name : (_a2 = decorator.import) == null ? void 0 : _a2.name;
if (name === void 0 || !names.includes(name)) {
return false;
}
return isCore || isAngularCore(decorator);
});
}
function unwrapExpression(node) {
while (import_typescript22.default.isAsExpression(node) || import_typescript22.default.isParenthesizedExpression(node)) {
node = node.expression;
}
return node;
}
function expandForwardRef(arg) {
arg = unwrapExpression(arg);
if (!import_typescript22.default.isArrowFunction(arg) && !import_typescript22.default.isFunctionExpression(arg)) {
return null;
}
const body = arg.body;
if (import_typescript22.default.isBlock(body)) {
if (body.statements.length !== 1) {
return null;
}
const stmt = body.statements[0];
if (!import_typescript22.default.isReturnStatement(stmt) || stmt.expression === void 0) {
return null;
}
return stmt.expression;
} else {
return body;
}
}
function tryUnwrapForwardRef(node, reflector) {
node = unwrapExpression(node);
if (!import_typescript22.default.isCallExpression(node) || node.arguments.length !== 1) {
return null;
}
const fn2 = import_typescript22.default.isPropertyAccessExpression(node.expression) ? node.expression.name : node.expression;
if (!import_typescript22.default.isIdentifier(fn2)) {
return null;
}
const expr = expandForwardRef(node.arguments[0]);
if (expr === null) {
return null;
}
const imp = reflector.getImportOfIdentifier(fn2);
if (imp === null || imp.from !== "@angular/core" || imp.name !== "forwardRef") {
return null;
}
return expr;
}
var forwardRefResolver = (fn2, callExpr, resolve5, unresolvable) => {
if (!isAngularCoreReference(fn2, "forwardRef") || callExpr.arguments.length !== 1) {
return unresolvable;
}
const expanded = expandForwardRef(callExpr.arguments[0]);
if (expanded !== null) {
return resolve5(expanded);
} else {
return unresolvable;
}
};
function combineResolvers(resolvers) {
return (fn2, callExpr, resolve5, unresolvable) => {
for (const resolver of resolvers) {
const resolved = resolver(fn2, callExpr, resolve5, unresolvable);
if (resolved !== unresolvable) {
return resolved;
}
}
return unresolvable;
};
}
function isExpressionForwardReference(expr, context, contextSource) {
if (isWrappedTsNodeExpr(expr)) {
const node = import_typescript22.default.getOriginalNode(expr.node);
return node.getSourceFile() === contextSource && context.pos < node.pos;
} else {
return false;
}
}
function isWrappedTsNodeExpr(expr) {
return expr instanceof WrappedNodeExpr;
}
function readBaseClass(node, reflector, evaluator) {
const baseExpression = reflector.getBaseClassExpression(node);
if (baseExpression !== null) {
const baseClass = evaluator.evaluate(baseExpression);
if (baseClass instanceof Reference2 && reflector.isClass(baseClass.node)) {
return baseClass;
} else {
return "dynamic";
}
}
return null;
}
var parensWrapperTransformerFactory = (context) => {
const visitor = (node) => {
const visited = import_typescript22.default.visitEachChild(node, visitor, context);
if (import_typescript22.default.isArrowFunction(visited) || import_typescript22.default.isFunctionExpression(visited)) {
return import_typescript22.default.factory.createParenthesizedExpression(visited);
}
return visited;
};
return (node) => import_typescript22.default.visitEachChild(node, visitor, context);
};
function wrapFunctionExpressionsInParens(expression) {
return import_typescript22.default.transform(expression, [parensWrapperTransformerFactory]).transformed[0];
}
function resolveProvidersRequiringFactory(rawProviders, reflector, evaluator) {
const providers = /* @__PURE__ */ new Set();
const resolvedProviders = evaluator.evaluate(rawProviders);
if (!Array.isArray(resolvedProviders)) {
return providers;
}
resolvedProviders.forEach(function processProviders(provider) {
let tokenClass = null;
if (Array.isArray(provider)) {
provider.forEach(processProviders);
} else if (provider instanceof Reference2) {
tokenClass = provider;
} else if (provider instanceof Map && provider.has("useClass") && !provider.has("deps")) {
const useExisting = provider.get("useClass");
if (useExisting instanceof Reference2) {
tokenClass = useExisting;
}
}
if (tokenClass !== null && !tokenClass.node.getSourceFile().isDeclarationFile && reflector.isClass(tokenClass.node)) {
const constructorParameters = reflector.getConstructorParameters(tokenClass.node);
if (constructorParameters !== null && constructorParameters.length > 0) {
providers.add(tokenClass);
}
}
});
return providers;
}
function wrapTypeReference(reflector, clazz) {
const value = new WrappedNodeExpr(clazz.name);
const type = value;
return { value, type };
}
function createSourceSpan(node) {
const sf = node.getSourceFile();
const [startOffset, endOffset] = [node.getStart(), node.getEnd()];
const { line: startLine, character: startCol } = sf.getLineAndCharacterOfPosition(startOffset);
const { line: endLine, character: endCol } = sf.getLineAndCharacterOfPosition(endOffset);
const parseSf = new ParseSourceFile(sf.getFullText(), sf.fileName);
return new ParseSourceSpan(new ParseLocation(parseSf, startOffset, startLine + 1, startCol + 1), new ParseLocation(parseSf, endOffset, endLine + 1, endCol + 1));
}
function compileResults(fac, def, metadataStmt, propName, additionalFields, deferrableImports, debugInfo = null) {
const statements = def.statements;
if (metadataStmt !== null) {
statements.push(metadataStmt);
}
if (debugInfo !== null) {
statements.push(debugInfo);
}
const results = [
fac,
{
name: propName,
initializer: def.expression,
statements: def.statements,
type: def.type,
deferrableImports
}
];
if (additionalFields !== null) {
results.push(...additionalFields);
}
return results;
}
function toFactoryMetadata(meta, target) {
return {
name: meta.name,
type: meta.type,
typeArgumentCount: meta.typeArgumentCount,
deps: meta.deps,
target
};
}
function resolveImportedFile(moduleResolver, importedFile, expr, origin) {
if (importedFile !== "unknown") {
return importedFile;
}
if (!(expr instanceof ExternalExpr)) {
return null;
}
return moduleResolver.resolveModule(expr.value.moduleName, origin.fileName);
}
function getOriginNodeForDiagnostics(expr, container) {
const nodeSf = expr.getSourceFile();
const exprSf = container.getSourceFile();
if (nodeSf === exprSf && expr.pos >= container.pos && expr.end <= container.end) {
return expr;
} else {
return container;
}
}
function isAbstractClassDeclaration(clazz) {
return import_typescript22.default.canHaveModifiers(clazz) && clazz.modifiers !== void 0 ? clazz.modifiers.some((mod) => mod.kind === import_typescript22.default.SyntaxKind.AbstractKeyword) : false;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/common/src/di.mjs
function getConstructorDependencies(clazz, reflector, isCore) {
const deps = [];
const errors = [];
let ctorParams = reflector.getConstructorParameters(clazz);
if (ctorParams === null) {
if (reflector.hasBaseClass(clazz)) {
return null;
} else {
ctorParams = [];
}
}
ctorParams.forEach((param, idx) => {
let token = valueReferenceToExpression(param.typeValueReference);
let attributeNameType = null;
let optional = false, self = false, skipSelf = false, host = false;
(param.decorators || []).filter((dec) => isCore || isAngularCore(dec)).forEach((dec) => {
const name = isCore || dec.import === null ? dec.name : dec.import.name;
if (name === "Inject") {
if (dec.args === null || dec.args.length !== 1) {
throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, dec.node, `Unexpected number of arguments to @Inject().`);
}
token = new WrappedNodeExpr(dec.args[0]);
} else if (name === "Optional") {
optional = true;
} else if (name === "SkipSelf") {
skipSelf = true;
} else if (name === "Self") {
self = true;
} else if (name === "Host") {
host = true;
} else if (name === "Attribute") {
if (dec.args === null || dec.args.length !== 1) {
throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, dec.node, `Unexpected number of arguments to @Attribute().`);
}
const attributeName = dec.args[0];
token = new WrappedNodeExpr(attributeName);
if (import_typescript23.default.isStringLiteralLike(attributeName)) {
attributeNameType = new LiteralExpr(attributeName.text);
} else {
attributeNameType = new WrappedNodeExpr(import_typescript23.default.factory.createKeywordTypeNode(import_typescript23.default.SyntaxKind.UnknownKeyword));
}
} else {
throw new FatalDiagnosticError(ErrorCode.DECORATOR_UNEXPECTED, dec.node, `Unexpected decorator ${name} on parameter.`);
}
});
if (token === null) {
if (param.typeValueReference.kind !== 2) {
throw new Error("Illegal state: expected value reference to be unavailable if no token is present");
}
errors.push({
index: idx,
param,
reason: param.typeValueReference.reason
});
} else {
deps.push({ token, attributeNameType, optional, self, skipSelf, host });
}
});
if (errors.length === 0) {
return { deps };
} else {
return { deps: null, errors };
}
}
function unwrapConstructorDependencies(deps) {
if (deps === null) {
return null;
} else if (deps.deps !== null) {
return deps.deps;
} else {
return "invalid";
}
}
function getValidConstructorDependencies(clazz, reflector, isCore) {
return validateConstructorDependencies(clazz, getConstructorDependencies(clazz, reflector, isCore));
}
function validateConstructorDependencies(clazz, deps) {
if (deps === null) {
return null;
} else if (deps.deps !== null) {
return deps.deps;
} else {
const error = deps.errors[0];
throw createUnsuitableInjectionTokenError(clazz, error);
}
}
function createUnsuitableInjectionTokenError(clazz, error) {
const { param, index, reason } = error;
let chainMessage = void 0;
let hints = void 0;
switch (reason.kind) {
case 5:
chainMessage = "Consider using the @Inject decorator to specify an injection token.";
hints = [
makeRelatedInformation(reason.typeNode, "This type is not supported as injection token.")
];
break;
case 1:
chainMessage = "Consider using the @Inject decorator to specify an injection token.";
hints = [
makeRelatedInformation(reason.typeNode, "This type does not have a value, so it cannot be used as injection token.")
];
if (reason.decl !== null) {
hints.push(makeRelatedInformation(reason.decl, "The type is declared here."));
}
break;
case 2:
chainMessage = "Consider changing the type-only import to a regular import, or use the @Inject decorator to specify an injection token.";
hints = [
makeRelatedInformation(reason.typeNode, "This type is imported using a type-only import, which prevents it from being usable as an injection token."),
makeRelatedInformation(reason.node, "The type-only import occurs here.")
];
break;
case 4:
chainMessage = "Consider using the @Inject decorator to specify an injection token.";
hints = [
makeRelatedInformation(reason.typeNode, "This type corresponds with a namespace, which cannot be used as injection token."),
makeRelatedInformation(reason.importClause, "The namespace import occurs here.")
];
break;
case 3:
chainMessage = "The type should reference a known declaration.";
hints = [makeRelatedInformation(reason.typeNode, "This type could not be resolved.")];
break;
case 0:
chainMessage = "Consider adding a type to the parameter or use the @Inject decorator to specify an injection token.";
break;
}
const chain2 = {
messageText: `No suitable injection token for parameter '${param.name || index}' of class '${clazz.name.text}'.`,
category: import_typescript23.default.DiagnosticCategory.Error,
code: 0,
next: [
{
messageText: chainMessage,
category: import_typescript23.default.DiagnosticCategory.Message,
code: 0
}
]
};
return new FatalDiagnosticError(ErrorCode.PARAM_MISSING_TOKEN, param.nameNode, chain2, hints);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/common/src/diagnostics.mjs
var import_typescript46 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/metadata/src/api.mjs
var MetaKind;
(function(MetaKind2) {
MetaKind2[MetaKind2["Directive"] = 0] = "Directive";
MetaKind2[MetaKind2["Pipe"] = 1] = "Pipe";
MetaKind2[MetaKind2["NgModule"] = 2] = "NgModule";
})(MetaKind || (MetaKind = {}));
var MatchSource;
(function(MatchSource2) {
MatchSource2[MatchSource2["Selector"] = 0] = "Selector";
MatchSource2[MatchSource2["HostDirective"] = 1] = "HostDirective";
})(MatchSource || (MatchSource = {}));
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/metadata/src/dts.mjs
var import_typescript26 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/metadata/src/property_mapping.mjs
var ClassPropertyMapping = class {
constructor(forwardMap) {
this.forwardMap = forwardMap;
this.reverseMap = reverseMapFromForwardMap(forwardMap);
}
static empty() {
return new ClassPropertyMapping(/* @__PURE__ */ new Map());
}
static fromMappedObject(obj) {
const forwardMap = /* @__PURE__ */ new Map();
for (const classPropertyName of Object.keys(obj)) {
const value = obj[classPropertyName];
let inputOrOutput;
if (typeof value === "string") {
inputOrOutput = {
classPropertyName,
bindingPropertyName: value,
isSignal: false
};
} else {
inputOrOutput = value;
}
forwardMap.set(classPropertyName, inputOrOutput);
}
return new ClassPropertyMapping(forwardMap);
}
static merge(a, b) {
const forwardMap = new Map(a.forwardMap.entries());
for (const [classPropertyName, inputOrOutput] of b.forwardMap) {
forwardMap.set(classPropertyName, inputOrOutput);
}
return new ClassPropertyMapping(forwardMap);
}
get classPropertyNames() {
return Array.from(this.forwardMap.keys());
}
get propertyNames() {
return Array.from(this.reverseMap.keys());
}
hasBindingPropertyName(propertyName) {
return this.reverseMap.has(propertyName);
}
getByBindingPropertyName(propertyName) {
return this.reverseMap.has(propertyName) ? this.reverseMap.get(propertyName) : null;
}
getByClassPropertyName(classPropertyName) {
return this.forwardMap.has(classPropertyName) ? this.forwardMap.get(classPropertyName) : null;
}
toDirectMappedObject() {
const obj = {};
for (const [classPropertyName, inputOrOutput] of this.forwardMap) {
obj[classPropertyName] = inputOrOutput.bindingPropertyName;
}
return obj;
}
toJointMappedObject(transform2) {
const obj = {};
for (const [classPropertyName, inputOrOutput] of this.forwardMap) {
obj[classPropertyName] = transform2(inputOrOutput);
}
return obj;
}
*[Symbol.iterator]() {
for (const inputOrOutput of this.forwardMap.values()) {
yield inputOrOutput;
}
}
};
function reverseMapFromForwardMap(forwardMap) {
const reverseMap = /* @__PURE__ */ new Map();
for (const [_, inputOrOutput] of forwardMap) {
if (!reverseMap.has(inputOrOutput.bindingPropertyName)) {
reverseMap.set(inputOrOutput.bindingPropertyName, []);
}
reverseMap.get(inputOrOutput.bindingPropertyName).push(inputOrOutput);
}
return reverseMap;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/metadata/src/util.mjs
var import_typescript24 = __toESM(require("typescript"), 1);
function extractReferencesFromType(checker, def, bestGuessOwningModule) {
if (!import_typescript24.default.isTupleTypeNode(def)) {
return [];
}
return def.elements.map((element2) => {
if (!import_typescript24.default.isTypeQueryNode(element2)) {
throw new Error(`Expected TypeQueryNode: ${nodeDebugInfo(element2)}`);
}
return extraReferenceFromTypeQuery(checker, element2, def, bestGuessOwningModule);
});
}
function extraReferenceFromTypeQuery(checker, typeNode, origin, bestGuessOwningModule) {
const type = typeNode.exprName;
const { node, from } = reflectTypeEntityToDeclaration(type, checker);
if (!isNamedClassDeclaration(node)) {
throw new Error(`Expected named ClassDeclaration: ${nodeDebugInfo(node)}`);
}
if (from !== null && !from.startsWith(".")) {
return new Reference2(node, {
specifier: from,
resolutionContext: origin.getSourceFile().fileName
});
}
return new Reference2(node, bestGuessOwningModule);
}
function readBooleanType(type) {
if (!import_typescript24.default.isLiteralTypeNode(type)) {
return null;
}
switch (type.literal.kind) {
case import_typescript24.default.SyntaxKind.TrueKeyword:
return true;
case import_typescript24.default.SyntaxKind.FalseKeyword:
return false;
default:
return null;
}
}
function readStringType(type) {
if (!import_typescript24.default.isLiteralTypeNode(type) || !import_typescript24.default.isStringLiteral(type.literal)) {
return null;
}
return type.literal.text;
}
function readMapType(type, valueTransform) {
if (!import_typescript24.default.isTypeLiteralNode(type)) {
return {};
}
const obj = {};
type.members.forEach((member) => {
if (!import_typescript24.default.isPropertySignature(member) || member.type === void 0 || member.name === void 0 || !import_typescript24.default.isStringLiteral(member.name) && !import_typescript24.default.isIdentifier(member.name)) {
return;
}
const value = valueTransform(member.type);
if (value !== null) {
obj[member.name.text] = value;
}
});
return obj;
}
function readStringArrayType(type) {
if (!import_typescript24.default.isTupleTypeNode(type)) {
return [];
}
const res = [];
type.elements.forEach((el) => {
if (!import_typescript24.default.isLiteralTypeNode(el) || !import_typescript24.default.isStringLiteral(el.literal)) {
return;
}
res.push(el.literal.text);
});
return res;
}
function extractDirectiveTypeCheckMeta(node, inputs, reflector) {
const members = reflector.getMembersOfClass(node);
const staticMembers = members.filter((member) => member.isStatic);
const ngTemplateGuards = staticMembers.map(extractTemplateGuard).filter((guard) => guard !== null);
const hasNgTemplateContextGuard = staticMembers.some((member) => member.kind === ClassMemberKind.Method && member.name === "ngTemplateContextGuard");
const coercedInputFields = new Set(staticMembers.map(extractCoercedInput).filter((inputName) => {
var _a2;
if (inputName === null || ((_a2 = inputs.getByClassPropertyName(inputName)) == null ? void 0 : _a2.isSignal)) {
return false;
}
return true;
}));
const restrictedInputFields = /* @__PURE__ */ new Set();
const stringLiteralInputFields = /* @__PURE__ */ new Set();
const undeclaredInputFields = /* @__PURE__ */ new Set();
for (const { classPropertyName, transform: transform2 } of inputs) {
const field = members.find((member) => member.name === classPropertyName);
if (field === void 0 || field.node === null) {
undeclaredInputFields.add(classPropertyName);
continue;
}
if (isRestricted(field.node)) {
restrictedInputFields.add(classPropertyName);
}
if (field.nameNode !== null && import_typescript24.default.isStringLiteral(field.nameNode)) {
stringLiteralInputFields.add(classPropertyName);
}
if (transform2 !== null) {
coercedInputFields.add(classPropertyName);
}
}
const arity = reflector.getGenericArityOfClass(node);
return {
hasNgTemplateContextGuard,
ngTemplateGuards,
coercedInputFields,
restrictedInputFields,
stringLiteralInputFields,
undeclaredInputFields,
isGeneric: arity !== null && arity > 0
};
}
function isRestricted(node) {
const modifiers = import_typescript24.default.canHaveModifiers(node) ? import_typescript24.default.getModifiers(node) : void 0;
return modifiers !== void 0 && modifiers.some(({ kind }) => {
return kind === import_typescript24.default.SyntaxKind.PrivateKeyword || kind === import_typescript24.default.SyntaxKind.ProtectedKeyword || kind === import_typescript24.default.SyntaxKind.ReadonlyKeyword;
});
}
function extractTemplateGuard(member) {
if (!member.name.startsWith("ngTemplateGuard_")) {
return null;
}
const inputName = afterUnderscore(member.name);
if (member.kind === ClassMemberKind.Property) {
let type = null;
if (member.type !== null && import_typescript24.default.isLiteralTypeNode(member.type) && import_typescript24.default.isStringLiteral(member.type.literal)) {
type = member.type.literal.text;
}
if (type !== "binding") {
return null;
}
return { inputName, type };
} else if (member.kind === ClassMemberKind.Method) {
return { inputName, type: "invocation" };
} else {
return null;
}
}
function extractCoercedInput(member) {
if (member.kind !== ClassMemberKind.Property || !member.name.startsWith("ngAcceptInputType_")) {
return null;
}
return afterUnderscore(member.name);
}
var CompoundMetadataReader = class {
constructor(readers) {
this.readers = readers;
}
getDirectiveMetadata(node) {
for (const reader of this.readers) {
const meta = reader.getDirectiveMetadata(node);
if (meta !== null) {
return meta;
}
}
return null;
}
getNgModuleMetadata(node) {
for (const reader of this.readers) {
const meta = reader.getNgModuleMetadata(node);
if (meta !== null) {
return meta;
}
}
return null;
}
getPipeMetadata(node) {
for (const reader of this.readers) {
const meta = reader.getPipeMetadata(node);
if (meta !== null) {
return meta;
}
}
return null;
}
};
function afterUnderscore(str) {
const pos = str.indexOf("_");
if (pos === -1) {
throw new Error(`Expected '${str}' to contain '_'`);
}
return str.slice(pos + 1);
}
function hasInjectableFields(clazz, host) {
const members = host.getMembersOfClass(clazz);
return members.some(({ isStatic, name }) => isStatic && (name === "\u0275prov" || name === "\u0275fac"));
}
function isHostDirectiveMetaForGlobalMode(hostDirectiveMeta) {
return hostDirectiveMeta.directive instanceof Reference2;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/metadata/src/dts.mjs
var DtsMetadataReader = class {
constructor(checker, reflector) {
this.checker = checker;
this.reflector = reflector;
}
getNgModuleMetadata(ref) {
const clazz = ref.node;
const ngModuleDef = this.reflector.getMembersOfClass(clazz).find((member) => member.name === "\u0275mod" && member.isStatic);
if (ngModuleDef === void 0) {
return null;
} else if (ngModuleDef.type === null || !import_typescript26.default.isTypeReferenceNode(ngModuleDef.type) || ngModuleDef.type.typeArguments === void 0 || ngModuleDef.type.typeArguments.length !== 4) {
return null;
}
const [_, declarationMetadata, importMetadata, exportMetadata] = ngModuleDef.type.typeArguments;
return {
kind: MetaKind.NgModule,
ref,
declarations: extractReferencesFromType(this.checker, declarationMetadata, ref.bestGuessOwningModule),
exports: extractReferencesFromType(this.checker, exportMetadata, ref.bestGuessOwningModule),
imports: extractReferencesFromType(this.checker, importMetadata, ref.bestGuessOwningModule),
schemas: [],
rawDeclarations: null,
rawImports: null,
rawExports: null,
decorator: null,
mayDeclareProviders: true
};
}
getDirectiveMetadata(ref) {
var _a2, _b2;
const clazz = ref.node;
const def = this.reflector.getMembersOfClass(clazz).find((field) => field.isStatic && (field.name === "\u0275cmp" || field.name === "\u0275dir"));
if (def === void 0) {
return null;
} else if (def.type === null || !import_typescript26.default.isTypeReferenceNode(def.type) || def.type.typeArguments === void 0 || def.type.typeArguments.length < 2) {
return null;
}
const isComponent = def.name === "\u0275cmp";
const ctorParams = this.reflector.getConstructorParameters(clazz);
const isStructural = !isComponent && ctorParams !== null && ctorParams.some((param) => {
return param.typeValueReference.kind === 1 && param.typeValueReference.moduleName === "@angular/core" && param.typeValueReference.importedName === "TemplateRef";
});
const ngContentSelectors = def.type.typeArguments.length > 6 ? readStringArrayType(def.type.typeArguments[6]) : null;
const isStandalone = def.type.typeArguments.length > 7 && ((_a2 = readBooleanType(def.type.typeArguments[7])) != null ? _a2 : false);
const inputs = ClassPropertyMapping.fromMappedObject(readInputsType(def.type.typeArguments[3]));
const outputs = ClassPropertyMapping.fromMappedObject(readMapType(def.type.typeArguments[4], readStringType));
const hostDirectives = def.type.typeArguments.length > 8 ? readHostDirectivesType(this.checker, def.type.typeArguments[8], ref.bestGuessOwningModule) : null;
const isSignal = def.type.typeArguments.length > 9 && ((_b2 = readBooleanType(def.type.typeArguments[9])) != null ? _b2 : false);
return __spreadProps(__spreadValues({
kind: MetaKind.Directive,
matchSource: MatchSource.Selector,
ref,
name: clazz.name.text,
isComponent,
selector: readStringType(def.type.typeArguments[1]),
exportAs: readStringArrayType(def.type.typeArguments[2]),
inputs,
outputs,
hostDirectives,
queries: readStringArrayType(def.type.typeArguments[5])
}, extractDirectiveTypeCheckMeta(clazz, inputs, this.reflector)), {
baseClass: readBaseClass2(clazz, this.checker, this.reflector),
isPoisoned: false,
isStructural,
animationTriggerNames: null,
ngContentSelectors,
isStandalone,
isSignal,
inputFieldNamesFromMetadataArray: null,
imports: null,
deferredImports: null,
schemas: null,
decorator: null,
assumedToExportProviders: isComponent && isStandalone,
preserveWhitespaces: false,
isExplicitlyDeferred: false
});
}
getPipeMetadata(ref) {
var _a2;
const def = this.reflector.getMembersOfClass(ref.node).find((field) => field.isStatic && field.name === "\u0275pipe");
if (def === void 0) {
return null;
} else if (def.type === null || !import_typescript26.default.isTypeReferenceNode(def.type) || def.type.typeArguments === void 0 || def.type.typeArguments.length < 2) {
return null;
}
const type = def.type.typeArguments[1];
if (!import_typescript26.default.isLiteralTypeNode(type) || !import_typescript26.default.isStringLiteral(type.literal)) {
return null;
}
const name = type.literal.text;
const isStandalone = def.type.typeArguments.length > 2 && ((_a2 = readBooleanType(def.type.typeArguments[2])) != null ? _a2 : false);
return {
kind: MetaKind.Pipe,
ref,
name,
nameExpr: null,
isStandalone,
decorator: null,
isExplicitlyDeferred: false
};
}
};
function readInputsType(type) {
const inputsMap = {};
if (import_typescript26.default.isTypeLiteralNode(type)) {
for (const member of type.members) {
if (!import_typescript26.default.isPropertySignature(member) || member.type === void 0 || member.name === void 0 || !import_typescript26.default.isStringLiteral(member.name) && !import_typescript26.default.isIdentifier(member.name)) {
continue;
}
const stringValue = readStringType(member.type);
const classPropertyName = member.name.text;
if (stringValue != null) {
inputsMap[classPropertyName] = {
bindingPropertyName: stringValue,
classPropertyName,
required: false,
isSignal: false,
transform: null
};
} else {
const config = readMapType(member.type, (innerValue) => {
var _a2;
return (_a2 = readStringType(innerValue)) != null ? _a2 : readBooleanType(innerValue);
});
inputsMap[classPropertyName] = {
classPropertyName,
bindingPropertyName: config.alias,
required: config.required,
isSignal: !!config.isSignal,
transform: null
};
}
}
}
return inputsMap;
}
function readBaseClass2(clazz, checker, reflector) {
if (!isNamedClassDeclaration(clazz)) {
return reflector.hasBaseClass(clazz) ? "dynamic" : null;
}
if (clazz.heritageClauses !== void 0) {
for (const clause of clazz.heritageClauses) {
if (clause.token === import_typescript26.default.SyntaxKind.ExtendsKeyword) {
const baseExpr = clause.types[0].expression;
let symbol = checker.getSymbolAtLocation(baseExpr);
if (symbol === void 0) {
return "dynamic";
} else if (symbol.flags & import_typescript26.default.SymbolFlags.Alias) {
symbol = checker.getAliasedSymbol(symbol);
}
if (symbol.valueDeclaration !== void 0 && isNamedClassDeclaration(symbol.valueDeclaration)) {
return new Reference2(symbol.valueDeclaration);
} else {
return "dynamic";
}
}
}
}
return null;
}
function readHostDirectivesType(checker, type, bestGuessOwningModule) {
if (!import_typescript26.default.isTupleTypeNode(type) || type.elements.length === 0) {
return null;
}
const result = [];
for (const hostDirectiveType of type.elements) {
const { directive, inputs, outputs } = readMapType(hostDirectiveType, (type2) => type2);
if (directive) {
if (!import_typescript26.default.isTypeQueryNode(directive)) {
throw new Error(`Expected TypeQueryNode: ${nodeDebugInfo(directive)}`);
}
result.push({
directive: extraReferenceFromTypeQuery(checker, directive, type, bestGuessOwningModule),
isForwardReference: false,
inputs: readMapType(inputs, readStringType),
outputs: readMapType(outputs, readStringType)
});
}
}
return result.length > 0 ? result : null;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/metadata/src/inheritance.mjs
function flattenInheritedDirectiveMetadata(reader, dir) {
const topMeta = reader.getDirectiveMetadata(dir);
if (topMeta === null) {
return null;
}
if (topMeta.baseClass === null) {
return topMeta;
}
const coercedInputFields = /* @__PURE__ */ new Set();
const undeclaredInputFields = /* @__PURE__ */ new Set();
const restrictedInputFields = /* @__PURE__ */ new Set();
const stringLiteralInputFields = /* @__PURE__ */ new Set();
let hostDirectives = null;
let isDynamic = false;
let inputs = ClassPropertyMapping.empty();
let outputs = ClassPropertyMapping.empty();
let isStructural = false;
const addMetadata = (meta) => {
if (meta.baseClass === "dynamic") {
isDynamic = true;
} else if (meta.baseClass !== null) {
const baseMeta = reader.getDirectiveMetadata(meta.baseClass);
if (baseMeta !== null) {
addMetadata(baseMeta);
} else {
isDynamic = true;
}
}
isStructural = isStructural || meta.isStructural;
inputs = ClassPropertyMapping.merge(inputs, meta.inputs);
outputs = ClassPropertyMapping.merge(outputs, meta.outputs);
for (const coercedInputField of meta.coercedInputFields) {
coercedInputFields.add(coercedInputField);
}
for (const undeclaredInputField of meta.undeclaredInputFields) {
undeclaredInputFields.add(undeclaredInputField);
}
for (const restrictedInputField of meta.restrictedInputFields) {
restrictedInputFields.add(restrictedInputField);
}
for (const field of meta.stringLiteralInputFields) {
stringLiteralInputFields.add(field);
}
if (meta.hostDirectives !== null && meta.hostDirectives.length > 0) {
hostDirectives != null ? hostDirectives : hostDirectives = [];
hostDirectives.push(...meta.hostDirectives);
}
};
addMetadata(topMeta);
return __spreadProps(__spreadValues({}, topMeta), {
inputs,
outputs,
coercedInputFields,
undeclaredInputFields,
restrictedInputFields,
stringLiteralInputFields,
baseClass: isDynamic ? "dynamic" : null,
isStructural,
hostDirectives
});
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/metadata/src/registry.mjs
var LocalMetadataRegistry = class {
constructor() {
this.directives = /* @__PURE__ */ new Map();
this.ngModules = /* @__PURE__ */ new Map();
this.pipes = /* @__PURE__ */ new Map();
}
getDirectiveMetadata(ref) {
return this.directives.has(ref.node) ? this.directives.get(ref.node) : null;
}
getNgModuleMetadata(ref) {
return this.ngModules.has(ref.node) ? this.ngModules.get(ref.node) : null;
}
getPipeMetadata(ref) {
return this.pipes.has(ref.node) ? this.pipes.get(ref.node) : null;
}
registerDirectiveMetadata(meta) {
this.directives.set(meta.ref.node, meta);
}
registerNgModuleMetadata(meta) {
this.ngModules.set(meta.ref.node, meta);
}
registerPipeMetadata(meta) {
this.pipes.set(meta.ref.node, meta);
}
getKnown(kind) {
switch (kind) {
case MetaKind.Directive:
return Array.from(this.directives.values()).map((v) => v.ref.node);
case MetaKind.Pipe:
return Array.from(this.pipes.values()).map((v) => v.ref.node);
case MetaKind.NgModule:
return Array.from(this.ngModules.values()).map((v) => v.ref.node);
}
}
};
var CompoundMetadataRegistry = class {
constructor(registries) {
this.registries = registries;
}
registerDirectiveMetadata(meta) {
for (const registry of this.registries) {
registry.registerDirectiveMetadata(meta);
}
}
registerNgModuleMetadata(meta) {
for (const registry of this.registries) {
registry.registerNgModuleMetadata(meta);
}
}
registerPipeMetadata(meta) {
for (const registry of this.registries) {
registry.registerPipeMetadata(meta);
}
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/metadata/src/resource_registry.mjs
var ResourceRegistry = class {
constructor() {
this.externalTemplateToComponentsMap = /* @__PURE__ */ new Map();
this.componentToTemplateMap = /* @__PURE__ */ new Map();
this.componentToStylesMap = /* @__PURE__ */ new Map();
this.externalStyleToComponentsMap = /* @__PURE__ */ new Map();
}
getComponentsWithTemplate(template2) {
if (!this.externalTemplateToComponentsMap.has(template2)) {
return /* @__PURE__ */ new Set();
}
return this.externalTemplateToComponentsMap.get(template2);
}
registerResources(resources, component) {
if (resources.template !== null) {
this.registerTemplate(resources.template, component);
}
for (const style of resources.styles) {
this.registerStyle(style, component);
}
}
registerTemplate(templateResource, component) {
const { path: path4 } = templateResource;
if (path4 !== null) {
if (!this.externalTemplateToComponentsMap.has(path4)) {
this.externalTemplateToComponentsMap.set(path4, /* @__PURE__ */ new Set());
}
this.externalTemplateToComponentsMap.get(path4).add(component);
}
this.componentToTemplateMap.set(component, templateResource);
}
getTemplate(component) {
if (!this.componentToTemplateMap.has(component)) {
return null;
}
return this.componentToTemplateMap.get(component);
}
registerStyle(styleResource, component) {
const { path: path4 } = styleResource;
if (!this.componentToStylesMap.has(component)) {
this.componentToStylesMap.set(component, /* @__PURE__ */ new Set());
}
if (path4 !== null) {
if (!this.externalStyleToComponentsMap.has(path4)) {
this.externalStyleToComponentsMap.set(path4, /* @__PURE__ */ new Set());
}
this.externalStyleToComponentsMap.get(path4).add(component);
}
this.componentToStylesMap.get(component).add(styleResource);
}
getStyles(component) {
if (!this.componentToStylesMap.has(component)) {
return /* @__PURE__ */ new Set();
}
return this.componentToStylesMap.get(component);
}
getComponentsWithStyle(styleUrl) {
if (!this.externalStyleToComponentsMap.has(styleUrl)) {
return /* @__PURE__ */ new Set();
}
return this.externalStyleToComponentsMap.get(styleUrl);
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/metadata/src/providers.mjs
var ExportedProviderStatusResolver = class {
constructor(metaReader) {
this.metaReader = metaReader;
this.calculating = /* @__PURE__ */ new Set();
}
mayExportProviders(ref, dependencyCallback) {
var _a2;
if (this.calculating.has(ref.node)) {
return false;
}
this.calculating.add(ref.node);
if (dependencyCallback !== void 0) {
dependencyCallback(ref);
}
try {
const dirMeta = this.metaReader.getDirectiveMetadata(ref);
if (dirMeta !== null) {
if (!dirMeta.isComponent || !dirMeta.isStandalone) {
return false;
}
if (dirMeta.assumedToExportProviders) {
return true;
}
return ((_a2 = dirMeta.imports) != null ? _a2 : []).some((importRef) => this.mayExportProviders(importRef, dependencyCallback));
}
const pipeMeta = this.metaReader.getPipeMetadata(ref);
if (pipeMeta !== null) {
return false;
}
const ngModuleMeta = this.metaReader.getNgModuleMetadata(ref);
if (ngModuleMeta !== null) {
if (ngModuleMeta.mayDeclareProviders) {
return true;
}
return ngModuleMeta.imports.some((importRef) => this.mayExportProviders(importRef, dependencyCallback));
}
return false;
} finally {
this.calculating.delete(ref.node);
}
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/metadata/src/host_directives_resolver.mjs
var EMPTY_ARRAY = [];
var HostDirectivesResolver = class {
constructor(metaReader) {
this.metaReader = metaReader;
this.cache = /* @__PURE__ */ new Map();
}
resolve(metadata) {
if (this.cache.has(metadata.ref.node)) {
return this.cache.get(metadata.ref.node);
}
const results = metadata.hostDirectives && metadata.hostDirectives.length > 0 ? this.walkHostDirectives(metadata.hostDirectives, []) : EMPTY_ARRAY;
this.cache.set(metadata.ref.node, results);
return results;
}
walkHostDirectives(directives, results) {
for (const current of directives) {
if (!isHostDirectiveMetaForGlobalMode(current)) {
throw new Error("Impossible state: resolving code path in local compilation mode");
}
const hostMeta = flattenInheritedDirectiveMetadata(this.metaReader, current.directive);
if (hostMeta === null) {
continue;
}
if (hostMeta.hostDirectives) {
this.walkHostDirectives(hostMeta.hostDirectives, results);
}
results.push(__spreadProps(__spreadValues({}, hostMeta), {
matchSource: MatchSource.HostDirective,
inputs: ClassPropertyMapping.fromMappedObject(this.filterMappings(hostMeta.inputs, current.inputs, resolveInput)),
outputs: ClassPropertyMapping.fromMappedObject(this.filterMappings(hostMeta.outputs, current.outputs, resolveOutput))
}));
}
return results;
}
filterMappings(source, allowedProperties, valueResolver) {
const result = {};
if (allowedProperties !== null) {
for (const publicName in allowedProperties) {
if (allowedProperties.hasOwnProperty(publicName)) {
const bindings = source.getByBindingPropertyName(publicName);
if (bindings !== null) {
for (const binding of bindings) {
result[binding.classPropertyName] = valueResolver(allowedProperties[publicName], binding);
}
}
}
}
}
return result;
}
};
function resolveInput(bindingName, binding) {
return {
bindingPropertyName: bindingName,
classPropertyName: binding.classPropertyName,
required: binding.required,
transform: binding.transform,
isSignal: binding.isSignal
};
}
function resolveOutput(bindingName) {
return bindingName;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/partial_evaluator/src/diagnostics.mjs
var import_typescript28 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/partial_evaluator/src/dynamic.mjs
var DynamicValue = class {
constructor(node, reason, code) {
this.node = node;
this.reason = reason;
this.code = code;
}
static fromDynamicInput(node, input) {
return new DynamicValue(node, input, 0);
}
static fromDynamicString(node) {
return new DynamicValue(node, void 0, 1);
}
static fromExternalReference(node, ref) {
return new DynamicValue(node, ref, 2);
}
static fromUnsupportedSyntax(node) {
return new DynamicValue(node, void 0, 3);
}
static fromUnknownIdentifier(node) {
return new DynamicValue(node, void 0, 4);
}
static fromInvalidExpressionType(node, value) {
return new DynamicValue(node, value, 5);
}
static fromComplexFunctionCall(node, fn2) {
return new DynamicValue(node, fn2, 6);
}
static fromDynamicType(node) {
return new DynamicValue(node, void 0, 7);
}
static fromSyntheticInput(node, value) {
return new DynamicValue(node, value, 8);
}
static fromUnknown(node) {
return new DynamicValue(node, void 0, 9);
}
isFromDynamicInput() {
return this.code === 0;
}
isFromDynamicString() {
return this.code === 1;
}
isFromExternalReference() {
return this.code === 2;
}
isFromUnsupportedSyntax() {
return this.code === 3;
}
isFromUnknownIdentifier() {
return this.code === 4;
}
isFromInvalidExpressionType() {
return this.code === 5;
}
isFromComplexFunctionCall() {
return this.code === 6;
}
isFromDynamicType() {
return this.code === 7;
}
isFromUnknown() {
return this.code === 9;
}
accept(visitor) {
switch (this.code) {
case 0:
return visitor.visitDynamicInput(this);
case 1:
return visitor.visitDynamicString(this);
case 2:
return visitor.visitExternalReference(this);
case 3:
return visitor.visitUnsupportedSyntax(this);
case 4:
return visitor.visitUnknownIdentifier(this);
case 5:
return visitor.visitInvalidExpressionType(this);
case 6:
return visitor.visitComplexFunctionCall(this);
case 7:
return visitor.visitDynamicType(this);
case 8:
return visitor.visitSyntheticInput(this);
case 9:
return visitor.visitUnknown(this);
}
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/partial_evaluator/src/result.mjs
var ResolvedModule = class {
constructor(exports, evaluate) {
this.exports = exports;
this.evaluate = evaluate;
}
getExport(name) {
if (!this.exports.has(name)) {
return void 0;
}
return this.evaluate(this.exports.get(name));
}
getExports() {
const map = /* @__PURE__ */ new Map();
this.exports.forEach((decl, name) => {
map.set(name, this.evaluate(decl));
});
return map;
}
};
var EnumValue = class {
constructor(enumRef, name, resolved) {
this.enumRef = enumRef;
this.name = name;
this.resolved = resolved;
}
};
var KnownFn = class {
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/partial_evaluator/src/diagnostics.mjs
function describeResolvedType(value, maxDepth = 1) {
var _a2, _b2;
if (value === null) {
return "null";
} else if (value === void 0) {
return "undefined";
} else if (typeof value === "number" || typeof value === "boolean" || typeof value === "string") {
return typeof value;
} else if (value instanceof Map) {
if (maxDepth === 0) {
return "object";
}
const entries = Array.from(value.entries()).map(([key, v]) => {
return `${quoteKey(key)}: ${describeResolvedType(v, maxDepth - 1)}`;
});
return entries.length > 0 ? `{ ${entries.join("; ")} }` : "{}";
} else if (value instanceof ResolvedModule) {
return "(module)";
} else if (value instanceof EnumValue) {
return (_a2 = value.enumRef.debugName) != null ? _a2 : "(anonymous)";
} else if (value instanceof Reference2) {
return (_b2 = value.debugName) != null ? _b2 : "(anonymous)";
} else if (Array.isArray(value)) {
if (maxDepth === 0) {
return "Array";
}
return `[${value.map((v) => describeResolvedType(v, maxDepth - 1)).join(", ")}]`;
} else if (value instanceof DynamicValue) {
return "(not statically analyzable)";
} else if (value instanceof KnownFn) {
return "Function";
} else {
return "unknown";
}
}
function quoteKey(key) {
if (/^[a-z0-9_]+$/i.test(key)) {
return key;
} else {
return `'${key.replace(/'/g, "\\'")}'`;
}
}
function traceDynamicValue(node, value) {
return value.accept(new TraceDynamicValueVisitor(node));
}
var TraceDynamicValueVisitor = class {
constructor(node) {
this.node = node;
this.currentContainerNode = null;
}
visitDynamicInput(value) {
const trace = value.reason.accept(this);
if (this.shouldTrace(value.node)) {
const info = makeRelatedInformation(value.node, "Unable to evaluate this expression statically.");
trace.unshift(info);
}
return trace;
}
visitSyntheticInput(value) {
return [makeRelatedInformation(value.node, "Unable to evaluate this expression further.")];
}
visitDynamicString(value) {
return [
makeRelatedInformation(value.node, "A string value could not be determined statically.")
];
}
visitExternalReference(value) {
const name = value.reason.debugName;
const description = name !== null ? `'${name}'` : "an anonymous declaration";
return [
makeRelatedInformation(value.node, `A value for ${description} cannot be determined statically, as it is an external declaration.`)
];
}
visitComplexFunctionCall(value) {
return [
makeRelatedInformation(value.node, "Unable to evaluate function call of complex function. A function must have exactly one return statement."),
makeRelatedInformation(value.reason.node, "Function is declared here.")
];
}
visitInvalidExpressionType(value) {
return [makeRelatedInformation(value.node, "Unable to evaluate an invalid expression.")];
}
visitUnknown(value) {
return [makeRelatedInformation(value.node, "Unable to evaluate statically.")];
}
visitUnknownIdentifier(value) {
return [makeRelatedInformation(value.node, "Unknown reference.")];
}
visitDynamicType(value) {
return [makeRelatedInformation(value.node, "Dynamic type.")];
}
visitUnsupportedSyntax(value) {
return [makeRelatedInformation(value.node, "This syntax is not supported.")];
}
shouldTrace(node) {
if (node === this.node) {
return false;
}
const container = getContainerNode(node);
if (container === this.currentContainerNode) {
return false;
}
this.currentContainerNode = container;
return true;
}
};
function getContainerNode(node) {
let currentNode = node;
while (currentNode !== void 0) {
switch (currentNode.kind) {
case import_typescript28.default.SyntaxKind.ExpressionStatement:
case import_typescript28.default.SyntaxKind.VariableStatement:
case import_typescript28.default.SyntaxKind.ReturnStatement:
case import_typescript28.default.SyntaxKind.IfStatement:
case import_typescript28.default.SyntaxKind.SwitchStatement:
case import_typescript28.default.SyntaxKind.DoStatement:
case import_typescript28.default.SyntaxKind.WhileStatement:
case import_typescript28.default.SyntaxKind.ForStatement:
case import_typescript28.default.SyntaxKind.ForInStatement:
case import_typescript28.default.SyntaxKind.ForOfStatement:
case import_typescript28.default.SyntaxKind.ContinueStatement:
case import_typescript28.default.SyntaxKind.BreakStatement:
case import_typescript28.default.SyntaxKind.ThrowStatement:
case import_typescript28.default.SyntaxKind.ObjectBindingPattern:
case import_typescript28.default.SyntaxKind.ArrayBindingPattern:
return currentNode;
}
currentNode = currentNode.parent;
}
return node.getSourceFile();
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/partial_evaluator/src/interpreter.mjs
var import_typescript29 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/partial_evaluator/src/builtin.mjs
var ArraySliceBuiltinFn = class extends KnownFn {
constructor(lhs) {
super();
this.lhs = lhs;
}
evaluate(node, args) {
if (args.length === 0) {
return this.lhs;
} else {
return DynamicValue.fromUnknown(node);
}
}
};
var ArrayConcatBuiltinFn = class extends KnownFn {
constructor(lhs) {
super();
this.lhs = lhs;
}
evaluate(node, args) {
const result = [...this.lhs];
for (const arg of args) {
if (arg instanceof DynamicValue) {
result.push(DynamicValue.fromDynamicInput(node, arg));
} else if (Array.isArray(arg)) {
result.push(...arg);
} else {
result.push(arg);
}
}
return result;
}
};
var StringConcatBuiltinFn = class extends KnownFn {
constructor(lhs) {
super();
this.lhs = lhs;
}
evaluate(node, args) {
let result = this.lhs;
for (const arg of args) {
const resolved = arg instanceof EnumValue ? arg.resolved : arg;
if (typeof resolved === "string" || typeof resolved === "number" || typeof resolved === "boolean" || resolved == null) {
result = result.concat(resolved);
} else {
return DynamicValue.fromUnknown(node);
}
}
return result;
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/partial_evaluator/src/synthetic.mjs
var SyntheticValue = class {
constructor(value) {
this.value = value;
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/partial_evaluator/src/interpreter.mjs
function literalBinaryOp(op) {
return { op, literal: true };
}
function referenceBinaryOp(op) {
return { op, literal: false };
}
var BINARY_OPERATORS2 = /* @__PURE__ */ new Map([
[import_typescript29.default.SyntaxKind.PlusToken, literalBinaryOp((a, b) => a + b)],
[import_typescript29.default.SyntaxKind.MinusToken, literalBinaryOp((a, b) => a - b)],
[import_typescript29.default.SyntaxKind.AsteriskToken, literalBinaryOp((a, b) => a * b)],
[import_typescript29.default.SyntaxKind.SlashToken, literalBinaryOp((a, b) => a / b)],
[import_typescript29.default.SyntaxKind.PercentToken, literalBinaryOp((a, b) => a % b)],
[import_typescript29.default.SyntaxKind.AmpersandToken, literalBinaryOp((a, b) => a & b)],
[import_typescript29.default.SyntaxKind.BarToken, literalBinaryOp((a, b) => a | b)],
[import_typescript29.default.SyntaxKind.CaretToken, literalBinaryOp((a, b) => a ^ b)],
[import_typescript29.default.SyntaxKind.LessThanToken, literalBinaryOp((a, b) => a < b)],
[import_typescript29.default.SyntaxKind.LessThanEqualsToken, literalBinaryOp((a, b) => a <= b)],
[import_typescript29.default.SyntaxKind.GreaterThanToken, literalBinaryOp((a, b) => a > b)],
[import_typescript29.default.SyntaxKind.GreaterThanEqualsToken, literalBinaryOp((a, b) => a >= b)],
[import_typescript29.default.SyntaxKind.EqualsEqualsToken, literalBinaryOp((a, b) => a == b)],
[import_typescript29.default.SyntaxKind.EqualsEqualsEqualsToken, literalBinaryOp((a, b) => a === b)],
[import_typescript29.default.SyntaxKind.ExclamationEqualsToken, literalBinaryOp((a, b) => a != b)],
[import_typescript29.default.SyntaxKind.ExclamationEqualsEqualsToken, literalBinaryOp((a, b) => a !== b)],
[import_typescript29.default.SyntaxKind.LessThanLessThanToken, literalBinaryOp((a, b) => a << b)],
[import_typescript29.default.SyntaxKind.GreaterThanGreaterThanToken, literalBinaryOp((a, b) => a >> b)],
[import_typescript29.default.SyntaxKind.GreaterThanGreaterThanGreaterThanToken, literalBinaryOp((a, b) => a >>> b)],
[import_typescript29.default.SyntaxKind.AsteriskAsteriskToken, literalBinaryOp((a, b) => Math.pow(a, b))],
[import_typescript29.default.SyntaxKind.AmpersandAmpersandToken, referenceBinaryOp((a, b) => a && b)],
[import_typescript29.default.SyntaxKind.BarBarToken, referenceBinaryOp((a, b) => a || b)]
]);
var UNARY_OPERATORS = /* @__PURE__ */ new Map([
[import_typescript29.default.SyntaxKind.TildeToken, (a) => ~a],
[import_typescript29.default.SyntaxKind.MinusToken, (a) => -a],
[import_typescript29.default.SyntaxKind.PlusToken, (a) => +a],
[import_typescript29.default.SyntaxKind.ExclamationToken, (a) => !a]
]);
var StaticInterpreter = class {
constructor(host, checker, dependencyTracker) {
this.host = host;
this.checker = checker;
this.dependencyTracker = dependencyTracker;
}
visit(node, context) {
return this.visitExpression(node, context);
}
visitExpression(node, context) {
let result;
if (node.kind === import_typescript29.default.SyntaxKind.TrueKeyword) {
return true;
} else if (node.kind === import_typescript29.default.SyntaxKind.FalseKeyword) {
return false;
} else if (node.kind === import_typescript29.default.SyntaxKind.NullKeyword) {
return null;
} else if (import_typescript29.default.isStringLiteral(node)) {
return node.text;
} else if (import_typescript29.default.isNoSubstitutionTemplateLiteral(node)) {
return node.text;
} else if (import_typescript29.default.isTemplateExpression(node)) {
result = this.visitTemplateExpression(node, context);
} else if (import_typescript29.default.isNumericLiteral(node)) {
return parseFloat(node.text);
} else if (import_typescript29.default.isObjectLiteralExpression(node)) {
result = this.visitObjectLiteralExpression(node, context);
} else if (import_typescript29.default.isIdentifier(node)) {
result = this.visitIdentifier(node, context);
} else if (import_typescript29.default.isPropertyAccessExpression(node)) {
result = this.visitPropertyAccessExpression(node, context);
} else if (import_typescript29.default.isCallExpression(node)) {
result = this.visitCallExpression(node, context);
} else if (import_typescript29.default.isConditionalExpression(node)) {
result = this.visitConditionalExpression(node, context);
} else if (import_typescript29.default.isPrefixUnaryExpression(node)) {
result = this.visitPrefixUnaryExpression(node, context);
} else if (import_typescript29.default.isBinaryExpression(node)) {
result = this.visitBinaryExpression(node, context);
} else if (import_typescript29.default.isArrayLiteralExpression(node)) {
result = this.visitArrayLiteralExpression(node, context);
} else if (import_typescript29.default.isParenthesizedExpression(node)) {
result = this.visitParenthesizedExpression(node, context);
} else if (import_typescript29.default.isElementAccessExpression(node)) {
result = this.visitElementAccessExpression(node, context);
} else if (import_typescript29.default.isAsExpression(node)) {
result = this.visitExpression(node.expression, context);
} else if (import_typescript29.default.isNonNullExpression(node)) {
result = this.visitExpression(node.expression, context);
} else if (this.host.isClass(node)) {
result = this.visitDeclaration(node, context);
} else {
return DynamicValue.fromUnsupportedSyntax(node);
}
if (result instanceof DynamicValue && result.node !== node) {
return DynamicValue.fromDynamicInput(node, result);
}
return result;
}
visitArrayLiteralExpression(node, context) {
const array = [];
for (let i = 0; i < node.elements.length; i++) {
const element2 = node.elements[i];
if (import_typescript29.default.isSpreadElement(element2)) {
array.push(...this.visitSpreadElement(element2, context));
} else {
array.push(this.visitExpression(element2, context));
}
}
return array;
}
visitObjectLiteralExpression(node, context) {
const map = /* @__PURE__ */ new Map();
for (let i = 0; i < node.properties.length; i++) {
const property2 = node.properties[i];
if (import_typescript29.default.isPropertyAssignment(property2)) {
const name = this.stringNameFromPropertyName(property2.name, context);
if (name === void 0) {
return DynamicValue.fromDynamicInput(node, DynamicValue.fromDynamicString(property2.name));
}
map.set(name, this.visitExpression(property2.initializer, context));
} else if (import_typescript29.default.isShorthandPropertyAssignment(property2)) {
const symbol = this.checker.getShorthandAssignmentValueSymbol(property2);
if (symbol === void 0 || symbol.valueDeclaration === void 0) {
map.set(property2.name.text, DynamicValue.fromUnknown(property2));
} else {
map.set(property2.name.text, this.visitDeclaration(symbol.valueDeclaration, context));
}
} else if (import_typescript29.default.isSpreadAssignment(property2)) {
const spread = this.visitExpression(property2.expression, context);
if (spread instanceof DynamicValue) {
return DynamicValue.fromDynamicInput(node, spread);
} else if (spread instanceof Map) {
spread.forEach((value, key) => map.set(key, value));
} else if (spread instanceof ResolvedModule) {
spread.getExports().forEach((value, key) => map.set(key, value));
} else {
return DynamicValue.fromDynamicInput(node, DynamicValue.fromInvalidExpressionType(property2, spread));
}
} else {
return DynamicValue.fromUnknown(node);
}
}
return map;
}
visitTemplateExpression(node, context) {
const pieces = [node.head.text];
for (let i = 0; i < node.templateSpans.length; i++) {
const span = node.templateSpans[i];
const value = literal2(this.visit(span.expression, context), () => DynamicValue.fromDynamicString(span.expression));
if (value instanceof DynamicValue) {
return DynamicValue.fromDynamicInput(node, value);
}
pieces.push(`${value}`, span.literal.text);
}
return pieces.join("");
}
visitIdentifier(node, context) {
const decl = this.host.getDeclarationOfIdentifier(node);
if (decl === null) {
if (import_typescript29.default.identifierToKeywordKind(node) === import_typescript29.default.SyntaxKind.UndefinedKeyword) {
return void 0;
} else {
if (this.dependencyTracker !== null && this.host.getImportOfIdentifier(node) !== null) {
this.dependencyTracker.recordDependencyAnalysisFailure(context.originatingFile);
}
return DynamicValue.fromUnknownIdentifier(node);
}
}
const declContext = __spreadValues(__spreadValues({}, context), joinModuleContext(context, node, decl));
const result = this.visitDeclaration(decl.node, declContext);
if (result instanceof Reference2) {
if (!result.synthetic) {
result.addIdentifier(node);
}
} else if (result instanceof DynamicValue) {
return DynamicValue.fromDynamicInput(node, result);
}
return result;
}
visitDeclaration(node, context) {
if (this.dependencyTracker !== null) {
this.dependencyTracker.addDependency(context.originatingFile, node.getSourceFile());
}
if (this.host.isClass(node)) {
return this.getReference(node, context);
} else if (import_typescript29.default.isVariableDeclaration(node)) {
return this.visitVariableDeclaration(node, context);
} else if (import_typescript29.default.isParameter(node) && context.scope.has(node)) {
return context.scope.get(node);
} else if (import_typescript29.default.isExportAssignment(node)) {
return this.visitExpression(node.expression, context);
} else if (import_typescript29.default.isEnumDeclaration(node)) {
return this.visitEnumDeclaration(node, context);
} else if (import_typescript29.default.isSourceFile(node)) {
return this.visitSourceFile(node, context);
} else if (import_typescript29.default.isBindingElement(node)) {
return this.visitBindingElement(node, context);
} else {
return this.getReference(node, context);
}
}
visitVariableDeclaration(node, context) {
const value = this.host.getVariableValue(node);
if (value !== null) {
return this.visitExpression(value, context);
} else if (isVariableDeclarationDeclared(node)) {
if (node.type !== void 0) {
const evaluatedType = this.visitType(node.type, context);
if (!(evaluatedType instanceof DynamicValue)) {
return evaluatedType;
}
}
return this.getReference(node, context);
} else {
return void 0;
}
}
visitEnumDeclaration(node, context) {
const enumRef = this.getReference(node, context);
const map = /* @__PURE__ */ new Map();
node.members.forEach((member) => {
const name = this.stringNameFromPropertyName(member.name, context);
if (name !== void 0) {
const resolved = member.initializer && this.visit(member.initializer, context);
map.set(name, new EnumValue(enumRef, name, resolved));
}
});
return map;
}
visitElementAccessExpression(node, context) {
const lhs = this.visitExpression(node.expression, context);
if (lhs instanceof DynamicValue) {
return DynamicValue.fromDynamicInput(node, lhs);
}
const rhs = this.visitExpression(node.argumentExpression, context);
if (rhs instanceof DynamicValue) {
return DynamicValue.fromDynamicInput(node, rhs);
}
if (typeof rhs !== "string" && typeof rhs !== "number") {
return DynamicValue.fromInvalidExpressionType(node, rhs);
}
return this.accessHelper(node, lhs, rhs, context);
}
visitPropertyAccessExpression(node, context) {
const lhs = this.visitExpression(node.expression, context);
const rhs = node.name.text;
if (lhs instanceof DynamicValue) {
return DynamicValue.fromDynamicInput(node, lhs);
}
return this.accessHelper(node, lhs, rhs, context);
}
visitSourceFile(node, context) {
const declarations = this.host.getExportsOfModule(node);
if (declarations === null) {
return DynamicValue.fromUnknown(node);
}
return new ResolvedModule(declarations, (decl) => {
const declContext = __spreadValues(__spreadValues({}, context), joinModuleContext(context, node, decl));
return this.visitDeclaration(decl.node, declContext);
});
}
accessHelper(node, lhs, rhs, context) {
const strIndex = `${rhs}`;
if (lhs instanceof Map) {
if (lhs.has(strIndex)) {
return lhs.get(strIndex);
} else {
return void 0;
}
} else if (lhs instanceof ResolvedModule) {
return lhs.getExport(strIndex);
} else if (Array.isArray(lhs)) {
if (rhs === "length") {
return lhs.length;
} else if (rhs === "slice") {
return new ArraySliceBuiltinFn(lhs);
} else if (rhs === "concat") {
return new ArrayConcatBuiltinFn(lhs);
}
if (typeof rhs !== "number" || !Number.isInteger(rhs)) {
return DynamicValue.fromInvalidExpressionType(node, rhs);
}
return lhs[rhs];
} else if (typeof lhs === "string" && rhs === "concat") {
return new StringConcatBuiltinFn(lhs);
} else if (lhs instanceof Reference2) {
const ref = lhs.node;
if (this.host.isClass(ref)) {
const module2 = owningModule(context, lhs.bestGuessOwningModule);
let value = void 0;
const member = this.host.getMembersOfClass(ref).find((member2) => member2.isStatic && member2.name === strIndex);
if (member !== void 0) {
if (member.value !== null) {
value = this.visitExpression(member.value, context);
} else if (member.implementation !== null) {
value = new Reference2(member.implementation, module2);
} else if (member.node) {
value = new Reference2(member.node, module2);
}
}
return value;
} else if (isDeclaration(ref)) {
return DynamicValue.fromDynamicInput(node, DynamicValue.fromExternalReference(ref, lhs));
}
} else if (lhs instanceof DynamicValue) {
return DynamicValue.fromDynamicInput(node, lhs);
} else if (lhs instanceof SyntheticValue) {
return DynamicValue.fromSyntheticInput(node, lhs);
}
return DynamicValue.fromUnknown(node);
}
visitCallExpression(node, context) {
const lhs = this.visitExpression(node.expression, context);
if (lhs instanceof DynamicValue) {
return DynamicValue.fromDynamicInput(node, lhs);
}
if (lhs instanceof KnownFn) {
return lhs.evaluate(node, this.evaluateFunctionArguments(node, context));
}
if (!(lhs instanceof Reference2)) {
return DynamicValue.fromInvalidExpressionType(node.expression, lhs);
}
const fn2 = this.host.getDefinitionOfFunction(lhs.node);
if (fn2 === null) {
return DynamicValue.fromInvalidExpressionType(node.expression, lhs);
}
if (!isFunctionOrMethodReference(lhs)) {
return DynamicValue.fromInvalidExpressionType(node.expression, lhs);
}
const resolveFfrExpr = (expr) => {
let contextExtension = {};
if (fn2.body === null && expr.getSourceFile() !== node.expression.getSourceFile() && lhs.bestGuessOwningModule !== null) {
contextExtension = {
absoluteModuleName: lhs.bestGuessOwningModule.specifier,
resolutionContext: lhs.bestGuessOwningModule.resolutionContext
};
}
return this.visitFfrExpression(expr, __spreadValues(__spreadValues({}, context), contextExtension));
};
if (fn2.body === null && context.foreignFunctionResolver !== void 0) {
const unresolvable = DynamicValue.fromDynamicInput(node, DynamicValue.fromExternalReference(node.expression, lhs));
return context.foreignFunctionResolver(lhs, node, resolveFfrExpr, unresolvable);
}
const res = this.visitFunctionBody(node, fn2, context);
if (res instanceof DynamicValue && context.foreignFunctionResolver !== void 0) {
const unresolvable = DynamicValue.fromComplexFunctionCall(node, fn2);
return context.foreignFunctionResolver(lhs, node, resolveFfrExpr, unresolvable);
}
return res;
}
visitFfrExpression(expr, context) {
const res = this.visitExpression(expr, context);
if (res instanceof Reference2) {
res.synthetic = true;
}
return res;
}
visitFunctionBody(node, fn2, context) {
if (fn2.body === null) {
return DynamicValue.fromUnknown(node);
} else if (fn2.body.length !== 1 || !import_typescript29.default.isReturnStatement(fn2.body[0])) {
return DynamicValue.fromComplexFunctionCall(node, fn2);
}
const ret = fn2.body[0];
const args = this.evaluateFunctionArguments(node, context);
const newScope = /* @__PURE__ */ new Map();
const calleeContext = __spreadProps(__spreadValues({}, context), { scope: newScope });
fn2.parameters.forEach((param, index) => {
let arg = args[index];
if (param.node.dotDotDotToken !== void 0) {
arg = args.slice(index);
}
if (arg === void 0 && param.initializer !== null) {
arg = this.visitExpression(param.initializer, calleeContext);
}
newScope.set(param.node, arg);
});
return ret.expression !== void 0 ? this.visitExpression(ret.expression, calleeContext) : void 0;
}
visitConditionalExpression(node, context) {
const condition = this.visitExpression(node.condition, context);
if (condition instanceof DynamicValue) {
return DynamicValue.fromDynamicInput(node, condition);
}
if (condition) {
return this.visitExpression(node.whenTrue, context);
} else {
return this.visitExpression(node.whenFalse, context);
}
}
visitPrefixUnaryExpression(node, context) {
const operatorKind = node.operator;
if (!UNARY_OPERATORS.has(operatorKind)) {
return DynamicValue.fromUnsupportedSyntax(node);
}
const op = UNARY_OPERATORS.get(operatorKind);
const value = this.visitExpression(node.operand, context);
if (value instanceof DynamicValue) {
return DynamicValue.fromDynamicInput(node, value);
} else {
return op(value);
}
}
visitBinaryExpression(node, context) {
const tokenKind = node.operatorToken.kind;
if (!BINARY_OPERATORS2.has(tokenKind)) {
return DynamicValue.fromUnsupportedSyntax(node);
}
const opRecord = BINARY_OPERATORS2.get(tokenKind);
let lhs, rhs;
if (opRecord.literal) {
lhs = literal2(this.visitExpression(node.left, context), (value) => DynamicValue.fromInvalidExpressionType(node.left, value));
rhs = literal2(this.visitExpression(node.right, context), (value) => DynamicValue.fromInvalidExpressionType(node.right, value));
} else {
lhs = this.visitExpression(node.left, context);
rhs = this.visitExpression(node.right, context);
}
if (lhs instanceof DynamicValue) {
return DynamicValue.fromDynamicInput(node, lhs);
} else if (rhs instanceof DynamicValue) {
return DynamicValue.fromDynamicInput(node, rhs);
} else {
return opRecord.op(lhs, rhs);
}
}
visitParenthesizedExpression(node, context) {
return this.visitExpression(node.expression, context);
}
evaluateFunctionArguments(node, context) {
const args = [];
for (const arg of node.arguments) {
if (import_typescript29.default.isSpreadElement(arg)) {
args.push(...this.visitSpreadElement(arg, context));
} else {
args.push(this.visitExpression(arg, context));
}
}
return args;
}
visitSpreadElement(node, context) {
const spread = this.visitExpression(node.expression, context);
if (spread instanceof DynamicValue) {
return [DynamicValue.fromDynamicInput(node, spread)];
} else if (!Array.isArray(spread)) {
return [DynamicValue.fromInvalidExpressionType(node, spread)];
} else {
return spread;
}
}
visitBindingElement(node, context) {
const path4 = [];
let closestDeclaration = node;
while (import_typescript29.default.isBindingElement(closestDeclaration) || import_typescript29.default.isArrayBindingPattern(closestDeclaration) || import_typescript29.default.isObjectBindingPattern(closestDeclaration)) {
if (import_typescript29.default.isBindingElement(closestDeclaration)) {
path4.unshift(closestDeclaration);
}
closestDeclaration = closestDeclaration.parent;
}
if (!import_typescript29.default.isVariableDeclaration(closestDeclaration) || closestDeclaration.initializer === void 0) {
return DynamicValue.fromUnknown(node);
}
let value = this.visit(closestDeclaration.initializer, context);
for (const element2 of path4) {
let key;
if (import_typescript29.default.isArrayBindingPattern(element2.parent)) {
key = element2.parent.elements.indexOf(element2);
} else {
const name = element2.propertyName || element2.name;
if (import_typescript29.default.isIdentifier(name)) {
key = name.text;
} else {
return DynamicValue.fromUnknown(element2);
}
}
value = this.accessHelper(element2, value, key, context);
if (value instanceof DynamicValue) {
return value;
}
}
return value;
}
stringNameFromPropertyName(node, context) {
if (import_typescript29.default.isIdentifier(node) || import_typescript29.default.isStringLiteral(node) || import_typescript29.default.isNumericLiteral(node)) {
return node.text;
} else if (import_typescript29.default.isComputedPropertyName(node)) {
const literal3 = this.visitExpression(node.expression, context);
return typeof literal3 === "string" ? literal3 : void 0;
} else {
return void 0;
}
}
getReference(node, context) {
return new Reference2(node, owningModule(context));
}
visitType(node, context) {
if (import_typescript29.default.isLiteralTypeNode(node)) {
return this.visitExpression(node.literal, context);
} else if (import_typescript29.default.isTupleTypeNode(node)) {
return this.visitTupleType(node, context);
} else if (import_typescript29.default.isNamedTupleMember(node)) {
return this.visitType(node.type, context);
} else if (import_typescript29.default.isTypeOperatorNode(node) && node.operator === import_typescript29.default.SyntaxKind.ReadonlyKeyword) {
return this.visitType(node.type, context);
} else if (import_typescript29.default.isTypeQueryNode(node)) {
return this.visitTypeQuery(node, context);
}
return DynamicValue.fromDynamicType(node);
}
visitTupleType(node, context) {
const res = [];
for (const elem of node.elements) {
res.push(this.visitType(elem, context));
}
return res;
}
visitTypeQuery(node, context) {
if (!import_typescript29.default.isIdentifier(node.exprName)) {
return DynamicValue.fromUnknown(node);
}
const decl = this.host.getDeclarationOfIdentifier(node.exprName);
if (decl === null) {
return DynamicValue.fromUnknownIdentifier(node.exprName);
}
const declContext = __spreadValues(__spreadValues({}, context), joinModuleContext(context, node, decl));
return this.visitDeclaration(decl.node, declContext);
}
};
function isFunctionOrMethodReference(ref) {
return import_typescript29.default.isFunctionDeclaration(ref.node) || import_typescript29.default.isMethodDeclaration(ref.node) || import_typescript29.default.isFunctionExpression(ref.node);
}
function literal2(value, reject) {
if (value instanceof EnumValue) {
value = value.resolved;
}
if (value instanceof DynamicValue || value === null || value === void 0 || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
return value;
}
return reject(value);
}
function isVariableDeclarationDeclared(node) {
if (node.parent === void 0 || !import_typescript29.default.isVariableDeclarationList(node.parent)) {
return false;
}
const declList = node.parent;
if (declList.parent === void 0 || !import_typescript29.default.isVariableStatement(declList.parent)) {
return false;
}
const varStmt = declList.parent;
const modifiers = import_typescript29.default.getModifiers(varStmt);
return modifiers !== void 0 && modifiers.some((mod) => mod.kind === import_typescript29.default.SyntaxKind.DeclareKeyword);
}
var EMPTY = {};
function joinModuleContext(existing, node, decl) {
if (typeof decl.viaModule === "string" && decl.viaModule !== existing.absoluteModuleName) {
return {
absoluteModuleName: decl.viaModule,
resolutionContext: node.getSourceFile().fileName
};
} else {
return EMPTY;
}
}
function owningModule(context, override = null) {
let specifier = context.absoluteModuleName;
if (override !== null) {
specifier = override.specifier;
}
if (specifier !== null) {
return {
specifier,
resolutionContext: context.resolutionContext
};
} else {
return null;
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/partial_evaluator/src/interface.mjs
var PartialEvaluator = class {
constructor(host, checker, dependencyTracker) {
this.host = host;
this.checker = checker;
this.dependencyTracker = dependencyTracker;
}
evaluate(expr, foreignFunctionResolver) {
const interpreter = new StaticInterpreter(this.host, this.checker, this.dependencyTracker);
const sourceFile = expr.getSourceFile();
return interpreter.visit(expr, {
originatingFile: sourceFile,
absoluteModuleName: null,
resolutionContext: sourceFile.fileName,
scope: /* @__PURE__ */ new Map(),
foreignFunctionResolver
});
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/transform/src/api.mjs
var CompilationMode;
(function(CompilationMode2) {
CompilationMode2[CompilationMode2["FULL"] = 0] = "FULL";
CompilationMode2[CompilationMode2["PARTIAL"] = 1] = "PARTIAL";
CompilationMode2[CompilationMode2["LOCAL"] = 2] = "LOCAL";
})(CompilationMode || (CompilationMode = {}));
var HandlerPrecedence;
(function(HandlerPrecedence2) {
HandlerPrecedence2[HandlerPrecedence2["PRIMARY"] = 0] = "PRIMARY";
HandlerPrecedence2[HandlerPrecedence2["SHARED"] = 1] = "SHARED";
HandlerPrecedence2[HandlerPrecedence2["WEAK"] = 2] = "WEAK";
})(HandlerPrecedence || (HandlerPrecedence = {}));
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/transform/src/alias.mjs
var import_typescript31 = __toESM(require("typescript"), 1);
function aliasTransformFactory(exportStatements) {
return () => {
return (file) => {
if (import_typescript31.default.isBundle(file) || !exportStatements.has(file.fileName)) {
return file;
}
const statements = [...file.statements];
exportStatements.get(file.fileName).forEach(([moduleName, symbolName], aliasName) => {
const stmt = import_typescript31.default.factory.createExportDeclaration(
void 0,
false,
import_typescript31.default.factory.createNamedExports([
import_typescript31.default.factory.createExportSpecifier(false, symbolName, aliasName)
]),
import_typescript31.default.factory.createStringLiteral(moduleName)
);
statements.push(stmt);
});
return import_typescript31.default.factory.updateSourceFile(file, statements);
};
};
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/transform/src/compilation.mjs
var import_typescript32 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/perf/src/api.mjs
var PerfPhase;
(function(PerfPhase2) {
PerfPhase2[PerfPhase2["Unaccounted"] = 0] = "Unaccounted";
PerfPhase2[PerfPhase2["Setup"] = 1] = "Setup";
PerfPhase2[PerfPhase2["TypeScriptProgramCreate"] = 2] = "TypeScriptProgramCreate";
PerfPhase2[PerfPhase2["Reconciliation"] = 3] = "Reconciliation";
PerfPhase2[PerfPhase2["ResourceUpdate"] = 4] = "ResourceUpdate";
PerfPhase2[PerfPhase2["TypeScriptDiagnostics"] = 5] = "TypeScriptDiagnostics";
PerfPhase2[PerfPhase2["Analysis"] = 6] = "Analysis";
PerfPhase2[PerfPhase2["Resolve"] = 7] = "Resolve";
PerfPhase2[PerfPhase2["CycleDetection"] = 8] = "CycleDetection";
PerfPhase2[PerfPhase2["TcbGeneration"] = 9] = "TcbGeneration";
PerfPhase2[PerfPhase2["TcbUpdateProgram"] = 10] = "TcbUpdateProgram";
PerfPhase2[PerfPhase2["TypeScriptEmit"] = 11] = "TypeScriptEmit";
PerfPhase2[PerfPhase2["Compile"] = 12] = "Compile";
PerfPhase2[PerfPhase2["TtcAutocompletion"] = 13] = "TtcAutocompletion";
PerfPhase2[PerfPhase2["TtcDiagnostics"] = 14] = "TtcDiagnostics";
PerfPhase2[PerfPhase2["TtcSymbol"] = 15] = "TtcSymbol";
PerfPhase2[PerfPhase2["LsReferencesAndRenames"] = 16] = "LsReferencesAndRenames";
PerfPhase2[PerfPhase2["LsQuickInfo"] = 17] = "LsQuickInfo";
PerfPhase2[PerfPhase2["LsDefinition"] = 18] = "LsDefinition";
PerfPhase2[PerfPhase2["LsCompletions"] = 19] = "LsCompletions";
PerfPhase2[PerfPhase2["LsTcb"] = 20] = "LsTcb";
PerfPhase2[PerfPhase2["LsDiagnostics"] = 21] = "LsDiagnostics";
PerfPhase2[PerfPhase2["LsComponentLocations"] = 22] = "LsComponentLocations";
PerfPhase2[PerfPhase2["LsSignatureHelp"] = 23] = "LsSignatureHelp";
PerfPhase2[PerfPhase2["OutliningSpans"] = 24] = "OutliningSpans";
PerfPhase2[PerfPhase2["LAST"] = 25] = "LAST";
PerfPhase2[PerfPhase2["LsCodeFixes"] = 26] = "LsCodeFixes";
PerfPhase2[PerfPhase2["LsCodeFixesAll"] = 27] = "LsCodeFixesAll";
PerfPhase2[PerfPhase2["LSComputeApplicableRefactorings"] = 28] = "LSComputeApplicableRefactorings";
PerfPhase2[PerfPhase2["LSApplyRefactoring"] = 29] = "LSApplyRefactoring";
})(PerfPhase || (PerfPhase = {}));
var PerfEvent;
(function(PerfEvent2) {
PerfEvent2[PerfEvent2["InputDtsFile"] = 0] = "InputDtsFile";
PerfEvent2[PerfEvent2["InputTsFile"] = 1] = "InputTsFile";
PerfEvent2[PerfEvent2["AnalyzeComponent"] = 2] = "AnalyzeComponent";
PerfEvent2[PerfEvent2["AnalyzeDirective"] = 3] = "AnalyzeDirective";
PerfEvent2[PerfEvent2["AnalyzeInjectable"] = 4] = "AnalyzeInjectable";
PerfEvent2[PerfEvent2["AnalyzeNgModule"] = 5] = "AnalyzeNgModule";
PerfEvent2[PerfEvent2["AnalyzePipe"] = 6] = "AnalyzePipe";
PerfEvent2[PerfEvent2["TraitAnalyze"] = 7] = "TraitAnalyze";
PerfEvent2[PerfEvent2["TraitReuseAnalysis"] = 8] = "TraitReuseAnalysis";
PerfEvent2[PerfEvent2["SourceFilePhysicalChange"] = 9] = "SourceFilePhysicalChange";
PerfEvent2[PerfEvent2["SourceFileLogicalChange"] = 10] = "SourceFileLogicalChange";
PerfEvent2[PerfEvent2["SourceFileReuseAnalysis"] = 11] = "SourceFileReuseAnalysis";
PerfEvent2[PerfEvent2["GenerateTcb"] = 12] = "GenerateTcb";
PerfEvent2[PerfEvent2["SkipGenerateTcbNoInline"] = 13] = "SkipGenerateTcbNoInline";
PerfEvent2[PerfEvent2["ReuseTypeCheckFile"] = 14] = "ReuseTypeCheckFile";
PerfEvent2[PerfEvent2["UpdateTypeCheckProgram"] = 15] = "UpdateTypeCheckProgram";
PerfEvent2[PerfEvent2["EmitSkipSourceFile"] = 16] = "EmitSkipSourceFile";
PerfEvent2[PerfEvent2["EmitSourceFile"] = 17] = "EmitSourceFile";
PerfEvent2[PerfEvent2["LAST"] = 18] = "LAST";
})(PerfEvent || (PerfEvent = {}));
var PerfCheckpoint;
(function(PerfCheckpoint2) {
PerfCheckpoint2[PerfCheckpoint2["Initial"] = 0] = "Initial";
PerfCheckpoint2[PerfCheckpoint2["TypeScriptProgramCreate"] = 1] = "TypeScriptProgramCreate";
PerfCheckpoint2[PerfCheckpoint2["PreAnalysis"] = 2] = "PreAnalysis";
PerfCheckpoint2[PerfCheckpoint2["Analysis"] = 3] = "Analysis";
PerfCheckpoint2[PerfCheckpoint2["Resolve"] = 4] = "Resolve";
PerfCheckpoint2[PerfCheckpoint2["TtcGeneration"] = 5] = "TtcGeneration";
PerfCheckpoint2[PerfCheckpoint2["TtcUpdateProgram"] = 6] = "TtcUpdateProgram";
PerfCheckpoint2[PerfCheckpoint2["PreEmit"] = 7] = "PreEmit";
PerfCheckpoint2[PerfCheckpoint2["Emit"] = 8] = "Emit";
PerfCheckpoint2[PerfCheckpoint2["LAST"] = 9] = "LAST";
})(PerfCheckpoint || (PerfCheckpoint = {}));
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/perf/src/noop.mjs
var NoopPerfRecorder = class {
eventCount() {
}
memory() {
}
phase() {
return PerfPhase.Unaccounted;
}
inPhase(phase, fn2) {
return fn2();
}
reset() {
}
};
var NOOP_PERF_RECORDER = new NoopPerfRecorder();
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/perf/src/clock.mjs
function mark() {
return process.hrtime();
}
function timeSinceInMicros(mark2) {
const delta = process.hrtime(mark2);
return delta[0] * 1e6 + Math.floor(delta[1] / 1e3);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/perf/src/recorder.mjs
var ActivePerfRecorder = class {
static zeroedToNow() {
return new ActivePerfRecorder(mark());
}
constructor(zeroTime) {
this.zeroTime = zeroTime;
this.currentPhase = PerfPhase.Unaccounted;
this.currentPhaseEntered = this.zeroTime;
this.counters = Array(PerfEvent.LAST).fill(0);
this.phaseTime = Array(PerfPhase.LAST).fill(0);
this.bytes = Array(PerfCheckpoint.LAST).fill(0);
this.memory(PerfCheckpoint.Initial);
}
reset() {
this.counters = Array(PerfEvent.LAST).fill(0);
this.phaseTime = Array(PerfPhase.LAST).fill(0);
this.bytes = Array(PerfCheckpoint.LAST).fill(0);
this.zeroTime = mark();
this.currentPhase = PerfPhase.Unaccounted;
this.currentPhaseEntered = this.zeroTime;
}
memory(after) {
this.bytes[after] = process.memoryUsage().heapUsed;
}
phase(phase) {
const previous = this.currentPhase;
this.phaseTime[this.currentPhase] += timeSinceInMicros(this.currentPhaseEntered);
this.currentPhase = phase;
this.currentPhaseEntered = mark();
return previous;
}
inPhase(phase, fn2) {
const previousPhase = this.phase(phase);
try {
return fn2();
} finally {
this.phase(previousPhase);
}
}
eventCount(counter, incrementBy = 1) {
this.counters[counter] += incrementBy;
}
finalize() {
this.phase(PerfPhase.Unaccounted);
const results = {
events: {},
phases: {},
memory: {}
};
for (let i = 0; i < this.phaseTime.length; i++) {
if (this.phaseTime[i] > 0) {
results.phases[PerfPhase[i]] = this.phaseTime[i];
}
}
for (let i = 0; i < this.phaseTime.length; i++) {
if (this.counters[i] > 0) {
results.events[PerfEvent[i]] = this.counters[i];
}
}
for (let i = 0; i < this.bytes.length; i++) {
if (this.bytes[i] > 0) {
results.memory[PerfCheckpoint[i]] = this.bytes[i];
}
}
return results;
}
};
var DelegatingPerfRecorder = class {
constructor(target) {
this.target = target;
}
eventCount(counter, incrementBy) {
this.target.eventCount(counter, incrementBy);
}
phase(phase) {
return this.target.phase(phase);
}
inPhase(phase, fn2) {
const previousPhase = this.target.phase(phase);
try {
return fn2();
} finally {
this.target.phase(previousPhase);
}
}
memory(after) {
this.target.memory(after);
}
reset() {
this.target.reset();
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/transform/src/trait.mjs
var TraitState;
(function(TraitState2) {
TraitState2[TraitState2["Pending"] = 0] = "Pending";
TraitState2[TraitState2["Analyzed"] = 1] = "Analyzed";
TraitState2[TraitState2["Resolved"] = 2] = "Resolved";
TraitState2[TraitState2["Skipped"] = 3] = "Skipped";
})(TraitState || (TraitState = {}));
var Trait = {
pending: (handler, detected) => TraitImpl.pending(handler, detected)
};
var TraitImpl = class {
constructor(handler, detected) {
this.state = TraitState.Pending;
this.analysis = null;
this.symbol = null;
this.resolution = null;
this.analysisDiagnostics = null;
this.resolveDiagnostics = null;
this.typeCheckDiagnostics = null;
this.handler = handler;
this.detected = detected;
}
toAnalyzed(analysis, diagnostics, symbol) {
this.assertTransitionLegal(TraitState.Pending, TraitState.Analyzed);
this.analysis = analysis;
this.analysisDiagnostics = diagnostics;
this.symbol = symbol;
this.state = TraitState.Analyzed;
return this;
}
toResolved(resolution, diagnostics) {
this.assertTransitionLegal(TraitState.Analyzed, TraitState.Resolved);
if (this.analysis === null) {
throw new Error(`Cannot transition an Analyzed trait with a null analysis to Resolved`);
}
this.resolution = resolution;
this.state = TraitState.Resolved;
this.resolveDiagnostics = diagnostics;
this.typeCheckDiagnostics = null;
return this;
}
toSkipped() {
this.assertTransitionLegal(TraitState.Pending, TraitState.Skipped);
this.state = TraitState.Skipped;
return this;
}
assertTransitionLegal(allowedState, transitionTo) {
if (!(this.state === allowedState)) {
throw new Error(`Assertion failure: cannot transition from ${TraitState[this.state]} to ${TraitState[transitionTo]}.`);
}
}
static pending(handler, detected) {
return new TraitImpl(handler, detected);
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/transform/src/compilation.mjs
var TraitCompiler = class {
constructor(handlers, reflector, perf, incrementalBuild, compileNonExportedClasses, compilationMode, dtsTransforms, semanticDepGraphUpdater, sourceFileTypeIdentifier) {
this.handlers = handlers;
this.reflector = reflector;
this.perf = perf;
this.incrementalBuild = incrementalBuild;
this.compileNonExportedClasses = compileNonExportedClasses;
this.compilationMode = compilationMode;
this.dtsTransforms = dtsTransforms;
this.semanticDepGraphUpdater = semanticDepGraphUpdater;
this.sourceFileTypeIdentifier = sourceFileTypeIdentifier;
this.classes = /* @__PURE__ */ new Map();
this.fileToClasses = /* @__PURE__ */ new Map();
this.filesWithoutTraits = /* @__PURE__ */ new Set();
this.reexportMap = /* @__PURE__ */ new Map();
this.handlersByName = /* @__PURE__ */ new Map();
for (const handler of handlers) {
this.handlersByName.set(handler.name, handler);
}
}
analyzeSync(sf) {
this.analyze(sf, false);
}
analyzeAsync(sf) {
return this.analyze(sf, true);
}
analyze(sf, preanalyze) {
if (sf.isDeclarationFile || this.sourceFileTypeIdentifier.isShim(sf) || this.sourceFileTypeIdentifier.isResource(sf)) {
return void 0;
}
const promises = [];
const priorWork = this.compilationMode !== CompilationMode.LOCAL ? this.incrementalBuild.priorAnalysisFor(sf) : null;
if (priorWork !== null) {
this.perf.eventCount(PerfEvent.SourceFileReuseAnalysis);
if (priorWork.length > 0) {
for (const priorRecord of priorWork) {
this.adopt(priorRecord);
}
this.perf.eventCount(PerfEvent.TraitReuseAnalysis, priorWork.length);
} else {
this.filesWithoutTraits.add(sf);
}
return;
}
const visit2 = (node) => {
if (this.reflector.isClass(node)) {
this.analyzeClass(node, preanalyze ? promises : null);
}
import_typescript32.default.forEachChild(node, visit2);
};
visit2(sf);
if (!this.fileToClasses.has(sf)) {
this.filesWithoutTraits.add(sf);
}
if (preanalyze && promises.length > 0) {
return Promise.all(promises).then(() => void 0);
} else {
return void 0;
}
}
recordFor(clazz) {
if (this.classes.has(clazz)) {
return this.classes.get(clazz);
} else {
return null;
}
}
getAnalyzedRecords() {
const result = /* @__PURE__ */ new Map();
for (const [sf, classes] of this.fileToClasses) {
const records = [];
for (const clazz of classes) {
records.push(this.classes.get(clazz));
}
result.set(sf, records);
}
for (const sf of this.filesWithoutTraits) {
result.set(sf, []);
}
return result;
}
adopt(priorRecord) {
const record = {
hasPrimaryHandler: priorRecord.hasPrimaryHandler,
hasWeakHandlers: priorRecord.hasWeakHandlers,
metaDiagnostics: priorRecord.metaDiagnostics,
node: priorRecord.node,
traits: []
};
for (const priorTrait of priorRecord.traits) {
const handler = this.handlersByName.get(priorTrait.handler.name);
let trait = Trait.pending(handler, priorTrait.detected);
if (priorTrait.state === TraitState.Analyzed || priorTrait.state === TraitState.Resolved) {
const symbol = this.makeSymbolForTrait(handler, record.node, priorTrait.analysis);
trait = trait.toAnalyzed(priorTrait.analysis, priorTrait.analysisDiagnostics, symbol);
if (trait.analysis !== null && trait.handler.register !== void 0) {
trait.handler.register(record.node, trait.analysis);
}
} else if (priorTrait.state === TraitState.Skipped) {
trait = trait.toSkipped();
}
record.traits.push(trait);
}
this.classes.set(record.node, record);
const sf = record.node.getSourceFile();
if (!this.fileToClasses.has(sf)) {
this.fileToClasses.set(sf, /* @__PURE__ */ new Set());
}
this.fileToClasses.get(sf).add(record.node);
}
scanClassForTraits(clazz) {
if (!this.compileNonExportedClasses && !this.reflector.isStaticallyExported(clazz)) {
return null;
}
const decorators = this.reflector.getDecoratorsOfDeclaration(clazz);
return this.detectTraits(clazz, decorators);
}
detectTraits(clazz, decorators) {
let record = this.recordFor(clazz);
let foundTraits = [];
const nonNgDecoratorsInLocalMode = this.compilationMode === CompilationMode.LOCAL ? new Set(decorators) : null;
for (const handler of this.handlers) {
const result = handler.detect(clazz, decorators);
if (result === void 0) {
continue;
}
if (nonNgDecoratorsInLocalMode !== null && result.decorator !== null) {
nonNgDecoratorsInLocalMode.delete(result.decorator);
}
const isPrimaryHandler = handler.precedence === HandlerPrecedence.PRIMARY;
const isWeakHandler = handler.precedence === HandlerPrecedence.WEAK;
const trait = Trait.pending(handler, result);
foundTraits.push(trait);
if (record === null) {
record = {
node: clazz,
traits: [trait],
metaDiagnostics: null,
hasPrimaryHandler: isPrimaryHandler,
hasWeakHandlers: isWeakHandler
};
this.classes.set(clazz, record);
const sf = clazz.getSourceFile();
if (!this.fileToClasses.has(sf)) {
this.fileToClasses.set(sf, /* @__PURE__ */ new Set());
}
this.fileToClasses.get(sf).add(clazz);
} else {
if (!isWeakHandler && record.hasWeakHandlers) {
record.traits = record.traits.filter((field) => field.handler.precedence !== HandlerPrecedence.WEAK);
record.hasWeakHandlers = false;
} else if (isWeakHandler && !record.hasWeakHandlers) {
continue;
}
if (isPrimaryHandler && record.hasPrimaryHandler) {
record.metaDiagnostics = [
{
category: import_typescript32.default.DiagnosticCategory.Error,
code: Number("-99" + ErrorCode.DECORATOR_COLLISION),
file: getSourceFile(clazz),
start: clazz.getStart(void 0, false),
length: clazz.getWidth(),
messageText: "Two incompatible decorators on class"
}
];
record.traits = foundTraits = [];
break;
}
record.traits.push(trait);
record.hasPrimaryHandler = record.hasPrimaryHandler || isPrimaryHandler;
}
}
if (nonNgDecoratorsInLocalMode !== null && nonNgDecoratorsInLocalMode.size > 0 && record !== null && record.metaDiagnostics === null) {
record.metaDiagnostics = [...nonNgDecoratorsInLocalMode].map((decorator) => ({
category: import_typescript32.default.DiagnosticCategory.Error,
code: Number("-99" + ErrorCode.DECORATOR_UNEXPECTED),
file: getSourceFile(clazz),
start: decorator.node.getStart(),
length: decorator.node.getWidth(),
messageText: "In local compilation mode, Angular does not support custom decorators. Ensure all class decorators are from Angular."
}));
record.traits = foundTraits = [];
}
return foundTraits.length > 0 ? foundTraits : null;
}
makeSymbolForTrait(handler, decl, analysis) {
if (analysis === null) {
return null;
}
const symbol = handler.symbol(decl, analysis);
if (symbol !== null && this.semanticDepGraphUpdater !== null) {
const isPrimary = handler.precedence === HandlerPrecedence.PRIMARY;
if (!isPrimary) {
throw new Error(`AssertionError: ${handler.name} returned a symbol but is not a primary handler.`);
}
this.semanticDepGraphUpdater.registerSymbol(symbol);
}
return symbol;
}
analyzeClass(clazz, preanalyzeQueue) {
const traits = this.scanClassForTraits(clazz);
if (traits === null) {
return;
}
for (const trait of traits) {
const analyze = () => this.analyzeTrait(clazz, trait);
let preanalysis = null;
if (preanalyzeQueue !== null && trait.handler.preanalyze !== void 0) {
try {
preanalysis = trait.handler.preanalyze(clazz, trait.detected.metadata) || null;
} catch (err) {
if (err instanceof FatalDiagnosticError) {
trait.toAnalyzed(null, [err.toDiagnostic()], null);
return;
} else {
throw err;
}
}
}
if (preanalysis !== null) {
preanalyzeQueue.push(preanalysis.then(analyze));
} else {
analyze();
}
}
}
analyzeTrait(clazz, trait) {
var _a2, _b2, _c2;
if (trait.state !== TraitState.Pending) {
throw new Error(`Attempt to analyze trait of ${clazz.name.text} in state ${TraitState[trait.state]} (expected DETECTED)`);
}
this.perf.eventCount(PerfEvent.TraitAnalyze);
let result;
try {
result = trait.handler.analyze(clazz, trait.detected.metadata);
} catch (err) {
if (err instanceof FatalDiagnosticError) {
trait.toAnalyzed(null, [err.toDiagnostic()], null);
return;
} else {
throw err;
}
}
const symbol = this.makeSymbolForTrait(trait.handler, clazz, (_a2 = result.analysis) != null ? _a2 : null);
if (result.analysis !== void 0 && trait.handler.register !== void 0) {
trait.handler.register(clazz, result.analysis);
}
trait = trait.toAnalyzed((_b2 = result.analysis) != null ? _b2 : null, (_c2 = result.diagnostics) != null ? _c2 : null, symbol);
}
resolve() {
var _a2, _b2;
const classes = this.classes.keys();
for (const clazz of classes) {
const record = this.classes.get(clazz);
for (let trait of record.traits) {
const handler = trait.handler;
switch (trait.state) {
case TraitState.Skipped:
continue;
case TraitState.Pending:
throw new Error(`Resolving a trait that hasn't been analyzed: ${clazz.name.text} / ${trait.handler.name}`);
case TraitState.Resolved:
throw new Error(`Resolving an already resolved trait`);
}
if (trait.analysis === null) {
continue;
}
if (handler.resolve === void 0) {
trait = trait.toResolved(null, null);
continue;
}
let result;
try {
result = handler.resolve(clazz, trait.analysis, trait.symbol);
} catch (err) {
if (err instanceof FatalDiagnosticError) {
trait = trait.toResolved(null, [err.toDiagnostic()]);
continue;
} else {
throw err;
}
}
trait = trait.toResolved((_a2 = result.data) != null ? _a2 : null, (_b2 = result.diagnostics) != null ? _b2 : null);
if (result.reexports !== void 0) {
const fileName = clazz.getSourceFile().fileName;
if (!this.reexportMap.has(fileName)) {
this.reexportMap.set(fileName, /* @__PURE__ */ new Map());
}
const fileReexports = this.reexportMap.get(fileName);
for (const reexport of result.reexports) {
fileReexports.set(reexport.asAlias, [reexport.fromModule, reexport.symbolName]);
}
}
}
}
}
typeCheck(sf, ctx) {
if (!this.fileToClasses.has(sf) || this.compilationMode === CompilationMode.LOCAL) {
return;
}
for (const clazz of this.fileToClasses.get(sf)) {
const record = this.classes.get(clazz);
for (const trait of record.traits) {
if (trait.state !== TraitState.Resolved) {
continue;
} else if (trait.handler.typeCheck === void 0) {
continue;
}
if (trait.resolution !== null) {
trait.handler.typeCheck(ctx, clazz, trait.analysis, trait.resolution);
}
}
}
}
runAdditionalChecks(sf, check) {
if (this.compilationMode === CompilationMode.LOCAL) {
return [];
}
const classes = this.fileToClasses.get(sf);
if (classes === void 0) {
return [];
}
const diagnostics = [];
for (const clazz of classes) {
if (!isNamedClassDeclaration(clazz)) {
continue;
}
const record = this.classes.get(clazz);
for (const trait of record.traits) {
const result = check(clazz, trait.handler);
if (result !== null) {
diagnostics.push(...result);
}
}
}
return diagnostics;
}
index(ctx) {
for (const clazz of this.classes.keys()) {
const record = this.classes.get(clazz);
for (const trait of record.traits) {
if (trait.state !== TraitState.Resolved) {
continue;
} else if (trait.handler.index === void 0) {
continue;
}
if (trait.resolution !== null) {
trait.handler.index(ctx, clazz, trait.analysis, trait.resolution);
}
}
}
}
xi18n(bundle) {
for (const clazz of this.classes.keys()) {
const record = this.classes.get(clazz);
for (const trait of record.traits) {
if (trait.state !== TraitState.Analyzed && trait.state !== TraitState.Resolved) {
continue;
} else if (trait.handler.xi18n === void 0) {
continue;
}
if (trait.analysis !== null) {
trait.handler.xi18n(bundle, clazz, trait.analysis);
}
}
}
}
updateResources(clazz) {
if (this.compilationMode === CompilationMode.LOCAL || !this.reflector.isClass(clazz) || !this.classes.has(clazz)) {
return;
}
const record = this.classes.get(clazz);
for (const trait of record.traits) {
if (trait.state !== TraitState.Resolved || trait.handler.updateResources === void 0) {
continue;
}
trait.handler.updateResources(clazz, trait.analysis, trait.resolution);
}
}
compile(clazz, constantPool) {
const original = import_typescript32.default.getOriginalNode(clazz);
if (!this.reflector.isClass(clazz) || !this.reflector.isClass(original) || !this.classes.has(original)) {
return null;
}
const record = this.classes.get(original);
let res = [];
for (const trait of record.traits) {
let compileRes;
if (trait.state !== TraitState.Resolved || containsErrors(trait.analysisDiagnostics) || containsErrors(trait.resolveDiagnostics)) {
continue;
}
if (this.compilationMode === CompilationMode.LOCAL) {
compileRes = trait.handler.compileLocal(clazz, trait.analysis, trait.resolution, constantPool);
} else {
if (this.compilationMode === CompilationMode.PARTIAL && trait.handler.compilePartial !== void 0) {
compileRes = trait.handler.compilePartial(clazz, trait.analysis, trait.resolution);
} else {
compileRes = trait.handler.compileFull(clazz, trait.analysis, trait.resolution, constantPool);
}
}
const compileMatchRes = compileRes;
if (Array.isArray(compileMatchRes)) {
for (const result of compileMatchRes) {
if (!res.some((r) => r.name === result.name)) {
res.push(result);
}
}
} else if (!res.some((result) => result.name === compileMatchRes.name)) {
res.push(compileMatchRes);
}
}
this.dtsTransforms.getIvyDeclarationTransform(original.getSourceFile()).addFields(original, res);
return res.length > 0 ? res : null;
}
decoratorsFor(node) {
const original = import_typescript32.default.getOriginalNode(node);
if (!this.reflector.isClass(original) || !this.classes.has(original)) {
return [];
}
const record = this.classes.get(original);
const decorators = [];
for (const trait of record.traits) {
if (this.compilationMode !== CompilationMode.LOCAL && trait.state !== TraitState.Resolved) {
continue;
}
if (trait.detected.trigger !== null && import_typescript32.default.isDecorator(trait.detected.trigger)) {
decorators.push(trait.detected.trigger);
}
}
return decorators;
}
get diagnostics() {
var _a2;
const diagnostics = [];
for (const clazz of this.classes.keys()) {
const record = this.classes.get(clazz);
if (record.metaDiagnostics !== null) {
diagnostics.push(...record.metaDiagnostics);
}
for (const trait of record.traits) {
if ((trait.state === TraitState.Analyzed || trait.state === TraitState.Resolved) && trait.analysisDiagnostics !== null) {
diagnostics.push(...trait.analysisDiagnostics);
}
if (trait.state === TraitState.Resolved) {
diagnostics.push(...(_a2 = trait.resolveDiagnostics) != null ? _a2 : []);
}
}
}
return diagnostics;
}
get exportStatements() {
return this.reexportMap;
}
};
function containsErrors(diagnostics) {
return diagnostics !== null && diagnostics.some((diag) => diag.category === import_typescript32.default.DiagnosticCategory.Error);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/transform/src/declaration.mjs
var import_typescript43 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/translator/src/context.mjs
var Context = class {
constructor(isStatement) {
this.isStatement = isStatement;
}
get withExpressionMode() {
return this.isStatement ? new Context(false) : this;
}
get withStatementMode() {
return !this.isStatement ? new Context(true) : this;
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/translator/src/import_manager/import_manager.mjs
var import_typescript38 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/translator/src/import_manager/check_unique_identifier_name.mjs
var import_typescript34 = __toESM(require("typescript"), 1);
function createGenerateUniqueIdentifierHelper() {
const generatedIdentifiers = /* @__PURE__ */ new Set();
const isGeneratedIdentifier = (sf, identifierName2) => generatedIdentifiers.has(`${sf.fileName}@@${identifierName2}`);
const markIdentifierAsGenerated = (sf, identifierName2) => generatedIdentifiers.add(`${sf.fileName}@@${identifierName2}`);
return (sourceFile, symbolName) => {
const sf = sourceFile;
if (sf.identifiers === void 0) {
throw new Error("Source file unexpectedly lacks map of parsed `identifiers`.");
}
const isUniqueIdentifier = (name2) => !sf.identifiers.has(name2) && !isGeneratedIdentifier(sf, name2);
if (isUniqueIdentifier(symbolName)) {
markIdentifierAsGenerated(sf, symbolName);
return null;
}
let name = null;
let counter = 1;
do {
name = `${symbolName}_${counter++}`;
} while (!isUniqueIdentifier(name));
markIdentifierAsGenerated(sf, name);
return import_typescript34.default.factory.createUniqueName(name, import_typescript34.default.GeneratedIdentifierFlags.Optimistic);
};
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/translator/src/import_manager/import_typescript_transform.mjs
var import_typescript35 = __toESM(require("typescript"), 1);
function createTsTransformForImportManager(manager, extraStatementsForFiles) {
return (ctx) => {
const { affectedFiles, newImports, updatedImports, reusedOriginalAliasDeclarations, deletedImports } = manager.finalize();
if (reusedOriginalAliasDeclarations.size > 0) {
const referencedAliasDeclarations = loadIsReferencedAliasDeclarationPatch(ctx);
reusedOriginalAliasDeclarations.forEach((aliasDecl) => referencedAliasDeclarations.add(aliasDecl));
}
if (extraStatementsForFiles !== void 0) {
for (const [fileName, statements] of extraStatementsForFiles.entries()) {
if (statements.length > 0) {
affectedFiles.add(fileName);
}
}
}
const visitStatement = (node) => {
if (!import_typescript35.default.isImportDeclaration(node)) {
return node;
}
if (deletedImports.has(node)) {
return void 0;
}
if (node.importClause === void 0 || !import_typescript35.default.isImportClause(node.importClause)) {
return node;
}
const clause = node.importClause;
if (clause.namedBindings === void 0 || !import_typescript35.default.isNamedImports(clause.namedBindings) || !updatedImports.has(clause.namedBindings)) {
return node;
}
const newClause = ctx.factory.updateImportClause(clause, clause.isTypeOnly, clause.name, updatedImports.get(clause.namedBindings));
const newImport = ctx.factory.updateImportDeclaration(node, node.modifiers, newClause, node.moduleSpecifier, node.attributes);
import_typescript35.default.setOriginalNode(newImport, {
importClause: newClause,
kind: newImport.kind
});
return newImport;
};
return (sourceFile) => {
var _a2, _b2;
if (!affectedFiles.has(sourceFile.fileName)) {
return sourceFile;
}
sourceFile = import_typescript35.default.visitEachChild(sourceFile, visitStatement, ctx);
const extraStatements = (_a2 = extraStatementsForFiles == null ? void 0 : extraStatementsForFiles.get(sourceFile.fileName)) != null ? _a2 : [];
const existingImports = [];
const body = [];
for (const statement of sourceFile.statements) {
if (isImportStatement(statement)) {
existingImports.push(statement);
} else {
body.push(statement);
}
}
return ctx.factory.updateSourceFile(sourceFile, [
...existingImports,
...(_b2 = newImports.get(sourceFile.fileName)) != null ? _b2 : [],
...extraStatements,
...body
], sourceFile.isDeclarationFile, sourceFile.referencedFiles, sourceFile.typeReferenceDirectives, sourceFile.hasNoDefaultLib, sourceFile.libReferenceDirectives);
};
};
}
function isImportStatement(stmt) {
return import_typescript35.default.isImportDeclaration(stmt) || import_typescript35.default.isImportEqualsDeclaration(stmt) || import_typescript35.default.isNamespaceImport(stmt);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/translator/src/import_manager/reuse_generated_imports.mjs
var import_typescript36 = __toESM(require("typescript"), 1);
function attemptToReuseGeneratedImports(tracker, request) {
const requestHash = hashImportRequest(request);
const existingExactImport = tracker.directReuseCache.get(requestHash);
if (existingExactImport !== void 0) {
return existingExactImport;
}
const potentialNamespaceImport = tracker.namespaceImportReuseCache.get(request.exportModuleSpecifier);
if (potentialNamespaceImport === void 0) {
return null;
}
if (request.exportSymbolName === null) {
return potentialNamespaceImport;
}
return [potentialNamespaceImport, import_typescript36.default.factory.createIdentifier(request.exportSymbolName)];
}
function captureGeneratedImport(request, tracker, referenceNode) {
tracker.directReuseCache.set(hashImportRequest(request), referenceNode);
if (request.exportSymbolName === null && !Array.isArray(referenceNode)) {
tracker.namespaceImportReuseCache.set(request.exportModuleSpecifier, referenceNode);
}
}
function hashImportRequest(req) {
return `${req.requestedFile.fileName}:${req.exportModuleSpecifier}:${req.exportSymbolName}${req.unsafeAliasOverride ? ":" + req.unsafeAliasOverride : ""}`;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/translator/src/import_manager/reuse_source_file_imports.mjs
var import_typescript37 = __toESM(require("typescript"), 1);
function attemptToReuseExistingSourceFileImports(tracker, sourceFile, request) {
let candidateImportToBeUpdated = null;
for (let i = sourceFile.statements.length - 1; i >= 0; i--) {
const statement = sourceFile.statements[i];
if (!import_typescript37.default.isImportDeclaration(statement) || !import_typescript37.default.isStringLiteral(statement.moduleSpecifier)) {
continue;
}
if (!statement.importClause || statement.importClause.isTypeOnly) {
continue;
}
const moduleSpecifier = statement.moduleSpecifier.text;
if (moduleSpecifier !== request.exportModuleSpecifier) {
continue;
}
if (statement.importClause.namedBindings) {
const namedBindings = statement.importClause.namedBindings;
if (import_typescript37.default.isNamespaceImport(namedBindings)) {
tracker.reusedAliasDeclarations.add(namedBindings);
if (request.exportSymbolName === null) {
return namedBindings.name;
}
return [namedBindings.name, import_typescript37.default.factory.createIdentifier(request.exportSymbolName)];
}
if (import_typescript37.default.isNamedImports(namedBindings) && request.exportSymbolName !== null) {
const existingElement = namedBindings.elements.find((e) => {
var _a2;
let nameMatches;
if (request.unsafeAliasOverride) {
nameMatches = ((_a2 = e.propertyName) == null ? void 0 : _a2.text) === request.exportSymbolName && e.name.text === request.unsafeAliasOverride;
} else {
nameMatches = e.propertyName ? e.propertyName.text === request.exportSymbolName : e.name.text === request.exportSymbolName;
}
return !e.isTypeOnly && nameMatches;
});
if (existingElement !== void 0) {
tracker.reusedAliasDeclarations.add(existingElement);
return existingElement.name;
}
candidateImportToBeUpdated = statement;
}
}
}
if (candidateImportToBeUpdated === null || request.exportSymbolName === null) {
return null;
}
if (!tracker.updatedImports.has(candidateImportToBeUpdated)) {
tracker.updatedImports.set(candidateImportToBeUpdated, []);
}
const symbolsToBeImported = tracker.updatedImports.get(candidateImportToBeUpdated);
const propertyName = import_typescript37.default.factory.createIdentifier(request.exportSymbolName);
const fileUniqueAlias = request.unsafeAliasOverride ? import_typescript37.default.factory.createIdentifier(request.unsafeAliasOverride) : tracker.generateUniqueIdentifier(sourceFile, request.exportSymbolName);
symbolsToBeImported.push({
propertyName,
fileUniqueAlias
});
return fileUniqueAlias != null ? fileUniqueAlias : propertyName;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/translator/src/import_manager/import_manager.mjs
var presetImportManagerForceNamespaceImports = {
disableOriginalSourceFileReuse: true,
forceGenerateNamespacesForNewImports: true
};
var ImportManager = class {
constructor(config = {}) {
var _a2, _b2, _c2, _d2, _e2, _f2;
this.newImports = /* @__PURE__ */ new Map();
this.removedImports = /* @__PURE__ */ new Map();
this.nextUniqueIndex = 0;
this.reuseGeneratedImportsTracker = {
directReuseCache: /* @__PURE__ */ new Map(),
namespaceImportReuseCache: /* @__PURE__ */ new Map()
};
this.config = {
shouldUseSingleQuotes: (_a2 = config.shouldUseSingleQuotes) != null ? _a2 : () => false,
rewriter: (_b2 = config.rewriter) != null ? _b2 : null,
disableOriginalSourceFileReuse: (_c2 = config.disableOriginalSourceFileReuse) != null ? _c2 : false,
forceGenerateNamespacesForNewImports: (_d2 = config.forceGenerateNamespacesForNewImports) != null ? _d2 : false,
namespaceImportPrefix: (_e2 = config.namespaceImportPrefix) != null ? _e2 : "i",
generateUniqueIdentifier: (_f2 = config.generateUniqueIdentifier) != null ? _f2 : createGenerateUniqueIdentifierHelper()
};
this.reuseSourceFileImportsTracker = {
generateUniqueIdentifier: this.config.generateUniqueIdentifier,
reusedAliasDeclarations: /* @__PURE__ */ new Set(),
updatedImports: /* @__PURE__ */ new Map()
};
}
addSideEffectImport(requestedFile, moduleSpecifier) {
if (this.config.rewriter !== null) {
moduleSpecifier = this.config.rewriter.rewriteSpecifier(moduleSpecifier, requestedFile.fileName);
}
this._getNewImportsTrackerForFile(requestedFile).sideEffectImports.add(moduleSpecifier);
}
addImport(request) {
var _a2, _b2;
if (this.config.rewriter !== null) {
if (request.exportSymbolName !== null) {
request.exportSymbolName = this.config.rewriter.rewriteSymbol(request.exportSymbolName, request.exportModuleSpecifier);
}
request.exportModuleSpecifier = this.config.rewriter.rewriteSpecifier(request.exportModuleSpecifier, request.requestedFile.fileName);
}
if (request.exportSymbolName !== null && !request.asTypeReference) {
(_b2 = (_a2 = this.removedImports.get(request.requestedFile)) == null ? void 0 : _a2.get(request.exportModuleSpecifier)) == null ? void 0 : _b2.delete(request.exportSymbolName);
}
const previousGeneratedImportRef = attemptToReuseGeneratedImports(this.reuseGeneratedImportsTracker, request);
if (previousGeneratedImportRef !== null) {
return createImportReference(!!request.asTypeReference, previousGeneratedImportRef);
}
const resultImportRef = this._generateNewImport(request);
captureGeneratedImport(request, this.reuseGeneratedImportsTracker, resultImportRef);
return createImportReference(!!request.asTypeReference, resultImportRef);
}
removeImport(requestedFile, exportSymbolName, moduleSpecifier) {
let moduleMap = this.removedImports.get(requestedFile);
if (!moduleMap) {
moduleMap = /* @__PURE__ */ new Map();
this.removedImports.set(requestedFile, moduleMap);
}
let removedSymbols = moduleMap.get(moduleSpecifier);
if (!removedSymbols) {
removedSymbols = /* @__PURE__ */ new Set();
moduleMap.set(moduleSpecifier, removedSymbols);
}
removedSymbols.add(exportSymbolName);
}
_generateNewImport(request) {
var _a2;
const { requestedFile: sourceFile } = request;
const disableOriginalSourceFileReuse = this.config.disableOriginalSourceFileReuse;
const forceGenerateNamespacesForNewImports = this.config.forceGenerateNamespacesForNewImports;
if (!disableOriginalSourceFileReuse) {
const reuseResult = attemptToReuseExistingSourceFileImports(this.reuseSourceFileImportsTracker, sourceFile, request);
if (reuseResult !== null) {
return reuseResult;
}
}
const { namedImports, namespaceImports } = this._getNewImportsTrackerForFile(sourceFile);
if (request.exportSymbolName === null || forceGenerateNamespacesForNewImports) {
const namespaceImportName = `${this.config.namespaceImportPrefix}${this.nextUniqueIndex++}`;
const namespaceImport2 = import_typescript38.default.factory.createNamespaceImport((_a2 = this.config.generateUniqueIdentifier(sourceFile, namespaceImportName)) != null ? _a2 : import_typescript38.default.factory.createIdentifier(namespaceImportName));
namespaceImports.set(request.exportModuleSpecifier, namespaceImport2);
captureGeneratedImport(__spreadProps(__spreadValues({}, request), { exportSymbolName: null }), this.reuseGeneratedImportsTracker, namespaceImport2.name);
if (request.exportSymbolName !== null) {
return [namespaceImport2.name, import_typescript38.default.factory.createIdentifier(request.exportSymbolName)];
}
return namespaceImport2.name;
}
if (!namedImports.has(request.exportModuleSpecifier)) {
namedImports.set(request.exportModuleSpecifier, []);
}
const exportSymbolName = import_typescript38.default.factory.createIdentifier(request.exportSymbolName);
const fileUniqueName = request.unsafeAliasOverride ? null : this.config.generateUniqueIdentifier(sourceFile, request.exportSymbolName);
let needsAlias;
let specifierName;
if (request.unsafeAliasOverride) {
needsAlias = true;
specifierName = import_typescript38.default.factory.createIdentifier(request.unsafeAliasOverride);
} else if (fileUniqueName !== null) {
needsAlias = true;
specifierName = fileUniqueName;
} else {
needsAlias = false;
specifierName = exportSymbolName;
}
namedImports.get(request.exportModuleSpecifier).push(import_typescript38.default.factory.createImportSpecifier(false, needsAlias ? exportSymbolName : void 0, specifierName));
return specifierName;
}
finalize() {
const affectedFiles = /* @__PURE__ */ new Set();
const updatedImportsResult = /* @__PURE__ */ new Map();
const newImportsResult = /* @__PURE__ */ new Map();
const deletedImports = /* @__PURE__ */ new Set();
const importDeclarationsPerFile = /* @__PURE__ */ new Map();
const addNewImport = (fileName, importDecl) => {
affectedFiles.add(fileName);
if (newImportsResult.has(fileName)) {
newImportsResult.get(fileName).push(importDecl);
} else {
newImportsResult.set(fileName, [importDecl]);
}
};
this.reuseSourceFileImportsTracker.updatedImports.forEach((expressions, importDecl) => {
const sourceFile = importDecl.getSourceFile();
const namedBindings = importDecl.importClause.namedBindings;
const moduleName = importDecl.moduleSpecifier.text;
const newElements = namedBindings.elements.concat(expressions.map(({ propertyName, fileUniqueAlias }) => import_typescript38.default.factory.createImportSpecifier(false, fileUniqueAlias !== null ? propertyName : void 0, fileUniqueAlias != null ? fileUniqueAlias : propertyName))).filter((specifier) => this._canAddSpecifier(sourceFile, moduleName, specifier));
affectedFiles.add(sourceFile.fileName);
if (newElements.length === 0) {
deletedImports.add(importDecl);
} else {
updatedImportsResult.set(namedBindings, import_typescript38.default.factory.updateNamedImports(namedBindings, newElements));
}
});
this.removedImports.forEach((removeMap, sourceFile) => {
var _a2;
if (removeMap.size === 0) {
return;
}
let allImports = importDeclarationsPerFile.get(sourceFile);
if (!allImports) {
allImports = sourceFile.statements.filter(import_typescript38.default.isImportDeclaration);
importDeclarationsPerFile.set(sourceFile, allImports);
}
for (const node of allImports) {
if (!((_a2 = node.importClause) == null ? void 0 : _a2.namedBindings) || !import_typescript38.default.isNamedImports(node.importClause.namedBindings) || this.reuseSourceFileImportsTracker.updatedImports.has(node) || deletedImports.has(node)) {
continue;
}
const namedBindings = node.importClause.namedBindings;
const moduleName = node.moduleSpecifier.text;
const newImports = namedBindings.elements.filter((specifier) => this._canAddSpecifier(sourceFile, moduleName, specifier));
if (newImports.length === 0) {
affectedFiles.add(sourceFile.fileName);
deletedImports.add(node);
} else if (newImports.length !== namedBindings.elements.length) {
affectedFiles.add(sourceFile.fileName);
updatedImportsResult.set(namedBindings, import_typescript38.default.factory.updateNamedImports(namedBindings, newImports));
}
}
});
this.newImports.forEach(({ namedImports, namespaceImports, sideEffectImports }, sourceFile) => {
const useSingleQuotes = this.config.shouldUseSingleQuotes(sourceFile);
const fileName = sourceFile.fileName;
sideEffectImports.forEach((moduleName) => {
addNewImport(fileName, import_typescript38.default.factory.createImportDeclaration(void 0, void 0, import_typescript38.default.factory.createStringLiteral(moduleName)));
});
namespaceImports.forEach((namespaceImport2, moduleName) => {
const newImport = import_typescript38.default.factory.createImportDeclaration(void 0, import_typescript38.default.factory.createImportClause(false, void 0, namespaceImport2), import_typescript38.default.factory.createStringLiteral(moduleName, useSingleQuotes));
import_typescript38.default.setOriginalNode(namespaceImport2.name, newImport);
addNewImport(fileName, newImport);
});
namedImports.forEach((specifiers, moduleName) => {
const filteredSpecifiers = specifiers.filter((specifier) => this._canAddSpecifier(sourceFile, moduleName, specifier));
if (filteredSpecifiers.length > 0) {
const newImport = import_typescript38.default.factory.createImportDeclaration(void 0, import_typescript38.default.factory.createImportClause(false, void 0, import_typescript38.default.factory.createNamedImports(filteredSpecifiers)), import_typescript38.default.factory.createStringLiteral(moduleName, useSingleQuotes));
addNewImport(fileName, newImport);
}
});
});
return {
affectedFiles,
newImports: newImportsResult,
updatedImports: updatedImportsResult,
reusedOriginalAliasDeclarations: this.reuseSourceFileImportsTracker.reusedAliasDeclarations,
deletedImports
};
}
toTsTransform(extraStatementsMap) {
return createTsTransformForImportManager(this, extraStatementsMap);
}
transformTsFile(ctx, file, extraStatementsAfterImports) {
const extraStatementsMap = extraStatementsAfterImports ? /* @__PURE__ */ new Map([[file.fileName, extraStatementsAfterImports]]) : void 0;
return this.toTsTransform(extraStatementsMap)(ctx)(file);
}
_getNewImportsTrackerForFile(file) {
if (!this.newImports.has(file)) {
this.newImports.set(file, {
namespaceImports: /* @__PURE__ */ new Map(),
namedImports: /* @__PURE__ */ new Map(),
sideEffectImports: /* @__PURE__ */ new Set()
});
}
return this.newImports.get(file);
}
_canAddSpecifier(sourceFile, moduleSpecifier, specifier) {
var _a2, _b2;
return !((_b2 = (_a2 = this.removedImports.get(sourceFile)) == null ? void 0 : _a2.get(moduleSpecifier)) == null ? void 0 : _b2.has((specifier.propertyName || specifier.name).text));
}
};
function createImportReference(asTypeReference, ref) {
if (asTypeReference) {
return Array.isArray(ref) ? import_typescript38.default.factory.createQualifiedName(ref[0], ref[1]) : ref;
} else {
return Array.isArray(ref) ? import_typescript38.default.factory.createPropertyAccessExpression(ref[0], ref[1]) : ref;
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/translator/src/translator.mjs
var UNARY_OPERATORS2 = /* @__PURE__ */ new Map([
[UnaryOperator.Minus, "-"],
[UnaryOperator.Plus, "+"]
]);
var BINARY_OPERATORS3 = /* @__PURE__ */ new Map([
[BinaryOperator.And, "&&"],
[BinaryOperator.Bigger, ">"],
[BinaryOperator.BiggerEquals, ">="],
[BinaryOperator.BitwiseAnd, "&"],
[BinaryOperator.BitwiseOr, "|"],
[BinaryOperator.Divide, "/"],
[BinaryOperator.Equals, "=="],
[BinaryOperator.Identical, "==="],
[BinaryOperator.Lower, "<"],
[BinaryOperator.LowerEquals, "<="],
[BinaryOperator.Minus, "-"],
[BinaryOperator.Modulo, "%"],
[BinaryOperator.Multiply, "*"],
[BinaryOperator.NotEquals, "!="],
[BinaryOperator.NotIdentical, "!=="],
[BinaryOperator.Or, "||"],
[BinaryOperator.Plus, "+"],
[BinaryOperator.NullishCoalesce, "??"]
]);
var ExpressionTranslatorVisitor = class {
constructor(factory11, imports, contextFile, options) {
this.factory = factory11;
this.imports = imports;
this.contextFile = contextFile;
this.downlevelTaggedTemplates = options.downlevelTaggedTemplates === true;
this.downlevelVariableDeclarations = options.downlevelVariableDeclarations === true;
this.recordWrappedNode = options.recordWrappedNode || (() => {
});
}
visitDeclareVarStmt(stmt, context) {
var _a2;
const varType = this.downlevelVariableDeclarations ? "var" : stmt.hasModifier(StmtModifier.Final) ? "const" : "let";
return this.attachComments(this.factory.createVariableDeclaration(stmt.name, (_a2 = stmt.value) == null ? void 0 : _a2.visitExpression(this, context.withExpressionMode), varType), stmt.leadingComments);
}
visitDeclareFunctionStmt(stmt, context) {
return this.attachComments(this.factory.createFunctionDeclaration(stmt.name, stmt.params.map((param) => param.name), this.factory.createBlock(this.visitStatements(stmt.statements, context.withStatementMode))), stmt.leadingComments);
}
visitExpressionStmt(stmt, context) {
return this.attachComments(this.factory.createExpressionStatement(stmt.expr.visitExpression(this, context.withStatementMode)), stmt.leadingComments);
}
visitReturnStmt(stmt, context) {
return this.attachComments(this.factory.createReturnStatement(stmt.value.visitExpression(this, context.withExpressionMode)), stmt.leadingComments);
}
visitIfStmt(stmt, context) {
return this.attachComments(this.factory.createIfStatement(stmt.condition.visitExpression(this, context), this.factory.createBlock(this.visitStatements(stmt.trueCase, context.withStatementMode)), stmt.falseCase.length > 0 ? this.factory.createBlock(this.visitStatements(stmt.falseCase, context.withStatementMode)) : null), stmt.leadingComments);
}
visitReadVarExpr(ast, _context) {
const identifier = this.factory.createIdentifier(ast.name);
this.setSourceMapRange(identifier, ast.sourceSpan);
return identifier;
}
visitWriteVarExpr(expr, context) {
const assignment = this.factory.createAssignment(this.setSourceMapRange(this.factory.createIdentifier(expr.name), expr.sourceSpan), expr.value.visitExpression(this, context));
return context.isStatement ? assignment : this.factory.createParenthesizedExpression(assignment);
}
visitWriteKeyExpr(expr, context) {
const exprContext = context.withExpressionMode;
const target = this.factory.createElementAccess(expr.receiver.visitExpression(this, exprContext), expr.index.visitExpression(this, exprContext));
const assignment = this.factory.createAssignment(target, expr.value.visitExpression(this, exprContext));
return context.isStatement ? assignment : this.factory.createParenthesizedExpression(assignment);
}
visitWritePropExpr(expr, context) {
const target = this.factory.createPropertyAccess(expr.receiver.visitExpression(this, context), expr.name);
return this.factory.createAssignment(target, expr.value.visitExpression(this, context));
}
visitInvokeFunctionExpr(ast, context) {
return this.setSourceMapRange(this.factory.createCallExpression(ast.fn.visitExpression(this, context), ast.args.map((arg) => arg.visitExpression(this, context)), ast.pure), ast.sourceSpan);
}
visitTaggedTemplateExpr(ast, context) {
return this.setSourceMapRange(this.createTaggedTemplateExpression(ast.tag.visitExpression(this, context), {
elements: ast.template.elements.map((e) => {
var _a2;
return createTemplateElement({
cooked: e.text,
raw: e.rawText,
range: (_a2 = e.sourceSpan) != null ? _a2 : ast.sourceSpan
});
}),
expressions: ast.template.expressions.map((e) => e.visitExpression(this, context))
}), ast.sourceSpan);
}
visitInstantiateExpr(ast, context) {
return this.factory.createNewExpression(ast.classExpr.visitExpression(this, context), ast.args.map((arg) => arg.visitExpression(this, context)));
}
visitLiteralExpr(ast, _context) {
return this.setSourceMapRange(this.factory.createLiteral(ast.value), ast.sourceSpan);
}
visitLocalizedString(ast, context) {
const elements = [createTemplateElement(ast.serializeI18nHead())];
const expressions = [];
for (let i = 0; i < ast.expressions.length; i++) {
const placeholder = this.setSourceMapRange(ast.expressions[i].visitExpression(this, context), ast.getPlaceholderSourceSpan(i));
expressions.push(placeholder);
elements.push(createTemplateElement(ast.serializeI18nTemplatePart(i + 1)));
}
const localizeTag = this.factory.createIdentifier("$localize");
return this.setSourceMapRange(this.createTaggedTemplateExpression(localizeTag, { elements, expressions }), ast.sourceSpan);
}
createTaggedTemplateExpression(tag, template2) {
return this.downlevelTaggedTemplates ? this.createES5TaggedTemplateFunctionCall(tag, template2) : this.factory.createTaggedTemplate(tag, template2);
}
createES5TaggedTemplateFunctionCall(tagHandler, { elements, expressions }) {
const __makeTemplateObjectHelper = this.imports.addImport({
exportModuleSpecifier: "tslib",
exportSymbolName: "__makeTemplateObject",
requestedFile: this.contextFile
});
const cooked = [];
const raw = [];
for (const element2 of elements) {
cooked.push(this.factory.setSourceMapRange(this.factory.createLiteral(element2.cooked), element2.range));
raw.push(this.factory.setSourceMapRange(this.factory.createLiteral(element2.raw), element2.range));
}
const templateHelperCall = this.factory.createCallExpression(
__makeTemplateObjectHelper,
[this.factory.createArrayLiteral(cooked), this.factory.createArrayLiteral(raw)],
false
);
return this.factory.createCallExpression(
tagHandler,
[templateHelperCall, ...expressions],
false
);
}
visitExternalExpr(ast, _context) {
if (ast.value.name === null) {
if (ast.value.moduleName === null) {
throw new Error("Invalid import without name nor moduleName");
}
return this.imports.addImport({
exportModuleSpecifier: ast.value.moduleName,
exportSymbolName: null,
requestedFile: this.contextFile
});
}
if (ast.value.moduleName !== null) {
return this.imports.addImport({
exportModuleSpecifier: ast.value.moduleName,
exportSymbolName: ast.value.name,
requestedFile: this.contextFile
});
} else {
return this.factory.createIdentifier(ast.value.name);
}
}
visitConditionalExpr(ast, context) {
let cond = ast.condition.visitExpression(this, context);
if (ast.condition instanceof ConditionalExpr) {
cond = this.factory.createParenthesizedExpression(cond);
}
return this.factory.createConditional(cond, ast.trueCase.visitExpression(this, context), ast.falseCase.visitExpression(this, context));
}
visitDynamicImportExpr(ast, context) {
return this.factory.createDynamicImport(ast.url);
}
visitNotExpr(ast, context) {
return this.factory.createUnaryExpression("!", ast.condition.visitExpression(this, context));
}
visitFunctionExpr(ast, context) {
var _a2;
return this.factory.createFunctionExpression((_a2 = ast.name) != null ? _a2 : null, ast.params.map((param) => param.name), this.factory.createBlock(this.visitStatements(ast.statements, context)));
}
visitArrowFunctionExpr(ast, context) {
return this.factory.createArrowFunctionExpression(ast.params.map((param) => param.name), Array.isArray(ast.body) ? this.factory.createBlock(this.visitStatements(ast.body, context)) : ast.body.visitExpression(this, context));
}
visitBinaryOperatorExpr(ast, context) {
if (!BINARY_OPERATORS3.has(ast.operator)) {
throw new Error(`Unknown binary operator: ${BinaryOperator[ast.operator]}`);
}
return this.factory.createBinaryExpression(ast.lhs.visitExpression(this, context), BINARY_OPERATORS3.get(ast.operator), ast.rhs.visitExpression(this, context));
}
visitReadPropExpr(ast, context) {
return this.factory.createPropertyAccess(ast.receiver.visitExpression(this, context), ast.name);
}
visitReadKeyExpr(ast, context) {
return this.factory.createElementAccess(ast.receiver.visitExpression(this, context), ast.index.visitExpression(this, context));
}
visitLiteralArrayExpr(ast, context) {
return this.factory.createArrayLiteral(ast.entries.map((expr) => this.setSourceMapRange(expr.visitExpression(this, context), ast.sourceSpan)));
}
visitLiteralMapExpr(ast, context) {
const properties = ast.entries.map((entry) => {
return {
propertyName: entry.key,
quoted: entry.quoted,
value: entry.value.visitExpression(this, context)
};
});
return this.setSourceMapRange(this.factory.createObjectLiteral(properties), ast.sourceSpan);
}
visitCommaExpr(ast, context) {
throw new Error("Method not implemented.");
}
visitWrappedNodeExpr(ast, _context) {
this.recordWrappedNode(ast);
return ast.node;
}
visitTypeofExpr(ast, context) {
return this.factory.createTypeOfExpression(ast.expr.visitExpression(this, context));
}
visitUnaryOperatorExpr(ast, context) {
if (!UNARY_OPERATORS2.has(ast.operator)) {
throw new Error(`Unknown unary operator: ${UnaryOperator[ast.operator]}`);
}
return this.factory.createUnaryExpression(UNARY_OPERATORS2.get(ast.operator), ast.expr.visitExpression(this, context));
}
visitStatements(statements, context) {
return statements.map((stmt) => stmt.visitStatement(this, context)).filter((stmt) => stmt !== void 0);
}
setSourceMapRange(ast, span) {
return this.factory.setSourceMapRange(ast, createRange(span));
}
attachComments(statement, leadingComments) {
if (leadingComments !== void 0) {
this.factory.attachComments(statement, leadingComments);
}
return statement;
}
};
function createTemplateElement({ cooked, raw, range }) {
return { cooked, raw, range: createRange(range) };
}
function createRange(span) {
if (span === null) {
return null;
}
const { start, end } = span;
const { url, content } = start.file;
if (!url) {
return null;
}
return {
url,
content,
start: { offset: start.offset, line: start.line, column: start.col },
end: { offset: end.offset, line: end.line, column: end.col }
};
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/translator/src/type_emitter.mjs
var import_typescript39 = __toESM(require("typescript"), 1);
var INELIGIBLE = {};
function canEmitType(type, canEmit) {
return canEmitTypeWorker(type);
function canEmitTypeWorker(type2) {
return visitNode(type2) !== INELIGIBLE;
}
function visitNode(node) {
if (import_typescript39.default.isImportTypeNode(node)) {
return INELIGIBLE;
}
if (import_typescript39.default.isTypeReferenceNode(node) && !canEmitTypeReference(node)) {
return INELIGIBLE;
} else {
return import_typescript39.default.forEachChild(node, visitNode);
}
}
function canEmitTypeReference(type2) {
if (!canEmit(type2)) {
return false;
}
return type2.typeArguments === void 0 || type2.typeArguments.every(canEmitTypeWorker);
}
}
var TypeEmitter = class {
constructor(translator) {
this.translator = translator;
}
emitType(type) {
const typeReferenceTransformer = (context) => {
const visitNode = (node) => {
if (import_typescript39.default.isImportTypeNode(node)) {
throw new Error("Unable to emit import type");
}
if (import_typescript39.default.isTypeReferenceNode(node)) {
return this.emitTypeReference(node);
} else if (import_typescript39.default.isLiteralExpression(node)) {
let clone;
if (import_typescript39.default.isStringLiteral(node)) {
clone = import_typescript39.default.factory.createStringLiteral(node.text);
} else if (import_typescript39.default.isNumericLiteral(node)) {
clone = import_typescript39.default.factory.createNumericLiteral(node.text);
} else if (import_typescript39.default.isBigIntLiteral(node)) {
clone = import_typescript39.default.factory.createBigIntLiteral(node.text);
} else if (import_typescript39.default.isNoSubstitutionTemplateLiteral(node)) {
clone = import_typescript39.default.factory.createNoSubstitutionTemplateLiteral(node.text, node.rawText);
} else if (import_typescript39.default.isRegularExpressionLiteral(node)) {
clone = import_typescript39.default.factory.createRegularExpressionLiteral(node.text);
} else {
throw new Error(`Unsupported literal kind ${import_typescript39.default.SyntaxKind[node.kind]}`);
}
import_typescript39.default.setTextRange(clone, { pos: -1, end: -1 });
return clone;
} else {
return import_typescript39.default.visitEachChild(node, visitNode, context);
}
};
return (node) => import_typescript39.default.visitNode(node, visitNode, import_typescript39.default.isTypeNode);
};
return import_typescript39.default.transform(type, [typeReferenceTransformer]).transformed[0];
}
emitTypeReference(type) {
const translatedType = this.translator(type);
if (translatedType === null) {
throw new Error("Unable to emit an unresolved reference");
}
let typeArguments = void 0;
if (type.typeArguments !== void 0) {
typeArguments = import_typescript39.default.factory.createNodeArray(type.typeArguments.map((typeArg) => this.emitType(typeArg)));
}
return import_typescript39.default.factory.updateTypeReferenceNode(type, translatedType.typeName, typeArguments);
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/translator/src/type_translator.mjs
var import_typescript41 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/translator/src/ts_util.mjs
var import_typescript40 = __toESM(require("typescript"), 1);
function tsNumericExpression(value) {
if (value < 0) {
const operand = import_typescript40.default.factory.createNumericLiteral(Math.abs(value));
return import_typescript40.default.factory.createPrefixUnaryExpression(import_typescript40.default.SyntaxKind.MinusToken, operand);
}
return import_typescript40.default.factory.createNumericLiteral(value);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/translator/src/type_translator.mjs
function translateType(type, contextFile, reflector, refEmitter, imports) {
return type.visitType(new TypeTranslatorVisitor(imports, contextFile, reflector, refEmitter), new Context(false));
}
var TypeTranslatorVisitor = class {
constructor(imports, contextFile, reflector, refEmitter) {
this.imports = imports;
this.contextFile = contextFile;
this.reflector = reflector;
this.refEmitter = refEmitter;
}
visitBuiltinType(type, context) {
switch (type.name) {
case BuiltinTypeName.Bool:
return import_typescript41.default.factory.createKeywordTypeNode(import_typescript41.default.SyntaxKind.BooleanKeyword);
case BuiltinTypeName.Dynamic:
return import_typescript41.default.factory.createKeywordTypeNode(import_typescript41.default.SyntaxKind.AnyKeyword);
case BuiltinTypeName.Int:
case BuiltinTypeName.Number:
return import_typescript41.default.factory.createKeywordTypeNode(import_typescript41.default.SyntaxKind.NumberKeyword);
case BuiltinTypeName.String:
return import_typescript41.default.factory.createKeywordTypeNode(import_typescript41.default.SyntaxKind.StringKeyword);
case BuiltinTypeName.None:
return import_typescript41.default.factory.createKeywordTypeNode(import_typescript41.default.SyntaxKind.NeverKeyword);
default:
throw new Error(`Unsupported builtin type: ${BuiltinTypeName[type.name]}`);
}
}
visitExpressionType(type, context) {
const typeNode = this.translateExpression(type.value, context);
if (type.typeParams === null) {
return typeNode;
}
if (!import_typescript41.default.isTypeReferenceNode(typeNode)) {
throw new Error("An ExpressionType with type arguments must translate into a TypeReferenceNode");
} else if (typeNode.typeArguments !== void 0) {
throw new Error(`An ExpressionType with type arguments cannot have multiple levels of type arguments`);
}
const typeArgs = type.typeParams.map((param) => this.translateType(param, context));
return import_typescript41.default.factory.createTypeReferenceNode(typeNode.typeName, typeArgs);
}
visitArrayType(type, context) {
return import_typescript41.default.factory.createArrayTypeNode(this.translateType(type.of, context));
}
visitMapType(type, context) {
const parameter = import_typescript41.default.factory.createParameterDeclaration(void 0, void 0, "key", void 0, import_typescript41.default.factory.createKeywordTypeNode(import_typescript41.default.SyntaxKind.StringKeyword));
const typeArgs = type.valueType !== null ? this.translateType(type.valueType, context) : import_typescript41.default.factory.createKeywordTypeNode(import_typescript41.default.SyntaxKind.UnknownKeyword);
const indexSignature = import_typescript41.default.factory.createIndexSignature(void 0, [parameter], typeArgs);
return import_typescript41.default.factory.createTypeLiteralNode([indexSignature]);
}
visitTransplantedType(ast, context) {
const node = ast.type instanceof Reference2 ? ast.type.node : ast.type;
if (!import_typescript41.default.isTypeNode(node)) {
throw new Error(`A TransplantedType must wrap a TypeNode`);
}
const viaModule = ast.type instanceof Reference2 ? ast.type.bestGuessOwningModule : null;
const emitter = new TypeEmitter((typeRef) => this.translateTypeReference(typeRef, context, viaModule));
return emitter.emitType(node);
}
visitReadVarExpr(ast, context) {
if (ast.name === null) {
throw new Error(`ReadVarExpr with no variable name in type`);
}
return import_typescript41.default.factory.createTypeQueryNode(import_typescript41.default.factory.createIdentifier(ast.name));
}
visitWriteVarExpr(expr, context) {
throw new Error("Method not implemented.");
}
visitWriteKeyExpr(expr, context) {
throw new Error("Method not implemented.");
}
visitWritePropExpr(expr, context) {
throw new Error("Method not implemented.");
}
visitInvokeFunctionExpr(ast, context) {
throw new Error("Method not implemented.");
}
visitTaggedTemplateExpr(ast, context) {
throw new Error("Method not implemented.");
}
visitInstantiateExpr(ast, context) {
throw new Error("Method not implemented.");
}
visitLiteralExpr(ast, context) {
if (ast.value === null) {
return import_typescript41.default.factory.createLiteralTypeNode(import_typescript41.default.factory.createNull());
} else if (ast.value === void 0) {
return import_typescript41.default.factory.createKeywordTypeNode(import_typescript41.default.SyntaxKind.UndefinedKeyword);
} else if (typeof ast.value === "boolean") {
return import_typescript41.default.factory.createLiteralTypeNode(ast.value ? import_typescript41.default.factory.createTrue() : import_typescript41.default.factory.createFalse());
} else if (typeof ast.value === "number") {
return import_typescript41.default.factory.createLiteralTypeNode(tsNumericExpression(ast.value));
} else {
return import_typescript41.default.factory.createLiteralTypeNode(import_typescript41.default.factory.createStringLiteral(ast.value));
}
}
visitLocalizedString(ast, context) {
throw new Error("Method not implemented.");
}
visitExternalExpr(ast, context) {
if (ast.value.moduleName === null || ast.value.name === null) {
throw new Error(`Import unknown module or symbol`);
}
const typeName = this.imports.addImport({
exportModuleSpecifier: ast.value.moduleName,
exportSymbolName: ast.value.name,
requestedFile: this.contextFile,
asTypeReference: true
});
const typeArguments = ast.typeParams !== null ? ast.typeParams.map((type) => this.translateType(type, context)) : void 0;
return import_typescript41.default.factory.createTypeReferenceNode(typeName, typeArguments);
}
visitConditionalExpr(ast, context) {
throw new Error("Method not implemented.");
}
visitDynamicImportExpr(ast, context) {
throw new Error("Method not implemented.");
}
visitNotExpr(ast, context) {
throw new Error("Method not implemented.");
}
visitFunctionExpr(ast, context) {
throw new Error("Method not implemented.");
}
visitArrowFunctionExpr(ast, context) {
throw new Error("Method not implemented.");
}
visitUnaryOperatorExpr(ast, context) {
throw new Error("Method not implemented.");
}
visitBinaryOperatorExpr(ast, context) {
throw new Error("Method not implemented.");
}
visitReadPropExpr(ast, context) {
throw new Error("Method not implemented.");
}
visitReadKeyExpr(ast, context) {
throw new Error("Method not implemented.");
}
visitLiteralArrayExpr(ast, context) {
const values = ast.entries.map((expr) => this.translateExpression(expr, context));
return import_typescript41.default.factory.createTupleTypeNode(values);
}
visitLiteralMapExpr(ast, context) {
const entries = ast.entries.map((entry) => {
const { key, quoted } = entry;
const type = this.translateExpression(entry.value, context);
return import_typescript41.default.factory.createPropertySignature(
void 0,
quoted ? import_typescript41.default.factory.createStringLiteral(key) : key,
void 0,
type
);
});
return import_typescript41.default.factory.createTypeLiteralNode(entries);
}
visitCommaExpr(ast, context) {
throw new Error("Method not implemented.");
}
visitWrappedNodeExpr(ast, context) {
const node = ast.node;
if (import_typescript41.default.isEntityName(node)) {
return import_typescript41.default.factory.createTypeReferenceNode(node, void 0);
} else if (import_typescript41.default.isTypeNode(node)) {
return node;
} else if (import_typescript41.default.isLiteralExpression(node)) {
return import_typescript41.default.factory.createLiteralTypeNode(node);
} else {
throw new Error(`Unsupported WrappedNodeExpr in TypeTranslatorVisitor: ${import_typescript41.default.SyntaxKind[node.kind]}`);
}
}
visitTypeofExpr(ast, context) {
const typeNode = this.translateExpression(ast.expr, context);
if (!import_typescript41.default.isTypeReferenceNode(typeNode)) {
throw new Error(`The target of a typeof expression must be a type reference, but it was
${import_typescript41.default.SyntaxKind[typeNode.kind]}`);
}
return import_typescript41.default.factory.createTypeQueryNode(typeNode.typeName);
}
translateType(type, context) {
const typeNode = type.visitType(this, context);
if (!import_typescript41.default.isTypeNode(typeNode)) {
throw new Error(`A Type must translate to a TypeNode, but was ${import_typescript41.default.SyntaxKind[typeNode.kind]}`);
}
return typeNode;
}
translateExpression(expr, context) {
const typeNode = expr.visitExpression(this, context);
if (!import_typescript41.default.isTypeNode(typeNode)) {
throw new Error(`An Expression must translate to a TypeNode, but was ${import_typescript41.default.SyntaxKind[typeNode.kind]}`);
}
return typeNode;
}
translateTypeReference(type, context, viaModule) {
const target = import_typescript41.default.isIdentifier(type.typeName) ? type.typeName : type.typeName.right;
const declaration = this.reflector.getDeclarationOfIdentifier(target);
if (declaration === null) {
throw new Error(`Unable to statically determine the declaration file of type node ${target.text}`);
}
let owningModule2 = viaModule;
if (typeof declaration.viaModule === "string") {
owningModule2 = {
specifier: declaration.viaModule,
resolutionContext: type.getSourceFile().fileName
};
}
const reference2 = new Reference2(declaration.node, declaration.viaModule === AmbientImport ? AmbientImport : owningModule2);
const emittedType = this.refEmitter.emit(reference2, this.contextFile, ImportFlags.NoAliasing | ImportFlags.AllowTypeImports | ImportFlags.AllowAmbientReferences);
assertSuccessfulReferenceEmit(emittedType, target, "type");
const typeNode = this.translateExpression(emittedType.expression, context);
if (!import_typescript41.default.isTypeReferenceNode(typeNode)) {
throw new Error(`Expected TypeReferenceNode for emitted reference, got ${import_typescript41.default.SyntaxKind[typeNode.kind]}.`);
}
return typeNode;
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/translator/src/typescript_ast_factory.mjs
var import_typescript42 = __toESM(require("typescript"), 1);
var PureAnnotation;
(function(PureAnnotation2) {
PureAnnotation2["CLOSURE"] = "* @pureOrBreakMyCode ";
PureAnnotation2["TERSER"] = "@__PURE__";
})(PureAnnotation || (PureAnnotation = {}));
var UNARY_OPERATORS3 = {
"+": import_typescript42.default.SyntaxKind.PlusToken,
"-": import_typescript42.default.SyntaxKind.MinusToken,
"!": import_typescript42.default.SyntaxKind.ExclamationToken
};
var BINARY_OPERATORS4 = {
"&&": import_typescript42.default.SyntaxKind.AmpersandAmpersandToken,
">": import_typescript42.default.SyntaxKind.GreaterThanToken,
">=": import_typescript42.default.SyntaxKind.GreaterThanEqualsToken,
"&": import_typescript42.default.SyntaxKind.AmpersandToken,
"|": import_typescript42.default.SyntaxKind.BarToken,
"/": import_typescript42.default.SyntaxKind.SlashToken,
"==": import_typescript42.default.SyntaxKind.EqualsEqualsToken,
"===": import_typescript42.default.SyntaxKind.EqualsEqualsEqualsToken,
"<": import_typescript42.default.SyntaxKind.LessThanToken,
"<=": import_typescript42.default.SyntaxKind.LessThanEqualsToken,
"-": import_typescript42.default.SyntaxKind.MinusToken,
"%": import_typescript42.default.SyntaxKind.PercentToken,
"*": import_typescript42.default.SyntaxKind.AsteriskToken,
"!=": import_typescript42.default.SyntaxKind.ExclamationEqualsToken,
"!==": import_typescript42.default.SyntaxKind.ExclamationEqualsEqualsToken,
"||": import_typescript42.default.SyntaxKind.BarBarToken,
"+": import_typescript42.default.SyntaxKind.PlusToken,
"??": import_typescript42.default.SyntaxKind.QuestionQuestionToken
};
var VAR_TYPES = {
"const": import_typescript42.default.NodeFlags.Const,
"let": import_typescript42.default.NodeFlags.Let,
"var": import_typescript42.default.NodeFlags.None
};
var TypeScriptAstFactory = class {
constructor(annotateForClosureCompiler) {
this.annotateForClosureCompiler = annotateForClosureCompiler;
this.externalSourceFiles = /* @__PURE__ */ new Map();
this.attachComments = attachComments;
this.createArrayLiteral = import_typescript42.default.factory.createArrayLiteralExpression;
this.createElementAccess = import_typescript42.default.factory.createElementAccessExpression;
this.createExpressionStatement = import_typescript42.default.factory.createExpressionStatement;
this.createIdentifier = import_typescript42.default.factory.createIdentifier;
this.createParenthesizedExpression = import_typescript42.default.factory.createParenthesizedExpression;
this.createPropertyAccess = import_typescript42.default.factory.createPropertyAccessExpression;
this.createThrowStatement = import_typescript42.default.factory.createThrowStatement;
this.createTypeOfExpression = import_typescript42.default.factory.createTypeOfExpression;
}
createAssignment(target, value) {
return import_typescript42.default.factory.createBinaryExpression(target, import_typescript42.default.SyntaxKind.EqualsToken, value);
}
createBinaryExpression(leftOperand, operator, rightOperand) {
return import_typescript42.default.factory.createBinaryExpression(leftOperand, BINARY_OPERATORS4[operator], rightOperand);
}
createBlock(body) {
return import_typescript42.default.factory.createBlock(body);
}
createCallExpression(callee, args, pure) {
const call2 = import_typescript42.default.factory.createCallExpression(callee, void 0, args);
if (pure) {
import_typescript42.default.addSyntheticLeadingComment(
call2,
import_typescript42.default.SyntaxKind.MultiLineCommentTrivia,
this.annotateForClosureCompiler ? PureAnnotation.CLOSURE : PureAnnotation.TERSER,
false
);
}
return call2;
}
createConditional(condition, whenTrue, whenFalse) {
return import_typescript42.default.factory.createConditionalExpression(condition, void 0, whenTrue, void 0, whenFalse);
}
createDynamicImport(url) {
return import_typescript42.default.factory.createCallExpression(
import_typescript42.default.factory.createToken(import_typescript42.default.SyntaxKind.ImportKeyword),
void 0,
[import_typescript42.default.factory.createStringLiteral(url)]
);
}
createFunctionDeclaration(functionName, parameters, body) {
if (!import_typescript42.default.isBlock(body)) {
throw new Error(`Invalid syntax, expected a block, but got ${import_typescript42.default.SyntaxKind[body.kind]}.`);
}
return import_typescript42.default.factory.createFunctionDeclaration(void 0, void 0, functionName, void 0, parameters.map((param) => import_typescript42.default.factory.createParameterDeclaration(void 0, void 0, param)), void 0, body);
}
createFunctionExpression(functionName, parameters, body) {
if (!import_typescript42.default.isBlock(body)) {
throw new Error(`Invalid syntax, expected a block, but got ${import_typescript42.default.SyntaxKind[body.kind]}.`);
}
return import_typescript42.default.factory.createFunctionExpression(void 0, void 0, functionName != null ? functionName : void 0, void 0, parameters.map((param) => import_typescript42.default.factory.createParameterDeclaration(void 0, void 0, param)), void 0, body);
}
createArrowFunctionExpression(parameters, body) {
if (import_typescript42.default.isStatement(body) && !import_typescript42.default.isBlock(body)) {
throw new Error(`Invalid syntax, expected a block, but got ${import_typescript42.default.SyntaxKind[body.kind]}.`);
}
return import_typescript42.default.factory.createArrowFunction(void 0, void 0, parameters.map((param) => import_typescript42.default.factory.createParameterDeclaration(void 0, void 0, param)), void 0, void 0, body);
}
createIfStatement(condition, thenStatement, elseStatement) {
return import_typescript42.default.factory.createIfStatement(condition, thenStatement, elseStatement != null ? elseStatement : void 0);
}
createLiteral(value) {
if (value === void 0) {
return import_typescript42.default.factory.createIdentifier("undefined");
} else if (value === null) {
return import_typescript42.default.factory.createNull();
} else if (typeof value === "boolean") {
return value ? import_typescript42.default.factory.createTrue() : import_typescript42.default.factory.createFalse();
} else if (typeof value === "number") {
return tsNumericExpression(value);
} else {
return import_typescript42.default.factory.createStringLiteral(value);
}
}
createNewExpression(expression, args) {
return import_typescript42.default.factory.createNewExpression(expression, void 0, args);
}
createObjectLiteral(properties) {
return import_typescript42.default.factory.createObjectLiteralExpression(properties.map((prop) => import_typescript42.default.factory.createPropertyAssignment(prop.quoted ? import_typescript42.default.factory.createStringLiteral(prop.propertyName) : import_typescript42.default.factory.createIdentifier(prop.propertyName), prop.value)));
}
createReturnStatement(expression) {
return import_typescript42.default.factory.createReturnStatement(expression != null ? expression : void 0);
}
createTaggedTemplate(tag, template2) {
let templateLiteral;
const length = template2.elements.length;
const head = template2.elements[0];
if (length === 1) {
templateLiteral = import_typescript42.default.factory.createNoSubstitutionTemplateLiteral(head.cooked, head.raw);
} else {
const spans = [];
for (let i = 1; i < length - 1; i++) {
const { cooked, raw, range } = template2.elements[i];
const middle = createTemplateMiddle(cooked, raw);
if (range !== null) {
this.setSourceMapRange(middle, range);
}
spans.push(import_typescript42.default.factory.createTemplateSpan(template2.expressions[i - 1], middle));
}
const resolvedExpression = template2.expressions[length - 2];
const templatePart = template2.elements[length - 1];
const templateTail = createTemplateTail(templatePart.cooked, templatePart.raw);
if (templatePart.range !== null) {
this.setSourceMapRange(templateTail, templatePart.range);
}
spans.push(import_typescript42.default.factory.createTemplateSpan(resolvedExpression, templateTail));
templateLiteral = import_typescript42.default.factory.createTemplateExpression(import_typescript42.default.factory.createTemplateHead(head.cooked, head.raw), spans);
}
if (head.range !== null) {
this.setSourceMapRange(templateLiteral, head.range);
}
return import_typescript42.default.factory.createTaggedTemplateExpression(tag, void 0, templateLiteral);
}
createUnaryExpression(operator, operand) {
return import_typescript42.default.factory.createPrefixUnaryExpression(UNARY_OPERATORS3[operator], operand);
}
createVariableDeclaration(variableName, initializer, type) {
return import_typescript42.default.factory.createVariableStatement(void 0, import_typescript42.default.factory.createVariableDeclarationList([
import_typescript42.default.factory.createVariableDeclaration(variableName, void 0, void 0, initializer != null ? initializer : void 0)
], VAR_TYPES[type]));
}
setSourceMapRange(node, sourceMapRange) {
if (sourceMapRange === null) {
return node;
}
const url = sourceMapRange.url;
if (!this.externalSourceFiles.has(url)) {
this.externalSourceFiles.set(url, import_typescript42.default.createSourceMapSource(url, sourceMapRange.content, (pos) => pos));
}
const source = this.externalSourceFiles.get(url);
import_typescript42.default.setSourceMapRange(node, {
pos: sourceMapRange.start.offset,
end: sourceMapRange.end.offset,
source
});
return node;
}
};
function createTemplateMiddle(cooked, raw) {
const node = import_typescript42.default.factory.createTemplateHead(cooked, raw);
node.kind = import_typescript42.default.SyntaxKind.TemplateMiddle;
return node;
}
function createTemplateTail(cooked, raw) {
const node = import_typescript42.default.factory.createTemplateHead(cooked, raw);
node.kind = import_typescript42.default.SyntaxKind.TemplateTail;
return node;
}
function attachComments(statement, leadingComments) {
for (const comment of leadingComments) {
const commentKind = comment.multiline ? import_typescript42.default.SyntaxKind.MultiLineCommentTrivia : import_typescript42.default.SyntaxKind.SingleLineCommentTrivia;
if (comment.multiline) {
import_typescript42.default.addSyntheticLeadingComment(statement, commentKind, comment.toString(), comment.trailingNewline);
} else {
for (const line of comment.toString().split("\n")) {
import_typescript42.default.addSyntheticLeadingComment(statement, commentKind, line, comment.trailingNewline);
}
}
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/translator/src/typescript_translator.mjs
function translateExpression(contextFile, expression, imports, options = {}) {
return expression.visitExpression(new ExpressionTranslatorVisitor(new TypeScriptAstFactory(options.annotateForClosureCompiler === true), imports, contextFile, options), new Context(false));
}
function translateStatement(contextFile, statement, imports, options = {}) {
return statement.visitStatement(new ExpressionTranslatorVisitor(new TypeScriptAstFactory(options.annotateForClosureCompiler === true), imports, contextFile, options), new Context(true));
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/transform/src/declaration.mjs
var DtsTransformRegistry = class {
constructor() {
this.ivyDeclarationTransforms = /* @__PURE__ */ new Map();
}
getIvyDeclarationTransform(sf) {
if (!this.ivyDeclarationTransforms.has(sf)) {
this.ivyDeclarationTransforms.set(sf, new IvyDeclarationDtsTransform());
}
return this.ivyDeclarationTransforms.get(sf);
}
getAllTransforms(sf) {
if (!sf.isDeclarationFile) {
return null;
}
const originalSf = import_typescript43.default.getOriginalNode(sf);
let transforms = null;
if (this.ivyDeclarationTransforms.has(originalSf)) {
transforms = [];
transforms.push(this.ivyDeclarationTransforms.get(originalSf));
}
return transforms;
}
};
function declarationTransformFactory(transformRegistry, reflector, refEmitter, importRewriter) {
return (context) => {
const transformer = new DtsTransformer(context, reflector, refEmitter, importRewriter);
return (fileOrBundle) => {
if (import_typescript43.default.isBundle(fileOrBundle)) {
return fileOrBundle;
}
const transforms = transformRegistry.getAllTransforms(fileOrBundle);
if (transforms === null) {
return fileOrBundle;
}
return transformer.transform(fileOrBundle, transforms);
};
};
}
var DtsTransformer = class {
constructor(ctx, reflector, refEmitter, importRewriter) {
this.ctx = ctx;
this.reflector = reflector;
this.refEmitter = refEmitter;
this.importRewriter = importRewriter;
}
transform(sf, transforms) {
const imports = new ImportManager(__spreadProps(__spreadValues({}, presetImportManagerForceNamespaceImports), {
rewriter: this.importRewriter
}));
const visitor = (node) => {
if (import_typescript43.default.isClassDeclaration(node)) {
return this.transformClassDeclaration(node, transforms, imports);
} else if (import_typescript43.default.isFunctionDeclaration(node)) {
return this.transformFunctionDeclaration(node, transforms, imports);
} else {
return import_typescript43.default.visitEachChild(node, visitor, this.ctx);
}
};
sf = import_typescript43.default.visitNode(sf, visitor, import_typescript43.default.isSourceFile) || sf;
return imports.transformTsFile(this.ctx, sf);
}
transformClassDeclaration(clazz, transforms, imports) {
let elements = clazz.members;
let elementsChanged = false;
for (const transform2 of transforms) {
if (transform2.transformClassElement !== void 0) {
for (let i = 0; i < elements.length; i++) {
const res = transform2.transformClassElement(elements[i], imports);
if (res !== elements[i]) {
if (!elementsChanged) {
elements = [...elements];
elementsChanged = true;
}
elements[i] = res;
}
}
}
}
let newClazz = clazz;
for (const transform2 of transforms) {
if (transform2.transformClass !== void 0) {
const inputMembers = clazz === newClazz ? elements : newClazz.members;
newClazz = transform2.transformClass(newClazz, inputMembers, this.reflector, this.refEmitter, imports);
}
}
if (elementsChanged && clazz === newClazz) {
newClazz = import_typescript43.default.factory.updateClassDeclaration(
clazz,
clazz.modifiers,
clazz.name,
clazz.typeParameters,
clazz.heritageClauses,
elements
);
}
return newClazz;
}
transformFunctionDeclaration(declaration, transforms, imports) {
let newDecl = declaration;
for (const transform2 of transforms) {
if (transform2.transformFunctionDeclaration !== void 0) {
newDecl = transform2.transformFunctionDeclaration(newDecl, imports);
}
}
return newDecl;
}
};
var IvyDeclarationDtsTransform = class {
constructor() {
this.declarationFields = /* @__PURE__ */ new Map();
}
addFields(decl, fields) {
this.declarationFields.set(decl, fields);
}
transformClass(clazz, members, reflector, refEmitter, imports) {
const original = import_typescript43.default.getOriginalNode(clazz);
if (!this.declarationFields.has(original)) {
return clazz;
}
const fields = this.declarationFields.get(original);
const newMembers = fields.map((decl) => {
const modifiers = [import_typescript43.default.factory.createModifier(import_typescript43.default.SyntaxKind.StaticKeyword)];
const typeRef = translateType(decl.type, original.getSourceFile(), reflector, refEmitter, imports);
markForEmitAsSingleLine(typeRef);
return import_typescript43.default.factory.createPropertyDeclaration(
modifiers,
decl.name,
void 0,
typeRef,
void 0
);
});
return import_typescript43.default.factory.updateClassDeclaration(
clazz,
clazz.modifiers,
clazz.name,
clazz.typeParameters,
clazz.heritageClauses,
[...members, ...newMembers]
);
}
};
function markForEmitAsSingleLine(node) {
import_typescript43.default.setEmitFlags(node, import_typescript43.default.EmitFlags.SingleLine);
import_typescript43.default.forEachChild(node, markForEmitAsSingleLine);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/transform/src/transform.mjs
var import_typescript45 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/util/src/visitor.mjs
var import_typescript44 = __toESM(require("typescript"), 1);
function visit(node, visitor, context) {
return visitor._visit(node, context);
}
var Visitor = class {
constructor() {
this._before = /* @__PURE__ */ new Map();
this._after = /* @__PURE__ */ new Map();
}
_visitListEntryNode(node, visitor) {
const result = visitor(node);
if (result.before !== void 0) {
this._before.set(result.node, result.before);
}
if (result.after !== void 0) {
this._after.set(result.node, result.after);
}
return result.node;
}
visitOtherNode(node) {
return node;
}
_visit(node, context) {
let visitedNode = null;
node = import_typescript44.default.visitEachChild(node, (child) => child && this._visit(child, context), context);
if (import_typescript44.default.isClassDeclaration(node)) {
visitedNode = this._visitListEntryNode(node, (node2) => this.visitClassDeclaration(node2));
} else {
visitedNode = this.visitOtherNode(node);
}
if (visitedNode && (import_typescript44.default.isBlock(visitedNode) || import_typescript44.default.isSourceFile(visitedNode))) {
visitedNode = this._maybeProcessStatements(visitedNode);
}
return visitedNode;
}
_maybeProcessStatements(node) {
if (node.statements.every((stmt) => !this._before.has(stmt) && !this._after.has(stmt))) {
return node;
}
const newStatements = [];
node.statements.forEach((stmt) => {
if (this._before.has(stmt)) {
newStatements.push(...this._before.get(stmt));
this._before.delete(stmt);
}
newStatements.push(stmt);
if (this._after.has(stmt)) {
newStatements.push(...this._after.get(stmt));
this._after.delete(stmt);
}
});
const statementsArray = import_typescript44.default.factory.createNodeArray(newStatements, node.statements.hasTrailingComma);
if (import_typescript44.default.isBlock(node)) {
return import_typescript44.default.factory.updateBlock(node, statementsArray);
} else {
return import_typescript44.default.factory.updateSourceFile(node, statementsArray, node.isDeclarationFile, node.referencedFiles, node.typeReferenceDirectives, node.hasNoDefaultLib, node.libReferenceDirectives);
}
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/transform/src/transform.mjs
var NO_DECORATORS = /* @__PURE__ */ new Set();
var CLOSURE_FILE_OVERVIEW_REGEXP = /\s+@fileoverview\s+/i;
function ivyTransformFactory(compilation, reflector, importRewriter, defaultImportTracker, localCompilationExtraImportsTracker, perf, isCore, isClosureCompilerEnabled) {
const recordWrappedNode = createRecorderFn(defaultImportTracker);
return (context) => {
return (file) => {
return perf.inPhase(PerfPhase.Compile, () => transformIvySourceFile(compilation, context, reflector, importRewriter, localCompilationExtraImportsTracker, file, isCore, isClosureCompilerEnabled, recordWrappedNode));
};
};
}
var IvyCompilationVisitor = class extends Visitor {
constructor(compilation, constantPool) {
super();
this.compilation = compilation;
this.constantPool = constantPool;
this.classCompilationMap = /* @__PURE__ */ new Map();
this.deferrableImports = /* @__PURE__ */ new Set();
}
visitClassDeclaration(node) {
const result = this.compilation.compile(node, this.constantPool);
if (result !== null) {
this.classCompilationMap.set(node, result);
for (const classResult of result) {
if (classResult.deferrableImports !== null && classResult.deferrableImports.size > 0) {
classResult.deferrableImports.forEach((importDecl) => this.deferrableImports.add(importDecl));
}
}
}
return { node };
}
};
var IvyTransformationVisitor = class extends Visitor {
constructor(compilation, classCompilationMap, reflector, importManager, recordWrappedNodeExpr, isClosureCompilerEnabled, isCore, deferrableImports) {
super();
this.compilation = compilation;
this.classCompilationMap = classCompilationMap;
this.reflector = reflector;
this.importManager = importManager;
this.recordWrappedNodeExpr = recordWrappedNodeExpr;
this.isClosureCompilerEnabled = isClosureCompilerEnabled;
this.isCore = isCore;
this.deferrableImports = deferrableImports;
}
visitClassDeclaration(node) {
if (!this.classCompilationMap.has(node)) {
return { node };
}
const translateOptions = {
recordWrappedNode: this.recordWrappedNodeExpr,
annotateForClosureCompiler: this.isClosureCompilerEnabled
};
const statements = [];
const members = [...node.members];
const sourceFile = import_typescript45.default.getOriginalNode(node).getSourceFile();
for (const field of this.classCompilationMap.get(node)) {
if (field.initializer === null) {
continue;
}
const exprNode = translateExpression(sourceFile, field.initializer, this.importManager, translateOptions);
const property2 = import_typescript45.default.factory.createPropertyDeclaration([import_typescript45.default.factory.createToken(import_typescript45.default.SyntaxKind.StaticKeyword)], field.name, void 0, void 0, exprNode);
if (this.isClosureCompilerEnabled) {
import_typescript45.default.addSyntheticLeadingComment(
property2,
import_typescript45.default.SyntaxKind.MultiLineCommentTrivia,
"* @nocollapse ",
false
);
}
field.statements.map((stmt) => translateStatement(sourceFile, stmt, this.importManager, translateOptions)).forEach((stmt) => statements.push(stmt));
members.push(property2);
}
const filteredDecorators = maybeFilterDecorator(import_typescript45.default.getDecorators(node), this.compilation.decoratorsFor(node));
const nodeModifiers = import_typescript45.default.getModifiers(node);
let updatedModifiers;
if ((filteredDecorators == null ? void 0 : filteredDecorators.length) || (nodeModifiers == null ? void 0 : nodeModifiers.length)) {
updatedModifiers = [...filteredDecorators || [], ...nodeModifiers || []];
}
node = import_typescript45.default.factory.updateClassDeclaration(
node,
updatedModifiers,
node.name,
node.typeParameters,
node.heritageClauses || [],
members.map((member) => this._stripAngularDecorators(member))
);
return { node, after: statements };
}
visitOtherNode(node) {
if (import_typescript45.default.isImportDeclaration(node) && this.deferrableImports.has(node)) {
return null;
}
return node;
}
_angularCoreDecorators(decl) {
const decorators = this.reflector.getDecoratorsOfDeclaration(decl);
if (decorators === null) {
return NO_DECORATORS;
}
const coreDecorators = decorators.filter((dec) => this.isCore || isFromAngularCore(dec)).map((dec) => dec.node);
if (coreDecorators.length > 0) {
return new Set(coreDecorators);
} else {
return NO_DECORATORS;
}
}
_nonCoreDecoratorsOnly(node) {
const decorators = import_typescript45.default.getDecorators(node);
if (decorators === void 0) {
return void 0;
}
const coreDecorators = this._angularCoreDecorators(node);
if (coreDecorators.size === decorators.length) {
return void 0;
} else if (coreDecorators.size === 0) {
return nodeArrayFromDecoratorsArray(decorators);
}
const filtered = decorators.filter((dec) => !coreDecorators.has(dec));
if (filtered.length === 0) {
return void 0;
}
return nodeArrayFromDecoratorsArray(filtered);
}
_stripAngularDecorators(node) {
const modifiers = import_typescript45.default.canHaveModifiers(node) ? import_typescript45.default.getModifiers(node) : void 0;
const nonCoreDecorators = import_typescript45.default.canHaveDecorators(node) ? this._nonCoreDecoratorsOnly(node) : void 0;
const combinedModifiers = [...nonCoreDecorators || [], ...modifiers || []];
if (import_typescript45.default.isParameter(node)) {
node = import_typescript45.default.factory.updateParameterDeclaration(node, combinedModifiers, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer);
} else if (import_typescript45.default.isMethodDeclaration(node)) {
node = import_typescript45.default.factory.updateMethodDeclaration(node, combinedModifiers, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body);
} else if (import_typescript45.default.isPropertyDeclaration(node)) {
node = import_typescript45.default.factory.updatePropertyDeclaration(node, combinedModifiers, node.name, node.questionToken, node.type, node.initializer);
} else if (import_typescript45.default.isGetAccessor(node)) {
node = import_typescript45.default.factory.updateGetAccessorDeclaration(node, combinedModifiers, node.name, node.parameters, node.type, node.body);
} else if (import_typescript45.default.isSetAccessor(node)) {
node = import_typescript45.default.factory.updateSetAccessorDeclaration(node, combinedModifiers, node.name, node.parameters, node.body);
} else if (import_typescript45.default.isConstructorDeclaration(node)) {
const parameters = node.parameters.map((param) => this._stripAngularDecorators(param));
node = import_typescript45.default.factory.updateConstructorDeclaration(node, modifiers, parameters, node.body);
}
return node;
}
};
function transformIvySourceFile(compilation, context, reflector, importRewriter, localCompilationExtraImportsTracker, file, isCore, isClosureCompilerEnabled, recordWrappedNode) {
const constantPool = new ConstantPool(isClosureCompilerEnabled);
const importManager = new ImportManager(__spreadProps(__spreadValues({}, presetImportManagerForceNamespaceImports), {
rewriter: importRewriter
}));
const compilationVisitor = new IvyCompilationVisitor(compilation, constantPool);
visit(file, compilationVisitor, context);
const transformationVisitor = new IvyTransformationVisitor(compilation, compilationVisitor.classCompilationMap, reflector, importManager, recordWrappedNode, isClosureCompilerEnabled, isCore, compilationVisitor.deferrableImports);
let sf = visit(file, transformationVisitor, context);
const downlevelTranslatedCode = getLocalizeCompileTarget(context) < import_typescript45.default.ScriptTarget.ES2015;
const constants = constantPool.statements.map((stmt) => translateStatement(file, stmt, importManager, {
recordWrappedNode,
downlevelTaggedTemplates: downlevelTranslatedCode,
downlevelVariableDeclarations: downlevelTranslatedCode,
annotateForClosureCompiler: isClosureCompilerEnabled
}));
const fileOverviewMeta = isClosureCompilerEnabled ? getFileOverviewComment(sf.statements) : null;
if (localCompilationExtraImportsTracker !== null) {
for (const moduleName of localCompilationExtraImportsTracker.getImportsForFile(sf)) {
importManager.addSideEffectImport(sf, moduleName);
}
}
sf = importManager.transformTsFile(context, sf, constants);
if (fileOverviewMeta !== null) {
sf = insertFileOverviewComment(sf, fileOverviewMeta);
}
return sf;
}
function getLocalizeCompileTarget(context) {
const target = context.getCompilerOptions().target || import_typescript45.default.ScriptTarget.ES2015;
return target !== import_typescript45.default.ScriptTarget.JSON ? target : import_typescript45.default.ScriptTarget.ES2015;
}
function getFileOverviewComment(statements) {
if (statements.length > 0) {
const host = statements[0];
let trailing = false;
let comments = import_typescript45.default.getSyntheticLeadingComments(host);
if (!comments || comments.length === 0) {
trailing = true;
comments = import_typescript45.default.getSyntheticTrailingComments(host);
}
if (comments && comments.length > 0 && CLOSURE_FILE_OVERVIEW_REGEXP.test(comments[0].text)) {
return { comments, host, trailing };
}
}
return null;
}
function insertFileOverviewComment(sf, fileoverview) {
const { comments, host, trailing } = fileoverview;
if (sf.statements.length > 0 && host !== sf.statements[0]) {
if (trailing) {
import_typescript45.default.setSyntheticTrailingComments(host, void 0);
} else {
import_typescript45.default.setSyntheticLeadingComments(host, void 0);
}
const commentNode = import_typescript45.default.factory.createNotEmittedStatement(sf);
import_typescript45.default.setSyntheticLeadingComments(commentNode, comments);
return import_typescript45.default.factory.updateSourceFile(sf, [commentNode, ...sf.statements], sf.isDeclarationFile, sf.referencedFiles, sf.typeReferenceDirectives, sf.hasNoDefaultLib, sf.libReferenceDirectives);
}
return sf;
}
function maybeFilterDecorator(decorators, toRemove) {
if (decorators === void 0) {
return void 0;
}
const filtered = decorators.filter((dec) => toRemove.find((decToRemove) => import_typescript45.default.getOriginalNode(dec) === decToRemove) === void 0);
if (filtered.length === 0) {
return void 0;
}
return import_typescript45.default.factory.createNodeArray(filtered);
}
function isFromAngularCore(decorator) {
return decorator.import !== null && decorator.import.from === "@angular/core";
}
function createRecorderFn(defaultImportTracker) {
return (node) => {
const importDecl = getDefaultImportDeclaration(node);
if (importDecl !== null) {
defaultImportTracker.recordUsedImport(importDecl);
}
};
}
function nodeArrayFromDecoratorsArray(decorators) {
const array = import_typescript45.default.factory.createNodeArray(decorators);
if (array.length > 0) {
array.pos = decorators[0].pos;
array.end = decorators[decorators.length - 1].end;
}
return array;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/common/src/diagnostics.mjs
function makeDuplicateDeclarationError(node, data, kind) {
const context = [];
for (const decl of data) {
if (decl.rawDeclarations === null) {
continue;
}
const contextNode = decl.ref.getOriginForDiagnostics(decl.rawDeclarations, decl.ngModule.name);
context.push(makeRelatedInformation(contextNode, `'${node.name.text}' is listed in the declarations of the NgModule '${decl.ngModule.name.text}'.`));
}
return makeDiagnostic(ErrorCode.NGMODULE_DECLARATION_NOT_UNIQUE, node.name, `The ${kind} '${node.name.text}' is declared by more than one NgModule.`, context);
}
function createValueHasWrongTypeError(node, value, messageText) {
var _a2;
let chainedMessage;
let relatedInformation;
if (value instanceof DynamicValue) {
chainedMessage = "Value could not be determined statically.";
relatedInformation = traceDynamicValue(node, value);
} else if (value instanceof Reference2) {
const target = value.debugName !== null ? `'${value.debugName}'` : "an anonymous declaration";
chainedMessage = `Value is a reference to ${target}.`;
const referenceNode = (_a2 = identifierOfNode(value.node)) != null ? _a2 : value.node;
relatedInformation = [makeRelatedInformation(referenceNode, "Reference is declared here.")];
} else {
chainedMessage = `Value is of type '${describeResolvedType(value)}'.`;
}
const chain2 = {
messageText,
category: import_typescript46.default.DiagnosticCategory.Error,
code: 0,
next: [
{
messageText: chainedMessage,
category: import_typescript46.default.DiagnosticCategory.Message,
code: 0
}
]
};
return new FatalDiagnosticError(ErrorCode.VALUE_HAS_WRONG_TYPE, node, chain2, relatedInformation);
}
function getProviderDiagnostics(providerClasses, providersDeclaration, registry) {
const diagnostics = [];
for (const provider of providerClasses) {
const injectableMeta = registry.getInjectableMeta(provider.node);
if (injectableMeta !== null) {
continue;
}
const contextNode = provider.getOriginForDiagnostics(providersDeclaration);
diagnostics.push(makeDiagnostic(ErrorCode.UNDECORATED_PROVIDER, contextNode, `The class '${provider.node.name.text}' cannot be created via dependency injection, as it does not have an Angular decorator. This will result in an error at runtime.
Either add the @Injectable() decorator to '${provider.node.name.text}', or configure a different provider (such as a provider with 'useFactory').
`, [makeRelatedInformation(provider.node, `'${provider.node.name.text}' is declared here.`)]));
}
return diagnostics;
}
function getDirectiveDiagnostics(node, injectableRegistry, evaluator, reflector, scopeRegistry, strictInjectionParameters, kind) {
let diagnostics = [];
const addDiagnostics = (more) => {
if (more === null) {
return;
} else if (diagnostics === null) {
diagnostics = Array.isArray(more) ? more : [more];
} else if (Array.isArray(more)) {
diagnostics.push(...more);
} else {
diagnostics.push(more);
}
};
const duplicateDeclarations = scopeRegistry.getDuplicateDeclarations(node);
if (duplicateDeclarations !== null) {
addDiagnostics(makeDuplicateDeclarationError(node, duplicateDeclarations, kind));
}
addDiagnostics(checkInheritanceOfInjectable(node, injectableRegistry, reflector, evaluator, strictInjectionParameters, kind));
return diagnostics;
}
function validateHostDirectives(origin, hostDirectives, metaReader) {
const diagnostics = [];
for (const current of hostDirectives) {
if (!isHostDirectiveMetaForGlobalMode(current)) {
throw new Error("Impossible state: diagnostics code path for local compilation");
}
const hostMeta = flattenInheritedDirectiveMetadata(metaReader, current.directive);
if (hostMeta === null) {
diagnostics.push(makeDiagnostic(ErrorCode.HOST_DIRECTIVE_INVALID, current.directive.getOriginForDiagnostics(origin), `${current.directive.debugName} must be a standalone directive to be used as a host directive`));
continue;
}
if (!hostMeta.isStandalone) {
diagnostics.push(makeDiagnostic(ErrorCode.HOST_DIRECTIVE_NOT_STANDALONE, current.directive.getOriginForDiagnostics(origin), `Host directive ${hostMeta.name} must be standalone`));
}
if (hostMeta.isComponent) {
diagnostics.push(makeDiagnostic(ErrorCode.HOST_DIRECTIVE_COMPONENT, current.directive.getOriginForDiagnostics(origin), `Host directive ${hostMeta.name} cannot be a component`));
}
const requiredInputNames = Array.from(hostMeta.inputs).filter((input) => input.required).map((input) => input.classPropertyName);
validateHostDirectiveMappings("input", current, hostMeta, origin, diagnostics, requiredInputNames.length > 0 ? new Set(requiredInputNames) : null);
validateHostDirectiveMappings("output", current, hostMeta, origin, diagnostics, null);
}
return diagnostics;
}
function validateHostDirectiveMappings(bindingType, hostDirectiveMeta, meta, origin, diagnostics, requiredBindings) {
if (!isHostDirectiveMetaForGlobalMode(hostDirectiveMeta)) {
throw new Error("Impossible state: diagnostics code path for local compilation");
}
const className = meta.name;
const hostDirectiveMappings = bindingType === "input" ? hostDirectiveMeta.inputs : hostDirectiveMeta.outputs;
const existingBindings = bindingType === "input" ? meta.inputs : meta.outputs;
const exposedRequiredBindings = /* @__PURE__ */ new Set();
for (const publicName in hostDirectiveMappings) {
if (hostDirectiveMappings.hasOwnProperty(publicName)) {
const bindings = existingBindings.getByBindingPropertyName(publicName);
if (bindings === null) {
diagnostics.push(makeDiagnostic(ErrorCode.HOST_DIRECTIVE_UNDEFINED_BINDING, hostDirectiveMeta.directive.getOriginForDiagnostics(origin), `Directive ${className} does not have an ${bindingType} with a public name of ${publicName}.`));
} else if (requiredBindings !== null) {
for (const field of bindings) {
if (requiredBindings.has(field.classPropertyName)) {
exposedRequiredBindings.add(field.classPropertyName);
}
}
}
const remappedPublicName = hostDirectiveMappings[publicName];
const bindingsForPublicName = existingBindings.getByBindingPropertyName(remappedPublicName);
if (bindingsForPublicName !== null) {
for (const binding of bindingsForPublicName) {
if (binding.bindingPropertyName !== publicName) {
diagnostics.push(makeDiagnostic(ErrorCode.HOST_DIRECTIVE_CONFLICTING_ALIAS, hostDirectiveMeta.directive.getOriginForDiagnostics(origin), `Cannot alias ${bindingType} ${publicName} of host directive ${className} to ${remappedPublicName}, because it already has a different ${bindingType} with the same public name.`));
}
}
}
}
}
if (requiredBindings !== null && requiredBindings.size !== exposedRequiredBindings.size) {
const missingBindings = [];
for (const publicName of requiredBindings) {
if (!exposedRequiredBindings.has(publicName)) {
const name = existingBindings.getByClassPropertyName(publicName);
if (name) {
missingBindings.push(`'${name.bindingPropertyName}'`);
}
}
}
diagnostics.push(makeDiagnostic(ErrorCode.HOST_DIRECTIVE_MISSING_REQUIRED_BINDING, hostDirectiveMeta.directive.getOriginForDiagnostics(origin), `Required ${bindingType}${missingBindings.length === 1 ? "" : "s"} ${missingBindings.join(", ")} from host directive ${className} must be exposed.`));
}
}
function getUndecoratedClassWithAngularFeaturesDiagnostic(node) {
return makeDiagnostic(ErrorCode.UNDECORATED_CLASS_USING_ANGULAR_FEATURES, node.name, `Class is using Angular features but is not decorated. Please add an explicit Angular decorator.`);
}
function checkInheritanceOfInjectable(node, injectableRegistry, reflector, evaluator, strictInjectionParameters, kind) {
const classWithCtor = findInheritedCtor(node, injectableRegistry, reflector, evaluator);
if (classWithCtor === null || classWithCtor.isCtorValid) {
return null;
}
if (!classWithCtor.isDecorated) {
return getInheritedUndecoratedCtorDiagnostic(node, classWithCtor.ref, kind);
}
if (isFromDtsFile(classWithCtor.ref.node)) {
return null;
}
if (!strictInjectionParameters || isAbstractClassDeclaration(node)) {
return null;
}
return getInheritedInvalidCtorDiagnostic(node, classWithCtor.ref, kind);
}
function findInheritedCtor(node, injectableRegistry, reflector, evaluator) {
if (!reflector.isClass(node) || reflector.getConstructorParameters(node) !== null) {
return null;
}
let baseClass = readBaseClass(node, reflector, evaluator);
while (baseClass !== null) {
if (baseClass === "dynamic") {
return null;
}
const injectableMeta = injectableRegistry.getInjectableMeta(baseClass.node);
if (injectableMeta !== null) {
if (injectableMeta.ctorDeps !== null) {
return {
ref: baseClass,
isCtorValid: injectableMeta.ctorDeps !== "invalid",
isDecorated: true
};
}
} else {
const baseClassConstructorParams = reflector.getConstructorParameters(baseClass.node);
if (baseClassConstructorParams !== null) {
return {
ref: baseClass,
isCtorValid: baseClassConstructorParams.length === 0,
isDecorated: false
};
}
}
baseClass = readBaseClass(baseClass.node, reflector, evaluator);
}
return null;
}
function getInheritedInvalidCtorDiagnostic(node, baseClass, kind) {
const baseClassName = baseClass.debugName;
return makeDiagnostic(ErrorCode.INJECTABLE_INHERITS_INVALID_CONSTRUCTOR, node.name, `The ${kind.toLowerCase()} ${node.name.text} inherits its constructor from ${baseClassName}, but the latter has a constructor parameter that is not compatible with dependency injection. Either add an explicit constructor to ${node.name.text} or change ${baseClassName}'s constructor to use parameters that are valid for DI.`);
}
function getInheritedUndecoratedCtorDiagnostic(node, baseClass, kind) {
const baseClassName = baseClass.debugName;
const baseNeedsDecorator = kind === "Component" || kind === "Directive" ? "Directive" : "Injectable";
return makeDiagnostic(ErrorCode.DIRECTIVE_INHERITS_UNDECORATED_CTOR, node.name, `The ${kind.toLowerCase()} ${node.name.text} inherits its constructor from ${baseClassName}, but the latter does not have an Angular decorator of its own. Dependency injection will not be able to resolve the parameters of ${baseClassName}'s constructor. Either add a @${baseNeedsDecorator} decorator to ${baseClassName}, or add an explicit constructor to ${node.name.text}.`);
}
function assertLocalCompilationUnresolvedConst(compilationMode, value, nodeToHighlight, errorMessage) {
if (compilationMode === CompilationMode.LOCAL && value instanceof DynamicValue && value.isFromUnknownIdentifier()) {
throw new FatalDiagnosticError(ErrorCode.LOCAL_COMPILATION_UNRESOLVED_CONST, nodeToHighlight != null ? nodeToHighlight : value.node, errorMessage);
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/common/src/evaluation.mjs
var import_typescript48 = __toESM(require("typescript"), 1);
function resolveEnumValue(evaluator, metadata, field, enumSymbolName) {
let resolved = null;
if (metadata.has(field)) {
const expr = metadata.get(field);
const value = evaluator.evaluate(expr);
if (value instanceof EnumValue && isAngularCoreReference(value.enumRef, enumSymbolName)) {
resolved = value.resolved;
} else {
throw createValueHasWrongTypeError(expr, value, `${field} must be a member of ${enumSymbolName} enum from @angular/core`);
}
}
return resolved;
}
function resolveEncapsulationEnumValueLocally(expr) {
if (!expr) {
return null;
}
const exprText = expr.getText().trim();
for (const key in ViewEncapsulation) {
if (!Number.isNaN(Number(key))) {
continue;
}
const suffix = `ViewEncapsulation.${key}`;
if (exprText === suffix || exprText.endsWith(`.${suffix}`)) {
const ans = Number(ViewEncapsulation[key]);
return ans;
}
}
return null;
}
function isStringArray(resolvedValue) {
return Array.isArray(resolvedValue) && resolvedValue.every((elem) => typeof elem === "string");
}
function resolveLiteral(decorator, literalCache) {
if (literalCache.has(decorator)) {
return literalCache.get(decorator);
}
if (decorator.args === null || decorator.args.length !== 1) {
throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, decorator.node, `Incorrect number of arguments to @${decorator.name} decorator`);
}
const meta = unwrapExpression(decorator.args[0]);
if (!import_typescript48.default.isObjectLiteralExpression(meta)) {
throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARG_NOT_LITERAL, meta, `Decorator argument must be literal.`);
}
literalCache.set(decorator, meta);
return meta;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/common/src/factory.mjs
function compileNgFactoryDefField(metadata) {
const res = compileFactoryFunction(metadata);
return {
name: "\u0275fac",
initializer: res.expression,
statements: res.statements,
type: res.type,
deferrableImports: null
};
}
function compileDeclareFactory(metadata) {
const res = compileDeclareFactoryFunction(metadata);
return {
name: "\u0275fac",
initializer: res.expression,
statements: res.statements,
type: res.type,
deferrableImports: null
};
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/common/src/injectable_registry.mjs
var InjectableClassRegistry = class {
constructor(host, isCore) {
this.host = host;
this.isCore = isCore;
this.classes = /* @__PURE__ */ new Map();
}
registerInjectable(declaration, meta) {
this.classes.set(declaration, meta);
}
getInjectableMeta(declaration) {
if (this.classes.has(declaration)) {
return this.classes.get(declaration);
}
if (!hasInjectableFields(declaration, this.host)) {
return null;
}
const ctorDeps = getConstructorDependencies(declaration, this.host, this.isCore);
const meta = {
ctorDeps: unwrapConstructorDependencies(ctorDeps)
};
this.classes.set(declaration, meta);
return meta;
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/common/src/metadata.mjs
var import_typescript49 = __toESM(require("typescript"), 1);
function extractClassMetadata(clazz, reflection, isCore, annotateForClosureCompiler, angularDecoratorTransform = (dec) => dec) {
if (!reflection.isClass(clazz)) {
return null;
}
const id = clazz.name;
const classDecorators = reflection.getDecoratorsOfDeclaration(clazz);
if (classDecorators === null) {
return null;
}
const ngClassDecorators = classDecorators.filter((dec) => isAngularDecorator3(dec, isCore)).map((decorator) => decoratorToMetadata(angularDecoratorTransform(decorator), annotateForClosureCompiler)).map((decorator) => removeIdentifierReferences(decorator, id.text));
if (ngClassDecorators.length === 0) {
return null;
}
const metaDecorators = new WrappedNodeExpr(import_typescript49.default.factory.createArrayLiteralExpression(ngClassDecorators));
let metaCtorParameters = null;
const classCtorParameters = reflection.getConstructorParameters(clazz);
if (classCtorParameters !== null) {
const ctorParameters = classCtorParameters.map((param) => ctorParameterToMetadata(param, isCore));
metaCtorParameters = new ArrowFunctionExpr([], new LiteralArrayExpr(ctorParameters));
}
let metaPropDecorators = null;
const classMembers = reflection.getMembersOfClass(clazz).filter((member) => !member.isStatic && member.decorators !== null && member.decorators.length > 0);
const duplicateDecoratedMemberNames = classMembers.map((member) => member.name).filter((name, i, arr) => arr.indexOf(name) < i);
if (duplicateDecoratedMemberNames.length > 0) {
throw new Error(`Duplicate decorated properties found on class '${clazz.name.text}': ` + duplicateDecoratedMemberNames.join(", "));
}
const decoratedMembers = classMembers.map((member) => {
var _a2;
return classMemberToMetadata((_a2 = member.nameNode) != null ? _a2 : member.name, member.decorators, isCore);
});
if (decoratedMembers.length > 0) {
metaPropDecorators = new WrappedNodeExpr(import_typescript49.default.factory.createObjectLiteralExpression(decoratedMembers));
}
return {
type: new WrappedNodeExpr(id),
decorators: metaDecorators,
ctorParameters: metaCtorParameters,
propDecorators: metaPropDecorators
};
}
function ctorParameterToMetadata(param, isCore) {
const type = param.typeValueReference.kind !== 2 ? valueReferenceToExpression(param.typeValueReference) : new LiteralExpr(void 0);
const mapEntries = [
{ key: "type", value: type, quoted: false }
];
if (param.decorators !== null) {
const ngDecorators = param.decorators.filter((dec) => isAngularDecorator3(dec, isCore)).map((decorator) => decoratorToMetadata(decorator));
const value = new WrappedNodeExpr(import_typescript49.default.factory.createArrayLiteralExpression(ngDecorators));
mapEntries.push({ key: "decorators", value, quoted: false });
}
return literalMap(mapEntries);
}
function classMemberToMetadata(name, decorators, isCore) {
const ngDecorators = decorators.filter((dec) => isAngularDecorator3(dec, isCore)).map((decorator) => decoratorToMetadata(decorator));
const decoratorMeta = import_typescript49.default.factory.createArrayLiteralExpression(ngDecorators);
return import_typescript49.default.factory.createPropertyAssignment(name, decoratorMeta);
}
function decoratorToMetadata(decorator, wrapFunctionsInParens) {
if (decorator.identifier === null) {
throw new Error("Illegal state: synthesized decorator cannot be emitted in class metadata.");
}
const properties = [
import_typescript49.default.factory.createPropertyAssignment("type", decorator.identifier)
];
if (decorator.args !== null && decorator.args.length > 0) {
const args = decorator.args.map((arg) => {
return wrapFunctionsInParens ? wrapFunctionExpressionsInParens(arg) : arg;
});
properties.push(import_typescript49.default.factory.createPropertyAssignment("args", import_typescript49.default.factory.createArrayLiteralExpression(args)));
}
return import_typescript49.default.factory.createObjectLiteralExpression(properties, true);
}
function isAngularDecorator3(decorator, isCore) {
return isCore || decorator.import !== null && decorator.import.from === "@angular/core";
}
function removeIdentifierReferences(node, names) {
const result = import_typescript49.default.transform(node, [
(context) => (root) => import_typescript49.default.visitNode(root, function walk(current) {
return import_typescript49.default.isIdentifier(current) && (typeof names === "string" ? current.text === names : names.has(current.text)) ? import_typescript49.default.factory.createIdentifier(current.text) : import_typescript49.default.visitEachChild(current, walk, context);
})
]);
return result.transformed[0];
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/common/src/debug_info.mjs
var path = __toESM(require("path"), 1);
function extractClassDebugInfo(clazz, reflection, rootDirs, forbidOrphanRendering) {
if (!reflection.isClass(clazz)) {
return null;
}
const srcFile = clazz.getSourceFile();
const srcFileMaybeRelativePath = computeRelativePathIfPossible(srcFile.fileName, rootDirs);
return {
type: new WrappedNodeExpr(clazz.name),
className: literal(clazz.name.getText()),
filePath: srcFileMaybeRelativePath ? literal(srcFileMaybeRelativePath) : null,
lineNumber: literal(srcFile.getLineAndCharacterOfPosition(clazz.name.pos).line + 1),
forbidOrphanRendering
};
}
function computeRelativePathIfPossible(filePath, rootDirs) {
for (const rootDir of rootDirs) {
const rel = path.relative(rootDir, filePath);
if (!rel.startsWith("..")) {
return rel;
}
}
return null;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/common/src/references_registry.mjs
var NoopReferencesRegistry = class {
add(source, ...references) {
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/common/src/schema.mjs
function extractSchemas(rawExpr, evaluator, context) {
const schemas = [];
const result = evaluator.evaluate(rawExpr);
if (!Array.isArray(result)) {
throw createValueHasWrongTypeError(rawExpr, result, `${context}.schemas must be an array`);
}
for (const schemaRef of result) {
if (!(schemaRef instanceof Reference2)) {
throw createValueHasWrongTypeError(rawExpr, result, `${context}.schemas must be an array of schemas`);
}
const id = schemaRef.getIdentityIn(schemaRef.node.getSourceFile());
if (id === null || schemaRef.ownedByModuleGuess !== "@angular/core") {
throw createValueHasWrongTypeError(rawExpr, result, `${context}.schemas must be an array of schemas`);
}
switch (id.text) {
case "CUSTOM_ELEMENTS_SCHEMA":
schemas.push(CUSTOM_ELEMENTS_SCHEMA);
break;
case "NO_ERRORS_SCHEMA":
schemas.push(NO_ERRORS_SCHEMA);
break;
default:
throw createValueHasWrongTypeError(rawExpr, schemaRef, `'${schemaRef.debugName}' is not a valid ${context} schema`);
}
}
return schemas;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/common/src/input_transforms.mjs
function compileInputTransformFields(inputs) {
const extraFields = [];
for (const input of inputs) {
if (input.transform) {
extraFields.push({
name: `ngAcceptInputType_${input.classPropertyName}`,
type: output_ast_exports.transplantedType(input.transform.type),
statements: [],
initializer: null,
deferrableImports: null
});
}
}
return extraFields;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/common/src/jit_declaration_registry.mjs
var JitDeclarationRegistry = class {
constructor() {
this.jitDeclarations = /* @__PURE__ */ new Set();
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/component/src/handler.mjs
var import_typescript88 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/incremental/semantic_graph/src/api.mjs
var import_typescript50 = __toESM(require("typescript"), 1);
var SemanticSymbol = class {
constructor(decl) {
this.decl = decl;
this.path = absoluteFromSourceFile(decl.getSourceFile());
this.identifier = getSymbolIdentifier(decl);
}
};
function getSymbolIdentifier(decl) {
if (!import_typescript50.default.isSourceFile(decl.parent)) {
return null;
}
return decl.name.text;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/incremental/semantic_graph/src/graph.mjs
var OpaqueSymbol = class extends SemanticSymbol {
isPublicApiAffected() {
return false;
}
isTypeCheckApiAffected() {
return false;
}
};
var SemanticDepGraph = class {
constructor() {
this.files = /* @__PURE__ */ new Map();
this.symbolByDecl = /* @__PURE__ */ new Map();
}
registerSymbol(symbol) {
this.symbolByDecl.set(symbol.decl, symbol);
if (symbol.identifier !== null) {
if (!this.files.has(symbol.path)) {
this.files.set(symbol.path, /* @__PURE__ */ new Map());
}
this.files.get(symbol.path).set(symbol.identifier, symbol);
}
}
getEquivalentSymbol(symbol) {
let previousSymbol = this.getSymbolByDecl(symbol.decl);
if (previousSymbol === null && symbol.identifier !== null) {
previousSymbol = this.getSymbolByName(symbol.path, symbol.identifier);
}
return previousSymbol;
}
getSymbolByName(path4, identifier) {
if (!this.files.has(path4)) {
return null;
}
const file = this.files.get(path4);
if (!file.has(identifier)) {
return null;
}
return file.get(identifier);
}
getSymbolByDecl(decl) {
if (!this.symbolByDecl.has(decl)) {
return null;
}
return this.symbolByDecl.get(decl);
}
};
var SemanticDepGraphUpdater = class {
constructor(priorGraph) {
this.priorGraph = priorGraph;
this.newGraph = new SemanticDepGraph();
this.opaqueSymbols = /* @__PURE__ */ new Map();
}
registerSymbol(symbol) {
this.newGraph.registerSymbol(symbol);
}
finalize() {
if (this.priorGraph === null) {
return {
needsEmit: /* @__PURE__ */ new Set(),
needsTypeCheckEmit: /* @__PURE__ */ new Set(),
newGraph: this.newGraph
};
}
const needsEmit = this.determineInvalidatedFiles(this.priorGraph);
const needsTypeCheckEmit = this.determineInvalidatedTypeCheckFiles(this.priorGraph);
return {
needsEmit,
needsTypeCheckEmit,
newGraph: this.newGraph
};
}
determineInvalidatedFiles(priorGraph) {
const isPublicApiAffected = /* @__PURE__ */ new Set();
for (const symbol of this.newGraph.symbolByDecl.values()) {
const previousSymbol = priorGraph.getEquivalentSymbol(symbol);
if (previousSymbol === null || symbol.isPublicApiAffected(previousSymbol)) {
isPublicApiAffected.add(symbol);
}
}
const needsEmit = /* @__PURE__ */ new Set();
for (const symbol of this.newGraph.symbolByDecl.values()) {
if (symbol.isEmitAffected === void 0) {
continue;
}
const previousSymbol = priorGraph.getEquivalentSymbol(symbol);
if (previousSymbol === null || symbol.isEmitAffected(previousSymbol, isPublicApiAffected)) {
needsEmit.add(symbol.path);
}
}
return needsEmit;
}
determineInvalidatedTypeCheckFiles(priorGraph) {
const isTypeCheckApiAffected = /* @__PURE__ */ new Set();
for (const symbol of this.newGraph.symbolByDecl.values()) {
const previousSymbol = priorGraph.getEquivalentSymbol(symbol);
if (previousSymbol === null || symbol.isTypeCheckApiAffected(previousSymbol)) {
isTypeCheckApiAffected.add(symbol);
}
}
const needsTypeCheckEmit = /* @__PURE__ */ new Set();
for (const symbol of this.newGraph.symbolByDecl.values()) {
if (symbol.isTypeCheckBlockAffected === void 0) {
continue;
}
const previousSymbol = priorGraph.getEquivalentSymbol(symbol);
if (previousSymbol === null || symbol.isTypeCheckBlockAffected(previousSymbol, isTypeCheckApiAffected)) {
needsTypeCheckEmit.add(symbol.path);
}
}
return needsTypeCheckEmit;
}
getSemanticReference(decl, expr) {
return {
symbol: this.getSymbol(decl),
importPath: getImportPath(expr)
};
}
getSymbol(decl) {
const symbol = this.newGraph.getSymbolByDecl(decl);
if (symbol === null) {
return this.getOpaqueSymbol(decl);
}
return symbol;
}
getOpaqueSymbol(decl) {
if (this.opaqueSymbols.has(decl)) {
return this.opaqueSymbols.get(decl);
}
const symbol = new OpaqueSymbol(decl);
this.opaqueSymbols.set(decl, symbol);
return symbol;
}
};
function getImportPath(expr) {
if (expr instanceof ExternalExpr) {
return `${expr.value.moduleName}$${expr.value.name}`;
} else {
return null;
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/incremental/semantic_graph/src/type_parameters.mjs
var import_typescript51 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/incremental/semantic_graph/src/util.mjs
function isSymbolEqual(a, b) {
if (a.decl === b.decl) {
return true;
}
if (a.identifier === null || b.identifier === null) {
return false;
}
return a.path === b.path && a.identifier === b.identifier;
}
function isReferenceEqual(a, b) {
if (!isSymbolEqual(a.symbol, b.symbol)) {
return false;
}
return a.importPath === b.importPath;
}
function referenceEquality(a, b) {
return a === b;
}
function isArrayEqual(a, b, equalityTester = referenceEquality) {
if (a === null || b === null) {
return a === b;
}
if (a.length !== b.length) {
return false;
}
return !a.some((item, index) => !equalityTester(item, b[index]));
}
function isSetEqual(a, b, equalityTester = referenceEquality) {
if (a === null || b === null) {
return a === b;
}
if (a.size !== b.size) {
return false;
}
for (const itemA of a) {
let found = false;
for (const itemB of b) {
if (equalityTester(itemA, itemB)) {
found = true;
break;
}
}
if (!found) {
return false;
}
}
return true;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/incremental/semantic_graph/src/type_parameters.mjs
function extractSemanticTypeParameters(node) {
if (!import_typescript51.default.isClassDeclaration(node) || node.typeParameters === void 0) {
return null;
}
return node.typeParameters.map((typeParam) => ({
hasGenericTypeBound: typeParam.constraint !== void 0
}));
}
function areTypeParametersEqual(current, previous) {
if (!isArrayEqual(current, previous, isTypeParameterEqual)) {
return false;
}
if (current !== null && current.some((typeParam) => typeParam.hasGenericTypeBound)) {
return false;
}
return true;
}
function isTypeParameterEqual(a, b) {
return a.hasGenericTypeBound === b.hasGenericTypeBound;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/scope/src/api.mjs
var ComponentScopeKind;
(function(ComponentScopeKind2) {
ComponentScopeKind2[ComponentScopeKind2["NgModule"] = 0] = "NgModule";
ComponentScopeKind2[ComponentScopeKind2["Standalone"] = 1] = "Standalone";
})(ComponentScopeKind || (ComponentScopeKind = {}));
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/scope/src/component_scope.mjs
var CompoundComponentScopeReader = class {
constructor(readers) {
this.readers = readers;
}
getScopeForComponent(clazz) {
for (const reader of this.readers) {
const meta = reader.getScopeForComponent(clazz);
if (meta !== null) {
return meta;
}
}
return null;
}
getRemoteScope(clazz) {
for (const reader of this.readers) {
const remoteScope = reader.getRemoteScope(clazz);
if (remoteScope !== null) {
return remoteScope;
}
}
return null;
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/scope/src/dependency.mjs
var MetadataDtsModuleScopeResolver = class {
constructor(dtsMetaReader, aliasingHost) {
this.dtsMetaReader = dtsMetaReader;
this.aliasingHost = aliasingHost;
this.cache = /* @__PURE__ */ new Map();
}
resolve(ref) {
const clazz = ref.node;
const sourceFile = clazz.getSourceFile();
if (!sourceFile.isDeclarationFile) {
throw new Error(`Debug error: DtsModuleScopeResolver.read(${ref.debugName} from ${sourceFile.fileName}), but not a .d.ts file`);
}
if (this.cache.has(clazz)) {
return this.cache.get(clazz);
}
const dependencies = [];
const meta = this.dtsMetaReader.getNgModuleMetadata(ref);
if (meta === null) {
this.cache.set(clazz, null);
return null;
}
const declarations = /* @__PURE__ */ new Set();
for (const declRef of meta.declarations) {
declarations.add(declRef.node);
}
for (const exportRef of meta.exports) {
const directive = this.dtsMetaReader.getDirectiveMetadata(exportRef);
if (directive !== null) {
const isReExport = !declarations.has(exportRef.node);
dependencies.push(this.maybeAlias(directive, sourceFile, isReExport));
continue;
}
const pipe2 = this.dtsMetaReader.getPipeMetadata(exportRef);
if (pipe2 !== null) {
const isReExport = !declarations.has(exportRef.node);
dependencies.push(this.maybeAlias(pipe2, sourceFile, isReExport));
continue;
}
const exportScope2 = this.resolve(exportRef);
if (exportScope2 !== null) {
if (this.aliasingHost === null) {
dependencies.push(...exportScope2.exported.dependencies);
} else {
for (const dep of exportScope2.exported.dependencies) {
dependencies.push(this.maybeAlias(dep, sourceFile, true));
}
}
}
continue;
}
const exportScope = {
exported: {
dependencies,
isPoisoned: false
}
};
this.cache.set(clazz, exportScope);
return exportScope;
}
maybeAlias(dirOrPipe, maybeAliasFrom, isReExport) {
const ref = dirOrPipe.ref;
if (this.aliasingHost === null || ref.node.getSourceFile() === maybeAliasFrom) {
return dirOrPipe;
}
const alias = this.aliasingHost.getAliasIn(ref.node, maybeAliasFrom, isReExport);
if (alias === null) {
return dirOrPipe;
}
return __spreadProps(__spreadValues({}, dirOrPipe), {
ref: ref.cloneWithAlias(alias)
});
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/scope/src/local.mjs
var import_typescript52 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/scope/src/util.mjs
function getDiagnosticNode(ref, rawExpr) {
return rawExpr !== null ? ref.getOriginForDiagnostics(rawExpr) : ref.node.name;
}
function makeNotStandaloneDiagnostic(scopeReader, ref, rawExpr, kind) {
const scope = scopeReader.getScopeForComponent(ref.node);
let message = `The ${kind} '${ref.node.name.text}' appears in 'imports', but is not standalone and cannot be imported directly.`;
let relatedInformation = void 0;
if (scope !== null && scope.kind === ComponentScopeKind.NgModule) {
const isExported2 = scope.exported.dependencies.some((dep) => dep.ref.node === ref.node);
const relatedInfoMessageText = isExported2 ? `It can be imported using its '${scope.ngModule.name.text}' NgModule instead.` : `It's declared in the '${scope.ngModule.name.text}' NgModule, but is not exported. Consider exporting it and importing the NgModule instead.`;
relatedInformation = [makeRelatedInformation(scope.ngModule.name, relatedInfoMessageText)];
} else {
}
if (relatedInformation === void 0) {
message += " It must be imported via an NgModule.";
}
return makeDiagnostic(ErrorCode.COMPONENT_IMPORT_NOT_STANDALONE, getDiagnosticNode(ref, rawExpr), message, relatedInformation);
}
function makeUnknownComponentImportDiagnostic(ref, rawExpr) {
return makeDiagnostic(ErrorCode.COMPONENT_UNKNOWN_IMPORT, getDiagnosticNode(ref, rawExpr), `Component imports must be standalone components, directives, pipes, or must be NgModules.`);
}
function makeUnknownComponentDeferredImportDiagnostic(ref, rawExpr) {
return makeDiagnostic(ErrorCode.COMPONENT_UNKNOWN_DEFERRED_IMPORT, getDiagnosticNode(ref, rawExpr), `Component deferred imports must be standalone components, directives or pipes.`);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/scope/src/local.mjs
var LocalModuleScopeRegistry = class {
constructor(localReader, fullReader, dependencyScopeReader, refEmitter, aliasingHost) {
this.localReader = localReader;
this.fullReader = fullReader;
this.dependencyScopeReader = dependencyScopeReader;
this.refEmitter = refEmitter;
this.aliasingHost = aliasingHost;
this.sealed = false;
this.declarationToModule = /* @__PURE__ */ new Map();
this.duplicateDeclarations = /* @__PURE__ */ new Map();
this.moduleToRef = /* @__PURE__ */ new Map();
this.cache = /* @__PURE__ */ new Map();
this.remoteScoping = /* @__PURE__ */ new Map();
this.scopeErrors = /* @__PURE__ */ new Map();
this.modulesWithStructuralErrors = /* @__PURE__ */ new Set();
}
registerNgModuleMetadata(data) {
this.assertCollecting();
const ngModule = data.ref.node;
this.moduleToRef.set(data.ref.node, data.ref);
for (const decl of data.declarations) {
this.registerDeclarationOfModule(ngModule, decl, data.rawDeclarations);
}
}
registerDirectiveMetadata(directive) {
}
registerPipeMetadata(pipe2) {
}
getScopeForComponent(clazz) {
const scope = !this.declarationToModule.has(clazz) ? null : this.getScopeOfModule(this.declarationToModule.get(clazz).ngModule);
return scope;
}
getDuplicateDeclarations(node) {
if (!this.duplicateDeclarations.has(node)) {
return null;
}
return Array.from(this.duplicateDeclarations.get(node).values());
}
getScopeOfModule(clazz) {
return this.moduleToRef.has(clazz) ? this.getScopeOfModuleReference(this.moduleToRef.get(clazz)) : null;
}
getDiagnosticsOfModule(clazz) {
this.getScopeOfModule(clazz);
if (this.scopeErrors.has(clazz)) {
return this.scopeErrors.get(clazz);
} else {
return null;
}
}
registerDeclarationOfModule(ngModule, decl, rawDeclarations) {
const declData = {
ngModule,
ref: decl,
rawDeclarations
};
if (this.duplicateDeclarations.has(decl.node)) {
this.duplicateDeclarations.get(decl.node).set(ngModule, declData);
} else if (this.declarationToModule.has(decl.node) && this.declarationToModule.get(decl.node).ngModule !== ngModule) {
const duplicateDeclMap = /* @__PURE__ */ new Map();
const firstDeclData = this.declarationToModule.get(decl.node);
this.modulesWithStructuralErrors.add(firstDeclData.ngModule);
this.modulesWithStructuralErrors.add(ngModule);
duplicateDeclMap.set(firstDeclData.ngModule, firstDeclData);
duplicateDeclMap.set(ngModule, declData);
this.duplicateDeclarations.set(decl.node, duplicateDeclMap);
this.declarationToModule.delete(decl.node);
} else {
this.declarationToModule.set(decl.node, declData);
}
}
getScopeOfModuleReference(ref) {
if (this.cache.has(ref.node)) {
return this.cache.get(ref.node);
}
this.sealed = true;
const ngModule = this.localReader.getNgModuleMetadata(ref);
if (ngModule === null) {
this.cache.set(ref.node, null);
return null;
}
const diagnostics = [];
const compilationDirectives = /* @__PURE__ */ new Map();
const compilationPipes = /* @__PURE__ */ new Map();
const declared = /* @__PURE__ */ new Set();
const exportDirectives = /* @__PURE__ */ new Map();
const exportPipes = /* @__PURE__ */ new Map();
let isPoisoned = false;
if (this.modulesWithStructuralErrors.has(ngModule.ref.node)) {
isPoisoned = true;
}
for (const decl of ngModule.imports) {
const importScope = this.getExportedScope(decl, diagnostics, ref.node, "import");
if (importScope !== null) {
if (importScope === "invalid" || importScope.exported.isPoisoned) {
diagnostics.push(invalidTransitiveNgModuleRef(decl, ngModule.rawImports, "import"));
isPoisoned = true;
if (importScope === "invalid") {
continue;
}
}
for (const dep of importScope.exported.dependencies) {
if (dep.kind === MetaKind.Directive) {
compilationDirectives.set(dep.ref.node, dep);
} else if (dep.kind === MetaKind.Pipe) {
compilationPipes.set(dep.ref.node, dep);
}
}
continue;
}
const directive = this.fullReader.getDirectiveMetadata(decl);
if (directive !== null) {
if (directive.isStandalone) {
compilationDirectives.set(directive.ref.node, directive);
} else {
diagnostics.push(makeNotStandaloneDiagnostic(this, decl, ngModule.rawImports, directive.isComponent ? "component" : "directive"));
isPoisoned = true;
}
continue;
}
const pipe2 = this.fullReader.getPipeMetadata(decl);
if (pipe2 !== null) {
if (pipe2.isStandalone) {
compilationPipes.set(pipe2.ref.node, pipe2);
} else {
diagnostics.push(makeNotStandaloneDiagnostic(this, decl, ngModule.rawImports, "pipe"));
isPoisoned = true;
}
continue;
}
diagnostics.push(invalidRef(decl, ngModule.rawImports, "import"));
isPoisoned = true;
}
for (const decl of ngModule.declarations) {
const directive = this.localReader.getDirectiveMetadata(decl);
const pipe2 = this.localReader.getPipeMetadata(decl);
if (directive !== null) {
if (directive.isStandalone) {
const refType = directive.isComponent ? "Component" : "Directive";
diagnostics.push(makeDiagnostic(ErrorCode.NGMODULE_DECLARATION_IS_STANDALONE, decl.getOriginForDiagnostics(ngModule.rawDeclarations), `${refType} ${decl.node.name.text} is standalone, and cannot be declared in an NgModule. Did you mean to import it instead?`));
isPoisoned = true;
continue;
}
compilationDirectives.set(decl.node, __spreadProps(__spreadValues({}, directive), { ref: decl }));
if (directive.isPoisoned) {
isPoisoned = true;
}
} else if (pipe2 !== null) {
if (pipe2.isStandalone) {
diagnostics.push(makeDiagnostic(ErrorCode.NGMODULE_DECLARATION_IS_STANDALONE, decl.getOriginForDiagnostics(ngModule.rawDeclarations), `Pipe ${decl.node.name.text} is standalone, and cannot be declared in an NgModule. Did you mean to import it instead?`));
isPoisoned = true;
continue;
}
compilationPipes.set(decl.node, __spreadProps(__spreadValues({}, pipe2), { ref: decl }));
} else {
const errorNode = decl.getOriginForDiagnostics(ngModule.rawDeclarations);
diagnostics.push(makeDiagnostic(ErrorCode.NGMODULE_INVALID_DECLARATION, errorNode, `The class '${decl.node.name.text}' is listed in the declarations of the NgModule '${ngModule.ref.node.name.text}', but is not a directive, a component, or a pipe. Either remove it from the NgModule's declarations, or add an appropriate Angular decorator.`, [makeRelatedInformation(decl.node.name, `'${decl.node.name.text}' is declared here.`)]));
isPoisoned = true;
continue;
}
declared.add(decl.node);
}
for (const decl of ngModule.exports) {
const exportScope = this.getExportedScope(decl, diagnostics, ref.node, "export");
if (exportScope === "invalid" || exportScope !== null && exportScope.exported.isPoisoned) {
diagnostics.push(invalidTransitiveNgModuleRef(decl, ngModule.rawExports, "export"));
isPoisoned = true;
if (exportScope === "invalid") {
continue;
}
} else if (exportScope !== null) {
for (const dep of exportScope.exported.dependencies) {
if (dep.kind == MetaKind.Directive) {
exportDirectives.set(dep.ref.node, dep);
} else if (dep.kind === MetaKind.Pipe) {
exportPipes.set(dep.ref.node, dep);
}
}
} else if (compilationDirectives.has(decl.node)) {
const directive = compilationDirectives.get(decl.node);
exportDirectives.set(decl.node, directive);
} else if (compilationPipes.has(decl.node)) {
const pipe2 = compilationPipes.get(decl.node);
exportPipes.set(decl.node, pipe2);
} else {
const dirMeta = this.fullReader.getDirectiveMetadata(decl);
const pipeMeta = this.fullReader.getPipeMetadata(decl);
if (dirMeta !== null || pipeMeta !== null) {
const isStandalone = dirMeta !== null ? dirMeta.isStandalone : pipeMeta.isStandalone;
diagnostics.push(invalidReexport(decl, ngModule.rawExports, isStandalone));
} else {
diagnostics.push(invalidRef(decl, ngModule.rawExports, "export"));
}
isPoisoned = true;
continue;
}
}
const exported = {
dependencies: [...exportDirectives.values(), ...exportPipes.values()],
isPoisoned
};
const reexports = this.getReexports(ngModule, ref, declared, exported.dependencies, diagnostics);
const scope = {
kind: ComponentScopeKind.NgModule,
ngModule: ngModule.ref.node,
compilation: {
dependencies: [...compilationDirectives.values(), ...compilationPipes.values()],
isPoisoned
},
exported,
reexports,
schemas: ngModule.schemas
};
if (diagnostics.length > 0) {
this.scopeErrors.set(ref.node, diagnostics);
this.modulesWithStructuralErrors.add(ref.node);
}
this.cache.set(ref.node, scope);
return scope;
}
getRemoteScope(node) {
return this.remoteScoping.has(node) ? this.remoteScoping.get(node) : null;
}
setComponentRemoteScope(node, directives, pipes) {
this.remoteScoping.set(node, { directives, pipes });
}
getExportedScope(ref, diagnostics, ownerForErrors, type) {
if (ref.node.getSourceFile().isDeclarationFile) {
if (!import_typescript52.default.isClassDeclaration(ref.node)) {
const code = type === "import" ? ErrorCode.NGMODULE_INVALID_IMPORT : ErrorCode.NGMODULE_INVALID_EXPORT;
diagnostics.push(makeDiagnostic(code, identifierOfNode(ref.node) || ref.node, `Appears in the NgModule.${type}s of ${nodeNameForError(ownerForErrors)}, but could not be resolved to an NgModule`));
return "invalid";
}
return this.dependencyScopeReader.resolve(ref);
} else {
return this.getScopeOfModuleReference(ref);
}
}
getReexports(ngModule, ref, declared, exported, diagnostics) {
let reexports = null;
const sourceFile = ref.node.getSourceFile();
if (this.aliasingHost === null) {
return null;
}
reexports = [];
const reexportMap = /* @__PURE__ */ new Map();
const ngModuleRef = ref;
const addReexport = (exportRef) => {
if (exportRef.node.getSourceFile() === sourceFile) {
return;
}
const isReExport = !declared.has(exportRef.node);
const exportName = this.aliasingHost.maybeAliasSymbolAs(exportRef, sourceFile, ngModule.ref.node.name.text, isReExport);
if (exportName === null) {
return;
}
if (!reexportMap.has(exportName)) {
if (exportRef.alias && exportRef.alias instanceof ExternalExpr) {
reexports.push({
fromModule: exportRef.alias.value.moduleName,
symbolName: exportRef.alias.value.name,
asAlias: exportName
});
} else {
const emittedRef = this.refEmitter.emit(exportRef.cloneWithNoIdentifiers(), sourceFile);
assertSuccessfulReferenceEmit(emittedRef, ngModuleRef.node.name, "class");
const expr = emittedRef.expression;
if (!(expr instanceof ExternalExpr) || expr.value.moduleName === null || expr.value.name === null) {
throw new Error("Expected ExternalExpr");
}
reexports.push({
fromModule: expr.value.moduleName,
symbolName: expr.value.name,
asAlias: exportName
});
}
reexportMap.set(exportName, exportRef);
} else {
const prevRef = reexportMap.get(exportName);
diagnostics.push(reexportCollision(ngModuleRef.node, prevRef, exportRef));
}
};
for (const { ref: ref2 } of exported) {
addReexport(ref2);
}
return reexports;
}
assertCollecting() {
if (this.sealed) {
throw new Error(`Assertion: LocalModuleScopeRegistry is not COLLECTING`);
}
}
};
function invalidRef(decl, rawExpr, type) {
const code = type === "import" ? ErrorCode.NGMODULE_INVALID_IMPORT : ErrorCode.NGMODULE_INVALID_EXPORT;
const resolveTarget = type === "import" ? "NgModule" : "NgModule, Component, Directive, or Pipe";
const message = `'${decl.node.name.text}' does not appear to be an ${resolveTarget} class.`;
const library = decl.ownedByModuleGuess !== null ? ` (${decl.ownedByModuleGuess})` : "";
const sf = decl.node.getSourceFile();
let relatedMessage;
if (!sf.isDeclarationFile) {
const annotationType = type === "import" ? "@NgModule" : "Angular";
relatedMessage = `Is it missing an ${annotationType} annotation?`;
} else if (sf.fileName.indexOf("node_modules") !== -1) {
relatedMessage = `This likely means that the library${library} which declares ${decl.debugName} is not compatible with Angular Ivy. Check if a newer version of the library is available, and update if so. Also consider checking with the library's authors to see if the library is expected to be compatible with Ivy.`;
} else {
relatedMessage = `This likely means that the dependency${library} which declares ${decl.debugName} is not compatible with Angular Ivy.`;
}
return makeDiagnostic(code, getDiagnosticNode(decl, rawExpr), message, [
makeRelatedInformation(decl.node.name, relatedMessage)
]);
}
function invalidTransitiveNgModuleRef(decl, rawExpr, type) {
const code = type === "import" ? ErrorCode.NGMODULE_INVALID_IMPORT : ErrorCode.NGMODULE_INVALID_EXPORT;
return makeDiagnostic(code, getDiagnosticNode(decl, rawExpr), `This ${type} contains errors, which may affect components that depend on this NgModule.`);
}
function invalidReexport(decl, rawExpr, isStandalone) {
let message = `Can't be exported from this NgModule, as `;
if (isStandalone) {
message += "it must be imported first";
} else if (decl.node.getSourceFile().isDeclarationFile) {
message += "it must be imported via its NgModule first";
} else {
message += "it must be either declared by this NgModule, or imported here via its NgModule first";
}
return makeDiagnostic(ErrorCode.NGMODULE_INVALID_REEXPORT, getDiagnosticNode(decl, rawExpr), message);
}
function reexportCollision(module2, refA, refB) {
const childMessageText = `This directive/pipe is part of the exports of '${module2.name.text}' and shares the same name as another exported directive/pipe.`;
return makeDiagnostic(ErrorCode.NGMODULE_REEXPORT_NAME_COLLISION, module2.name, `
There was a name collision between two classes named '${refA.node.name.text}', which are both part of the exports of '${module2.name.text}'.
Angular generates re-exports of an NgModule's exported directives/pipes from the module's source file in certain cases, using the declared name of the class. If two classes of the same name are exported, this automatic naming does not work.
To fix this problem please re-export one or both classes directly from this file.
`.trim(), [
makeRelatedInformation(refA.node.name, childMessageText),
makeRelatedInformation(refB.node.name, childMessageText)
]);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/scope/src/typecheck.mjs
var import_typescript54 = __toESM(require("typescript"), 1);
var TypeCheckScopeRegistry = class {
constructor(scopeReader, metaReader, hostDirectivesResolver) {
this.scopeReader = scopeReader;
this.metaReader = metaReader;
this.hostDirectivesResolver = hostDirectivesResolver;
this.flattenedDirectiveMetaCache = /* @__PURE__ */ new Map();
this.scopeCache = /* @__PURE__ */ new Map();
}
getTypeCheckScope(node) {
const matcher = new SelectorMatcher();
const directives = [];
const pipes = /* @__PURE__ */ new Map();
const scope = this.scopeReader.getScopeForComponent(node);
if (scope === null) {
return {
matcher,
directives,
pipes,
schemas: [],
isPoisoned: false
};
}
const isNgModuleScope = scope.kind === ComponentScopeKind.NgModule;
const cacheKey = isNgModuleScope ? scope.ngModule : scope.component;
const dependencies = isNgModuleScope ? scope.compilation.dependencies : scope.dependencies;
if (this.scopeCache.has(cacheKey)) {
return this.scopeCache.get(cacheKey);
}
let allDependencies = dependencies;
if (!isNgModuleScope && Array.isArray(scope.deferredDependencies) && scope.deferredDependencies.length > 0) {
allDependencies = [...allDependencies, ...scope.deferredDependencies];
}
for (const meta of allDependencies) {
if (meta.kind === MetaKind.Directive && meta.selector !== null) {
const extMeta = this.getTypeCheckDirectiveMetadata(meta.ref);
if (extMeta === null) {
continue;
}
const directiveMeta = this.applyExplicitlyDeferredFlag(extMeta, meta.isExplicitlyDeferred);
matcher.addSelectables(CssSelector.parse(meta.selector), [
...this.hostDirectivesResolver.resolve(directiveMeta),
directiveMeta
]);
directives.push(directiveMeta);
} else if (meta.kind === MetaKind.Pipe) {
if (!import_typescript54.default.isClassDeclaration(meta.ref.node)) {
throw new Error(`Unexpected non-class declaration ${import_typescript54.default.SyntaxKind[meta.ref.node.kind]} for pipe ${meta.ref.debugName}`);
}
pipes.set(meta.name, meta);
}
}
const typeCheckScope = {
matcher,
directives,
pipes,
schemas: scope.schemas,
isPoisoned: scope.kind === ComponentScopeKind.NgModule ? scope.compilation.isPoisoned || scope.exported.isPoisoned : scope.isPoisoned
};
this.scopeCache.set(cacheKey, typeCheckScope);
return typeCheckScope;
}
getTypeCheckDirectiveMetadata(ref) {
const clazz = ref.node;
if (this.flattenedDirectiveMetaCache.has(clazz)) {
return this.flattenedDirectiveMetaCache.get(clazz);
}
const meta = flattenInheritedDirectiveMetadata(this.metaReader, ref);
if (meta === null) {
return null;
}
this.flattenedDirectiveMetaCache.set(clazz, meta);
return meta;
}
applyExplicitlyDeferredFlag(meta, isExplicitlyDeferred) {
return isExplicitlyDeferred === true ? __spreadProps(__spreadValues({}, meta), { isExplicitlyDeferred }) : meta;
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/directive/src/shared.mjs
var import_typescript58 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/directive/src/initializer_function_access.mjs
function validateAccessOfInitializerApiMember({ api, call: call2 }, member) {
if (!api.allowedAccessLevels.includes(member.accessLevel)) {
throw new FatalDiagnosticError(ErrorCode.INITIALIZER_API_DISALLOWED_MEMBER_VISIBILITY, call2, makeDiagnosticChain(`Cannot use "${api.functionName}" on a class member that is declared as ${classMemberAccessLevelToString(member.accessLevel)}.`, [
makeDiagnosticChain(`Update the class field to be either: ` + api.allowedAccessLevels.map((l) => classMemberAccessLevelToString(l)).join(", "))
]));
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/directive/src/initializer_functions.mjs
var import_typescript55 = __toESM(require("typescript"), 1);
function tryParseInitializerApi(functions, expression, reflector, importTracker) {
if (!import_typescript55.default.isCallExpression(expression)) {
return null;
}
const staticResult = parseTopLevelCall(expression, functions, importTracker) || parseTopLevelRequiredCall(expression, functions, importTracker) || parseTopLevelCallFromNamespace(expression, functions, importTracker);
if (staticResult === null) {
return null;
}
const { api, apiReference, isRequired } = staticResult;
const resolvedImport = reflector.getImportOfIdentifier(apiReference);
if (resolvedImport === null || api.functionName !== resolvedImport.name || api.owningModule !== resolvedImport.from) {
return null;
}
return {
api,
call: expression,
isRequired
};
}
function parseTopLevelCall(call2, functions, importTracker) {
const node = call2.expression;
if (!import_typescript55.default.isIdentifier(node)) {
return null;
}
const matchingApi = functions.find((fn2) => importTracker.isPotentialReferenceToNamedImport(node, fn2.functionName, fn2.owningModule));
if (matchingApi === void 0) {
return null;
}
return { api: matchingApi, apiReference: node, isRequired: false };
}
function parseTopLevelRequiredCall(call2, functions, importTracker) {
const node = call2.expression;
if (!import_typescript55.default.isPropertyAccessExpression(node) || !import_typescript55.default.isIdentifier(node.expression) || node.name.text !== "required") {
return null;
}
const expression = node.expression;
const matchingApi = functions.find((fn2) => importTracker.isPotentialReferenceToNamedImport(expression, fn2.functionName, fn2.owningModule));
if (matchingApi === void 0) {
return null;
}
return { api: matchingApi, apiReference: expression, isRequired: true };
}
function parseTopLevelCallFromNamespace(call2, functions, importTracker) {
const node = call2.expression;
if (!import_typescript55.default.isPropertyAccessExpression(node)) {
return null;
}
let apiReference = null;
let matchingApi = void 0;
let isRequired = false;
if (import_typescript55.default.isIdentifier(node.expression) && import_typescript55.default.isIdentifier(node.name)) {
const namespaceRef = node.expression;
apiReference = node.name;
matchingApi = functions.find((fn2) => node.name.text === fn2.functionName && importTracker.isPotentialReferenceToNamespaceImport(namespaceRef, fn2.owningModule));
} else if (import_typescript55.default.isPropertyAccessExpression(node.expression) && import_typescript55.default.isIdentifier(node.expression.expression) && import_typescript55.default.isIdentifier(node.expression.name) && node.name.text === "required") {
const potentialName = node.expression.name.text;
const namespaceRef = node.expression.expression;
apiReference = node.expression.name;
matchingApi = functions.find((fn2) => fn2.functionName === potentialName && importTracker.isPotentialReferenceToNamespaceImport(namespaceRef, fn2.owningModule));
isRequired = true;
}
if (matchingApi === void 0 || apiReference === null) {
return null;
}
return { api: matchingApi, apiReference, isRequired };
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/directive/src/input_output_parse_options.mjs
var import_typescript56 = __toESM(require("typescript"), 1);
function parseAndValidateInputAndOutputOptions(optionsNode) {
if (!import_typescript56.default.isObjectLiteralExpression(optionsNode)) {
throw new FatalDiagnosticError(ErrorCode.VALUE_HAS_WRONG_TYPE, optionsNode, "Argument needs to be an object literal that is statically analyzable.");
}
const options = reflectObjectLiteral(optionsNode);
let alias = void 0;
if (options.has("alias")) {
const aliasExpr = options.get("alias");
if (!import_typescript56.default.isStringLiteralLike(aliasExpr)) {
throw new FatalDiagnosticError(ErrorCode.VALUE_HAS_WRONG_TYPE, aliasExpr, "Alias needs to be a string that is statically analyzable.");
}
alias = aliasExpr.text;
}
return { alias };
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/directive/src/input_function.mjs
var INPUT_INITIALIZER_FN = {
functionName: "input",
owningModule: "@angular/core",
allowedAccessLevels: [
ClassMemberAccessLevel.PublicWritable,
ClassMemberAccessLevel.PublicReadonly,
ClassMemberAccessLevel.Protected
]
};
function tryParseSignalInputMapping(member, reflector, importTracker) {
var _a2;
if (member.value === null) {
return null;
}
const signalInput = tryParseInitializerApi([INPUT_INITIALIZER_FN], member.value, reflector, importTracker);
if (signalInput === null) {
return null;
}
validateAccessOfInitializerApiMember(signalInput, member);
const optionsNode = signalInput.isRequired ? signalInput.call.arguments[0] : signalInput.call.arguments[1];
const options = optionsNode !== void 0 ? parseAndValidateInputAndOutputOptions(optionsNode) : null;
const classPropertyName = member.name;
return {
isSignal: true,
classPropertyName,
bindingPropertyName: (_a2 = options == null ? void 0 : options.alias) != null ? _a2 : classPropertyName,
required: signalInput.isRequired,
transform: null
};
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/directive/src/model_function.mjs
var MODEL_INITIALIZER_FN = {
functionName: "model",
owningModule: "@angular/core",
allowedAccessLevels: [
ClassMemberAccessLevel.PublicWritable,
ClassMemberAccessLevel.PublicReadonly,
ClassMemberAccessLevel.Protected
]
};
function tryParseSignalModelMapping(member, reflector, importTracker) {
var _a2;
if (member.value === null) {
return null;
}
const model = tryParseInitializerApi([MODEL_INITIALIZER_FN], member.value, reflector, importTracker);
if (model === null) {
return null;
}
validateAccessOfInitializerApiMember(model, member);
const optionsNode = model.isRequired ? model.call.arguments[0] : model.call.arguments[1];
const options = optionsNode !== void 0 ? parseAndValidateInputAndOutputOptions(optionsNode) : null;
const classPropertyName = member.name;
const bindingPropertyName = (_a2 = options == null ? void 0 : options.alias) != null ? _a2 : classPropertyName;
return {
call: model.call,
input: {
isSignal: true,
transform: null,
classPropertyName,
bindingPropertyName,
required: model.isRequired
},
output: {
isSignal: false,
classPropertyName,
bindingPropertyName: bindingPropertyName + "Change"
}
};
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/directive/src/output_function.mjs
var allowedAccessLevels = [
ClassMemberAccessLevel.PublicWritable,
ClassMemberAccessLevel.PublicReadonly,
ClassMemberAccessLevel.Protected
];
var OUTPUT_INITIALIZER_FNS = [
{
functionName: "output",
owningModule: "@angular/core",
allowedAccessLevels
},
{
functionName: "outputFromObservable",
owningModule: "@angular/core/rxjs-interop",
allowedAccessLevels
}
];
function tryParseInitializerBasedOutput(member, reflector, importTracker) {
var _a2;
if (member.value === null) {
return null;
}
const output = tryParseInitializerApi(OUTPUT_INITIALIZER_FNS, member.value, reflector, importTracker);
if (output === null) {
return null;
}
if (output.isRequired) {
throw new FatalDiagnosticError(ErrorCode.INITIALIZER_API_NO_REQUIRED_FUNCTION, output.call, `Output does not support ".required()".`);
}
validateAccessOfInitializerApiMember(output, member);
const optionsNode = output.api.functionName === "output" ? output.call.arguments[0] : output.call.arguments[1];
const options = optionsNode !== void 0 ? parseAndValidateInputAndOutputOptions(optionsNode) : null;
const classPropertyName = member.name;
return {
call: output.call,
metadata: {
isSignal: false,
classPropertyName,
bindingPropertyName: (_a2 = options == null ? void 0 : options.alias) != null ? _a2 : classPropertyName
}
};
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/directive/src/query_functions.mjs
var import_typescript57 = __toESM(require("typescript"), 1);
var queryFunctionNames = [
"viewChild",
"viewChildren",
"contentChild",
"contentChildren"
];
var QUERY_INITIALIZER_FNS = queryFunctionNames.map((fnName) => ({
functionName: fnName,
owningModule: "@angular/core",
allowedAccessLevels: [
ClassMemberAccessLevel.PublicWritable,
ClassMemberAccessLevel.PublicReadonly,
ClassMemberAccessLevel.Protected,
ClassMemberAccessLevel.Private
]
}));
var defaultDescendantsValue = (type) => type !== "contentChildren";
function tryParseSignalQueryFromInitializer(member, reflector, importTracker) {
if (member.value === null) {
return null;
}
const query = tryParseInitializerApi(QUERY_INITIALIZER_FNS, member.value, reflector, importTracker);
if (query === null) {
return null;
}
validateAccessOfInitializerApiMember(query, member);
const { functionName } = query.api;
const isSingleQuery = functionName === "viewChild" || functionName === "contentChild";
const predicateNode = query.call.arguments[0];
if (predicateNode === void 0) {
throw new FatalDiagnosticError(ErrorCode.VALUE_HAS_WRONG_TYPE, query.call, "No locator specified.");
}
const optionsNode = query.call.arguments[1];
if (optionsNode !== void 0 && !import_typescript57.default.isObjectLiteralExpression(optionsNode)) {
throw new FatalDiagnosticError(ErrorCode.VALUE_HAS_WRONG_TYPE, optionsNode, "Argument needs to be an object literal.");
}
const options = optionsNode && reflectObjectLiteral(optionsNode);
const read = (options == null ? void 0 : options.has("read")) ? parseReadOption(options.get("read")) : null;
const descendants = (options == null ? void 0 : options.has("descendants")) ? parseDescendantsOption(options.get("descendants")) : defaultDescendantsValue(functionName);
return {
name: functionName,
call: query.call,
metadata: {
isSignal: true,
propertyName: member.name,
static: false,
emitDistinctChangesOnly: true,
predicate: parseLocator(predicateNode, reflector),
first: isSingleQuery,
read,
descendants
}
};
}
function parseLocator(expression, reflector) {
const unwrappedExpression = tryUnwrapForwardRef(expression, reflector);
if (unwrappedExpression !== null) {
expression = unwrappedExpression;
}
if (import_typescript57.default.isStringLiteralLike(expression)) {
return [expression.text];
}
return createMayBeForwardRefExpression(new output_ast_exports.WrappedNodeExpr(expression), unwrappedExpression !== null ? 2 : 0);
}
function parseReadOption(value) {
if (import_typescript57.default.isExpressionWithTypeArguments(value) || import_typescript57.default.isParenthesizedExpression(value) || import_typescript57.default.isAsExpression(value)) {
return parseReadOption(value.expression);
}
if (import_typescript57.default.isPropertyAccessExpression(value) && import_typescript57.default.isIdentifier(value.expression) || import_typescript57.default.isIdentifier(value)) {
return new output_ast_exports.WrappedNodeExpr(value);
}
throw new FatalDiagnosticError(ErrorCode.VALUE_NOT_LITERAL, value, `Query "read" option expected a literal class reference.`);
}
function parseDescendantsOption(value) {
if (value.kind === import_typescript57.default.SyntaxKind.TrueKeyword) {
return true;
} else if (value.kind === import_typescript57.default.SyntaxKind.FalseKeyword) {
return false;
}
throw new FatalDiagnosticError(ErrorCode.VALUE_HAS_WRONG_TYPE, value, `Expected "descendants" option to be a boolean literal.`);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/directive/src/shared.mjs
var EMPTY_OBJECT = {};
var queryDecoratorNames = [
"ViewChild",
"ViewChildren",
"ContentChild",
"ContentChildren"
];
var QUERY_TYPES = new Set(queryDecoratorNames);
function extractDirectiveMetadata(clazz, decorator, reflector, importTracker, evaluator, refEmitter, referencesRegistry, isCore, annotateForClosureCompiler, compilationMode, defaultSelector) {
let directive;
if (decorator.args === null || decorator.args.length === 0) {
directive = /* @__PURE__ */ new Map();
} else if (decorator.args.length !== 1) {
throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, decorator.node, `Incorrect number of arguments to @${decorator.name} decorator`);
} else {
const meta = unwrapExpression(decorator.args[0]);
if (!import_typescript58.default.isObjectLiteralExpression(meta)) {
throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARG_NOT_LITERAL, meta, `@${decorator.name} argument must be an object literal`);
}
directive = reflectObjectLiteral(meta);
}
if (directive.has("jit")) {
return { jitForced: true };
}
const members = reflector.getMembersOfClass(clazz);
const decoratedElements = members.filter((member) => !member.isStatic && member.decorators !== null);
const coreModule = isCore ? void 0 : "@angular/core";
const inputsFromMeta = parseInputsArray2(clazz, directive, evaluator, reflector, refEmitter, compilationMode);
const inputsFromFields = parseInputFields(clazz, members, evaluator, reflector, importTracker, refEmitter, isCore, compilationMode, inputsFromMeta, decorator);
const inputs = ClassPropertyMapping.fromMappedObject(__spreadValues(__spreadValues({}, inputsFromMeta), inputsFromFields));
const outputsFromMeta = parseOutputsArray(directive, evaluator);
const outputsFromFields = parseOutputFields(clazz, decorator, members, isCore, reflector, importTracker, evaluator, outputsFromMeta);
const outputs = ClassPropertyMapping.fromMappedObject(__spreadValues(__spreadValues({}, outputsFromMeta), outputsFromFields));
const { viewQueries, contentQueries } = parseQueriesOfClassFields(members, reflector, importTracker, evaluator, isCore);
if (directive.has("queries")) {
const signalQueryFields = new Set([...viewQueries, ...contentQueries].filter((q) => q.isSignal).map((q) => q.propertyName));
const queriesFromDecorator = extractQueriesFromDecorator(directive.get("queries"), reflector, evaluator, isCore);
const checkAndUnwrapQuery = (q) => {
if (signalQueryFields.has(q.metadata.propertyName)) {
throw new FatalDiagnosticError(ErrorCode.INITIALIZER_API_DECORATOR_METADATA_COLLISION, q.expr, `Query is declared multiple times. "@${decorator.name}" declares a query for the same property.`);
}
return q.metadata;
};
contentQueries.push(...queriesFromDecorator.content.map((q) => checkAndUnwrapQuery(q)));
viewQueries.push(...queriesFromDecorator.view.map((q) => checkAndUnwrapQuery(q)));
}
let selector = defaultSelector;
if (directive.has("selector")) {
const expr = directive.get("selector");
const resolved = evaluator.evaluate(expr);
assertLocalCompilationUnresolvedConst(compilationMode, resolved, null, "Unresolved identifier found for @Component.selector field! Did you import this identifier from a file outside of the compilation unit? This is not allowed when Angular compiler runs in local mode. Possible solutions: 1) Move the declarations into a file within the compilation unit, 2) Inline the selector");
if (typeof resolved !== "string") {
throw createValueHasWrongTypeError(expr, resolved, `selector must be a string`);
}
selector = resolved === "" ? defaultSelector : resolved;
if (!selector) {
throw new FatalDiagnosticError(ErrorCode.DIRECTIVE_MISSING_SELECTOR, expr, `Directive ${clazz.name.text} has no selector, please add it!`);
}
}
const host = extractHostBindings2(decoratedElements, evaluator, coreModule, compilationMode, directive);
const providers = directive.has("providers") ? new WrappedNodeExpr(annotateForClosureCompiler ? wrapFunctionExpressionsInParens(directive.get("providers")) : directive.get("providers")) : null;
const usesOnChanges = members.some((member) => !member.isStatic && member.kind === ClassMemberKind.Method && member.name === "ngOnChanges");
let exportAs = null;
if (directive.has("exportAs")) {
const expr = directive.get("exportAs");
const resolved = evaluator.evaluate(expr);
assertLocalCompilationUnresolvedConst(compilationMode, resolved, null, "Unresolved identifier found for exportAs field! Did you import this identifier from a file outside of the compilation unit? This is not allowed when Angular compiler runs in local mode. Possible solutions: 1) Move the declarations into a file within the compilation unit, 2) Inline the selector");
if (typeof resolved !== "string") {
throw createValueHasWrongTypeError(expr, resolved, `exportAs must be a string`);
}
exportAs = resolved.split(",").map((part) => part.trim());
}
const rawCtorDeps = getConstructorDependencies(clazz, reflector, isCore);
const ctorDeps = selector !== null ? validateConstructorDependencies(clazz, rawCtorDeps) : unwrapConstructorDependencies(rawCtorDeps);
const isStructural = ctorDeps !== null && ctorDeps !== "invalid" && ctorDeps.some((dep) => dep.token instanceof ExternalExpr && dep.token.value.moduleName === "@angular/core" && dep.token.value.name === "TemplateRef");
let isStandalone = false;
if (directive.has("standalone")) {
const expr = directive.get("standalone");
const resolved = evaluator.evaluate(expr);
if (typeof resolved !== "boolean") {
throw createValueHasWrongTypeError(expr, resolved, `standalone flag must be a boolean`);
}
isStandalone = resolved;
}
let isSignal = false;
if (directive.has("signals")) {
const expr = directive.get("signals");
const resolved = evaluator.evaluate(expr);
if (typeof resolved !== "boolean") {
throw createValueHasWrongTypeError(expr, resolved, `signals flag must be a boolean`);
}
isSignal = resolved;
}
const usesInheritance = reflector.hasBaseClass(clazz);
const sourceFile = clazz.getSourceFile();
const type = wrapTypeReference(reflector, clazz);
const rawHostDirectives = directive.get("hostDirectives") || null;
const hostDirectives = rawHostDirectives === null ? null : extractHostDirectives(rawHostDirectives, evaluator, compilationMode);
if (compilationMode !== CompilationMode.LOCAL && hostDirectives !== null) {
referencesRegistry.add(clazz, ...hostDirectives.map((hostDir) => {
if (!isHostDirectiveMetaForGlobalMode(hostDir)) {
throw new Error("Impossible state");
}
return hostDir.directive;
}));
}
const metadata = {
name: clazz.name.text,
deps: ctorDeps,
host: __spreadValues({}, host),
lifecycle: {
usesOnChanges
},
inputs: inputs.toJointMappedObject(toR3InputMetadata),
outputs: outputs.toDirectMappedObject(),
queries: contentQueries,
viewQueries,
selector,
fullInheritance: false,
type,
typeArgumentCount: reflector.getGenericArityOfClass(clazz) || 0,
typeSourceSpan: createSourceSpan(clazz.name),
usesInheritance,
exportAs,
providers,
isStandalone,
isSignal,
hostDirectives: (hostDirectives == null ? void 0 : hostDirectives.map((hostDir) => toHostDirectiveMetadata(hostDir, sourceFile, refEmitter))) || null
};
return {
jitForced: false,
decorator: directive,
metadata,
inputs,
outputs,
isStructural,
hostDirectives,
rawHostDirectives,
inputFieldNamesFromMetadataArray: new Set(Object.values(inputsFromMeta).map((i) => i.classPropertyName))
};
}
function extractDecoratorQueryMetadata(exprNode, name, args, propertyName, reflector, evaluator) {
if (args.length === 0) {
throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, exprNode, `@${name} must have arguments`);
}
const first = name === "ViewChild" || name === "ContentChild";
const forwardReferenceTarget = tryUnwrapForwardRef(args[0], reflector);
const node = forwardReferenceTarget != null ? forwardReferenceTarget : args[0];
const arg = evaluator.evaluate(node);
let isStatic = false;
let predicate = null;
if (arg instanceof Reference2 || arg instanceof DynamicValue) {
predicate = createMayBeForwardRefExpression(new WrappedNodeExpr(node), forwardReferenceTarget !== null ? 2 : 0);
} else if (typeof arg === "string") {
predicate = [arg];
} else if (isStringArrayOrDie(arg, `@${name} predicate`, node)) {
predicate = arg;
} else {
throw createValueHasWrongTypeError(node, arg, `@${name} predicate cannot be interpreted`);
}
let read = null;
let descendants = name !== "ContentChildren";
let emitDistinctChangesOnly = emitDistinctChangesOnlyDefaultValue;
if (args.length === 2) {
const optionsExpr = unwrapExpression(args[1]);
if (!import_typescript58.default.isObjectLiteralExpression(optionsExpr)) {
throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARG_NOT_LITERAL, optionsExpr, `@${name} options must be an object literal`);
}
const options = reflectObjectLiteral(optionsExpr);
if (options.has("read")) {
read = new WrappedNodeExpr(options.get("read"));
}
if (options.has("descendants")) {
const descendantsExpr = options.get("descendants");
const descendantsValue = evaluator.evaluate(descendantsExpr);
if (typeof descendantsValue !== "boolean") {
throw createValueHasWrongTypeError(descendantsExpr, descendantsValue, `@${name} options.descendants must be a boolean`);
}
descendants = descendantsValue;
}
if (options.has("emitDistinctChangesOnly")) {
const emitDistinctChangesOnlyExpr = options.get("emitDistinctChangesOnly");
const emitDistinctChangesOnlyValue = evaluator.evaluate(emitDistinctChangesOnlyExpr);
if (typeof emitDistinctChangesOnlyValue !== "boolean") {
throw createValueHasWrongTypeError(emitDistinctChangesOnlyExpr, emitDistinctChangesOnlyValue, `@${name} options.emitDistinctChangesOnly must be a boolean`);
}
emitDistinctChangesOnly = emitDistinctChangesOnlyValue;
}
if (options.has("static")) {
const staticValue = evaluator.evaluate(options.get("static"));
if (typeof staticValue !== "boolean") {
throw createValueHasWrongTypeError(node, staticValue, `@${name} options.static must be a boolean`);
}
isStatic = staticValue;
}
} else if (args.length > 2) {
throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, node, `@${name} has too many arguments`);
}
return {
isSignal: false,
propertyName,
predicate,
first,
descendants,
read,
static: isStatic,
emitDistinctChangesOnly
};
}
function extractHostBindings2(members, evaluator, coreModule, compilationMode, metadata) {
let bindings;
if (metadata && metadata.has("host")) {
bindings = evaluateHostExpressionBindings(metadata.get("host"), evaluator);
} else {
bindings = parseHostBindings({});
}
filterToMembersWithDecorator(members, "HostBinding", coreModule).forEach(({ member, decorators }) => {
decorators.forEach((decorator) => {
let hostPropertyName = member.name;
if (decorator.args !== null && decorator.args.length > 0) {
if (decorator.args.length !== 1) {
throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, decorator.node, `@HostBinding can have at most one argument, got ${decorator.args.length} argument(s)`);
}
const resolved = evaluator.evaluate(decorator.args[0]);
assertLocalCompilationUnresolvedConst(compilationMode, resolved, null, "Unresolved identifier found for @HostBinding's argument! Did you import this identifier from a file outside of the compilation unit? This is not allowed when Angular compiler runs in local mode. Possible solutions: 1) Move the declaration into a file within the compilation unit, 2) Inline the argument");
if (typeof resolved !== "string") {
throw createValueHasWrongTypeError(decorator.node, resolved, `@HostBinding's argument must be a string`);
}
hostPropertyName = resolved;
}
bindings.properties[hostPropertyName] = getSafePropertyAccessString("this", member.name);
});
});
filterToMembersWithDecorator(members, "HostListener", coreModule).forEach(({ member, decorators }) => {
decorators.forEach((decorator) => {
let eventName = member.name;
let args = [];
if (decorator.args !== null && decorator.args.length > 0) {
if (decorator.args.length > 2) {
throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, decorator.args[2], `@HostListener can have at most two arguments`);
}
const resolved = evaluator.evaluate(decorator.args[0]);
assertLocalCompilationUnresolvedConst(compilationMode, resolved, null, "Unresolved identifier found for @HostListener's event name argument! Did you import this identifier from a file outside of the compilation unit? This is not allowed when Angular compiler runs in local mode. Possible solutions: 1) Move the declaration into a file within the compilation unit, 2) Inline the argument");
if (typeof resolved !== "string") {
throw createValueHasWrongTypeError(decorator.args[0], resolved, `@HostListener's event name argument must be a string`);
}
eventName = resolved;
if (decorator.args.length === 2) {
const expression = decorator.args[1];
const resolvedArgs = evaluator.evaluate(decorator.args[1]);
if (!isStringArrayOrDie(resolvedArgs, "@HostListener.args", expression)) {
throw createValueHasWrongTypeError(decorator.args[1], resolvedArgs, `@HostListener's second argument must be a string array`);
}
args = resolvedArgs;
}
}
bindings.listeners[eventName] = `${member.name}(${args.join(",")})`;
});
});
return bindings;
}
function extractQueriesFromDecorator(queryData, reflector, evaluator, isCore) {
const content = [];
const view = [];
if (!import_typescript58.default.isObjectLiteralExpression(queryData)) {
throw new FatalDiagnosticError(ErrorCode.VALUE_HAS_WRONG_TYPE, queryData, "Decorator queries metadata must be an object literal");
}
reflectObjectLiteral(queryData).forEach((queryExpr, propertyName) => {
queryExpr = unwrapExpression(queryExpr);
if (!import_typescript58.default.isNewExpression(queryExpr)) {
throw new FatalDiagnosticError(ErrorCode.VALUE_HAS_WRONG_TYPE, queryData, "Decorator query metadata must be an instance of a query type");
}
const queryType = import_typescript58.default.isPropertyAccessExpression(queryExpr.expression) ? queryExpr.expression.name : queryExpr.expression;
if (!import_typescript58.default.isIdentifier(queryType)) {
throw new FatalDiagnosticError(ErrorCode.VALUE_HAS_WRONG_TYPE, queryData, "Decorator query metadata must be an instance of a query type");
}
const type = reflector.getImportOfIdentifier(queryType);
if (type === null || !isCore && type.from !== "@angular/core" || !QUERY_TYPES.has(type.name)) {
throw new FatalDiagnosticError(ErrorCode.VALUE_HAS_WRONG_TYPE, queryData, "Decorator query metadata must be an instance of a query type");
}
const query = extractDecoratorQueryMetadata(queryExpr, type.name, queryExpr.arguments || [], propertyName, reflector, evaluator);
if (type.name.startsWith("Content")) {
content.push({ expr: queryExpr, metadata: query });
} else {
view.push({ expr: queryExpr, metadata: query });
}
});
return { content, view };
}
function parseDirectiveStyles(directive, evaluator, compilationMode) {
var _a2;
const expression = directive.get("styles");
if (!expression) {
return null;
}
const evaluated = evaluator.evaluate(expression);
const value = typeof evaluated === "string" ? [evaluated] : evaluated;
if (compilationMode === CompilationMode.LOCAL) {
let unresolvedNode = null;
if (Array.isArray(value)) {
const entry = value.find((e) => e instanceof DynamicValue && e.isFromUnknownIdentifier());
unresolvedNode = (_a2 = entry == null ? void 0 : entry.node) != null ? _a2 : null;
} else if (value instanceof DynamicValue && value.isFromUnknownIdentifier()) {
unresolvedNode = value.node;
}
if (unresolvedNode !== null) {
throw new FatalDiagnosticError(ErrorCode.LOCAL_COMPILATION_UNRESOLVED_CONST, unresolvedNode, "Unresolved identifier found for @Component.styles field! Did you import this identifier from a file outside of the compilation unit? This is not allowed when Angular compiler runs in local mode. Possible solutions: 1) Move the declarations into a file within the compilation unit, 2) Inline the styles, 3) Move the styles into separate files and include it using @Component.styleUrls");
}
}
if (!isStringArrayOrDie(value, "styles", expression)) {
throw createValueHasWrongTypeError(expression, value, `Failed to resolve @Component.styles to a string or an array of strings`);
}
return value;
}
function parseFieldStringArrayValue(directive, field, evaluator) {
if (!directive.has(field)) {
return null;
}
const expression = directive.get(field);
const value = evaluator.evaluate(expression);
if (!isStringArrayOrDie(value, field, expression)) {
throw createValueHasWrongTypeError(expression, value, `Failed to resolve @Directive.${field} to a string array`);
}
return value;
}
function isStringArrayOrDie(value, name, node) {
if (!Array.isArray(value)) {
return false;
}
for (let i = 0; i < value.length; i++) {
if (typeof value[i] !== "string") {
throw createValueHasWrongTypeError(node, value[i], `Failed to resolve ${name} at position ${i} to a string`);
}
}
return true;
}
function tryGetQueryFromFieldDecorator(member, reflector, evaluator, isCore) {
var _a2, _b2, _c2;
const decorators = member.decorators;
if (decorators === null) {
return null;
}
const queryDecorators = getAngularDecorators(decorators, queryDecoratorNames, isCore);
if (queryDecorators.length === 0) {
return null;
}
if (queryDecorators.length !== 1) {
throw new FatalDiagnosticError(ErrorCode.DECORATOR_COLLISION, (_a2 = member.node) != null ? _a2 : queryDecorators[0].node, "Cannot combine multiple query decorators.");
}
const decorator = queryDecorators[0];
const node = member.node || decorator.node;
if (decorators.some((v) => v.name === "Input")) {
throw new FatalDiagnosticError(ErrorCode.DECORATOR_COLLISION, node, "Cannot combine @Input decorators with query decorators");
}
if (!isPropertyTypeMember(member)) {
throw new FatalDiagnosticError(ErrorCode.DECORATOR_UNEXPECTED, node, "Query decorator must go on a property-type member");
}
const name = (_c2 = (_b2 = decorator.import) == null ? void 0 : _b2.name) != null ? _c2 : decorator.name;
return {
name,
decorator,
metadata: extractDecoratorQueryMetadata(node, name, decorator.args || [], member.name, reflector, evaluator)
};
}
function isPropertyTypeMember(member) {
return member.kind === ClassMemberKind.Getter || member.kind === ClassMemberKind.Setter || member.kind === ClassMemberKind.Property;
}
function parseMappingStringArray2(values) {
return values.reduce((results, value) => {
if (typeof value !== "string") {
throw new Error("Mapping value must be a string");
}
const [bindingPropertyName, fieldName] = parseMappingString2(value);
results[fieldName] = bindingPropertyName;
return results;
}, {});
}
function parseMappingString2(value) {
const [fieldName, bindingPropertyName] = value.split(":", 2).map((str) => str.trim());
return [bindingPropertyName != null ? bindingPropertyName : fieldName, fieldName];
}
function parseInputsArray2(clazz, decoratorMetadata, evaluator, reflector, refEmitter, compilationMode) {
const inputsField = decoratorMetadata.get("inputs");
if (inputsField === void 0) {
return {};
}
const inputs = {};
const inputsArray = evaluator.evaluate(inputsField);
if (!Array.isArray(inputsArray)) {
throw createValueHasWrongTypeError(inputsField, inputsArray, `Failed to resolve @Directive.inputs to an array`);
}
for (let i = 0; i < inputsArray.length; i++) {
const value = inputsArray[i];
if (typeof value === "string") {
const [bindingPropertyName, classPropertyName] = parseMappingString2(value);
inputs[classPropertyName] = {
bindingPropertyName,
classPropertyName,
required: false,
transform: null,
isSignal: false
};
} else if (value instanceof Map) {
const name = value.get("name");
const alias = value.get("alias");
const required = value.get("required");
let transform2 = null;
if (typeof name !== "string") {
throw createValueHasWrongTypeError(inputsField, name, `Value at position ${i} of @Directive.inputs array must have a "name" property`);
}
if (value.has("transform")) {
const transformValue = value.get("transform");
if (!(transformValue instanceof DynamicValue) && !(transformValue instanceof Reference2)) {
throw createValueHasWrongTypeError(inputsField, transformValue, `Transform of value at position ${i} of @Directive.inputs array must be a function`);
}
transform2 = parseDecoratorInputTransformFunction(clazz, name, transformValue, reflector, refEmitter, compilationMode);
}
inputs[name] = {
classPropertyName: name,
bindingPropertyName: typeof alias === "string" ? alias : name,
required: required === true,
isSignal: false,
transform: transform2
};
} else {
throw createValueHasWrongTypeError(inputsField, value, `@Directive.inputs array can only contain strings or object literals`);
}
}
return inputs;
}
function tryGetDecoratorOnMember(member, decoratorName, isCore) {
if (member.decorators === null) {
return null;
}
for (const decorator of member.decorators) {
if (isAngularDecorator2(decorator, decoratorName, isCore)) {
return decorator;
}
}
return null;
}
function tryParseInputFieldMapping(clazz, member, evaluator, reflector, importTracker, isCore, refEmitter, compilationMode) {
const classPropertyName = member.name;
const decorator = tryGetDecoratorOnMember(member, "Input", isCore);
const signalInputMapping = tryParseSignalInputMapping(member, reflector, importTracker);
const modelInputMapping = tryParseSignalModelMapping(member, reflector, importTracker);
if (decorator !== null && signalInputMapping !== null) {
throw new FatalDiagnosticError(ErrorCode.INITIALIZER_API_WITH_DISALLOWED_DECORATOR, decorator.node, `Using @Input with a signal input is not allowed.`);
}
if (decorator !== null && modelInputMapping !== null) {
throw new FatalDiagnosticError(ErrorCode.INITIALIZER_API_WITH_DISALLOWED_DECORATOR, decorator.node, `Using @Input with a model input is not allowed.`);
}
if (decorator !== null) {
if (decorator.args !== null && decorator.args.length > 1) {
throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, decorator.node, `@${decorator.name} can have at most one argument, got ${decorator.args.length} argument(s)`);
}
const optionsNode = decorator.args !== null && decorator.args.length === 1 ? decorator.args[0] : void 0;
const options = optionsNode !== void 0 ? evaluator.evaluate(optionsNode) : null;
const required = options instanceof Map ? options.get("required") === true : false;
if (options !== null && typeof options !== "string" && !(options instanceof Map)) {
throw createValueHasWrongTypeError(decorator.node, options, `@${decorator.name} decorator argument must resolve to a string or an object literal`);
}
let alias = null;
if (typeof options === "string") {
alias = options;
} else if (options instanceof Map && typeof options.get("alias") === "string") {
alias = options.get("alias");
}
const publicInputName = alias != null ? alias : classPropertyName;
let transform2 = null;
if (options instanceof Map && options.has("transform")) {
const transformValue = options.get("transform");
if (!(transformValue instanceof DynamicValue) && !(transformValue instanceof Reference2)) {
throw createValueHasWrongTypeError(optionsNode, transformValue, `Input transform must be a function`);
}
transform2 = parseDecoratorInputTransformFunction(clazz, classPropertyName, transformValue, reflector, refEmitter, compilationMode);
}
return {
isSignal: false,
classPropertyName,
bindingPropertyName: publicInputName,
transform: transform2,
required
};
}
if (signalInputMapping !== null) {
return signalInputMapping;
}
if (modelInputMapping !== null) {
return modelInputMapping.input;
}
return null;
}
function parseInputFields(clazz, members, evaluator, reflector, importTracker, refEmitter, isCore, compilationMode, inputsFromClassDecorator, classDecorator) {
var _a2, _b2;
const inputs = {};
for (const member of members) {
const classPropertyName = member.name;
const inputMapping = tryParseInputFieldMapping(clazz, member, evaluator, reflector, importTracker, isCore, refEmitter, compilationMode);
if (inputMapping === null) {
continue;
}
if (member.isStatic) {
throw new FatalDiagnosticError(ErrorCode.INCORRECTLY_DECLARED_ON_STATIC_MEMBER, (_a2 = member.node) != null ? _a2 : clazz, `Input "${member.name}" is incorrectly declared as static member of "${clazz.name.text}".`);
}
if (inputMapping.isSignal && inputsFromClassDecorator.hasOwnProperty(classPropertyName)) {
throw new FatalDiagnosticError(ErrorCode.INITIALIZER_API_DECORATOR_METADATA_COLLISION, (_b2 = member.node) != null ? _b2 : clazz, `Input "${member.name}" is also declared as non-signal in @${classDecorator.name}.`);
}
inputs[classPropertyName] = inputMapping;
}
return inputs;
}
function parseDecoratorInputTransformFunction(clazz, classPropertyName, value, reflector, refEmitter, compilationMode) {
var _a2;
if (compilationMode === CompilationMode.LOCAL) {
const node2 = value instanceof Reference2 ? value.getIdentityIn(clazz.getSourceFile()) : value.node;
if (node2 === null) {
throw createValueHasWrongTypeError(value.node, value, "Input transform function could not be referenced");
}
return {
node: node2,
type: new Reference2(import_typescript58.default.factory.createKeywordTypeNode(import_typescript58.default.SyntaxKind.UnknownKeyword))
};
}
const definition = reflector.getDefinitionOfFunction(value.node);
if (definition === null) {
throw createValueHasWrongTypeError(value.node, value, "Input transform must be a function");
}
if (definition.typeParameters !== null && definition.typeParameters.length > 0) {
throw createValueHasWrongTypeError(value.node, value, "Input transform function cannot be generic");
}
if (definition.signatureCount > 1) {
throw createValueHasWrongTypeError(value.node, value, "Input transform function cannot have multiple signatures");
}
const members = reflector.getMembersOfClass(clazz);
for (const member of members) {
const conflictingName = `ngAcceptInputType_${classPropertyName}`;
if (member.name === conflictingName && member.isStatic) {
throw new FatalDiagnosticError(ErrorCode.CONFLICTING_INPUT_TRANSFORM, value.node, `Class cannot have both a transform function on Input ${classPropertyName} and a static member called ${conflictingName}`);
}
}
const node = value instanceof Reference2 ? value.getIdentityIn(clazz.getSourceFile()) : value.node;
if (node === null) {
throw createValueHasWrongTypeError(value.node, value, "Input transform function could not be referenced");
}
const firstParam = ((_a2 = definition.parameters[0]) == null ? void 0 : _a2.name) === "this" ? definition.parameters[1] : definition.parameters[0];
if (!firstParam) {
return {
node,
type: new Reference2(import_typescript58.default.factory.createKeywordTypeNode(import_typescript58.default.SyntaxKind.UnknownKeyword))
};
}
if (!firstParam.type) {
throw createValueHasWrongTypeError(value.node, value, "Input transform function first parameter must have a type");
}
if (firstParam.node.dotDotDotToken) {
throw createValueHasWrongTypeError(value.node, value, "Input transform function first parameter cannot be a spread parameter");
}
assertEmittableInputType(firstParam.type, clazz.getSourceFile(), reflector, refEmitter);
const viaModule = value instanceof Reference2 ? value.bestGuessOwningModule : null;
return { node, type: new Reference2(firstParam.type, viaModule) };
}
function assertEmittableInputType(type, contextFile, reflector, refEmitter) {
(function walk(node) {
if (import_typescript58.default.isTypeReferenceNode(node) && import_typescript58.default.isIdentifier(node.typeName)) {
const declaration = reflector.getDeclarationOfIdentifier(node.typeName);
if (declaration !== null) {
if (declaration.node.getSourceFile() !== contextFile) {
const emittedType = refEmitter.emit(new Reference2(declaration.node, declaration.viaModule === AmbientImport ? AmbientImport : null), contextFile, ImportFlags.NoAliasing | ImportFlags.AllowTypeImports | ImportFlags.AllowRelativeDtsImports | ImportFlags.AllowAmbientReferences);
assertSuccessfulReferenceEmit(emittedType, node, "type");
} else if (!reflector.isStaticallyExported(declaration.node)) {
throw new FatalDiagnosticError(ErrorCode.SYMBOL_NOT_EXPORTED, type, `Symbol must be exported in order to be used as the type of an Input transform function`, [makeRelatedInformation(declaration.node, `The symbol is declared here.`)]);
}
}
}
node.forEachChild(walk);
})(type);
}
function parseQueriesOfClassFields(members, reflector, importTracker, evaluator, isCore) {
var _a2;
const viewQueries = [];
const contentQueries = [];
const decoratorViewChild = [];
const decoratorViewChildren = [];
const decoratorContentChild = [];
const decoratorContentChildren = [];
for (const member of members) {
const decoratorQuery = tryGetQueryFromFieldDecorator(member, reflector, evaluator, isCore);
const signalQuery = tryParseSignalQueryFromInitializer(member, reflector, importTracker);
if (decoratorQuery !== null && signalQuery !== null) {
throw new FatalDiagnosticError(ErrorCode.INITIALIZER_API_WITH_DISALLOWED_DECORATOR, decoratorQuery.decorator.node, `Using @${decoratorQuery.name} with a signal-based query is not allowed.`);
}
const queryNode = (_a2 = decoratorQuery == null ? void 0 : decoratorQuery.decorator.node) != null ? _a2 : signalQuery == null ? void 0 : signalQuery.call;
if (queryNode !== void 0 && member.isStatic) {
throw new FatalDiagnosticError(ErrorCode.INCORRECTLY_DECLARED_ON_STATIC_MEMBER, queryNode, `Query is incorrectly declared on a static class member.`);
}
if (decoratorQuery !== null) {
switch (decoratorQuery.name) {
case "ViewChild":
decoratorViewChild.push(decoratorQuery.metadata);
break;
case "ViewChildren":
decoratorViewChildren.push(decoratorQuery.metadata);
break;
case "ContentChild":
decoratorContentChild.push(decoratorQuery.metadata);
break;
case "ContentChildren":
decoratorContentChildren.push(decoratorQuery.metadata);
break;
}
} else if (signalQuery !== null) {
switch (signalQuery.name) {
case "viewChild":
case "viewChildren":
viewQueries.push(signalQuery.metadata);
break;
case "contentChild":
case "contentChildren":
contentQueries.push(signalQuery.metadata);
break;
}
}
}
return {
viewQueries: [...viewQueries, ...decoratorViewChild, ...decoratorViewChildren],
contentQueries: [...contentQueries, ...decoratorContentChild, ...decoratorContentChildren]
};
}
function parseOutputsArray(directive, evaluator) {
const metaValues = parseFieldStringArrayValue(directive, "outputs", evaluator);
return metaValues ? parseMappingStringArray2(metaValues) : EMPTY_OBJECT;
}
function parseOutputFields(clazz, classDecorator, members, isCore, reflector, importTracker, evaluator, outputsFromMeta) {
var _a2, _b2, _c2;
const outputs = {};
for (const member of members) {
const decoratorOutput = tryParseDecoratorOutput(member, evaluator, isCore);
const initializerOutput = tryParseInitializerBasedOutput(member, reflector, importTracker);
const modelMapping = tryParseSignalModelMapping(member, reflector, importTracker);
if (decoratorOutput !== null && initializerOutput !== null) {
throw new FatalDiagnosticError(ErrorCode.INITIALIZER_API_WITH_DISALLOWED_DECORATOR, decoratorOutput.decorator.node, `Using "@Output" with "output()" is not allowed.`);
}
if (decoratorOutput !== null && modelMapping !== null) {
throw new FatalDiagnosticError(ErrorCode.INITIALIZER_API_WITH_DISALLOWED_DECORATOR, decoratorOutput.decorator.node, `Using @Output with a model input is not allowed.`);
}
const queryNode = (_b2 = (_a2 = decoratorOutput == null ? void 0 : decoratorOutput.decorator.node) != null ? _a2 : initializerOutput == null ? void 0 : initializerOutput.call) != null ? _b2 : modelMapping == null ? void 0 : modelMapping.call;
if (queryNode !== void 0 && member.isStatic) {
throw new FatalDiagnosticError(ErrorCode.INCORRECTLY_DECLARED_ON_STATIC_MEMBER, queryNode, `Output is incorrectly declared on a static class member.`);
}
let bindingPropertyName;
if (decoratorOutput !== null) {
bindingPropertyName = decoratorOutput.metadata.bindingPropertyName;
} else if (initializerOutput !== null) {
bindingPropertyName = initializerOutput.metadata.bindingPropertyName;
} else if (modelMapping !== null) {
bindingPropertyName = modelMapping.output.bindingPropertyName;
} else {
continue;
}
if ((initializerOutput !== null || modelMapping !== null) && outputsFromMeta.hasOwnProperty(member.name)) {
throw new FatalDiagnosticError(ErrorCode.INITIALIZER_API_DECORATOR_METADATA_COLLISION, (_c2 = member.node) != null ? _c2 : clazz, `Output "${member.name}" is unexpectedly declared in @${classDecorator.name} as well.`);
}
outputs[member.name] = bindingPropertyName;
}
return outputs;
}
function tryParseDecoratorOutput(member, evaluator, isCore) {
var _a2;
const decorator = tryGetDecoratorOnMember(member, "Output", isCore);
if (decorator === null) {
return null;
}
if (decorator.args !== null && decorator.args.length > 1) {
throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, decorator.node, `@Output can have at most one argument, got ${decorator.args.length} argument(s)`);
}
const classPropertyName = member.name;
let alias = null;
if (((_a2 = decorator.args) == null ? void 0 : _a2.length) === 1) {
const resolvedAlias = evaluator.evaluate(decorator.args[0]);
if (typeof resolvedAlias !== "string") {
throw createValueHasWrongTypeError(decorator.node, resolvedAlias, `@Output decorator argument must resolve to a string`);
}
alias = resolvedAlias;
}
return {
decorator,
metadata: {
isSignal: false,
classPropertyName,
bindingPropertyName: alias != null ? alias : classPropertyName
}
};
}
function evaluateHostExpressionBindings(hostExpr, evaluator) {
const hostMetaMap = evaluator.evaluate(hostExpr);
if (!(hostMetaMap instanceof Map)) {
throw createValueHasWrongTypeError(hostExpr, hostMetaMap, `Decorator host metadata must be an object`);
}
const hostMetadata = {};
hostMetaMap.forEach((value, key) => {
if (value instanceof EnumValue) {
value = value.resolved;
}
if (typeof key !== "string") {
throw createValueHasWrongTypeError(hostExpr, key, `Decorator host metadata must be a string -> string object, but found unparseable key`);
}
if (typeof value == "string") {
hostMetadata[key] = value;
} else if (value instanceof DynamicValue) {
hostMetadata[key] = new WrappedNodeExpr(value.node);
} else {
throw createValueHasWrongTypeError(hostExpr, value, `Decorator host metadata must be a string -> string object, but found unparseable value`);
}
});
const bindings = parseHostBindings(hostMetadata);
const errors = verifyHostBindings(bindings, createSourceSpan(hostExpr));
if (errors.length > 0) {
throw new FatalDiagnosticError(
ErrorCode.HOST_BINDING_PARSE_ERROR,
hostExpr,
errors.map((error) => error.msg).join("\n")
);
}
return bindings;
}
function extractHostDirectives(rawHostDirectives, evaluator, compilationMode) {
const resolved = evaluator.evaluate(rawHostDirectives, forwardRefResolver);
if (!Array.isArray(resolved)) {
throw createValueHasWrongTypeError(rawHostDirectives, resolved, "hostDirectives must be an array");
}
return resolved.map((value) => {
const hostReference = value instanceof Map ? value.get("directive") : value;
if (compilationMode !== CompilationMode.LOCAL) {
if (!(hostReference instanceof Reference2)) {
throw createValueHasWrongTypeError(rawHostDirectives, hostReference, "Host directive must be a reference");
}
if (!isNamedClassDeclaration(hostReference.node)) {
throw createValueHasWrongTypeError(rawHostDirectives, hostReference, "Host directive reference must be a class");
}
}
let directive;
let nameForErrors = (fieldName) => "@Directive.hostDirectives";
if (compilationMode === CompilationMode.LOCAL && hostReference instanceof DynamicValue) {
if (!import_typescript58.default.isIdentifier(hostReference.node) && !import_typescript58.default.isPropertyAccessExpression(hostReference.node)) {
throw new FatalDiagnosticError(ErrorCode.LOCAL_COMPILATION_UNSUPPORTED_EXPRESSION, hostReference.node, `In local compilation mode, host directive cannot be an expression. Use an identifier instead`);
}
directive = new WrappedNodeExpr(hostReference.node);
} else if (hostReference instanceof Reference2) {
directive = hostReference;
nameForErrors = (fieldName) => `@Directive.hostDirectives.${directive.node.name.text}.${fieldName}`;
} else {
throw new Error("Impossible state");
}
const meta = {
directive,
isForwardReference: hostReference instanceof Reference2 && hostReference.synthetic,
inputs: parseHostDirectivesMapping("inputs", value, nameForErrors("input"), rawHostDirectives),
outputs: parseHostDirectivesMapping("outputs", value, nameForErrors("output"), rawHostDirectives)
};
return meta;
});
}
function parseHostDirectivesMapping(field, resolvedValue, nameForErrors, sourceExpression) {
if (resolvedValue instanceof Map && resolvedValue.has(field)) {
const rawInputs = resolvedValue.get(field);
if (isStringArrayOrDie(rawInputs, nameForErrors, sourceExpression)) {
return parseMappingStringArray2(rawInputs);
}
}
return null;
}
function toHostDirectiveMetadata(hostDirective, context, refEmitter) {
let directive;
if (hostDirective.directive instanceof Reference2) {
directive = toR3Reference(hostDirective.directive.node, hostDirective.directive, context, refEmitter);
} else {
directive = {
value: hostDirective.directive,
type: hostDirective.directive
};
}
return {
directive,
isForwardReference: hostDirective.isForwardReference,
inputs: hostDirective.inputs || null,
outputs: hostDirective.outputs || null
};
}
function toR3InputMetadata(mapping) {
return {
classPropertyName: mapping.classPropertyName,
bindingPropertyName: mapping.bindingPropertyName,
required: mapping.required,
transformFunction: mapping.transform !== null ? new WrappedNodeExpr(mapping.transform.node) : null,
isSignal: mapping.isSignal
};
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/directive/src/symbol.mjs
var DirectiveSymbol = class extends SemanticSymbol {
constructor(decl, selector, inputs, outputs, exportAs, typeCheckMeta, typeParameters) {
super(decl);
this.selector = selector;
this.inputs = inputs;
this.outputs = outputs;
this.exportAs = exportAs;
this.typeCheckMeta = typeCheckMeta;
this.typeParameters = typeParameters;
this.baseClass = null;
}
isPublicApiAffected(previousSymbol) {
if (!(previousSymbol instanceof DirectiveSymbol)) {
return true;
}
return this.selector !== previousSymbol.selector || !isArrayEqual(this.inputs.propertyNames, previousSymbol.inputs.propertyNames) || !isArrayEqual(this.outputs.propertyNames, previousSymbol.outputs.propertyNames) || !isArrayEqual(this.exportAs, previousSymbol.exportAs);
}
isTypeCheckApiAffected(previousSymbol) {
if (this.isPublicApiAffected(previousSymbol)) {
return true;
}
if (!(previousSymbol instanceof DirectiveSymbol)) {
return true;
}
if (!isArrayEqual(Array.from(this.inputs), Array.from(previousSymbol.inputs), isInputMappingEqual) || !isArrayEqual(Array.from(this.outputs), Array.from(previousSymbol.outputs), isInputOrOutputEqual)) {
return true;
}
if (!areTypeParametersEqual(this.typeParameters, previousSymbol.typeParameters)) {
return true;
}
if (!isTypeCheckMetaEqual(this.typeCheckMeta, previousSymbol.typeCheckMeta)) {
return true;
}
if (!isBaseClassEqual(this.baseClass, previousSymbol.baseClass)) {
return true;
}
return false;
}
};
function isInputMappingEqual(current, previous) {
return isInputOrOutputEqual(current, previous) && current.required === previous.required;
}
function isInputOrOutputEqual(current, previous) {
return current.classPropertyName === previous.classPropertyName && current.bindingPropertyName === previous.bindingPropertyName && current.isSignal === previous.isSignal;
}
function isTypeCheckMetaEqual(current, previous) {
if (current.hasNgTemplateContextGuard !== previous.hasNgTemplateContextGuard) {
return false;
}
if (current.isGeneric !== previous.isGeneric) {
return false;
}
if (!isArrayEqual(current.ngTemplateGuards, previous.ngTemplateGuards, isTemplateGuardEqual)) {
return false;
}
if (!isSetEqual(current.coercedInputFields, previous.coercedInputFields)) {
return false;
}
if (!isSetEqual(current.restrictedInputFields, previous.restrictedInputFields)) {
return false;
}
if (!isSetEqual(current.stringLiteralInputFields, previous.stringLiteralInputFields)) {
return false;
}
if (!isSetEqual(current.undeclaredInputFields, previous.undeclaredInputFields)) {
return false;
}
return true;
}
function isTemplateGuardEqual(current, previous) {
return current.inputName === previous.inputName && current.type === previous.type;
}
function isBaseClassEqual(current, previous) {
if (current === null || previous === null) {
return current === previous;
}
return isSymbolEqual(current, previous);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/directive/src/handler.mjs
var FIELD_DECORATORS = [
"Input",
"Output",
"ViewChild",
"ViewChildren",
"ContentChild",
"ContentChildren",
"HostBinding",
"HostListener"
];
var LIFECYCLE_HOOKS = /* @__PURE__ */ new Set([
"ngOnChanges",
"ngOnInit",
"ngOnDestroy",
"ngDoCheck",
"ngAfterViewInit",
"ngAfterViewChecked",
"ngAfterContentInit",
"ngAfterContentChecked"
]);
var DirectiveDecoratorHandler = class {
constructor(reflector, evaluator, metaRegistry, scopeRegistry, metaReader, injectableRegistry, refEmitter, referencesRegistry, isCore, strictCtorDeps, semanticDepGraphUpdater, annotateForClosureCompiler, perf, importTracker, includeClassMetadata, compilationMode, jitDeclarationRegistry) {
this.reflector = reflector;
this.evaluator = evaluator;
this.metaRegistry = metaRegistry;
this.scopeRegistry = scopeRegistry;
this.metaReader = metaReader;
this.injectableRegistry = injectableRegistry;
this.refEmitter = refEmitter;
this.referencesRegistry = referencesRegistry;
this.isCore = isCore;
this.strictCtorDeps = strictCtorDeps;
this.semanticDepGraphUpdater = semanticDepGraphUpdater;
this.annotateForClosureCompiler = annotateForClosureCompiler;
this.perf = perf;
this.importTracker = importTracker;
this.includeClassMetadata = includeClassMetadata;
this.compilationMode = compilationMode;
this.jitDeclarationRegistry = jitDeclarationRegistry;
this.precedence = HandlerPrecedence.PRIMARY;
this.name = "DirectiveDecoratorHandler";
}
detect(node, decorators) {
if (!decorators) {
const angularField = this.findClassFieldWithAngularFeatures(node);
return angularField ? { trigger: angularField.node, decorator: null, metadata: null } : void 0;
} else {
const decorator = findAngularDecorator(decorators, "Directive", this.isCore);
return decorator ? { trigger: decorator.node, decorator, metadata: decorator } : void 0;
}
}
analyze(node, decorator) {
var _a2;
if (decorator === null) {
if (this.isCore) {
return {};
}
return { diagnostics: [getUndecoratedClassWithAngularFeaturesDiagnostic(node)] };
}
this.perf.eventCount(PerfEvent.AnalyzeDirective);
const directiveResult = extractDirectiveMetadata(
node,
decorator,
this.reflector,
this.importTracker,
this.evaluator,
this.refEmitter,
this.referencesRegistry,
this.isCore,
this.annotateForClosureCompiler,
this.compilationMode,
null
);
if (directiveResult.jitForced) {
this.jitDeclarationRegistry.jitDeclarations.add(node);
return {};
}
const analysis = directiveResult.metadata;
let providersRequiringFactory = null;
if (directiveResult !== void 0 && directiveResult.decorator.has("providers")) {
providersRequiringFactory = resolveProvidersRequiringFactory(directiveResult.decorator.get("providers"), this.reflector, this.evaluator);
}
return {
analysis: {
inputs: directiveResult.inputs,
inputFieldNamesFromMetadataArray: directiveResult.inputFieldNamesFromMetadataArray,
outputs: directiveResult.outputs,
meta: analysis,
hostDirectives: directiveResult.hostDirectives,
rawHostDirectives: directiveResult.rawHostDirectives,
classMetadata: this.includeClassMetadata ? extractClassMetadata(node, this.reflector, this.isCore, this.annotateForClosureCompiler) : null,
baseClass: readBaseClass(node, this.reflector, this.evaluator),
typeCheckMeta: extractDirectiveTypeCheckMeta(node, directiveResult.inputs, this.reflector),
providersRequiringFactory,
isPoisoned: false,
isStructural: directiveResult.isStructural,
decorator: (_a2 = decorator == null ? void 0 : decorator.node) != null ? _a2 : null
}
};
}
symbol(node, analysis) {
const typeParameters = extractSemanticTypeParameters(node);
return new DirectiveSymbol(node, analysis.meta.selector, analysis.inputs, analysis.outputs, analysis.meta.exportAs, analysis.typeCheckMeta, typeParameters);
}
register(node, analysis) {
const ref = new Reference2(node);
this.metaRegistry.registerDirectiveMetadata(__spreadProps(__spreadValues({
kind: MetaKind.Directive,
matchSource: MatchSource.Selector,
ref,
name: node.name.text,
selector: analysis.meta.selector,
exportAs: analysis.meta.exportAs,
inputs: analysis.inputs,
inputFieldNamesFromMetadataArray: analysis.inputFieldNamesFromMetadataArray,
outputs: analysis.outputs,
queries: analysis.meta.queries.map((query) => query.propertyName),
isComponent: false,
baseClass: analysis.baseClass,
hostDirectives: analysis.hostDirectives
}, analysis.typeCheckMeta), {
isPoisoned: analysis.isPoisoned,
isStructural: analysis.isStructural,
animationTriggerNames: null,
isStandalone: analysis.meta.isStandalone,
isSignal: analysis.meta.isSignal,
imports: null,
deferredImports: null,
schemas: null,
ngContentSelectors: null,
decorator: analysis.decorator,
preserveWhitespaces: false,
assumedToExportProviders: false,
isExplicitlyDeferred: false
}));
this.injectableRegistry.registerInjectable(node, {
ctorDeps: analysis.meta.deps
});
}
resolve(node, analysis, symbol) {
if (this.compilationMode === CompilationMode.LOCAL) {
return {};
}
if (this.semanticDepGraphUpdater !== null && analysis.baseClass instanceof Reference2) {
symbol.baseClass = this.semanticDepGraphUpdater.getSymbol(analysis.baseClass.node);
}
const diagnostics = [];
if (analysis.providersRequiringFactory !== null && analysis.meta.providers instanceof WrappedNodeExpr) {
const providerDiagnostics = getProviderDiagnostics(analysis.providersRequiringFactory, analysis.meta.providers.node, this.injectableRegistry);
diagnostics.push(...providerDiagnostics);
}
const directiveDiagnostics = getDirectiveDiagnostics(node, this.injectableRegistry, this.evaluator, this.reflector, this.scopeRegistry, this.strictCtorDeps, "Directive");
if (directiveDiagnostics !== null) {
diagnostics.push(...directiveDiagnostics);
}
const hostDirectivesDiagnotics = analysis.hostDirectives && analysis.rawHostDirectives ? validateHostDirectives(analysis.rawHostDirectives, analysis.hostDirectives, this.metaReader) : null;
if (hostDirectivesDiagnotics !== null) {
diagnostics.push(...hostDirectivesDiagnotics);
}
return { diagnostics: diagnostics.length > 0 ? diagnostics : void 0 };
}
compileFull(node, analysis, resolution, pool) {
const fac = compileNgFactoryDefField(toFactoryMetadata(analysis.meta, FactoryTarget.Directive));
const def = compileDirectiveFromMetadata(analysis.meta, pool, makeBindingParser());
const inputTransformFields = compileInputTransformFields(analysis.inputs);
const classMetadata = analysis.classMetadata !== null ? compileClassMetadata(analysis.classMetadata).toStmt() : null;
return compileResults(fac, def, classMetadata, "\u0275dir", inputTransformFields, null);
}
compilePartial(node, analysis, resolution) {
const fac = compileDeclareFactory(toFactoryMetadata(analysis.meta, FactoryTarget.Directive));
const def = compileDeclareDirectiveFromMetadata(analysis.meta);
const inputTransformFields = compileInputTransformFields(analysis.inputs);
const classMetadata = analysis.classMetadata !== null ? compileDeclareClassMetadata(analysis.classMetadata).toStmt() : null;
return compileResults(fac, def, classMetadata, "\u0275dir", inputTransformFields, null);
}
compileLocal(node, analysis, resolution, pool) {
const fac = compileNgFactoryDefField(toFactoryMetadata(analysis.meta, FactoryTarget.Directive));
const def = compileDirectiveFromMetadata(analysis.meta, pool, makeBindingParser());
const inputTransformFields = compileInputTransformFields(analysis.inputs);
const classMetadata = analysis.classMetadata !== null ? compileClassMetadata(analysis.classMetadata).toStmt() : null;
return compileResults(fac, def, classMetadata, "\u0275dir", inputTransformFields, null);
}
findClassFieldWithAngularFeatures(node) {
return this.reflector.getMembersOfClass(node).find((member) => {
if (!member.isStatic && member.kind === ClassMemberKind.Method && LIFECYCLE_HOOKS.has(member.name)) {
return true;
}
if (member.decorators) {
return member.decorators.some((decorator) => FIELD_DECORATORS.some((decoratorName) => isAngularDecorator2(decorator, decoratorName, this.isCore)));
}
return false;
});
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/ng_module/src/handler.mjs
var import_typescript60 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/ng_module/src/module_with_providers.mjs
var import_typescript59 = __toESM(require("typescript"), 1);
function createModuleWithProvidersResolver(reflector, isCore) {
function _reflectModuleFromTypeParam(type, node) {
if (!import_typescript59.default.isTypeReferenceNode(type)) {
return null;
}
const typeName = type && (import_typescript59.default.isIdentifier(type.typeName) && type.typeName || import_typescript59.default.isQualifiedName(type.typeName) && type.typeName.right) || null;
if (typeName === null) {
return null;
}
const id = reflector.getImportOfIdentifier(typeName);
if (id === null || id.name !== "ModuleWithProviders") {
return null;
}
if (!isCore && id.from !== "@angular/core") {
return null;
}
if (type.typeArguments === void 0 || type.typeArguments.length !== 1) {
const parent = import_typescript59.default.isMethodDeclaration(node) && import_typescript59.default.isClassDeclaration(node.parent) ? node.parent : null;
const symbolName = (parent && parent.name ? parent.name.getText() + "." : "") + (node.name ? node.name.getText() : "anonymous");
throw new FatalDiagnosticError(ErrorCode.NGMODULE_MODULE_WITH_PROVIDERS_MISSING_GENERIC, type, `${symbolName} returns a ModuleWithProviders type without a generic type argument. Please add a generic type argument to the ModuleWithProviders type. If this occurrence is in library code you don't control, please contact the library authors.`);
}
const arg = type.typeArguments[0];
return typeNodeToValueExpr(arg);
}
function _reflectModuleFromLiteralType(type) {
if (!import_typescript59.default.isIntersectionTypeNode(type)) {
return null;
}
for (const t of type.types) {
if (import_typescript59.default.isTypeLiteralNode(t)) {
for (const m of t.members) {
const ngModuleType = import_typescript59.default.isPropertySignature(m) && import_typescript59.default.isIdentifier(m.name) && m.name.text === "ngModule" && m.type || null;
let ngModuleExpression = null;
if (ngModuleType !== null && import_typescript59.default.isTypeQueryNode(ngModuleType)) {
ngModuleExpression = entityNameToValue(ngModuleType.exprName);
} else if (ngModuleType !== null) {
ngModuleExpression = typeNodeToValueExpr(ngModuleType);
}
if (ngModuleExpression) {
return ngModuleExpression;
}
}
}
}
return null;
}
return (fn2, callExpr, resolve5, unresolvable) => {
var _a2;
const rawType = fn2.node.type;
if (rawType === void 0) {
return unresolvable;
}
const type = (_a2 = _reflectModuleFromTypeParam(rawType, fn2.node)) != null ? _a2 : _reflectModuleFromLiteralType(rawType);
if (type === null) {
return unresolvable;
}
const ngModule = resolve5(type);
if (!(ngModule instanceof Reference2) || !isNamedClassDeclaration(ngModule.node)) {
return unresolvable;
}
return new SyntheticValue({
ngModule,
mwpCall: callExpr
});
};
}
function isResolvedModuleWithProviders(sv) {
return typeof sv.value === "object" && sv.value != null && sv.value.hasOwnProperty("ngModule") && sv.value.hasOwnProperty("mwpCall");
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/ng_module/src/handler.mjs
var NgModuleSymbol = class extends SemanticSymbol {
constructor(decl, hasProviders) {
super(decl);
this.hasProviders = hasProviders;
this.remotelyScopedComponents = [];
this.transitiveImportsFromStandaloneComponents = /* @__PURE__ */ new Set();
}
isPublicApiAffected(previousSymbol) {
if (!(previousSymbol instanceof NgModuleSymbol)) {
return true;
}
if (previousSymbol.hasProviders !== this.hasProviders) {
return true;
}
return false;
}
isEmitAffected(previousSymbol) {
if (!(previousSymbol instanceof NgModuleSymbol)) {
return true;
}
if (previousSymbol.remotelyScopedComponents.length !== this.remotelyScopedComponents.length) {
return true;
}
for (const currEntry of this.remotelyScopedComponents) {
const prevEntry = previousSymbol.remotelyScopedComponents.find((prevEntry2) => {
return isSymbolEqual(prevEntry2.component, currEntry.component);
});
if (prevEntry === void 0) {
return true;
}
if (!isArrayEqual(currEntry.usedDirectives, prevEntry.usedDirectives, isReferenceEqual)) {
return true;
}
if (!isArrayEqual(currEntry.usedPipes, prevEntry.usedPipes, isReferenceEqual)) {
return true;
}
}
if (previousSymbol.transitiveImportsFromStandaloneComponents.size !== this.transitiveImportsFromStandaloneComponents.size) {
return true;
}
const previousImports = Array.from(previousSymbol.transitiveImportsFromStandaloneComponents);
for (const transitiveImport of this.transitiveImportsFromStandaloneComponents) {
const prevEntry = previousImports.find((prevEntry2) => isSymbolEqual(prevEntry2, transitiveImport));
if (prevEntry === void 0) {
return true;
}
if (transitiveImport.isPublicApiAffected(prevEntry)) {
return true;
}
}
return false;
}
isTypeCheckApiAffected(previousSymbol) {
if (!(previousSymbol instanceof NgModuleSymbol)) {
return true;
}
return false;
}
addRemotelyScopedComponent(component, usedDirectives, usedPipes) {
this.remotelyScopedComponents.push({ component, usedDirectives, usedPipes });
}
addTransitiveImportFromStandaloneComponent(importedSymbol) {
this.transitiveImportsFromStandaloneComponents.add(importedSymbol);
}
};
var NgModuleDecoratorHandler = class {
constructor(reflector, evaluator, metaReader, metaRegistry, scopeRegistry, referencesRegistry, exportedProviderStatusResolver, semanticDepGraphUpdater, isCore, refEmitter, annotateForClosureCompiler, onlyPublishPublicTypings, injectableRegistry, perf, includeClassMetadata, includeSelectorScope, compilationMode, localCompilationExtraImportsTracker, jitDeclarationRegistry) {
this.reflector = reflector;
this.evaluator = evaluator;
this.metaReader = metaReader;
this.metaRegistry = metaRegistry;
this.scopeRegistry = scopeRegistry;
this.referencesRegistry = referencesRegistry;
this.exportedProviderStatusResolver = exportedProviderStatusResolver;
this.semanticDepGraphUpdater = semanticDepGraphUpdater;
this.isCore = isCore;
this.refEmitter = refEmitter;
this.annotateForClosureCompiler = annotateForClosureCompiler;
this.onlyPublishPublicTypings = onlyPublishPublicTypings;
this.injectableRegistry = injectableRegistry;
this.perf = perf;
this.includeClassMetadata = includeClassMetadata;
this.includeSelectorScope = includeSelectorScope;
this.compilationMode = compilationMode;
this.localCompilationExtraImportsTracker = localCompilationExtraImportsTracker;
this.jitDeclarationRegistry = jitDeclarationRegistry;
this.precedence = HandlerPrecedence.PRIMARY;
this.name = "NgModuleDecoratorHandler";
}
detect(node, decorators) {
if (!decorators) {
return void 0;
}
const decorator = findAngularDecorator(decorators, "NgModule", this.isCore);
if (decorator !== void 0) {
return {
trigger: decorator.node,
decorator,
metadata: decorator
};
} else {
return void 0;
}
}
analyze(node, decorator) {
var _a2, _b2, _c2, _d2, _e2;
this.perf.eventCount(PerfEvent.AnalyzeNgModule);
const name = node.name.text;
if (decorator.args === null || decorator.args.length > 1) {
throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, decorator.node, `Incorrect number of arguments to @NgModule decorator`);
}
const meta = decorator.args.length === 1 ? unwrapExpression(decorator.args[0]) : import_typescript60.default.factory.createObjectLiteralExpression([]);
if (!import_typescript60.default.isObjectLiteralExpression(meta)) {
throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARG_NOT_LITERAL, meta, "@NgModule argument must be an object literal");
}
const ngModule = reflectObjectLiteral(meta);
if (ngModule.has("jit")) {
this.jitDeclarationRegistry.jitDeclarations.add(node);
return {};
}
const moduleResolvers = combineResolvers([
createModuleWithProvidersResolver(this.reflector, this.isCore),
forwardRefResolver
]);
const diagnostics = [];
let declarationRefs = [];
const rawDeclarations = (_a2 = ngModule.get("declarations")) != null ? _a2 : null;
if (rawDeclarations !== null) {
const declarationMeta = this.evaluator.evaluate(rawDeclarations, forwardRefResolver);
declarationRefs = this.resolveTypeList(rawDeclarations, declarationMeta, name, "declarations", 0, this.compilationMode === CompilationMode.LOCAL).references;
for (const ref of declarationRefs) {
if (ref.node.getSourceFile().isDeclarationFile) {
const errorNode = ref.getOriginForDiagnostics(rawDeclarations);
diagnostics.push(makeDiagnostic(ErrorCode.NGMODULE_INVALID_DECLARATION, errorNode, `Cannot declare '${ref.node.name.text}' in an NgModule as it's not a part of the current compilation.`, [makeRelatedInformation(ref.node.name, `'${ref.node.name.text}' is declared here.`)]));
}
}
}
if (diagnostics.length > 0) {
return { diagnostics };
}
let importRefs = [];
let rawImports = (_b2 = ngModule.get("imports")) != null ? _b2 : null;
if (rawImports !== null) {
const importsMeta = this.evaluator.evaluate(rawImports, moduleResolvers);
const result = this.resolveTypeList(rawImports, importsMeta, name, "imports", 0, this.compilationMode === CompilationMode.LOCAL);
if (this.compilationMode === CompilationMode.LOCAL && this.localCompilationExtraImportsTracker !== null) {
for (const d of result.dynamicValues) {
this.localCompilationExtraImportsTracker.addGlobalImportFromIdentifier(d.node);
}
}
importRefs = result.references;
}
let exportRefs = [];
const rawExports = (_c2 = ngModule.get("exports")) != null ? _c2 : null;
if (rawExports !== null) {
const exportsMeta = this.evaluator.evaluate(rawExports, moduleResolvers);
exportRefs = this.resolveTypeList(rawExports, exportsMeta, name, "exports", 0, this.compilationMode === CompilationMode.LOCAL).references;
this.referencesRegistry.add(node, ...exportRefs);
}
let bootstrapRefs = [];
const rawBootstrap = (_d2 = ngModule.get("bootstrap")) != null ? _d2 : null;
if (this.compilationMode !== CompilationMode.LOCAL && rawBootstrap !== null) {
const bootstrapMeta = this.evaluator.evaluate(rawBootstrap, forwardRefResolver);
bootstrapRefs = this.resolveTypeList(
rawBootstrap,
bootstrapMeta,
name,
"bootstrap",
0,
false
).references;
for (const ref of bootstrapRefs) {
const dirMeta = this.metaReader.getDirectiveMetadata(ref);
if (dirMeta == null ? void 0 : dirMeta.isStandalone) {
diagnostics.push(makeStandaloneBootstrapDiagnostic(node, ref, rawBootstrap));
}
}
}
const schemas = this.compilationMode !== CompilationMode.LOCAL && ngModule.has("schemas") ? extractSchemas(ngModule.get("schemas"), this.evaluator, "NgModule") : [];
let id = null;
if (ngModule.has("id")) {
const idExpr = ngModule.get("id");
if (!isModuleIdExpression(idExpr)) {
id = new WrappedNodeExpr(idExpr);
} else {
const diag = makeDiagnostic(ErrorCode.WARN_NGMODULE_ID_UNNECESSARY, idExpr, `Using 'module.id' for NgModule.id is a common anti-pattern that is ignored by the Angular compiler.`);
diag.category = import_typescript60.default.DiagnosticCategory.Warning;
diagnostics.push(diag);
}
}
const valueContext = node.getSourceFile();
const exportedNodes = new Set(exportRefs.map((ref) => ref.node));
const declarations = [];
const exportedDeclarations = [];
const bootstrap = bootstrapRefs.map((bootstrap2) => this._toR3Reference(bootstrap2.getOriginForDiagnostics(meta, node.name), bootstrap2, valueContext));
for (const ref of declarationRefs) {
const decl = this._toR3Reference(ref.getOriginForDiagnostics(meta, node.name), ref, valueContext);
declarations.push(decl);
if (exportedNodes.has(ref.node)) {
exportedDeclarations.push(decl.type);
}
}
const imports = importRefs.map((imp) => this._toR3Reference(imp.getOriginForDiagnostics(meta, node.name), imp, valueContext));
const exports = exportRefs.map((exp) => this._toR3Reference(exp.getOriginForDiagnostics(meta, node.name), exp, valueContext));
const isForwardReference = (ref) => isExpressionForwardReference(ref.value, node.name, valueContext);
const containsForwardDecls = bootstrap.some(isForwardReference) || declarations.some(isForwardReference) || imports.some(isForwardReference) || exports.some(isForwardReference);
const type = wrapTypeReference(this.reflector, node);
let ngModuleMetadata;
if (this.compilationMode === CompilationMode.LOCAL) {
ngModuleMetadata = {
kind: R3NgModuleMetadataKind.Local,
type,
bootstrapExpression: rawBootstrap ? new WrappedNodeExpr(rawBootstrap) : null,
declarationsExpression: rawDeclarations ? new WrappedNodeExpr(rawDeclarations) : null,
exportsExpression: rawExports ? new WrappedNodeExpr(rawExports) : null,
importsExpression: rawImports ? new WrappedNodeExpr(rawImports) : null,
id,
selectorScopeMode: R3SelectorScopeMode.SideEffect,
schemas: []
};
} else {
ngModuleMetadata = {
kind: R3NgModuleMetadataKind.Global,
type,
bootstrap,
declarations,
publicDeclarationTypes: this.onlyPublishPublicTypings ? exportedDeclarations : null,
exports,
imports,
includeImportTypes: !this.onlyPublishPublicTypings,
containsForwardDecls,
id,
selectorScopeMode: this.includeSelectorScope ? R3SelectorScopeMode.SideEffect : R3SelectorScopeMode.Omit,
schemas: []
};
}
const rawProviders = ngModule.has("providers") ? ngModule.get("providers") : null;
let wrappedProviders = null;
if (rawProviders !== null && (!import_typescript60.default.isArrayLiteralExpression(rawProviders) || rawProviders.elements.length > 0)) {
wrappedProviders = new WrappedNodeExpr(this.annotateForClosureCompiler ? wrapFunctionExpressionsInParens(rawProviders) : rawProviders);
}
const topLevelImports = [];
if (this.compilationMode !== CompilationMode.LOCAL && ngModule.has("imports")) {
const rawImports2 = unwrapExpression(ngModule.get("imports"));
let topLevelExpressions = [];
if (import_typescript60.default.isArrayLiteralExpression(rawImports2)) {
for (const element2 of rawImports2.elements) {
if (import_typescript60.default.isSpreadElement(element2)) {
topLevelExpressions.push(element2.expression);
continue;
}
topLevelExpressions.push(element2);
}
} else {
topLevelExpressions.push(rawImports2);
}
let absoluteIndex = 0;
for (const importExpr2 of topLevelExpressions) {
const resolved = this.evaluator.evaluate(importExpr2, moduleResolvers);
const { references, hasModuleWithProviders } = this.resolveTypeList(
importExpr2,
[resolved],
node.name.text,
"imports",
absoluteIndex,
false
);
absoluteIndex += references.length;
topLevelImports.push({
expression: importExpr2,
resolvedReferences: references,
hasModuleWithProviders
});
}
}
const injectorMetadata = {
name,
type,
providers: wrappedProviders,
imports: []
};
if (this.compilationMode === CompilationMode.LOCAL) {
for (const exp of [rawImports, rawExports]) {
if (exp === null) {
continue;
}
if (import_typescript60.default.isArrayLiteralExpression(exp)) {
if (exp.elements) {
injectorMetadata.imports.push(...exp.elements.map((n2) => new WrappedNodeExpr(n2)));
}
} else {
injectorMetadata.imports.push(new WrappedNodeExpr(exp));
}
}
}
const factoryMetadata = {
name,
type,
typeArgumentCount: 0,
deps: getValidConstructorDependencies(node, this.reflector, this.isCore),
target: FactoryTarget.NgModule
};
const remoteScopesMayRequireCycleProtection = declarationRefs.some(isSyntheticReference) || importRefs.some(isSyntheticReference);
return {
diagnostics: diagnostics.length > 0 ? diagnostics : void 0,
analysis: {
id,
schemas,
mod: ngModuleMetadata,
inj: injectorMetadata,
fac: factoryMetadata,
declarations: declarationRefs,
rawDeclarations,
imports: topLevelImports,
rawImports,
importRefs,
exports: exportRefs,
rawExports,
providers: rawProviders,
providersRequiringFactory: rawProviders ? resolveProvidersRequiringFactory(rawProviders, this.reflector, this.evaluator) : null,
classMetadata: this.includeClassMetadata ? extractClassMetadata(node, this.reflector, this.isCore, this.annotateForClosureCompiler) : null,
factorySymbolName: node.name.text,
remoteScopesMayRequireCycleProtection,
decorator: (_e2 = decorator == null ? void 0 : decorator.node) != null ? _e2 : null
}
};
}
symbol(node, analysis) {
return new NgModuleSymbol(node, analysis.providers !== null);
}
register(node, analysis) {
this.metaRegistry.registerNgModuleMetadata({
kind: MetaKind.NgModule,
ref: new Reference2(node),
schemas: analysis.schemas,
declarations: analysis.declarations,
imports: analysis.importRefs,
exports: analysis.exports,
rawDeclarations: analysis.rawDeclarations,
rawImports: analysis.rawImports,
rawExports: analysis.rawExports,
decorator: analysis.decorator,
mayDeclareProviders: analysis.providers !== null
});
this.injectableRegistry.registerInjectable(node, {
ctorDeps: analysis.fac.deps
});
}
resolve(node, analysis) {
if (this.compilationMode === CompilationMode.LOCAL) {
return {};
}
const scope = this.scopeRegistry.getScopeOfModule(node);
const diagnostics = [];
const scopeDiagnostics = this.scopeRegistry.getDiagnosticsOfModule(node);
if (scopeDiagnostics !== null) {
diagnostics.push(...scopeDiagnostics);
}
if (analysis.providersRequiringFactory !== null) {
const providerDiagnostics = getProviderDiagnostics(analysis.providersRequiringFactory, analysis.providers, this.injectableRegistry);
diagnostics.push(...providerDiagnostics);
}
const data = {
injectorImports: []
};
for (const topLevelImport of analysis.imports) {
if (topLevelImport.hasModuleWithProviders) {
data.injectorImports.push(new WrappedNodeExpr(topLevelImport.expression));
continue;
}
const refsToEmit = [];
let symbol = null;
if (this.semanticDepGraphUpdater !== null) {
const sym = this.semanticDepGraphUpdater.getSymbol(node);
if (sym instanceof NgModuleSymbol) {
symbol = sym;
}
}
for (const ref of topLevelImport.resolvedReferences) {
const dirMeta = this.metaReader.getDirectiveMetadata(ref);
if (dirMeta !== null) {
if (!dirMeta.isComponent) {
continue;
}
const mayExportProviders = this.exportedProviderStatusResolver.mayExportProviders(dirMeta.ref, (importRef) => {
if (symbol !== null && this.semanticDepGraphUpdater !== null) {
const importSymbol = this.semanticDepGraphUpdater.getSymbol(importRef.node);
symbol.addTransitiveImportFromStandaloneComponent(importSymbol);
}
});
if (!mayExportProviders) {
continue;
}
}
const pipeMeta = dirMeta === null ? this.metaReader.getPipeMetadata(ref) : null;
if (pipeMeta !== null) {
continue;
}
refsToEmit.push(ref);
}
if (refsToEmit.length === topLevelImport.resolvedReferences.length) {
data.injectorImports.push(new WrappedNodeExpr(topLevelImport.expression));
} else {
const context = node.getSourceFile();
for (const ref of refsToEmit) {
const emittedRef = this.refEmitter.emit(ref, context);
assertSuccessfulReferenceEmit(emittedRef, topLevelImport.expression, "class");
data.injectorImports.push(emittedRef.expression);
}
}
}
if (scope !== null && !scope.compilation.isPoisoned) {
const context = getSourceFile(node);
for (const exportRef of analysis.exports) {
if (isNgModule(exportRef.node, scope.compilation)) {
const type = this.refEmitter.emit(exportRef, context);
assertSuccessfulReferenceEmit(type, node, "NgModule");
data.injectorImports.push(type.expression);
}
}
for (const decl of analysis.declarations) {
const dirMeta = this.metaReader.getDirectiveMetadata(decl);
if (dirMeta !== null) {
const refType = dirMeta.isComponent ? "Component" : "Directive";
if (dirMeta.selector === null) {
throw new FatalDiagnosticError(ErrorCode.DIRECTIVE_MISSING_SELECTOR, decl.node, `${refType} ${decl.node.name.text} has no selector, please add it!`);
}
continue;
}
}
}
if (diagnostics.length > 0) {
return { diagnostics };
}
if (scope === null || scope.compilation.isPoisoned || scope.exported.isPoisoned || scope.reexports === null) {
return { data };
} else {
return {
data,
reexports: scope.reexports
};
}
}
compileFull(node, { inj, mod, fac, classMetadata, declarations, remoteScopesMayRequireCycleProtection }, { injectorImports }) {
const factoryFn = compileNgFactoryDefField(fac);
const ngInjectorDef = compileInjector(__spreadProps(__spreadValues({}, inj), {
imports: injectorImports
}));
const ngModuleDef = compileNgModule(mod);
const statements = ngModuleDef.statements;
const metadata = classMetadata !== null ? compileClassMetadata(classMetadata) : null;
this.insertMetadataStatement(statements, metadata);
this.appendRemoteScopingStatements(statements, node, declarations, remoteScopesMayRequireCycleProtection);
return this.compileNgModule(factoryFn, ngInjectorDef, ngModuleDef);
}
compilePartial(node, { inj, fac, mod, classMetadata }, { injectorImports }) {
const factoryFn = compileDeclareFactory(fac);
const injectorDef = compileDeclareInjectorFromMetadata(__spreadProps(__spreadValues({}, inj), {
imports: injectorImports
}));
const ngModuleDef = compileDeclareNgModuleFromMetadata(mod);
const metadata = classMetadata !== null ? compileDeclareClassMetadata(classMetadata) : null;
this.insertMetadataStatement(ngModuleDef.statements, metadata);
return this.compileNgModule(factoryFn, injectorDef, ngModuleDef);
}
compileLocal(node, { inj, mod, fac, classMetadata, declarations, remoteScopesMayRequireCycleProtection }) {
const factoryFn = compileNgFactoryDefField(fac);
const ngInjectorDef = compileInjector(__spreadValues({}, inj));
const ngModuleDef = compileNgModule(mod);
const statements = ngModuleDef.statements;
const metadata = classMetadata !== null ? compileClassMetadata(classMetadata) : null;
this.insertMetadataStatement(statements, metadata);
this.appendRemoteScopingStatements(statements, node, declarations, remoteScopesMayRequireCycleProtection);
return this.compileNgModule(factoryFn, ngInjectorDef, ngModuleDef);
}
insertMetadataStatement(ngModuleStatements, metadata) {
if (metadata !== null) {
ngModuleStatements.unshift(metadata.toStmt());
}
}
appendRemoteScopingStatements(ngModuleStatements, node, declarations, remoteScopesMayRequireCycleProtection) {
if (this.compilationMode === CompilationMode.LOCAL) {
return;
}
const context = getSourceFile(node);
for (const decl of declarations) {
const remoteScope = this.scopeRegistry.getRemoteScope(decl.node);
if (remoteScope !== null) {
const directives = remoteScope.directives.map((directive) => {
const type = this.refEmitter.emit(directive, context);
assertSuccessfulReferenceEmit(type, node, "directive");
return type.expression;
});
const pipes = remoteScope.pipes.map((pipe2) => {
const type = this.refEmitter.emit(pipe2, context);
assertSuccessfulReferenceEmit(type, node, "pipe");
return type.expression;
});
const directiveArray = new LiteralArrayExpr(directives);
const pipesArray = new LiteralArrayExpr(pipes);
const directiveExpr = remoteScopesMayRequireCycleProtection && directives.length > 0 ? new FunctionExpr([], [new ReturnStatement(directiveArray)]) : directiveArray;
const pipesExpr = remoteScopesMayRequireCycleProtection && pipes.length > 0 ? new FunctionExpr([], [new ReturnStatement(pipesArray)]) : pipesArray;
const componentType = this.refEmitter.emit(decl, context);
assertSuccessfulReferenceEmit(componentType, node, "component");
const declExpr = componentType.expression;
const setComponentScope = new ExternalExpr(Identifiers.setComponentScope);
const callExpr = new InvokeFunctionExpr(setComponentScope, [
declExpr,
directiveExpr,
pipesExpr
]);
ngModuleStatements.push(callExpr.toStmt());
}
}
}
compileNgModule(factoryFn, injectorDef, ngModuleDef) {
const res = [
factoryFn,
{
name: "\u0275mod",
initializer: ngModuleDef.expression,
statements: ngModuleDef.statements,
type: ngModuleDef.type,
deferrableImports: null
},
{
name: "\u0275inj",
initializer: injectorDef.expression,
statements: injectorDef.statements,
type: injectorDef.type,
deferrableImports: null
}
];
return res;
}
_toR3Reference(origin, valueRef, valueContext) {
if (valueRef.hasOwningModuleGuess) {
return toR3Reference(origin, valueRef, valueContext, this.refEmitter);
} else {
return toR3Reference(origin, valueRef, valueContext, this.refEmitter);
}
}
isClassDeclarationReference(ref) {
return this.reflector.isClass(ref.node);
}
resolveTypeList(expr, resolvedList, className, arrayName, absoluteIndex, allowUnresolvedReferences) {
let hasModuleWithProviders = false;
const refList = [];
const dynamicValueSet = /* @__PURE__ */ new Set();
if (!Array.isArray(resolvedList)) {
if (allowUnresolvedReferences) {
return {
references: [],
hasModuleWithProviders: false,
dynamicValues: []
};
}
throw createValueHasWrongTypeError(expr, resolvedList, `Expected array when reading the NgModule.${arrayName} of ${className}`);
}
for (let idx = 0; idx < resolvedList.length; idx++) {
let entry = resolvedList[idx];
if (entry instanceof SyntheticValue && isResolvedModuleWithProviders(entry)) {
entry = entry.value.ngModule;
hasModuleWithProviders = true;
} else if (entry instanceof Map && entry.has("ngModule")) {
entry = entry.get("ngModule");
hasModuleWithProviders = true;
}
if (Array.isArray(entry)) {
const recursiveResult = this.resolveTypeList(expr, entry, className, arrayName, absoluteIndex, allowUnresolvedReferences);
refList.push(...recursiveResult.references);
for (const d of recursiveResult.dynamicValues) {
dynamicValueSet.add(d);
}
absoluteIndex += recursiveResult.references.length;
hasModuleWithProviders = hasModuleWithProviders || recursiveResult.hasModuleWithProviders;
} else if (entry instanceof Reference2) {
if (!this.isClassDeclarationReference(entry)) {
throw createValueHasWrongTypeError(entry.node, entry, `Value at position ${absoluteIndex} in the NgModule.${arrayName} of ${className} is not a class`);
}
refList.push(entry);
absoluteIndex += 1;
} else if (entry instanceof DynamicValue && allowUnresolvedReferences) {
dynamicValueSet.add(entry);
continue;
} else {
throw createValueHasWrongTypeError(expr, entry, `Value at position ${absoluteIndex} in the NgModule.${arrayName} of ${className} is not a reference`);
}
}
return {
references: refList,
hasModuleWithProviders,
dynamicValues: [...dynamicValueSet]
};
}
};
function isNgModule(node, compilation) {
return !compilation.dependencies.some((dep) => dep.ref.node === node);
}
function isModuleIdExpression(expr) {
return import_typescript60.default.isPropertyAccessExpression(expr) && import_typescript60.default.isIdentifier(expr.expression) && expr.expression.text === "module" && expr.name.text === "id";
}
function makeStandaloneBootstrapDiagnostic(ngModuleClass, bootstrappedClassRef, rawBootstrapExpr) {
const componentClassName = bootstrappedClassRef.node.name.text;
const message = `The \`${componentClassName}\` class is a standalone component, which can not be used in the \`@NgModule.bootstrap\` array. Use the \`bootstrapApplication\` function for bootstrap instead.`;
const relatedInformation = [
makeRelatedInformation(ngModuleClass, `The 'bootstrap' array is present on this NgModule.`)
];
return makeDiagnostic(ErrorCode.NGMODULE_BOOTSTRAP_IS_STANDALONE, getDiagnosticNode(bootstrappedClassRef, rawBootstrapExpr), message, relatedInformation);
}
function isSyntheticReference(ref) {
return ref.synthetic;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/component/src/diagnostics.mjs
function makeCyclicImportInfo(ref, type, cycle) {
const name = ref.debugName || "(unknown)";
const path4 = cycle.getPath().map((sf) => sf.fileName).join(" -> ");
const message = `The ${type} '${name}' is used in the template but importing it would create a cycle: `;
return makeRelatedInformation(ref.node, message + path4);
}
function checkCustomElementSelectorForErrors(selector) {
if (selector.includes(".") || selector.includes("[") && selector.includes("]")) {
return null;
}
if (!/^[a-z]/.test(selector)) {
return "Selector of a ShadowDom-encapsulated component must start with a lower case letter.";
}
if (/[A-Z]/.test(selector)) {
return "Selector of a ShadowDom-encapsulated component must all be in lower case.";
}
if (!selector.includes("-")) {
return "Selector of a component that uses ViewEncapsulation.ShadowDom must contain a hyphen.";
}
return null;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/component/src/resources.mjs
var import_typescript62 = __toESM(require("typescript"), 1);
function getTemplateDeclarationNodeForError(declaration) {
return declaration.isInline ? declaration.expression : declaration.templateUrlExpression;
}
function extractTemplate(node, template2, evaluator, depTracker, resourceLoader, options, compilationMode) {
if (template2.isInline) {
let sourceStr;
let sourceParseRange = null;
let templateContent;
let sourceMapping;
let escapedString = false;
let sourceMapUrl;
if (import_typescript62.default.isStringLiteral(template2.expression) || import_typescript62.default.isNoSubstitutionTemplateLiteral(template2.expression)) {
sourceParseRange = getTemplateRange(template2.expression);
sourceStr = template2.expression.getSourceFile().text;
templateContent = template2.expression.text;
escapedString = true;
sourceMapping = {
type: "direct",
node: template2.expression
};
sourceMapUrl = template2.resolvedTemplateUrl;
} else {
const resolvedTemplate = evaluator.evaluate(template2.expression);
assertLocalCompilationUnresolvedConst(compilationMode, resolvedTemplate, template2.expression, "Unresolved identifier found for @Component.template field! Did you import this identifier from a file outside of the compilation unit? This is not allowed when Angular compiler runs in local mode. Possible solutions: 1) Move the declaration into a file within the compilation unit, 2) Inline the template, 3) Move the template into a separate .html file and include it using @Component.templateUrl");
if (typeof resolvedTemplate !== "string") {
throw createValueHasWrongTypeError(template2.expression, resolvedTemplate, "template must be a string");
}
sourceStr = resolvedTemplate;
templateContent = resolvedTemplate;
sourceMapping = {
type: "indirect",
node: template2.expression,
componentClass: node,
template: templateContent
};
sourceMapUrl = null;
}
return __spreadProps(__spreadValues({}, parseExtractedTemplate(template2, sourceStr, sourceParseRange, escapedString, sourceMapUrl, options)), {
content: templateContent,
sourceMapping,
declaration: template2
});
} else {
const templateContent = resourceLoader.load(template2.resolvedTemplateUrl);
if (depTracker !== null) {
depTracker.addResourceDependency(node.getSourceFile(), absoluteFrom(template2.resolvedTemplateUrl));
}
return __spreadProps(__spreadValues({}, parseExtractedTemplate(
template2,
templateContent,
null,
false,
template2.resolvedTemplateUrl,
options
)), {
content: templateContent,
sourceMapping: {
type: "external",
componentClass: node,
node: template2.templateUrlExpression,
template: templateContent,
templateUrl: template2.resolvedTemplateUrl
},
declaration: template2
});
}
}
function parseExtractedTemplate(template2, sourceStr, sourceParseRange, escapedString, sourceMapUrl, options) {
const i18nNormalizeLineEndingsInICUs = escapedString || options.i18nNormalizeLineEndingsInICUs;
const commonParseOptions = {
interpolationConfig: template2.interpolationConfig,
range: sourceParseRange != null ? sourceParseRange : void 0,
enableI18nLegacyMessageIdFormat: options.enableI18nLegacyMessageIdFormat,
i18nNormalizeLineEndingsInICUs,
alwaysAttemptHtmlToR3AstConversion: options.usePoisonedData,
escapedString,
enableBlockSyntax: options.enableBlockSyntax,
enableLetSyntax: options.enableLetSyntax
};
const parsedTemplate = parseTemplate(sourceStr, sourceMapUrl != null ? sourceMapUrl : "", __spreadProps(__spreadValues({}, commonParseOptions), {
preserveWhitespaces: template2.preserveWhitespaces,
preserveSignificantWhitespace: options.preserveSignificantWhitespace
}));
const { nodes: diagNodes } = parseTemplate(sourceStr, sourceMapUrl != null ? sourceMapUrl : "", __spreadProps(__spreadValues({}, commonParseOptions), {
preserveWhitespaces: true,
preserveLineEndings: true,
preserveSignificantWhitespace: true,
leadingTriviaChars: []
}));
return __spreadProps(__spreadValues({}, parsedTemplate), {
diagNodes,
file: new ParseSourceFile(sourceStr, sourceMapUrl != null ? sourceMapUrl : "")
});
}
function parseTemplateDeclaration(node, decorator, component, containingFile, evaluator, depTracker, resourceLoader, defaultPreserveWhitespaces) {
let preserveWhitespaces = defaultPreserveWhitespaces;
if (component.has("preserveWhitespaces")) {
const expr = component.get("preserveWhitespaces");
const value = evaluator.evaluate(expr);
if (typeof value !== "boolean") {
throw createValueHasWrongTypeError(expr, value, "preserveWhitespaces must be a boolean");
}
preserveWhitespaces = value;
}
let interpolationConfig = DEFAULT_INTERPOLATION_CONFIG;
if (component.has("interpolation")) {
const expr = component.get("interpolation");
const value = evaluator.evaluate(expr);
if (!Array.isArray(value) || value.length !== 2 || !value.every((element2) => typeof element2 === "string")) {
throw createValueHasWrongTypeError(expr, value, "interpolation must be an array with 2 elements of string type");
}
interpolationConfig = InterpolationConfig.fromArray(value);
}
if (component.has("templateUrl")) {
const templateUrlExpr = component.get("templateUrl");
const templateUrl = evaluator.evaluate(templateUrlExpr);
if (typeof templateUrl !== "string") {
throw createValueHasWrongTypeError(templateUrlExpr, templateUrl, "templateUrl must be a string");
}
try {
const resourceUrl = resourceLoader.resolve(templateUrl, containingFile);
return {
isInline: false,
interpolationConfig,
preserveWhitespaces,
templateUrl,
templateUrlExpression: templateUrlExpr,
resolvedTemplateUrl: resourceUrl
};
} catch (e) {
if (depTracker !== null) {
depTracker.recordDependencyAnalysisFailure(node.getSourceFile());
}
throw makeResourceNotFoundError(templateUrl, templateUrlExpr, 0);
}
} else if (component.has("template")) {
return {
isInline: true,
interpolationConfig,
preserveWhitespaces,
expression: component.get("template"),
templateUrl: containingFile,
resolvedTemplateUrl: containingFile
};
} else {
throw new FatalDiagnosticError(ErrorCode.COMPONENT_MISSING_TEMPLATE, decorator.node, "component is missing a template");
}
}
function preloadAndParseTemplate(evaluator, resourceLoader, depTracker, preanalyzeTemplateCache, node, decorator, component, containingFile, defaultPreserveWhitespaces, options, compilationMode) {
if (component.has("templateUrl")) {
const templateUrlExpr = component.get("templateUrl");
const templateUrl = evaluator.evaluate(templateUrlExpr);
if (typeof templateUrl !== "string") {
throw createValueHasWrongTypeError(templateUrlExpr, templateUrl, "templateUrl must be a string");
}
try {
const resourceUrl = resourceLoader.resolve(templateUrl, containingFile);
const templatePromise = resourceLoader.preload(resourceUrl, {
type: "template",
containingFile
});
if (templatePromise !== void 0) {
return templatePromise.then(() => {
const templateDecl = parseTemplateDeclaration(node, decorator, component, containingFile, evaluator, depTracker, resourceLoader, defaultPreserveWhitespaces);
const template2 = extractTemplate(node, templateDecl, evaluator, depTracker, resourceLoader, options, compilationMode);
preanalyzeTemplateCache.set(node, template2);
return template2;
});
} else {
return Promise.resolve(null);
}
} catch (e) {
if (depTracker !== null) {
depTracker.recordDependencyAnalysisFailure(node.getSourceFile());
}
throw makeResourceNotFoundError(templateUrl, templateUrlExpr, 0);
}
} else {
const templateDecl = parseTemplateDeclaration(node, decorator, component, containingFile, evaluator, depTracker, resourceLoader, defaultPreserveWhitespaces);
const template2 = extractTemplate(node, templateDecl, evaluator, depTracker, resourceLoader, options, compilationMode);
preanalyzeTemplateCache.set(node, template2);
return Promise.resolve(template2);
}
}
function getTemplateRange(templateExpr) {
const startPos = templateExpr.getStart() + 1;
const { line, character } = import_typescript62.default.getLineAndCharacterOfPosition(templateExpr.getSourceFile(), startPos);
return {
startPos,
startLine: line,
startCol: character,
endPos: templateExpr.getEnd() - 1
};
}
function makeResourceNotFoundError(file, nodeForError, resourceType) {
let errorText;
switch (resourceType) {
case 0:
errorText = `Could not find template file '${file}'.`;
break;
case 1:
errorText = `Could not find stylesheet file '${file}' linked from the template.`;
break;
case 2:
errorText = `Could not find stylesheet file '${file}'.`;
break;
}
return new FatalDiagnosticError(ErrorCode.COMPONENT_RESOURCE_NOT_FOUND, nodeForError, errorText);
}
function transformDecoratorResources(dec, component, styles, template2) {
if (dec.name !== "Component") {
return dec;
}
if (!component.has("templateUrl") && !component.has("styleUrls") && !component.has("styleUrl") && !component.has("styles")) {
return dec;
}
const metadata = new Map(component);
if (metadata.has("templateUrl")) {
metadata.delete("templateUrl");
metadata.set("template", import_typescript62.default.factory.createStringLiteral(template2.content));
}
if (metadata.has("styleUrls") || metadata.has("styleUrl") || metadata.has("styles")) {
metadata.delete("styles");
metadata.delete("styleUrls");
metadata.delete("styleUrl");
if (styles.length > 0) {
const styleNodes = styles.reduce((result, style) => {
if (style.trim().length > 0) {
result.push(import_typescript62.default.factory.createStringLiteral(style));
}
return result;
}, []);
if (styleNodes.length > 0) {
metadata.set("styles", import_typescript62.default.factory.createArrayLiteralExpression(styleNodes));
}
}
}
const newMetadataFields = [];
for (const [name, value] of metadata.entries()) {
newMetadataFields.push(import_typescript62.default.factory.createPropertyAssignment(name, value));
}
return __spreadProps(__spreadValues({}, dec), { args: [import_typescript62.default.factory.createObjectLiteralExpression(newMetadataFields)] });
}
function extractComponentStyleUrls(evaluator, component) {
const styleUrlsExpr = component.get("styleUrls");
const styleUrlExpr = component.get("styleUrl");
if (styleUrlsExpr !== void 0 && styleUrlExpr !== void 0) {
throw new FatalDiagnosticError(ErrorCode.COMPONENT_INVALID_STYLE_URLS, styleUrlExpr, "@Component cannot define both `styleUrl` and `styleUrls`. Use `styleUrl` if the component has one stylesheet, or `styleUrls` if it has multiple");
}
if (styleUrlsExpr !== void 0) {
return extractStyleUrlsFromExpression(evaluator, component.get("styleUrls"));
}
if (styleUrlExpr !== void 0) {
const styleUrl = evaluator.evaluate(styleUrlExpr);
if (typeof styleUrl !== "string") {
throw createValueHasWrongTypeError(styleUrlExpr, styleUrl, "styleUrl must be a string");
}
return [
{
url: styleUrl,
source: 2,
nodeForError: styleUrlExpr
}
];
}
return [];
}
function extractStyleUrlsFromExpression(evaluator, styleUrlsExpr) {
const styleUrls = [];
if (import_typescript62.default.isArrayLiteralExpression(styleUrlsExpr)) {
for (const styleUrlExpr of styleUrlsExpr.elements) {
if (import_typescript62.default.isSpreadElement(styleUrlExpr)) {
styleUrls.push(...extractStyleUrlsFromExpression(evaluator, styleUrlExpr.expression));
} else {
const styleUrl = evaluator.evaluate(styleUrlExpr);
if (typeof styleUrl !== "string") {
throw createValueHasWrongTypeError(styleUrlExpr, styleUrl, "styleUrl must be a string");
}
styleUrls.push({
url: styleUrl,
source: 2,
nodeForError: styleUrlExpr
});
}
}
} else {
const evaluatedStyleUrls = evaluator.evaluate(styleUrlsExpr);
if (!isStringArray(evaluatedStyleUrls)) {
throw createValueHasWrongTypeError(styleUrlsExpr, evaluatedStyleUrls, "styleUrls must be an array of strings");
}
for (const styleUrl of evaluatedStyleUrls) {
styleUrls.push({
url: styleUrl,
source: 2,
nodeForError: styleUrlsExpr
});
}
}
return styleUrls;
}
function extractStyleResources(resourceLoader, component, containingFile) {
const styles = /* @__PURE__ */ new Set();
function stringLiteralElements(array) {
return array.elements.filter((e) => import_typescript62.default.isStringLiteralLike(e));
}
const styleUrlExpr = component.get("styleUrl");
const styleUrlsExpr = component.get("styleUrls");
if (styleUrlsExpr !== void 0 && import_typescript62.default.isArrayLiteralExpression(styleUrlsExpr)) {
for (const expression of stringLiteralElements(styleUrlsExpr)) {
const resource = stringLiteralUrlToResource(resourceLoader, expression, containingFile);
if (resource !== null) {
styles.add(resource);
}
}
} else if (styleUrlExpr !== void 0 && import_typescript62.default.isStringLiteralLike(styleUrlExpr)) {
const resource = stringLiteralUrlToResource(resourceLoader, styleUrlExpr, containingFile);
if (resource !== null) {
styles.add(resource);
}
}
const stylesExpr = component.get("styles");
if (stylesExpr !== void 0) {
if (import_typescript62.default.isArrayLiteralExpression(stylesExpr)) {
for (const expression of stringLiteralElements(stylesExpr)) {
styles.add({ path: null, expression });
}
} else if (import_typescript62.default.isStringLiteralLike(stylesExpr)) {
styles.add({ path: null, expression: stylesExpr });
}
}
return styles;
}
function stringLiteralUrlToResource(resourceLoader, expression, containingFile) {
try {
const resourceUrl = resourceLoader.resolve(expression.text, containingFile);
return { path: absoluteFrom(resourceUrl), expression };
} catch (e) {
return null;
}
}
function _extractTemplateStyleUrls(template2) {
if (template2.styleUrls === null) {
return [];
}
const nodeForError = getTemplateDeclarationNodeForError(template2.declaration);
return template2.styleUrls.map((url) => ({
url,
source: 1,
nodeForError
}));
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/component/src/symbol.mjs
var ComponentSymbol = class extends DirectiveSymbol {
constructor() {
super(...arguments);
this.usedDirectives = [];
this.usedPipes = [];
this.isRemotelyScoped = false;
}
isEmitAffected(previousSymbol, publicApiAffected) {
if (!(previousSymbol instanceof ComponentSymbol)) {
return true;
}
const isSymbolUnaffected = (current, previous) => isReferenceEqual(current, previous) && !publicApiAffected.has(current.symbol);
return this.isRemotelyScoped !== previousSymbol.isRemotelyScoped || !isArrayEqual(this.usedDirectives, previousSymbol.usedDirectives, isSymbolUnaffected) || !isArrayEqual(this.usedPipes, previousSymbol.usedPipes, isSymbolUnaffected);
}
isTypeCheckBlockAffected(previousSymbol, typeCheckApiAffected) {
if (!(previousSymbol instanceof ComponentSymbol)) {
return true;
}
const isInheritanceChainAffected = (symbol) => {
let currentSymbol = symbol;
while (currentSymbol instanceof DirectiveSymbol) {
if (typeCheckApiAffected.has(currentSymbol)) {
return true;
}
currentSymbol = currentSymbol.baseClass;
}
return false;
};
const isDirectiveUnaffected = (current, previous) => isReferenceEqual(current, previous) && !isInheritanceChainAffected(current.symbol);
const isPipeUnaffected = (current, previous) => isReferenceEqual(current, previous) && !typeCheckApiAffected.has(current.symbol);
return !isArrayEqual(this.usedDirectives, previousSymbol.usedDirectives, isDirectiveUnaffected) || !isArrayEqual(this.usedPipes, previousSymbol.usedPipes, isPipeUnaffected);
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/component/src/util.mjs
function collectAnimationNames(value, animationTriggerNames) {
if (value instanceof Map) {
const name = value.get("name");
if (typeof name === "string") {
animationTriggerNames.staticTriggerNames.push(name);
} else {
animationTriggerNames.includesDynamicAnimations = true;
}
} else if (Array.isArray(value)) {
for (const resolvedValue of value) {
collectAnimationNames(resolvedValue, animationTriggerNames);
}
} else {
animationTriggerNames.includesDynamicAnimations = true;
}
}
function isAngularAnimationsReference(reference2, symbolName) {
return reference2.ownedByModuleGuess === "@angular/animations" && reference2.debugName === symbolName;
}
var animationTriggerResolver = (fn2, node, resolve5, unresolvable) => {
const animationTriggerMethodName = "trigger";
if (!isAngularAnimationsReference(fn2, animationTriggerMethodName)) {
return unresolvable;
}
const triggerNameExpression = node.arguments[0];
if (!triggerNameExpression) {
return unresolvable;
}
const res = /* @__PURE__ */ new Map();
res.set("name", resolve5(triggerNameExpression));
return res;
};
function validateAndFlattenComponentImports(imports, expr, isDeferred) {
const flattened = [];
const errorMessage = isDeferred ? `'deferredImports' must be an array of components, directives, or pipes.` : `'imports' must be an array of components, directives, pipes, or NgModules.`;
if (!Array.isArray(imports)) {
const error = createValueHasWrongTypeError(expr, imports, errorMessage).toDiagnostic();
return {
imports: [],
diagnostics: [error]
};
}
const diagnostics = [];
for (const ref of imports) {
if (Array.isArray(ref)) {
const { imports: childImports, diagnostics: childDiagnostics } = validateAndFlattenComponentImports(ref, expr, isDeferred);
flattened.push(...childImports);
diagnostics.push(...childDiagnostics);
} else if (ref instanceof Reference2) {
if (isNamedClassDeclaration(ref.node)) {
flattened.push(ref);
} else {
diagnostics.push(createValueHasWrongTypeError(ref.getOriginForDiagnostics(expr), ref, errorMessage).toDiagnostic());
}
} else if (isLikelyModuleWithProviders(ref)) {
let origin = expr;
if (ref instanceof SyntheticValue) {
origin = getOriginNodeForDiagnostics(ref.value.mwpCall, expr);
}
diagnostics.push(makeDiagnostic(ErrorCode.COMPONENT_UNKNOWN_IMPORT, origin, `Component imports contains a ModuleWithProviders value, likely the result of a 'Module.forRoot()'-style call. These calls are not used to configure components and are not valid in standalone component imports - consider importing them in the application bootstrap instead.`));
} else {
diagnostics.push(createValueHasWrongTypeError(expr, imports, errorMessage).toDiagnostic());
}
}
return { imports: flattened, diagnostics };
}
function isLikelyModuleWithProviders(value) {
if (value instanceof SyntheticValue && isResolvedModuleWithProviders(value)) {
return true;
}
if (value instanceof Map && value.has("ngModule")) {
return true;
}
return false;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/program_driver/src/api.mjs
var NgOriginalFile = Symbol("NgOriginalFile");
var UpdateMode;
(function(UpdateMode2) {
UpdateMode2[UpdateMode2["Complete"] = 0] = "Complete";
UpdateMode2[UpdateMode2["Incremental"] = 1] = "Incremental";
})(UpdateMode || (UpdateMode = {}));
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/program_driver/src/ts_create_program_driver.mjs
var import_typescript66 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/shims/src/adapter.mjs
var import_typescript63 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/shims/src/expando.mjs
var NgExtension = Symbol("NgExtension");
function isExtended(sf) {
return sf[NgExtension] !== void 0;
}
function sfExtensionData(sf) {
const extSf = sf;
if (extSf[NgExtension] !== void 0) {
return extSf[NgExtension];
}
const extension = {
isTopLevelShim: false,
fileShim: null,
originalReferencedFiles: null,
taggedReferenceFiles: null
};
extSf[NgExtension] = extension;
return extension;
}
function isFileShimSourceFile(sf) {
return isExtended(sf) && sf[NgExtension].fileShim !== null;
}
function isShim(sf) {
return isExtended(sf) && (sf[NgExtension].fileShim !== null || sf[NgExtension].isTopLevelShim);
}
function copyFileShimData(from, to) {
if (!isFileShimSourceFile(from)) {
return;
}
sfExtensionData(to).fileShim = sfExtensionData(from).fileShim;
}
function untagAllTsFiles(program) {
for (const sf of program.getSourceFiles()) {
untagTsFile(sf);
}
}
function retagAllTsFiles(program) {
for (const sf of program.getSourceFiles()) {
retagTsFile(sf);
}
}
function untagTsFile(sf) {
if (sf.isDeclarationFile || !isExtended(sf)) {
return;
}
const ext = sfExtensionData(sf);
if (ext.originalReferencedFiles !== null) {
sf.referencedFiles = ext.originalReferencedFiles;
}
}
function retagTsFile(sf) {
if (sf.isDeclarationFile || !isExtended(sf)) {
return;
}
const ext = sfExtensionData(sf);
if (ext.taggedReferenceFiles !== null) {
sf.referencedFiles = ext.taggedReferenceFiles;
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/shims/src/util.mjs
var TS_EXTENSIONS = /\.tsx?$/i;
function makeShimFileName(fileName, suffix) {
return absoluteFrom(fileName.replace(TS_EXTENSIONS, suffix));
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/shims/src/adapter.mjs
var ShimAdapter = class {
constructor(delegate, tsRootFiles, topLevelGenerators, perFileGenerators, oldProgram) {
this.delegate = delegate;
this.shims = /* @__PURE__ */ new Map();
this.priorShims = /* @__PURE__ */ new Map();
this.notShims = /* @__PURE__ */ new Set();
this.generators = [];
this.ignoreForEmit = /* @__PURE__ */ new Set();
this.extensionPrefixes = [];
for (const gen of perFileGenerators) {
const pattern = `^(.*)\\.${gen.extensionPrefix}\\.ts$`;
const regexp = new RegExp(pattern, "i");
this.generators.push({
generator: gen,
test: regexp,
suffix: `.${gen.extensionPrefix}.ts`
});
this.extensionPrefixes.push(gen.extensionPrefix);
}
const extraInputFiles = [];
for (const gen of topLevelGenerators) {
const sf = gen.makeTopLevelShim();
sfExtensionData(sf).isTopLevelShim = true;
if (!gen.shouldEmit) {
this.ignoreForEmit.add(sf);
}
const fileName = absoluteFromSourceFile(sf);
this.shims.set(fileName, sf);
extraInputFiles.push(fileName);
}
for (const rootFile of tsRootFiles) {
for (const gen of this.generators) {
extraInputFiles.push(makeShimFileName(rootFile, gen.suffix));
}
}
this.extraInputFiles = extraInputFiles;
if (oldProgram !== null) {
for (const oldSf of oldProgram.getSourceFiles()) {
if (oldSf.isDeclarationFile || !isFileShimSourceFile(oldSf)) {
continue;
}
this.priorShims.set(absoluteFromSourceFile(oldSf), oldSf);
}
}
}
maybeGenerate(fileName) {
if (this.notShims.has(fileName)) {
return null;
} else if (this.shims.has(fileName)) {
return this.shims.get(fileName);
}
if (isDtsPath(fileName)) {
this.notShims.add(fileName);
return null;
}
for (const record of this.generators) {
const match = record.test.exec(fileName);
if (match === null) {
continue;
}
const prefix = match[1];
let baseFileName = absoluteFrom(prefix + ".ts");
let inputFile = this.delegate.getSourceFile(baseFileName, import_typescript63.default.ScriptTarget.Latest);
if (inputFile === void 0) {
baseFileName = absoluteFrom(prefix + ".tsx");
inputFile = this.delegate.getSourceFile(baseFileName, import_typescript63.default.ScriptTarget.Latest);
}
if (inputFile === void 0 || isShim(inputFile)) {
return void 0;
}
return this.generateSpecific(fileName, record.generator, inputFile);
}
this.notShims.add(fileName);
return null;
}
generateSpecific(fileName, generator, inputFile) {
let priorShimSf = null;
if (this.priorShims.has(fileName)) {
priorShimSf = this.priorShims.get(fileName);
this.priorShims.delete(fileName);
}
const shimSf = generator.generateShimForFile(inputFile, fileName, priorShimSf);
sfExtensionData(shimSf).fileShim = {
extension: generator.extensionPrefix,
generatedFrom: absoluteFromSourceFile(inputFile)
};
if (!generator.shouldEmit) {
this.ignoreForEmit.add(shimSf);
}
this.shims.set(fileName, shimSf);
return shimSf;
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/shims/src/reference_tagger.mjs
var ShimReferenceTagger = class {
constructor(shimExtensions) {
this.tagged = /* @__PURE__ */ new Set();
this.enabled = true;
this.suffixes = shimExtensions.map((extension) => `.${extension}.ts`);
}
tag(sf) {
if (!this.enabled || sf.isDeclarationFile || isShim(sf) || this.tagged.has(sf) || !isNonDeclarationTsPath(sf.fileName)) {
return;
}
const ext = sfExtensionData(sf);
if (ext.originalReferencedFiles === null) {
ext.originalReferencedFiles = sf.referencedFiles;
}
const referencedFiles = [...ext.originalReferencedFiles];
const sfPath = absoluteFromSourceFile(sf);
for (const suffix of this.suffixes) {
referencedFiles.push({
fileName: makeShimFileName(sfPath, suffix),
pos: 0,
end: 0
});
}
ext.taggedReferenceFiles = referencedFiles;
sf.referencedFiles = referencedFiles;
this.tagged.add(sf);
}
finalize() {
this.enabled = false;
this.tagged.clear();
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/program_driver/src/ts_create_program_driver.mjs
var DelegatingCompilerHost = class {
get jsDocParsingMode() {
return this.delegate.jsDocParsingMode;
}
set jsDocParsingMode(mode) {
this.delegate.jsDocParsingMode = mode;
}
constructor(delegate) {
this.delegate = delegate;
this.createHash = this.delegateMethod("createHash");
this.directoryExists = this.delegateMethod("directoryExists");
this.getCancellationToken = this.delegateMethod("getCancellationToken");
this.getCanonicalFileName = this.delegateMethod("getCanonicalFileName");
this.getCurrentDirectory = this.delegateMethod("getCurrentDirectory");
this.getDefaultLibFileName = this.delegateMethod("getDefaultLibFileName");
this.getDefaultLibLocation = this.delegateMethod("getDefaultLibLocation");
this.getDirectories = this.delegateMethod("getDirectories");
this.getEnvironmentVariable = this.delegateMethod("getEnvironmentVariable");
this.getNewLine = this.delegateMethod("getNewLine");
this.getParsedCommandLine = this.delegateMethod("getParsedCommandLine");
this.getSourceFileByPath = this.delegateMethod("getSourceFileByPath");
this.readDirectory = this.delegateMethod("readDirectory");
this.readFile = this.delegateMethod("readFile");
this.realpath = this.delegateMethod("realpath");
this.resolveModuleNames = this.delegateMethod("resolveModuleNames");
this.resolveTypeReferenceDirectives = this.delegateMethod("resolveTypeReferenceDirectives");
this.trace = this.delegateMethod("trace");
this.useCaseSensitiveFileNames = this.delegateMethod("useCaseSensitiveFileNames");
this.getModuleResolutionCache = this.delegateMethod("getModuleResolutionCache");
this.hasInvalidatedResolutions = this.delegateMethod("hasInvalidatedResolutions");
this.resolveModuleNameLiterals = this.delegateMethod("resolveModuleNameLiterals");
this.resolveTypeReferenceDirectiveReferences = this.delegateMethod("resolveTypeReferenceDirectiveReferences");
}
delegateMethod(name) {
return this.delegate[name] !== void 0 ? this.delegate[name].bind(this.delegate) : void 0;
}
};
var UpdatedProgramHost = class extends DelegatingCompilerHost {
constructor(sfMap, originalProgram, delegate, shimExtensionPrefixes) {
super(delegate);
this.originalProgram = originalProgram;
this.shimExtensionPrefixes = shimExtensionPrefixes;
this.shimTagger = new ShimReferenceTagger(this.shimExtensionPrefixes);
this.sfMap = sfMap;
}
getSourceFile(fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile) {
let delegateSf = this.originalProgram.getSourceFile(fileName);
if (delegateSf === void 0) {
delegateSf = this.delegate.getSourceFile(fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile);
}
if (delegateSf === void 0) {
return void 0;
}
let sf;
if (this.sfMap.has(fileName)) {
sf = this.sfMap.get(fileName);
copyFileShimData(delegateSf, sf);
} else {
sf = delegateSf;
}
sf = toUnredirectedSourceFile(sf);
this.shimTagger.tag(sf);
return sf;
}
postProgramCreationCleanup() {
this.shimTagger.finalize();
}
writeFile() {
throw new Error(`TypeCheckProgramHost should never write files`);
}
fileExists(fileName) {
return this.sfMap.has(fileName) || this.delegate.fileExists(fileName);
}
};
var TsCreateProgramDriver = class {
constructor(originalProgram, originalHost, options, shimExtensionPrefixes) {
this.originalProgram = originalProgram;
this.originalHost = originalHost;
this.options = options;
this.shimExtensionPrefixes = shimExtensionPrefixes;
this.sfMap = /* @__PURE__ */ new Map();
this.supportsInlineOperations = true;
this.program = this.originalProgram;
}
getProgram() {
return this.program;
}
updateFiles(contents, updateMode) {
if (contents.size === 0) {
if (updateMode !== UpdateMode.Complete || this.sfMap.size === 0) {
return;
}
}
if (updateMode === UpdateMode.Complete) {
this.sfMap.clear();
}
for (const [filePath, { newText, originalFile }] of contents.entries()) {
const sf = import_typescript66.default.createSourceFile(filePath, newText, import_typescript66.default.ScriptTarget.Latest, true);
if (originalFile !== null) {
sf[NgOriginalFile] = originalFile;
}
this.sfMap.set(filePath, sf);
}
const host = new UpdatedProgramHost(this.sfMap, this.originalProgram, this.originalHost, this.shimExtensionPrefixes);
const oldProgram = this.program;
retagAllTsFiles(oldProgram);
this.program = import_typescript66.default.createProgram({
host,
rootNames: this.program.getRootFileNames(),
options: this.options,
oldProgram
});
host.postProgramCreationCleanup();
untagAllTsFiles(oldProgram);
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/api/checker.mjs
var OptimizeFor;
(function(OptimizeFor2) {
OptimizeFor2[OptimizeFor2["SingleFile"] = 0] = "SingleFile";
OptimizeFor2[OptimizeFor2["WholeProgram"] = 1] = "WholeProgram";
})(OptimizeFor || (OptimizeFor = {}));
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/api/completion.mjs
var CompletionKind;
(function(CompletionKind2) {
CompletionKind2[CompletionKind2["Reference"] = 0] = "Reference";
CompletionKind2[CompletionKind2["Variable"] = 1] = "Variable";
CompletionKind2[CompletionKind2["LetDeclaration"] = 2] = "LetDeclaration";
})(CompletionKind || (CompletionKind = {}));
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/api/scope.mjs
var PotentialImportKind;
(function(PotentialImportKind2) {
PotentialImportKind2[PotentialImportKind2["NgModule"] = 0] = "NgModule";
PotentialImportKind2[PotentialImportKind2["Standalone"] = 1] = "Standalone";
})(PotentialImportKind || (PotentialImportKind = {}));
var PotentialImportMode;
(function(PotentialImportMode2) {
PotentialImportMode2[PotentialImportMode2["Normal"] = 0] = "Normal";
PotentialImportMode2[PotentialImportMode2["ForceDirect"] = 1] = "ForceDirect";
})(PotentialImportMode || (PotentialImportMode = {}));
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/api/symbols.mjs
var SymbolKind;
(function(SymbolKind2) {
SymbolKind2[SymbolKind2["Input"] = 0] = "Input";
SymbolKind2[SymbolKind2["Output"] = 1] = "Output";
SymbolKind2[SymbolKind2["Binding"] = 2] = "Binding";
SymbolKind2[SymbolKind2["Reference"] = 3] = "Reference";
SymbolKind2[SymbolKind2["Variable"] = 4] = "Variable";
SymbolKind2[SymbolKind2["Directive"] = 5] = "Directive";
SymbolKind2[SymbolKind2["Element"] = 6] = "Element";
SymbolKind2[SymbolKind2["Template"] = 7] = "Template";
SymbolKind2[SymbolKind2["Expression"] = 8] = "Expression";
SymbolKind2[SymbolKind2["DomBinding"] = 9] = "DomBinding";
SymbolKind2[SymbolKind2["Pipe"] = 10] = "Pipe";
SymbolKind2[SymbolKind2["LetDeclaration"] = 11] = "LetDeclaration";
})(SymbolKind || (SymbolKind = {}));
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/diagnostics/src/diagnostic.mjs
var import_typescript68 = __toESM(require("typescript"), 1);
function makeTemplateDiagnostic(templateId, mapping, span, category, code, messageText, relatedMessages) {
var _a2;
if (mapping.type === "direct") {
let relatedInformation = void 0;
if (relatedMessages !== void 0) {
relatedInformation = [];
for (const relatedMessage of relatedMessages) {
relatedInformation.push({
category: import_typescript68.default.DiagnosticCategory.Message,
code: 0,
file: relatedMessage.sourceFile,
start: relatedMessage.start,
length: relatedMessage.end - relatedMessage.start,
messageText: relatedMessage.text
});
}
}
return {
source: "ngtsc",
code,
category,
messageText,
file: mapping.node.getSourceFile(),
componentFile: mapping.node.getSourceFile(),
templateId,
start: span.start.offset,
length: span.end.offset - span.start.offset,
relatedInformation
};
} else if (mapping.type === "indirect" || mapping.type === "external") {
const componentSf = mapping.componentClass.getSourceFile();
const componentName = mapping.componentClass.name.text;
const fileName = mapping.type === "indirect" ? `${componentSf.fileName} (${componentName} template)` : mapping.templateUrl;
let relatedInformation = [];
if (relatedMessages !== void 0) {
for (const relatedMessage of relatedMessages) {
relatedInformation.push({
category: import_typescript68.default.DiagnosticCategory.Message,
code: 0,
file: relatedMessage.sourceFile,
start: relatedMessage.start,
length: relatedMessage.end - relatedMessage.start,
messageText: relatedMessage.text
});
}
}
let sf;
try {
sf = getParsedTemplateSourceFile(fileName, mapping);
} catch (e) {
const failureChain = makeDiagnosticChain(`Failed to report an error in '${fileName}' at ${span.start.line + 1}:${span.start.col + 1}`, [makeDiagnosticChain((_a2 = e == null ? void 0 : e.stack) != null ? _a2 : `${e}`)]);
return {
source: "ngtsc",
category,
code,
messageText: addDiagnosticChain(messageText, [failureChain]),
file: componentSf,
componentFile: componentSf,
templateId,
start: mapping.node.getStart(),
length: mapping.node.getEnd() - mapping.node.getStart(),
relatedInformation
};
}
relatedInformation.push({
category: import_typescript68.default.DiagnosticCategory.Message,
code: 0,
file: componentSf,
start: mapping.node.getStart(),
length: mapping.node.getEnd() - mapping.node.getStart(),
messageText: `Error occurs in the template of component ${componentName}.`
});
return {
source: "ngtsc",
category,
code,
messageText,
file: sf,
componentFile: componentSf,
templateId,
start: span.start.offset,
length: span.end.offset - span.start.offset,
relatedInformation
};
} else {
throw new Error(`Unexpected source mapping type: ${mapping.type}`);
}
}
var TemplateSourceFile = Symbol("TemplateSourceFile");
function getParsedTemplateSourceFile(fileName, mapping) {
if (mapping[TemplateSourceFile] === void 0) {
mapping[TemplateSourceFile] = parseTemplateAsSourceFile(fileName, mapping.template);
}
return mapping[TemplateSourceFile];
}
var parseTemplateAsSourceFileForTest = null;
function parseTemplateAsSourceFile(fileName, template2) {
if (parseTemplateAsSourceFileForTest !== null) {
return parseTemplateAsSourceFileForTest(fileName, template2);
}
return import_typescript68.default.createSourceFile(
fileName,
template2,
import_typescript68.default.ScriptTarget.Latest,
false,
import_typescript68.default.ScriptKind.JSX
);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/diagnostics/src/id.mjs
var TEMPLATE_ID = Symbol("ngTemplateId");
var NEXT_TEMPLATE_ID = Symbol("ngNextTemplateId");
function getTemplateId(clazz) {
const node = clazz;
if (node[TEMPLATE_ID] === void 0) {
node[TEMPLATE_ID] = allocateTemplateId(node.getSourceFile());
}
return node[TEMPLATE_ID];
}
function allocateTemplateId(sf) {
if (sf[NEXT_TEMPLATE_ID] === void 0) {
sf[NEXT_TEMPLATE_ID] = 1;
}
return `tcb${sf[NEXT_TEMPLATE_ID]++}`;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/completion.mjs
var import_typescript70 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/comments.mjs
var import_typescript69 = __toESM(require("typescript"), 1);
var parseSpanComment = /^(\d+),(\d+)$/;
function readSpanComment(node, sourceFile = node.getSourceFile()) {
return import_typescript69.default.forEachTrailingCommentRange(sourceFile.text, node.getEnd(), (pos, end, kind) => {
if (kind !== import_typescript69.default.SyntaxKind.MultiLineCommentTrivia) {
return null;
}
const commentText = sourceFile.text.substring(pos + 2, end - 2);
const match = commentText.match(parseSpanComment);
if (match === null) {
return null;
}
return new AbsoluteSourceSpan(+match[1], +match[2]);
}) || null;
}
var CommentTriviaType;
(function(CommentTriviaType2) {
CommentTriviaType2["DIAGNOSTIC"] = "D";
CommentTriviaType2["EXPRESSION_TYPE_IDENTIFIER"] = "T";
})(CommentTriviaType || (CommentTriviaType = {}));
var ExpressionIdentifier;
(function(ExpressionIdentifier2) {
ExpressionIdentifier2["DIRECTIVE"] = "DIR";
ExpressionIdentifier2["COMPONENT_COMPLETION"] = "COMPCOMP";
ExpressionIdentifier2["EVENT_PARAMETER"] = "EP";
ExpressionIdentifier2["VARIABLE_AS_EXPRESSION"] = "VAE";
})(ExpressionIdentifier || (ExpressionIdentifier = {}));
function addExpressionIdentifier(node, identifier) {
import_typescript69.default.addSyntheticTrailingComment(
node,
import_typescript69.default.SyntaxKind.MultiLineCommentTrivia,
`${CommentTriviaType.EXPRESSION_TYPE_IDENTIFIER}:${identifier}`,
false
);
}
var IGNORE_FOR_DIAGNOSTICS_MARKER = `${CommentTriviaType.DIAGNOSTIC}:ignore`;
function markIgnoreDiagnostics(node) {
import_typescript69.default.addSyntheticTrailingComment(
node,
import_typescript69.default.SyntaxKind.MultiLineCommentTrivia,
IGNORE_FOR_DIAGNOSTICS_MARKER,
false
);
}
function hasIgnoreForDiagnosticsMarker(node, sourceFile) {
return import_typescript69.default.forEachTrailingCommentRange(sourceFile.text, node.getEnd(), (pos, end, kind) => {
if (kind !== import_typescript69.default.SyntaxKind.MultiLineCommentTrivia) {
return null;
}
const commentText = sourceFile.text.substring(pos + 2, end - 2);
return commentText === IGNORE_FOR_DIAGNOSTICS_MARKER;
}) === true;
}
function makeRecursiveVisitor(visitor) {
function recursiveVisitor(node) {
const res = visitor(node);
return res !== null ? res : node.forEachChild(recursiveVisitor);
}
return recursiveVisitor;
}
function getSpanFromOptions(opts) {
let withSpan = null;
if (opts.withSpan !== void 0) {
if (opts.withSpan instanceof AbsoluteSourceSpan) {
withSpan = opts.withSpan;
} else {
withSpan = { start: opts.withSpan.start.offset, end: opts.withSpan.end.offset };
}
}
return withSpan;
}
function findFirstMatchingNode(tcb, opts) {
var _a2;
const withSpan = getSpanFromOptions(opts);
const withExpressionIdentifier = opts.withExpressionIdentifier;
const sf = tcb.getSourceFile();
const visitor = makeRecursiveVisitor((node) => {
if (!opts.filter(node)) {
return null;
}
if (withSpan !== null) {
const comment = readSpanComment(node, sf);
if (comment === null || withSpan.start !== comment.start || withSpan.end !== comment.end) {
return null;
}
}
if (withExpressionIdentifier !== void 0 && !hasExpressionIdentifier(sf, node, withExpressionIdentifier)) {
return null;
}
return node;
});
return (_a2 = tcb.forEachChild(visitor)) != null ? _a2 : null;
}
function findAllMatchingNodes(tcb, opts) {
const withSpan = getSpanFromOptions(opts);
const withExpressionIdentifier = opts.withExpressionIdentifier;
const results = [];
const stack = [tcb];
const sf = tcb.getSourceFile();
while (stack.length > 0) {
const node = stack.pop();
if (!opts.filter(node)) {
stack.push(...node.getChildren());
continue;
}
if (withSpan !== null) {
const comment = readSpanComment(node, sf);
if (comment === null || withSpan.start !== comment.start || withSpan.end !== comment.end) {
stack.push(...node.getChildren());
continue;
}
}
if (withExpressionIdentifier !== void 0 && !hasExpressionIdentifier(sf, node, withExpressionIdentifier)) {
continue;
}
results.push(node);
}
return results;
}
function hasExpressionIdentifier(sourceFile, node, identifier) {
return import_typescript69.default.forEachTrailingCommentRange(sourceFile.text, node.getEnd(), (pos, end, kind) => {
if (kind !== import_typescript69.default.SyntaxKind.MultiLineCommentTrivia) {
return false;
}
const commentText = sourceFile.text.substring(pos + 2, end - 2);
return commentText === `${CommentTriviaType.EXPRESSION_TYPE_IDENTIFIER}:${identifier}`;
}) || false;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/completion.mjs
var CompletionEngine = class {
constructor(tcb, data, tcbPath, tcbIsShim) {
this.tcb = tcb;
this.data = data;
this.tcbPath = tcbPath;
this.tcbIsShim = tcbIsShim;
this.templateContextCache = /* @__PURE__ */ new Map();
this.expressionCompletionCache = /* @__PURE__ */ new Map();
const globalRead = findFirstMatchingNode(this.tcb, {
filter: import_typescript70.default.isPropertyAccessExpression,
withExpressionIdentifier: ExpressionIdentifier.COMPONENT_COMPLETION
});
if (globalRead !== null) {
this.componentContext = {
tcbPath: this.tcbPath,
isShimFile: this.tcbIsShim,
positionInFile: globalRead.name.getStart()
};
} else {
this.componentContext = null;
}
}
getGlobalCompletions(context, node) {
if (this.componentContext === null) {
return null;
}
const templateContext = this.getTemplateContextCompletions(context);
if (templateContext === null) {
return null;
}
let nodeContext = null;
if (node instanceof EmptyExpr) {
const nodeLocation = findFirstMatchingNode(this.tcb, {
filter: import_typescript70.default.isIdentifier,
withSpan: node.sourceSpan
});
if (nodeLocation !== null) {
nodeContext = {
tcbPath: this.tcbPath,
isShimFile: this.tcbIsShim,
positionInFile: nodeLocation.getStart()
};
}
}
if (node instanceof PropertyRead && node.receiver instanceof ImplicitReceiver) {
const nodeLocation = findFirstMatchingNode(this.tcb, {
filter: import_typescript70.default.isPropertyAccessExpression,
withSpan: node.sourceSpan
});
if (nodeLocation) {
nodeContext = {
tcbPath: this.tcbPath,
isShimFile: this.tcbIsShim,
positionInFile: nodeLocation.getStart()
};
}
}
return {
componentContext: this.componentContext,
templateContext,
nodeContext
};
}
getExpressionCompletionLocation(expr) {
if (this.expressionCompletionCache.has(expr)) {
return this.expressionCompletionCache.get(expr);
}
let tsExpr = null;
if (expr instanceof PropertyRead || expr instanceof PropertyWrite) {
tsExpr = findFirstMatchingNode(this.tcb, {
filter: import_typescript70.default.isPropertyAccessExpression,
withSpan: expr.nameSpan
});
} else if (expr instanceof SafePropertyRead) {
const ternaryExpr = findFirstMatchingNode(this.tcb, {
filter: import_typescript70.default.isParenthesizedExpression,
withSpan: expr.sourceSpan
});
if (ternaryExpr === null || !import_typescript70.default.isConditionalExpression(ternaryExpr.expression)) {
return null;
}
const whenTrue = ternaryExpr.expression.whenTrue;
if (import_typescript70.default.isPropertyAccessExpression(whenTrue)) {
tsExpr = whenTrue;
} else if (import_typescript70.default.isCallExpression(whenTrue) && import_typescript70.default.isPropertyAccessExpression(whenTrue.expression)) {
tsExpr = whenTrue.expression;
}
}
if (tsExpr === null) {
return null;
}
const res = {
tcbPath: this.tcbPath,
isShimFile: this.tcbIsShim,
positionInFile: tsExpr.name.getEnd()
};
this.expressionCompletionCache.set(expr, res);
return res;
}
getLiteralCompletionLocation(expr) {
if (this.expressionCompletionCache.has(expr)) {
return this.expressionCompletionCache.get(expr);
}
let tsExpr = null;
if (expr instanceof TextAttribute) {
const strNode = findFirstMatchingNode(this.tcb, {
filter: import_typescript70.default.isParenthesizedExpression,
withSpan: expr.sourceSpan
});
if (strNode !== null && import_typescript70.default.isStringLiteral(strNode.expression)) {
tsExpr = strNode.expression;
}
} else {
tsExpr = findFirstMatchingNode(this.tcb, {
filter: (n2) => import_typescript70.default.isStringLiteral(n2) || import_typescript70.default.isNumericLiteral(n2),
withSpan: expr.sourceSpan
});
}
if (tsExpr === null) {
return null;
}
let positionInShimFile = tsExpr.getEnd();
if (import_typescript70.default.isStringLiteral(tsExpr)) {
positionInShimFile -= 1;
}
const res = {
tcbPath: this.tcbPath,
isShimFile: this.tcbIsShim,
positionInFile: positionInShimFile
};
this.expressionCompletionCache.set(expr, res);
return res;
}
getTemplateContextCompletions(context) {
if (this.templateContextCache.has(context)) {
return this.templateContextCache.get(context);
}
const templateContext = /* @__PURE__ */ new Map();
for (const node of this.data.boundTarget.getEntitiesInScope(context)) {
if (node instanceof Reference) {
templateContext.set(node.name, {
kind: CompletionKind.Reference,
node
});
} else if (node instanceof LetDeclaration) {
templateContext.set(node.name, {
kind: CompletionKind.LetDeclaration,
node
});
} else {
templateContext.set(node.name, {
kind: CompletionKind.Variable,
node
});
}
}
this.templateContextCache.set(context, templateContext);
return templateContext;
}
};
// node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
var comma = ",".charCodeAt(0);
var semicolon = ";".charCodeAt(0);
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var intToChar = new Uint8Array(64);
var charToInt = new Uint8Array(128);
for (let i = 0; i < chars.length; i++) {
const c = chars.charCodeAt(i);
intToChar[i] = c;
charToInt[c] = i;
}
function encodeInteger(builder, num, relative8) {
let delta = num - relative8;
delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
do {
let clamped = delta & 31;
delta >>>= 5;
if (delta > 0)
clamped |= 32;
builder.write(intToChar[clamped]);
} while (delta > 0);
return num;
}
var bufLength = 1024 * 16;
var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? {
decode(buf) {
const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
return out.toString();
}
} : {
decode(buf) {
let out = "";
for (let i = 0; i < buf.length; i++) {
out += String.fromCharCode(buf[i]);
}
return out;
}
};
var StringWriter = class {
constructor() {
this.pos = 0;
this.out = "";
this.buffer = new Uint8Array(bufLength);
}
write(v) {
const { buffer } = this;
buffer[this.pos++] = v;
if (this.pos === bufLength) {
this.out += td.decode(buffer);
this.pos = 0;
}
}
flush() {
const { buffer, out, pos } = this;
return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
}
};
function encode(decoded) {
const writer = new StringWriter();
let sourcesIndex = 0;
let sourceLine = 0;
let sourceColumn = 0;
let namesIndex = 0;
for (let i = 0; i < decoded.length; i++) {
const line = decoded[i];
if (i > 0)
writer.write(semicolon);
if (line.length === 0)
continue;
let genColumn = 0;
for (let j = 0; j < line.length; j++) {
const segment = line[j];
if (j > 0)
writer.write(comma);
genColumn = encodeInteger(writer, segment[0], genColumn);
if (segment.length === 1)
continue;
sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
sourceLine = encodeInteger(writer, segment[2], sourceLine);
sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
if (segment.length === 4)
continue;
namesIndex = encodeInteger(writer, segment[4], namesIndex);
}
}
return writer.flush();
}
// node_modules/magic-string/dist/magic-string.es.mjs
var BitSet = class {
constructor(arg) {
this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
}
add(n2) {
this.bits[n2 >> 5] |= 1 << (n2 & 31);
}
has(n2) {
return !!(this.bits[n2 >> 5] & 1 << (n2 & 31));
}
};
var Chunk = class {
constructor(start, end, content) {
this.start = start;
this.end = end;
this.original = content;
this.intro = "";
this.outro = "";
this.content = content;
this.storeName = false;
this.edited = false;
{
this.previous = null;
this.next = null;
}
}
appendLeft(content) {
this.outro += content;
}
appendRight(content) {
this.intro = this.intro + content;
}
clone() {
const chunk = new Chunk(this.start, this.end, this.original);
chunk.intro = this.intro;
chunk.outro = this.outro;
chunk.content = this.content;
chunk.storeName = this.storeName;
chunk.edited = this.edited;
return chunk;
}
contains(index) {
return this.start < index && index < this.end;
}
eachNext(fn2) {
let chunk = this;
while (chunk) {
fn2(chunk);
chunk = chunk.next;
}
}
eachPrevious(fn2) {
let chunk = this;
while (chunk) {
fn2(chunk);
chunk = chunk.previous;
}
}
edit(content, storeName, contentOnly) {
this.content = content;
if (!contentOnly) {
this.intro = "";
this.outro = "";
}
this.storeName = storeName;
this.edited = true;
return this;
}
prependLeft(content) {
this.outro = content + this.outro;
}
prependRight(content) {
this.intro = content + this.intro;
}
reset() {
this.intro = "";
this.outro = "";
if (this.edited) {
this.content = this.original;
this.storeName = false;
this.edited = false;
}
}
split(index) {
const sliceIndex = index - this.start;
const originalBefore = this.original.slice(0, sliceIndex);
const originalAfter = this.original.slice(sliceIndex);
this.original = originalBefore;
const newChunk = new Chunk(index, this.end, originalAfter);
newChunk.outro = this.outro;
this.outro = "";
this.end = index;
if (this.edited) {
newChunk.edit("", false);
this.content = "";
} else {
this.content = originalBefore;
}
newChunk.next = this.next;
if (newChunk.next)
newChunk.next.previous = newChunk;
newChunk.previous = this;
this.next = newChunk;
return newChunk;
}
toString() {
return this.intro + this.content + this.outro;
}
trimEnd(rx) {
this.outro = this.outro.replace(rx, "");
if (this.outro.length)
return true;
const trimmed = this.content.replace(rx, "");
if (trimmed.length) {
if (trimmed !== this.content) {
this.split(this.start + trimmed.length).edit("", void 0, true);
if (this.edited) {
this.edit(trimmed, this.storeName, true);
}
}
return true;
} else {
this.edit("", void 0, true);
this.intro = this.intro.replace(rx, "");
if (this.intro.length)
return true;
}
}
trimStart(rx) {
this.intro = this.intro.replace(rx, "");
if (this.intro.length)
return true;
const trimmed = this.content.replace(rx, "");
if (trimmed.length) {
if (trimmed !== this.content) {
const newChunk = this.split(this.end - trimmed.length);
if (this.edited) {
newChunk.edit(trimmed, this.storeName, true);
}
this.edit("", void 0, true);
}
return true;
} else {
this.edit("", void 0, true);
this.outro = this.outro.replace(rx, "");
if (this.outro.length)
return true;
}
}
};
function getBtoa() {
if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") {
return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
} else if (typeof Buffer === "function") {
return (str) => Buffer.from(str, "utf-8").toString("base64");
} else {
return () => {
throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported.");
};
}
}
var btoa = /* @__PURE__ */ getBtoa();
var SourceMap = class {
constructor(properties) {
this.version = 3;
this.file = properties.file;
this.sources = properties.sources;
this.sourcesContent = properties.sourcesContent;
this.names = properties.names;
this.mappings = encode(properties.mappings);
if (typeof properties.x_google_ignoreList !== "undefined") {
this.x_google_ignoreList = properties.x_google_ignoreList;
}
}
toString() {
return JSON.stringify(this);
}
toUrl() {
return "data:application/json;charset=utf-8;base64," + btoa(this.toString());
}
};
function guessIndent(code) {
const lines = code.split("\n");
const tabbed = lines.filter((line) => /^\t+/.test(line));
const spaced = lines.filter((line) => /^ {2,}/.test(line));
if (tabbed.length === 0 && spaced.length === 0) {
return null;
}
if (tabbed.length >= spaced.length) {
return " ";
}
const min = spaced.reduce((previous, current) => {
const numSpaces = /^ +/.exec(current)[0].length;
return Math.min(numSpaces, previous);
}, Infinity);
return new Array(min + 1).join(" ");
}
function getRelativePath(from, to) {
const fromParts = from.split(/[/\\]/);
const toParts = to.split(/[/\\]/);
fromParts.pop();
while (fromParts[0] === toParts[0]) {
fromParts.shift();
toParts.shift();
}
if (fromParts.length) {
let i = fromParts.length;
while (i--)
fromParts[i] = "..";
}
return fromParts.concat(toParts).join("/");
}
var toString = Object.prototype.toString;
function isObject(thing) {
return toString.call(thing) === "[object Object]";
}
function getLocator(source) {
const originalLines = source.split("\n");
const lineOffsets = [];
for (let i = 0, pos = 0; i < originalLines.length; i++) {
lineOffsets.push(pos);
pos += originalLines[i].length + 1;
}
return function locate(index) {
let i = 0;
let j = lineOffsets.length;
while (i < j) {
const m = i + j >> 1;
if (index < lineOffsets[m]) {
j = m;
} else {
i = m + 1;
}
}
const line = i - 1;
const column = index - lineOffsets[line];
return { line, column };
};
}
var wordRegex = /\w/;
var Mappings = class {
constructor(hires) {
this.hires = hires;
this.generatedCodeLine = 0;
this.generatedCodeColumn = 0;
this.raw = [];
this.rawSegments = this.raw[this.generatedCodeLine] = [];
this.pending = null;
}
addEdit(sourceIndex, content, loc, nameIndex) {
if (content.length) {
const contentLengthMinusOne = content.length - 1;
let contentLineEnd = content.indexOf("\n", 0);
let previousContentLineEnd = -1;
while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
const segment2 = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
if (nameIndex >= 0) {
segment2.push(nameIndex);
}
this.rawSegments.push(segment2);
this.generatedCodeLine += 1;
this.raw[this.generatedCodeLine] = this.rawSegments = [];
this.generatedCodeColumn = 0;
previousContentLineEnd = contentLineEnd;
contentLineEnd = content.indexOf("\n", contentLineEnd + 1);
}
const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
if (nameIndex >= 0) {
segment.push(nameIndex);
}
this.rawSegments.push(segment);
this.advance(content.slice(previousContentLineEnd + 1));
} else if (this.pending) {
this.rawSegments.push(this.pending);
this.advance(content);
}
this.pending = null;
}
addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
let originalCharIndex = chunk.start;
let first = true;
let charInHiresBoundary = false;
while (originalCharIndex < chunk.end) {
if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
if (this.hires === "boundary") {
if (wordRegex.test(original[originalCharIndex])) {
if (!charInHiresBoundary) {
this.rawSegments.push(segment);
charInHiresBoundary = true;
}
} else {
this.rawSegments.push(segment);
charInHiresBoundary = false;
}
} else {
this.rawSegments.push(segment);
}
}
if (original[originalCharIndex] === "\n") {
loc.line += 1;
loc.column = 0;
this.generatedCodeLine += 1;
this.raw[this.generatedCodeLine] = this.rawSegments = [];
this.generatedCodeColumn = 0;
first = true;
} else {
loc.column += 1;
this.generatedCodeColumn += 1;
first = false;
}
originalCharIndex += 1;
}
this.pending = null;
}
advance(str) {
if (!str)
return;
const lines = str.split("\n");
if (lines.length > 1) {
for (let i = 0; i < lines.length - 1; i++) {
this.generatedCodeLine++;
this.raw[this.generatedCodeLine] = this.rawSegments = [];
}
this.generatedCodeColumn = 0;
}
this.generatedCodeColumn += lines[lines.length - 1].length;
}
};
var n = "\n";
var warned = {
insertLeft: false,
insertRight: false,
storeName: false
};
var MagicString = class {
constructor(string, options = {}) {
const chunk = new Chunk(0, string.length, string);
Object.defineProperties(this, {
original: { writable: true, value: string },
outro: { writable: true, value: "" },
intro: { writable: true, value: "" },
firstChunk: { writable: true, value: chunk },
lastChunk: { writable: true, value: chunk },
lastSearchedChunk: { writable: true, value: chunk },
byStart: { writable: true, value: {} },
byEnd: { writable: true, value: {} },
filename: { writable: true, value: options.filename },
indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
sourcemapLocations: { writable: true, value: new BitSet() },
storedNames: { writable: true, value: {} },
indentStr: { writable: true, value: void 0 },
ignoreList: { writable: true, value: options.ignoreList }
});
this.byStart[0] = chunk;
this.byEnd[string.length] = chunk;
}
addSourcemapLocation(char) {
this.sourcemapLocations.add(char);
}
append(content) {
if (typeof content !== "string")
throw new TypeError("outro content must be a string");
this.outro += content;
return this;
}
appendLeft(index, content) {
if (typeof content !== "string")
throw new TypeError("inserted content must be a string");
this._split(index);
const chunk = this.byEnd[index];
if (chunk) {
chunk.appendLeft(content);
} else {
this.intro += content;
}
return this;
}
appendRight(index, content) {
if (typeof content !== "string")
throw new TypeError("inserted content must be a string");
this._split(index);
const chunk = this.byStart[index];
if (chunk) {
chunk.appendRight(content);
} else {
this.outro += content;
}
return this;
}
clone() {
const cloned = new MagicString(this.original, { filename: this.filename });
let originalChunk = this.firstChunk;
let clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone();
while (originalChunk) {
cloned.byStart[clonedChunk.start] = clonedChunk;
cloned.byEnd[clonedChunk.end] = clonedChunk;
const nextOriginalChunk = originalChunk.next;
const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
if (nextClonedChunk) {
clonedChunk.next = nextClonedChunk;
nextClonedChunk.previous = clonedChunk;
clonedChunk = nextClonedChunk;
}
originalChunk = nextOriginalChunk;
}
cloned.lastChunk = clonedChunk;
if (this.indentExclusionRanges) {
cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
}
cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
cloned.intro = this.intro;
cloned.outro = this.outro;
return cloned;
}
generateDecodedMap(options) {
options = options || {};
const sourceIndex = 0;
const names = Object.keys(this.storedNames);
const mappings = new Mappings(options.hires);
const locate = getLocator(this.original);
if (this.intro) {
mappings.advance(this.intro);
}
this.firstChunk.eachNext((chunk) => {
const loc = locate(chunk.start);
if (chunk.intro.length)
mappings.advance(chunk.intro);
if (chunk.edited) {
mappings.addEdit(
sourceIndex,
chunk.content,
loc,
chunk.storeName ? names.indexOf(chunk.original) : -1
);
} else {
mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
}
if (chunk.outro.length)
mappings.advance(chunk.outro);
});
return {
file: options.file ? options.file.split(/[/\\]/).pop() : void 0,
sources: [
options.source ? getRelativePath(options.file || "", options.source) : options.file || ""
],
sourcesContent: options.includeContent ? [this.original] : void 0,
names,
mappings: mappings.raw,
x_google_ignoreList: this.ignoreList ? [sourceIndex] : void 0
};
}
generateMap(options) {
return new SourceMap(this.generateDecodedMap(options));
}
_ensureindentStr() {
if (this.indentStr === void 0) {
this.indentStr = guessIndent(this.original);
}
}
_getRawIndentString() {
this._ensureindentStr();
return this.indentStr;
}
getIndentString() {
this._ensureindentStr();
return this.indentStr === null ? " " : this.indentStr;
}
indent(indentStr, options) {
const pattern = /^[^\r\n]/gm;
if (isObject(indentStr)) {
options = indentStr;
indentStr = void 0;
}
if (indentStr === void 0) {
this._ensureindentStr();
indentStr = this.indentStr || " ";
}
if (indentStr === "")
return this;
options = options || {};
const isExcluded = {};
if (options.exclude) {
const exclusions = typeof options.exclude[0] === "number" ? [options.exclude] : options.exclude;
exclusions.forEach((exclusion) => {
for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
isExcluded[i] = true;
}
});
}
let shouldIndentNextCharacter = options.indentStart !== false;
const replacer = (match) => {
if (shouldIndentNextCharacter)
return `${indentStr}${match}`;
shouldIndentNextCharacter = true;
return match;
};
this.intro = this.intro.replace(pattern, replacer);
let charIndex = 0;
let chunk = this.firstChunk;
while (chunk) {
const end = chunk.end;
if (chunk.edited) {
if (!isExcluded[charIndex]) {
chunk.content = chunk.content.replace(pattern, replacer);
if (chunk.content.length) {
shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === "\n";
}
}
} else {
charIndex = chunk.start;
while (charIndex < end) {
if (!isExcluded[charIndex]) {
const char = this.original[charIndex];
if (char === "\n") {
shouldIndentNextCharacter = true;
} else if (char !== "\r" && shouldIndentNextCharacter) {
shouldIndentNextCharacter = false;
if (charIndex === chunk.start) {
chunk.prependRight(indentStr);
} else {
this._splitChunk(chunk, charIndex);
chunk = chunk.next;
chunk.prependRight(indentStr);
}
}
}
charIndex += 1;
}
}
charIndex = chunk.end;
chunk = chunk.next;
}
this.outro = this.outro.replace(pattern, replacer);
return this;
}
insert() {
throw new Error(
"magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)"
);
}
insertLeft(index, content) {
if (!warned.insertLeft) {
console.warn(
"magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead"
);
warned.insertLeft = true;
}
return this.appendLeft(index, content);
}
insertRight(index, content) {
if (!warned.insertRight) {
console.warn(
"magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead"
);
warned.insertRight = true;
}
return this.prependRight(index, content);
}
move(start, end, index) {
if (index >= start && index <= end)
throw new Error("Cannot move a selection inside itself");
this._split(start);
this._split(end);
this._split(index);
const first = this.byStart[start];
const last = this.byEnd[end];
const oldLeft = first.previous;
const oldRight = last.next;
const newRight = this.byStart[index];
if (!newRight && last === this.lastChunk)
return this;
const newLeft = newRight ? newRight.previous : this.lastChunk;
if (oldLeft)
oldLeft.next = oldRight;
if (oldRight)
oldRight.previous = oldLeft;
if (newLeft)
newLeft.next = first;
if (newRight)
newRight.previous = last;
if (!first.previous)
this.firstChunk = last.next;
if (!last.next) {
this.lastChunk = first.previous;
this.lastChunk.next = null;
}
first.previous = newLeft;
last.next = newRight || null;
if (!newLeft)
this.firstChunk = first;
if (!newRight)
this.lastChunk = last;
return this;
}
overwrite(start, end, content, options) {
options = options || {};
return this.update(start, end, content, __spreadProps(__spreadValues({}, options), { overwrite: !options.contentOnly }));
}
update(start, end, content, options) {
if (typeof content !== "string")
throw new TypeError("replacement content must be a string");
if (this.original.length !== 0) {
while (start < 0)
start += this.original.length;
while (end < 0)
end += this.original.length;
}
if (end > this.original.length)
throw new Error("end is out of bounds");
if (start === end)
throw new Error(
"Cannot overwrite a zero-length range \u2013 use appendLeft or prependRight instead"
);
this._split(start);
this._split(end);
if (options === true) {
if (!warned.storeName) {
console.warn(
"The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string"
);
warned.storeName = true;
}
options = { storeName: true };
}
const storeName = options !== void 0 ? options.storeName : false;
const overwrite = options !== void 0 ? options.overwrite : false;
if (storeName) {
const original = this.original.slice(start, end);
Object.defineProperty(this.storedNames, original, {
writable: true,
value: true,
enumerable: true
});
}
const first = this.byStart[start];
const last = this.byEnd[end];
if (first) {
let chunk = first;
while (chunk !== last) {
if (chunk.next !== this.byStart[chunk.end]) {
throw new Error("Cannot overwrite across a split point");
}
chunk = chunk.next;
chunk.edit("", false);
}
first.edit(content, storeName, !overwrite);
} else {
const newChunk = new Chunk(start, end, "").edit(content, storeName);
last.next = newChunk;
newChunk.previous = last;
}
return this;
}
prepend(content) {
if (typeof content !== "string")
throw new TypeError("outro content must be a string");
this.intro = content + this.intro;
return this;
}
prependLeft(index, content) {
if (typeof content !== "string")
throw new TypeError("inserted content must be a string");
this._split(index);
const chunk = this.byEnd[index];
if (chunk) {
chunk.prependLeft(content);
} else {
this.intro = content + this.intro;
}
return this;
}
prependRight(index, content) {
if (typeof content !== "string")
throw new TypeError("inserted content must be a string");
this._split(index);
const chunk = this.byStart[index];
if (chunk) {
chunk.prependRight(content);
} else {
this.outro = content + this.outro;
}
return this;
}
remove(start, end) {
if (this.original.length !== 0) {
while (start < 0)
start += this.original.length;
while (end < 0)
end += this.original.length;
}
if (start === end)
return this;
if (start < 0 || end > this.original.length)
throw new Error("Character is out of bounds");
if (start > end)
throw new Error("end must be greater than start");
this._split(start);
this._split(end);
let chunk = this.byStart[start];
while (chunk) {
chunk.intro = "";
chunk.outro = "";
chunk.edit("");
chunk = end > chunk.end ? this.byStart[chunk.end] : null;
}
return this;
}
reset(start, end) {
if (this.original.length !== 0) {
while (start < 0)
start += this.original.length;
while (end < 0)
end += this.original.length;
}
if (start === end)
return this;
if (start < 0 || end > this.original.length)
throw new Error("Character is out of bounds");
if (start > end)
throw new Error("end must be greater than start");
this._split(start);
this._split(end);
let chunk = this.byStart[start];
while (chunk) {
chunk.reset();
chunk = end > chunk.end ? this.byStart[chunk.end] : null;
}
return this;
}
lastChar() {
if (this.outro.length)
return this.outro[this.outro.length - 1];
let chunk = this.lastChunk;
do {
if (chunk.outro.length)
return chunk.outro[chunk.outro.length - 1];
if (chunk.content.length)
return chunk.content[chunk.content.length - 1];
if (chunk.intro.length)
return chunk.intro[chunk.intro.length - 1];
} while (chunk = chunk.previous);
if (this.intro.length)
return this.intro[this.intro.length - 1];
return "";
}
lastLine() {
let lineIndex = this.outro.lastIndexOf(n);
if (lineIndex !== -1)
return this.outro.substr(lineIndex + 1);
let lineStr = this.outro;
let chunk = this.lastChunk;
do {
if (chunk.outro.length > 0) {
lineIndex = chunk.outro.lastIndexOf(n);
if (lineIndex !== -1)
return chunk.outro.substr(lineIndex + 1) + lineStr;
lineStr = chunk.outro + lineStr;
}
if (chunk.content.length > 0) {
lineIndex = chunk.content.lastIndexOf(n);
if (lineIndex !== -1)
return chunk.content.substr(lineIndex + 1) + lineStr;
lineStr = chunk.content + lineStr;
}
if (chunk.intro.length > 0) {
lineIndex = chunk.intro.lastIndexOf(n);
if (lineIndex !== -1)
return chunk.intro.substr(lineIndex + 1) + lineStr;
lineStr = chunk.intro + lineStr;
}
} while (chunk = chunk.previous);
lineIndex = this.intro.lastIndexOf(n);
if (lineIndex !== -1)
return this.intro.substr(lineIndex + 1) + lineStr;
return this.intro + lineStr;
}
slice(start = 0, end = this.original.length) {
if (this.original.length !== 0) {
while (start < 0)
start += this.original.length;
while (end < 0)
end += this.original.length;
}
let result = "";
let chunk = this.firstChunk;
while (chunk && (chunk.start > start || chunk.end <= start)) {
if (chunk.start < end && chunk.end >= end) {
return result;
}
chunk = chunk.next;
}
if (chunk && chunk.edited && chunk.start !== start)
throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
const startChunk = chunk;
while (chunk) {
if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
result += chunk.intro;
}
const containsEnd = chunk.start < end && chunk.end >= end;
if (containsEnd && chunk.edited && chunk.end !== end)
throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
const sliceStart = startChunk === chunk ? start - chunk.start : 0;
const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
result += chunk.content.slice(sliceStart, sliceEnd);
if (chunk.outro && (!containsEnd || chunk.end === end)) {
result += chunk.outro;
}
if (containsEnd) {
break;
}
chunk = chunk.next;
}
return result;
}
snip(start, end) {
const clone = this.clone();
clone.remove(0, start);
clone.remove(end, clone.original.length);
return clone;
}
_split(index) {
if (this.byStart[index] || this.byEnd[index])
return;
let chunk = this.lastSearchedChunk;
const searchForward = index > chunk.end;
while (chunk) {
if (chunk.contains(index))
return this._splitChunk(chunk, index);
chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
}
}
_splitChunk(chunk, index) {
if (chunk.edited && chunk.content.length) {
const loc = getLocator(this.original)(index);
throw new Error(
`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} \u2013 "${chunk.original}")`
);
}
const newChunk = chunk.split(index);
this.byEnd[index] = chunk;
this.byStart[index] = newChunk;
this.byEnd[newChunk.end] = newChunk;
if (chunk === this.lastChunk)
this.lastChunk = newChunk;
this.lastSearchedChunk = chunk;
return true;
}
toString() {
let str = this.intro;
let chunk = this.firstChunk;
while (chunk) {
str += chunk.toString();
chunk = chunk.next;
}
return str + this.outro;
}
isEmpty() {
let chunk = this.firstChunk;
do {
if (chunk.intro.length && chunk.intro.trim() || chunk.content.length && chunk.content.trim() || chunk.outro.length && chunk.outro.trim())
return false;
} while (chunk = chunk.next);
return true;
}
length() {
let chunk = this.firstChunk;
let length = 0;
do {
length += chunk.intro.length + chunk.content.length + chunk.outro.length;
} while (chunk = chunk.next);
return length;
}
trimLines() {
return this.trim("[\\r\\n]");
}
trim(charType) {
return this.trimStart(charType).trimEnd(charType);
}
trimEndAborted(charType) {
const rx = new RegExp((charType || "\\s") + "+$");
this.outro = this.outro.replace(rx, "");
if (this.outro.length)
return true;
let chunk = this.lastChunk;
do {
const end = chunk.end;
const aborted = chunk.trimEnd(rx);
if (chunk.end !== end) {
if (this.lastChunk === chunk) {
this.lastChunk = chunk.next;
}
this.byEnd[chunk.end] = chunk;
this.byStart[chunk.next.start] = chunk.next;
this.byEnd[chunk.next.end] = chunk.next;
}
if (aborted)
return true;
chunk = chunk.previous;
} while (chunk);
return false;
}
trimEnd(charType) {
this.trimEndAborted(charType);
return this;
}
trimStartAborted(charType) {
const rx = new RegExp("^" + (charType || "\\s") + "+");
this.intro = this.intro.replace(rx, "");
if (this.intro.length)
return true;
let chunk = this.firstChunk;
do {
const end = chunk.end;
const aborted = chunk.trimStart(rx);
if (chunk.end !== end) {
if (chunk === this.lastChunk)
this.lastChunk = chunk.next;
this.byEnd[chunk.end] = chunk;
this.byStart[chunk.next.start] = chunk.next;
this.byEnd[chunk.next.end] = chunk.next;
}
if (aborted)
return true;
chunk = chunk.next;
} while (chunk);
return false;
}
trimStart(charType) {
this.trimStartAborted(charType);
return this;
}
hasChanged() {
return this.original !== this.toString();
}
_replaceRegexp(searchValue, replacement) {
function getReplacement(match, str) {
if (typeof replacement === "string") {
return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
if (i === "$")
return "$";
if (i === "&")
return match[0];
const num = +i;
if (num < match.length)
return match[+i];
return `$${i}`;
});
} else {
return replacement(...match, match.index, str, match.groups);
}
}
function matchAll(re, str) {
let match;
const matches = [];
while (match = re.exec(str)) {
matches.push(match);
}
return matches;
}
if (searchValue.global) {
const matches = matchAll(searchValue, this.original);
matches.forEach((match) => {
if (match.index != null) {
const replacement2 = getReplacement(match, this.original);
if (replacement2 !== match[0]) {
this.overwrite(
match.index,
match.index + match[0].length,
replacement2
);
}
}
});
} else {
const match = this.original.match(searchValue);
if (match && match.index != null) {
const replacement2 = getReplacement(match, this.original);
if (replacement2 !== match[0]) {
this.overwrite(
match.index,
match.index + match[0].length,
replacement2
);
}
}
}
return this;
}
_replaceString(string, replacement) {
const { original } = this;
const index = original.indexOf(string);
if (index !== -1) {
this.overwrite(index, index + string.length, replacement);
}
return this;
}
replace(searchValue, replacement) {
if (typeof searchValue === "string") {
return this._replaceString(searchValue, replacement);
}
return this._replaceRegexp(searchValue, replacement);
}
_replaceAllString(string, replacement) {
const { original } = this;
const stringLength = string.length;
for (let index = original.indexOf(string); index !== -1; index = original.indexOf(string, index + stringLength)) {
const previous = original.slice(index, index + stringLength);
if (previous !== replacement)
this.overwrite(index, index + stringLength, replacement);
}
return this;
}
replaceAll(searchValue, replacement) {
if (typeof searchValue === "string") {
return this._replaceAllString(searchValue, replacement);
}
if (!searchValue.global) {
throw new TypeError(
"MagicString.prototype.replaceAll called with a non-global RegExp argument"
);
}
return this._replaceRegexp(searchValue, replacement);
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/context.mjs
var import_typescript84 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/dom.mjs
var import_typescript71 = __toESM(require("typescript"), 1);
var REGISTRY = new DomElementSchemaRegistry();
var REMOVE_XHTML_REGEX = /^:xhtml:/;
var RegistryDomSchemaChecker = class {
get diagnostics() {
return this._diagnostics;
}
constructor(resolver) {
this.resolver = resolver;
this._diagnostics = [];
}
checkElement(id, element2, schemas, hostIsStandalone) {
const name = element2.name.replace(REMOVE_XHTML_REGEX, "");
if (!REGISTRY.hasElement(name, schemas)) {
const mapping = this.resolver.getSourceMapping(id);
const schemas2 = `'${hostIsStandalone ? "@Component" : "@NgModule"}.schemas'`;
let errorMsg = `'${name}' is not a known element:
`;
errorMsg += `1. If '${name}' is an Angular component, then verify that it is ${hostIsStandalone ? "included in the '@Component.imports' of this component" : "part of this module"}.
`;
if (name.indexOf("-") > -1) {
errorMsg += `2. If '${name}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the ${schemas2} of this component to suppress this message.`;
} else {
errorMsg += `2. To allow any element add 'NO_ERRORS_SCHEMA' to the ${schemas2} of this component.`;
}
const diag = makeTemplateDiagnostic(id, mapping, element2.startSourceSpan, import_typescript71.default.DiagnosticCategory.Error, ngErrorCode(ErrorCode.SCHEMA_INVALID_ELEMENT), errorMsg);
this._diagnostics.push(diag);
}
}
checkProperty(id, element2, name, span, schemas, hostIsStandalone) {
if (!REGISTRY.hasProperty(element2.name, name, schemas)) {
const mapping = this.resolver.getSourceMapping(id);
const decorator = hostIsStandalone ? "@Component" : "@NgModule";
const schemas2 = `'${decorator}.schemas'`;
let errorMsg = `Can't bind to '${name}' since it isn't a known property of '${element2.name}'.`;
if (element2.name.startsWith("ng-")) {
errorMsg += `
1. If '${name}' is an Angular directive, then add 'CommonModule' to the '${decorator}.imports' of this component.
2. To allow any property add 'NO_ERRORS_SCHEMA' to the ${schemas2} of this component.`;
} else if (element2.name.indexOf("-") > -1) {
errorMsg += `
1. If '${element2.name}' is an Angular component and it has '${name}' input, then verify that it is ${hostIsStandalone ? "included in the '@Component.imports' of this component" : "part of this module"}.
2. If '${element2.name}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the ${schemas2} of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the ${schemas2} of this component.`;
}
const diag = makeTemplateDiagnostic(id, mapping, span, import_typescript71.default.DiagnosticCategory.Error, ngErrorCode(ErrorCode.SCHEMA_INVALID_ATTRIBUTE), errorMsg);
this._diagnostics.push(diag);
}
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/environment.mjs
var import_typescript77 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/reference_emit_environment.mjs
var ReferenceEmitEnvironment = class {
constructor(importManager, refEmitter, reflector, contextFile) {
this.importManager = importManager;
this.refEmitter = refEmitter;
this.reflector = reflector;
this.contextFile = contextFile;
}
canReferenceType(ref, flags = ImportFlags.NoAliasing | ImportFlags.AllowTypeImports | ImportFlags.AllowRelativeDtsImports) {
const result = this.refEmitter.emit(ref, this.contextFile, flags);
return result.kind === 0;
}
referenceType(ref, flags = ImportFlags.NoAliasing | ImportFlags.AllowTypeImports | ImportFlags.AllowRelativeDtsImports) {
const ngExpr = this.refEmitter.emit(ref, this.contextFile, flags);
assertSuccessfulReferenceEmit(ngExpr, this.contextFile, "symbol");
return translateType(new ExpressionType(ngExpr.expression), this.contextFile, this.reflector, this.refEmitter, this.importManager);
}
referenceExternalSymbol(moduleName, name) {
const external = new ExternalExpr({ moduleName, name });
return translateExpression(this.contextFile, external, this.importManager);
}
referenceExternalType(moduleName, name, typeParams) {
const external = new ExternalExpr({ moduleName, name });
return translateType(new ExpressionType(external, TypeModifier.None, typeParams), this.contextFile, this.reflector, this.refEmitter, this.importManager);
}
referenceTransplantedType(type) {
return translateType(type, this.contextFile, this.reflector, this.refEmitter, this.importManager);
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/ts_util.mjs
var import_typescript72 = __toESM(require("typescript"), 1);
var SAFE_TO_CAST_WITHOUT_PARENS = /* @__PURE__ */ new Set([
import_typescript72.default.SyntaxKind.ParenthesizedExpression,
import_typescript72.default.SyntaxKind.Identifier,
import_typescript72.default.SyntaxKind.CallExpression,
import_typescript72.default.SyntaxKind.NonNullExpression,
import_typescript72.default.SyntaxKind.ElementAccessExpression,
import_typescript72.default.SyntaxKind.PropertyAccessExpression,
import_typescript72.default.SyntaxKind.ArrayLiteralExpression,
import_typescript72.default.SyntaxKind.ObjectLiteralExpression,
import_typescript72.default.SyntaxKind.StringLiteral,
import_typescript72.default.SyntaxKind.NumericLiteral,
import_typescript72.default.SyntaxKind.TrueKeyword,
import_typescript72.default.SyntaxKind.FalseKeyword,
import_typescript72.default.SyntaxKind.NullKeyword,
import_typescript72.default.SyntaxKind.UndefinedKeyword
]);
function tsCastToAny(expr) {
if (!SAFE_TO_CAST_WITHOUT_PARENS.has(expr.kind)) {
expr = import_typescript72.default.factory.createParenthesizedExpression(expr);
}
return import_typescript72.default.factory.createParenthesizedExpression(import_typescript72.default.factory.createAsExpression(expr, import_typescript72.default.factory.createKeywordTypeNode(import_typescript72.default.SyntaxKind.AnyKeyword)));
}
function tsCreateElement(tagName) {
const createElement = import_typescript72.default.factory.createPropertyAccessExpression(
import_typescript72.default.factory.createIdentifier("document"),
"createElement"
);
return import_typescript72.default.factory.createCallExpression(
createElement,
void 0,
[import_typescript72.default.factory.createStringLiteral(tagName)]
);
}
function tsDeclareVariable(id, type) {
addExpressionIdentifier(type, ExpressionIdentifier.VARIABLE_AS_EXPRESSION);
const initializer = import_typescript72.default.factory.createAsExpression(import_typescript72.default.factory.createNonNullExpression(import_typescript72.default.factory.createNull()), type);
const decl = import_typescript72.default.factory.createVariableDeclaration(
id,
void 0,
void 0,
initializer
);
return import_typescript72.default.factory.createVariableStatement(
void 0,
[decl]
);
}
function tsCreateTypeQueryForCoercedInput(typeName, coercedInputName) {
return import_typescript72.default.factory.createTypeQueryNode(import_typescript72.default.factory.createQualifiedName(typeName, `ngAcceptInputType_${coercedInputName}`));
}
function tsCreateVariable(id, initializer, flags = null) {
const decl = import_typescript72.default.factory.createVariableDeclaration(
id,
void 0,
void 0,
initializer
);
return import_typescript72.default.factory.createVariableStatement(
void 0,
flags === null ? [decl] : import_typescript72.default.factory.createVariableDeclarationList([decl], flags)
);
}
function tsCallMethod(receiver, methodName, args = []) {
const methodAccess = import_typescript72.default.factory.createPropertyAccessExpression(receiver, methodName);
return import_typescript72.default.factory.createCallExpression(
methodAccess,
void 0,
args
);
}
function isAccessExpression2(node) {
return import_typescript72.default.isPropertyAccessExpression(node) || import_typescript72.default.isElementAccessExpression(node);
}
function tsNumericExpression2(value) {
if (value < 0) {
const operand = import_typescript72.default.factory.createNumericLiteral(Math.abs(value));
return import_typescript72.default.factory.createPrefixUnaryExpression(import_typescript72.default.SyntaxKind.MinusToken, operand);
}
return import_typescript72.default.factory.createNumericLiteral(value);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/type_constructor.mjs
var import_typescript76 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/tcb_util.mjs
var import_typescript74 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/type_parameter_emitter.mjs
var import_typescript73 = __toESM(require("typescript"), 1);
var TypeParameterEmitter = class {
constructor(typeParameters, reflector) {
this.typeParameters = typeParameters;
this.reflector = reflector;
}
canEmit(canEmitReference) {
if (this.typeParameters === void 0) {
return true;
}
return this.typeParameters.every((typeParam) => {
return this.canEmitType(typeParam.constraint, canEmitReference) && this.canEmitType(typeParam.default, canEmitReference);
});
}
canEmitType(type, canEmitReference) {
if (type === void 0) {
return true;
}
return canEmitType(type, (typeReference) => {
const reference2 = this.resolveTypeReference(typeReference);
if (reference2 === null) {
return false;
}
if (reference2 instanceof Reference2) {
return canEmitReference(reference2);
}
return true;
});
}
emit(emitReference) {
if (this.typeParameters === void 0) {
return void 0;
}
const emitter = new TypeEmitter((type) => this.translateTypeReference(type, emitReference));
return this.typeParameters.map((typeParam) => {
const constraint = typeParam.constraint !== void 0 ? emitter.emitType(typeParam.constraint) : void 0;
const defaultType = typeParam.default !== void 0 ? emitter.emitType(typeParam.default) : void 0;
return import_typescript73.default.factory.updateTypeParameterDeclaration(typeParam, typeParam.modifiers, typeParam.name, constraint, defaultType);
});
}
resolveTypeReference(type) {
const target = import_typescript73.default.isIdentifier(type.typeName) ? type.typeName : type.typeName.right;
const declaration = this.reflector.getDeclarationOfIdentifier(target);
if (declaration === null || declaration.node === null) {
return null;
}
if (this.isLocalTypeParameter(declaration.node)) {
return type;
}
let owningModule2 = null;
if (typeof declaration.viaModule === "string") {
owningModule2 = {
specifier: declaration.viaModule,
resolutionContext: type.getSourceFile().fileName
};
}
return new Reference2(declaration.node, declaration.viaModule === AmbientImport ? AmbientImport : owningModule2);
}
translateTypeReference(type, emitReference) {
const reference2 = this.resolveTypeReference(type);
if (!(reference2 instanceof Reference2)) {
return reference2;
}
const typeNode = emitReference(reference2);
if (typeNode === null) {
return null;
}
if (!import_typescript73.default.isTypeReferenceNode(typeNode)) {
throw new Error(`Expected TypeReferenceNode for emitted reference, got ${import_typescript73.default.SyntaxKind[typeNode.kind]}.`);
}
return typeNode;
}
isLocalTypeParameter(decl) {
return this.typeParameters.some((param) => param === decl);
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/tcb_util.mjs
var TCB_FILE_IMPORT_GRAPH_PREPARE_IDENTIFIERS = [
Identifiers.InputSignalBrandWriteType
];
var TcbInliningRequirement;
(function(TcbInliningRequirement2) {
TcbInliningRequirement2[TcbInliningRequirement2["MustInline"] = 0] = "MustInline";
TcbInliningRequirement2[TcbInliningRequirement2["ShouldInlineForGenericBounds"] = 1] = "ShouldInlineForGenericBounds";
TcbInliningRequirement2[TcbInliningRequirement2["None"] = 2] = "None";
})(TcbInliningRequirement || (TcbInliningRequirement = {}));
function requiresInlineTypeCheckBlock(ref, env, usedPipes, reflector) {
if (!env.canReferenceType(ref)) {
return TcbInliningRequirement.MustInline;
} else if (!checkIfGenericTypeBoundsCanBeEmitted(ref.node, reflector, env)) {
return TcbInliningRequirement.ShouldInlineForGenericBounds;
} else if (usedPipes.some((pipeRef) => !env.canReferenceType(pipeRef))) {
return TcbInliningRequirement.MustInline;
} else {
return TcbInliningRequirement.None;
}
}
function getTemplateMapping(shimSf, position, resolver, isDiagnosticRequest) {
const node = getTokenAtPosition(shimSf, position);
const sourceLocation = findSourceLocation(node, shimSf, isDiagnosticRequest);
if (sourceLocation === null) {
return null;
}
const mapping = resolver.getSourceMapping(sourceLocation.id);
const span = resolver.toParseSourceSpan(sourceLocation.id, sourceLocation.span);
if (span === null) {
return null;
}
return { sourceLocation, templateSourceMapping: mapping, span };
}
function findTypeCheckBlock(file, id, isDiagnosticRequest) {
for (const stmt of file.statements) {
if (import_typescript74.default.isFunctionDeclaration(stmt) && getTemplateId2(stmt, file, isDiagnosticRequest) === id) {
return stmt;
}
}
return null;
}
function findSourceLocation(node, sourceFile, isDiagnosticsRequest) {
while (node !== void 0 && !import_typescript74.default.isFunctionDeclaration(node)) {
if (hasIgnoreForDiagnosticsMarker(node, sourceFile) && isDiagnosticsRequest) {
return null;
}
const span = readSpanComment(node, sourceFile);
if (span !== null) {
const id = getTemplateId2(node, sourceFile, isDiagnosticsRequest);
if (id === null) {
return null;
}
return { id, span };
}
node = node.parent;
}
return null;
}
function getTemplateId2(node, sourceFile, isDiagnosticRequest) {
while (!import_typescript74.default.isFunctionDeclaration(node)) {
if (hasIgnoreForDiagnosticsMarker(node, sourceFile) && isDiagnosticRequest) {
return null;
}
node = node.parent;
if (node === void 0) {
return null;
}
}
const start = node.getFullStart();
return import_typescript74.default.forEachLeadingCommentRange(sourceFile.text, start, (pos, end, kind) => {
if (kind !== import_typescript74.default.SyntaxKind.MultiLineCommentTrivia) {
return null;
}
const commentText = sourceFile.text.substring(pos + 2, end - 2);
return commentText;
}) || null;
}
function ensureTypeCheckFilePreparationImports(env) {
for (const identifier of TCB_FILE_IMPORT_GRAPH_PREPARE_IDENTIFIERS) {
env.importManager.addImport({
exportModuleSpecifier: identifier.moduleName,
exportSymbolName: identifier.name,
requestedFile: env.contextFile
});
}
}
function checkIfGenericTypeBoundsCanBeEmitted(node, reflector, env) {
const emitter = new TypeParameterEmitter(node.typeParameters, reflector);
return emitter.canEmit((ref) => env.canReferenceType(ref));
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/type_constructor.mjs
function generateTypeCtorDeclarationFn(env, meta, nodeTypeRef, typeParams) {
const rawTypeArgs = typeParams !== void 0 ? generateGenericArgs(typeParams) : void 0;
const rawType = import_typescript76.default.factory.createTypeReferenceNode(nodeTypeRef, rawTypeArgs);
const initParam = constructTypeCtorParameter(env, meta, rawType);
const typeParameters = typeParametersWithDefaultTypes(typeParams);
if (meta.body) {
const fnType = import_typescript76.default.factory.createFunctionTypeNode(
typeParameters,
[initParam],
rawType
);
const decl = import_typescript76.default.factory.createVariableDeclaration(
meta.fnName,
void 0,
fnType,
import_typescript76.default.factory.createNonNullExpression(import_typescript76.default.factory.createNull())
);
const declList = import_typescript76.default.factory.createVariableDeclarationList([decl], import_typescript76.default.NodeFlags.Const);
return import_typescript76.default.factory.createVariableStatement(
void 0,
declList
);
} else {
return import_typescript76.default.factory.createFunctionDeclaration(
[import_typescript76.default.factory.createModifier(import_typescript76.default.SyntaxKind.DeclareKeyword)],
void 0,
meta.fnName,
typeParameters,
[initParam],
rawType,
void 0
);
}
}
function generateInlineTypeCtor(env, node, meta) {
const rawTypeArgs = node.typeParameters !== void 0 ? generateGenericArgs(node.typeParameters) : void 0;
const rawType = import_typescript76.default.factory.createTypeReferenceNode(node.name, rawTypeArgs);
const initParam = constructTypeCtorParameter(env, meta, rawType);
let body = void 0;
if (meta.body) {
body = import_typescript76.default.factory.createBlock([
import_typescript76.default.factory.createReturnStatement(import_typescript76.default.factory.createNonNullExpression(import_typescript76.default.factory.createNull()))
]);
}
return import_typescript76.default.factory.createMethodDeclaration(
[import_typescript76.default.factory.createModifier(import_typescript76.default.SyntaxKind.StaticKeyword)],
void 0,
meta.fnName,
void 0,
typeParametersWithDefaultTypes(node.typeParameters),
[initParam],
rawType,
body
);
}
function constructTypeCtorParameter(env, meta, rawType) {
let initType = null;
const plainKeys = [];
const coercedKeys = [];
const signalInputKeys = [];
for (const { classPropertyName, transform: transform2, isSignal } of meta.fields.inputs) {
if (isSignal) {
signalInputKeys.push(import_typescript76.default.factory.createLiteralTypeNode(import_typescript76.default.factory.createStringLiteral(classPropertyName)));
} else if (!meta.coercedInputFields.has(classPropertyName)) {
plainKeys.push(import_typescript76.default.factory.createLiteralTypeNode(import_typescript76.default.factory.createStringLiteral(classPropertyName)));
} else {
const coercionType = transform2 != null ? transform2.type.node : tsCreateTypeQueryForCoercedInput(rawType.typeName, classPropertyName);
coercedKeys.push(import_typescript76.default.factory.createPropertySignature(
void 0,
classPropertyName,
void 0,
coercionType
));
}
}
if (plainKeys.length > 0) {
const keyTypeUnion = import_typescript76.default.factory.createUnionTypeNode(plainKeys);
initType = import_typescript76.default.factory.createTypeReferenceNode("Pick", [rawType, keyTypeUnion]);
}
if (coercedKeys.length > 0) {
const coercedLiteral = import_typescript76.default.factory.createTypeLiteralNode(coercedKeys);
initType = initType !== null ? import_typescript76.default.factory.createIntersectionTypeNode([initType, coercedLiteral]) : coercedLiteral;
}
if (signalInputKeys.length > 0) {
const keyTypeUnion = import_typescript76.default.factory.createUnionTypeNode(signalInputKeys);
const unwrapDirectiveSignalInputsExpr = env.referenceExternalType(Identifiers.UnwrapDirectiveSignalInputs.moduleName, Identifiers.UnwrapDirectiveSignalInputs.name, [
new ExpressionType(new WrappedNodeExpr(rawType)),
new ExpressionType(new WrappedNodeExpr(keyTypeUnion))
]);
initType = initType !== null ? import_typescript76.default.factory.createIntersectionTypeNode([initType, unwrapDirectiveSignalInputsExpr]) : unwrapDirectiveSignalInputsExpr;
}
if (initType === null) {
initType = import_typescript76.default.factory.createTypeLiteralNode([]);
}
return import_typescript76.default.factory.createParameterDeclaration(
void 0,
void 0,
"init",
void 0,
initType,
void 0
);
}
function generateGenericArgs(params) {
return params.map((param) => import_typescript76.default.factory.createTypeReferenceNode(param.name, void 0));
}
function requiresInlineTypeCtor(node, host, env) {
return !checkIfGenericTypeBoundsCanBeEmitted(node, host, env);
}
function typeParametersWithDefaultTypes(params) {
if (params === void 0) {
return void 0;
}
return params.map((param) => {
if (param.default === void 0) {
return import_typescript76.default.factory.updateTypeParameterDeclaration(param, param.modifiers, param.name, param.constraint, import_typescript76.default.factory.createKeywordTypeNode(import_typescript76.default.SyntaxKind.AnyKeyword));
} else {
return param;
}
});
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/environment.mjs
var Environment = class extends ReferenceEmitEnvironment {
constructor(config, importManager, refEmitter, reflector, contextFile) {
super(importManager, refEmitter, reflector, contextFile);
this.config = config;
this.nextIds = {
pipeInst: 1,
typeCtor: 1
};
this.typeCtors = /* @__PURE__ */ new Map();
this.typeCtorStatements = [];
this.pipeInsts = /* @__PURE__ */ new Map();
this.pipeInstStatements = [];
}
typeCtorFor(dir) {
const dirRef = dir.ref;
const node = dirRef.node;
if (this.typeCtors.has(node)) {
return this.typeCtors.get(node);
}
if (requiresInlineTypeCtor(node, this.reflector, this)) {
const ref = this.reference(dirRef);
const typeCtorExpr = import_typescript77.default.factory.createPropertyAccessExpression(ref, "ngTypeCtor");
this.typeCtors.set(node, typeCtorExpr);
return typeCtorExpr;
} else {
const fnName = `_ctor${this.nextIds.typeCtor++}`;
const nodeTypeRef = this.referenceType(dirRef);
if (!import_typescript77.default.isTypeReferenceNode(nodeTypeRef)) {
throw new Error(`Expected TypeReferenceNode from reference to ${dirRef.debugName}`);
}
const meta = {
fnName,
body: true,
fields: {
inputs: dir.inputs,
queries: dir.queries
},
coercedInputFields: dir.coercedInputFields
};
const typeParams = this.emitTypeParameters(node);
const typeCtor = generateTypeCtorDeclarationFn(this, meta, nodeTypeRef.typeName, typeParams);
this.typeCtorStatements.push(typeCtor);
const fnId = import_typescript77.default.factory.createIdentifier(fnName);
this.typeCtors.set(node, fnId);
return fnId;
}
}
pipeInst(ref) {
if (this.pipeInsts.has(ref.node)) {
return this.pipeInsts.get(ref.node);
}
const pipeType = this.referenceType(ref);
const pipeInstId = import_typescript77.default.factory.createIdentifier(`_pipe${this.nextIds.pipeInst++}`);
this.pipeInstStatements.push(tsDeclareVariable(pipeInstId, pipeType));
this.pipeInsts.set(ref.node, pipeInstId);
return pipeInstId;
}
reference(ref) {
const ngExpr = this.refEmitter.emit(ref, this.contextFile, ImportFlags.NoAliasing);
assertSuccessfulReferenceEmit(ngExpr, this.contextFile, "class");
return translateExpression(this.contextFile, ngExpr.expression, this.importManager);
}
emitTypeParameters(declaration) {
const emitter = new TypeParameterEmitter(declaration.typeParameters, this.reflector);
return emitter.emit((ref) => this.referenceType(ref));
}
getPreludeStatements() {
return [...this.pipeInstStatements, ...this.typeCtorStatements];
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/oob.mjs
var import_typescript78 = __toESM(require("typescript"), 1);
var OutOfBandDiagnosticRecorderImpl = class {
constructor(resolver) {
this.resolver = resolver;
this._diagnostics = [];
this.recordedPipes = /* @__PURE__ */ new Set();
}
get diagnostics() {
return this._diagnostics;
}
missingReferenceTarget(templateId, ref) {
const mapping = this.resolver.getSourceMapping(templateId);
const value = ref.value.trim();
const errorMsg = `No directive found with exportAs '${value}'.`;
this._diagnostics.push(makeTemplateDiagnostic(templateId, mapping, ref.valueSpan || ref.sourceSpan, import_typescript78.default.DiagnosticCategory.Error, ngErrorCode(ErrorCode.MISSING_REFERENCE_TARGET), errorMsg));
}
missingPipe(templateId, ast) {
if (this.recordedPipes.has(ast)) {
return;
}
const mapping = this.resolver.getSourceMapping(templateId);
const errorMsg = `No pipe found with name '${ast.name}'.`;
const sourceSpan = this.resolver.toParseSourceSpan(templateId, ast.nameSpan);
if (sourceSpan === null) {
throw new Error(`Assertion failure: no SourceLocation found for usage of pipe '${ast.name}'.`);
}
this._diagnostics.push(makeTemplateDiagnostic(templateId, mapping, sourceSpan, import_typescript78.default.DiagnosticCategory.Error, ngErrorCode(ErrorCode.MISSING_PIPE), errorMsg));
this.recordedPipes.add(ast);
}
deferredPipeUsedEagerly(templateId, ast) {
if (this.recordedPipes.has(ast)) {
return;
}
const mapping = this.resolver.getSourceMapping(templateId);
const errorMsg = `Pipe '${ast.name}' was imported via \`@Component.deferredImports\`, but was used outside of a \`@defer\` block in a template. To fix this, either use the '${ast.name}' pipe inside of a \`@defer\` block or import this dependency using the \`@Component.imports\` field.`;
const sourceSpan = this.resolver.toParseSourceSpan(templateId, ast.nameSpan);
if (sourceSpan === null) {
throw new Error(`Assertion failure: no SourceLocation found for usage of pipe '${ast.name}'.`);
}
this._diagnostics.push(makeTemplateDiagnostic(templateId, mapping, sourceSpan, import_typescript78.default.DiagnosticCategory.Error, ngErrorCode(ErrorCode.DEFERRED_PIPE_USED_EAGERLY), errorMsg));
this.recordedPipes.add(ast);
}
deferredComponentUsedEagerly(templateId, element2) {
const mapping = this.resolver.getSourceMapping(templateId);
const errorMsg = `Element '${element2.name}' contains a component or a directive that was imported via \`@Component.deferredImports\`, but the element itself is located outside of a \`@defer\` block in a template. To fix this, either use the '${element2.name}' element inside of a \`@defer\` block or import referenced component/directive dependency using the \`@Component.imports\` field.`;
const { start, end } = element2.startSourceSpan;
const absoluteSourceSpan = new AbsoluteSourceSpan(start.offset, end.offset);
const sourceSpan = this.resolver.toParseSourceSpan(templateId, absoluteSourceSpan);
if (sourceSpan === null) {
throw new Error(`Assertion failure: no SourceLocation found for usage of pipe '${element2.name}'.`);
}
this._diagnostics.push(makeTemplateDiagnostic(templateId, mapping, sourceSpan, import_typescript78.default.DiagnosticCategory.Error, ngErrorCode(ErrorCode.DEFERRED_DIRECTIVE_USED_EAGERLY), errorMsg));
}
duplicateTemplateVar(templateId, variable2, firstDecl) {
const mapping = this.resolver.getSourceMapping(templateId);
const errorMsg = `Cannot redeclare variable '${variable2.name}' as it was previously declared elsewhere for the same template.`;
this._diagnostics.push(makeTemplateDiagnostic(templateId, mapping, variable2.sourceSpan, import_typescript78.default.DiagnosticCategory.Error, ngErrorCode(ErrorCode.DUPLICATE_VARIABLE_DECLARATION), errorMsg, [
{
text: `The variable '${firstDecl.name}' was first declared here.`,
start: firstDecl.sourceSpan.start.offset,
end: firstDecl.sourceSpan.end.offset,
sourceFile: mapping.node.getSourceFile()
}
]));
}
requiresInlineTcb(templateId, node) {
this._diagnostics.push(makeInlineDiagnostic(templateId, ErrorCode.INLINE_TCB_REQUIRED, node.name, `This component requires inline template type-checking, which is not supported by the current environment.`));
}
requiresInlineTypeConstructors(templateId, node, directives) {
let message;
if (directives.length > 1) {
message = `This component uses directives which require inline type constructors, which are not supported by the current environment.`;
} else {
message = `This component uses a directive which requires an inline type constructor, which is not supported by the current environment.`;
}
this._diagnostics.push(makeInlineDiagnostic(templateId, ErrorCode.INLINE_TYPE_CTOR_REQUIRED, node.name, message, directives.map((dir) => makeRelatedInformation(dir.name, `Requires an inline type constructor.`))));
}
suboptimalTypeInference(templateId, variables) {
const mapping = this.resolver.getSourceMapping(templateId);
let diagnosticVar = null;
for (const variable2 of variables) {
if (diagnosticVar === null || variable2.value === "" || variable2.value === "$implicit") {
diagnosticVar = variable2;
}
}
if (diagnosticVar === null) {
return;
}
let varIdentification = `'${diagnosticVar.name}'`;
if (variables.length === 2) {
varIdentification += ` (and 1 other)`;
} else if (variables.length > 2) {
varIdentification += ` (and ${variables.length - 1} others)`;
}
const message = `This structural directive supports advanced type inference, but the current compiler configuration prevents its usage. The variable ${varIdentification} will have type 'any' as a result.
Consider enabling the 'strictTemplates' option in your tsconfig.json for better type inference within this template.`;
this._diagnostics.push(makeTemplateDiagnostic(templateId, mapping, diagnosticVar.keySpan, import_typescript78.default.DiagnosticCategory.Suggestion, ngErrorCode(ErrorCode.SUGGEST_SUBOPTIMAL_TYPE_INFERENCE), message));
}
splitTwoWayBinding(templateId, input, output, inputConsumer, outputConsumer) {
const mapping = this.resolver.getSourceMapping(templateId);
const errorMsg = `The property and event halves of the two-way binding '${input.name}' are not bound to the same target.
Find more at https://angular.dev/guide/templates/two-way-binding#how-two-way-binding-works`;
const relatedMessages = [];
relatedMessages.push({
text: `The property half of the binding is to the '${inputConsumer.name.text}' component.`,
start: inputConsumer.name.getStart(),
end: inputConsumer.name.getEnd(),
sourceFile: inputConsumer.name.getSourceFile()
});
if (outputConsumer instanceof Element) {
let message = `The event half of the binding is to a native event called '${input.name}' on the <${outputConsumer.name}> DOM element.`;
if (!mapping.node.getSourceFile().isDeclarationFile) {
message += `
Are you missing an output declaration called '${output.name}'?`;
}
relatedMessages.push({
text: message,
start: outputConsumer.sourceSpan.start.offset + 1,
end: outputConsumer.sourceSpan.start.offset + outputConsumer.name.length + 1,
sourceFile: mapping.node.getSourceFile()
});
} else {
relatedMessages.push({
text: `The event half of the binding is to the '${outputConsumer.name.text}' component.`,
start: outputConsumer.name.getStart(),
end: outputConsumer.name.getEnd(),
sourceFile: outputConsumer.name.getSourceFile()
});
}
this._diagnostics.push(makeTemplateDiagnostic(templateId, mapping, input.keySpan, import_typescript78.default.DiagnosticCategory.Error, ngErrorCode(ErrorCode.SPLIT_TWO_WAY_BINDING), errorMsg, relatedMessages));
}
missingRequiredInputs(templateId, element2, directiveName, isComponent, inputAliases) {
const message = `Required input${inputAliases.length === 1 ? "" : "s"} ${inputAliases.map((n2) => `'${n2}'`).join(", ")} from ${isComponent ? "component" : "directive"} ${directiveName} must be specified.`;
this._diagnostics.push(makeTemplateDiagnostic(templateId, this.resolver.getSourceMapping(templateId), element2.startSourceSpan, import_typescript78.default.DiagnosticCategory.Error, ngErrorCode(ErrorCode.MISSING_REQUIRED_INPUTS), message));
}
illegalForLoopTrackAccess(templateId, block, access) {
const sourceSpan = this.resolver.toParseSourceSpan(templateId, access.sourceSpan);
if (sourceSpan === null) {
throw new Error(`Assertion failure: no SourceLocation found for property read.`);
}
const messageVars = [block.item, ...block.contextVariables.filter((v) => v.value === "$index")].map((v) => `'${v.name}'`).join(", ");
const message = `Cannot access '${access.name}' inside of a track expression. Only ${messageVars} and properties on the containing component are available to this expression.`;
this._diagnostics.push(makeTemplateDiagnostic(templateId, this.resolver.getSourceMapping(templateId), sourceSpan, import_typescript78.default.DiagnosticCategory.Error, ngErrorCode(ErrorCode.ILLEGAL_FOR_LOOP_TRACK_ACCESS), message));
}
inaccessibleDeferredTriggerElement(templateId, trigger) {
let message;
if (trigger.reference === null) {
message = `Trigger cannot find reference. Make sure that the @defer block has a @placeholder with at least one root element node.`;
} else {
message = `Trigger cannot find reference "${trigger.reference}".
Check that an element with #${trigger.reference} exists in the same template and it's accessible from the @defer block.
Deferred blocks can only access triggers in same view, a parent embedded view or the root view of the @placeholder block.`;
}
this._diagnostics.push(makeTemplateDiagnostic(templateId, this.resolver.getSourceMapping(templateId), trigger.sourceSpan, import_typescript78.default.DiagnosticCategory.Error, ngErrorCode(ErrorCode.INACCESSIBLE_DEFERRED_TRIGGER_ELEMENT), message));
}
controlFlowPreventingContentProjection(templateId, category, projectionNode, componentName, slotSelector, controlFlowNode, preservesWhitespaces) {
const blockName = controlFlowNode.nameSpan.toString().trim();
const lines = [
`Node matches the "${slotSelector}" slot of the "${componentName}" component, but will not be projected into the specific slot because the surrounding ${blockName} has more than one node at its root. To project the node in the right slot, you can:
`,
`1. Wrap the content of the ${blockName} block in an that matches the "${slotSelector}" selector.`,
`2. Split the content of the ${blockName} block across multiple ${blockName} blocks such that each one only has a single projectable node at its root.`,
`3. Remove all content from the ${blockName} block, except for the node being projected.`
];
if (preservesWhitespaces) {
lines.push("Note: the host component has `preserveWhitespaces: true` which may cause whitespace to affect content projection.");
}
lines.push("", 'This check can be disabled using the `extendedDiagnostics.checks.controlFlowPreventingContentProjection = "suppress" compiler option.`');
this._diagnostics.push(makeTemplateDiagnostic(templateId, this.resolver.getSourceMapping(templateId), projectionNode.startSourceSpan, category, ngErrorCode(ErrorCode.CONTROL_FLOW_PREVENTING_CONTENT_PROJECTION), lines.join("\n")));
}
illegalWriteToLetDeclaration(templateId, node, target) {
const sourceSpan = this.resolver.toParseSourceSpan(templateId, node.sourceSpan);
if (sourceSpan === null) {
throw new Error(`Assertion failure: no SourceLocation found for property write.`);
}
this._diagnostics.push(makeTemplateDiagnostic(templateId, this.resolver.getSourceMapping(templateId), sourceSpan, import_typescript78.default.DiagnosticCategory.Error, ngErrorCode(ErrorCode.ILLEGAL_LET_WRITE), `Cannot assign to @let declaration '${target.name}'.`));
}
letUsedBeforeDefinition(templateId, node, target) {
const sourceSpan = this.resolver.toParseSourceSpan(templateId, node.sourceSpan);
if (sourceSpan === null) {
throw new Error(`Assertion failure: no SourceLocation found for property read.`);
}
this._diagnostics.push(makeTemplateDiagnostic(templateId, this.resolver.getSourceMapping(templateId), sourceSpan, import_typescript78.default.DiagnosticCategory.Error, ngErrorCode(ErrorCode.LET_USED_BEFORE_DEFINITION), `Cannot read @let declaration '${target.name}' before it has been defined.`));
}
conflictingDeclaration(templateId, decl) {
const mapping = this.resolver.getSourceMapping(templateId);
const errorMsg = `Cannot declare @let called '${decl.name}' as there is another symbol in the template with the same name.`;
this._diagnostics.push(makeTemplateDiagnostic(templateId, mapping, decl.sourceSpan, import_typescript78.default.DiagnosticCategory.Error, ngErrorCode(ErrorCode.CONFLICTING_LET_DECLARATION), errorMsg));
}
};
function makeInlineDiagnostic(templateId, code, node, messageText, relatedInformation) {
return __spreadProps(__spreadValues({}, makeDiagnostic(code, node, messageText, relatedInformation)), {
componentFile: node.getSourceFile(),
templateId
});
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/shim.mjs
var import_typescript79 = __toESM(require("typescript"), 1);
var TypeCheckShimGenerator = class {
constructor() {
this.extensionPrefix = "ngtypecheck";
this.shouldEmit = false;
}
generateShimForFile(sf, genFilePath, priorShimSf) {
if (priorShimSf !== null) {
return priorShimSf;
}
return import_typescript79.default.createSourceFile(genFilePath, "export const USED_FOR_NG_TYPE_CHECKING = true;", import_typescript79.default.ScriptTarget.Latest, true, import_typescript79.default.ScriptKind.TS);
}
static shimFor(fileName) {
return absoluteFrom(fileName.replace(/\.tsx?$/, ".ngtypecheck.ts"));
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.mjs
var import_typescript82 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/diagnostics.mjs
var import_typescript80 = __toESM(require("typescript"), 1);
function wrapForDiagnostics(expr) {
return import_typescript80.default.factory.createParenthesizedExpression(expr);
}
function wrapForTypeChecker(expr) {
return import_typescript80.default.factory.createParenthesizedExpression(expr);
}
function addParseSpanInfo(node, span) {
let commentText;
if (span instanceof AbsoluteSourceSpan) {
commentText = `${span.start},${span.end}`;
} else {
commentText = `${span.start.offset},${span.end.offset}`;
}
import_typescript80.default.addSyntheticTrailingComment(
node,
import_typescript80.default.SyntaxKind.MultiLineCommentTrivia,
commentText,
false
);
}
function addTemplateId(tcb, id) {
import_typescript80.default.addSyntheticLeadingComment(tcb, import_typescript80.default.SyntaxKind.MultiLineCommentTrivia, id, true);
}
function shouldReportDiagnostic(diagnostic) {
const { code } = diagnostic;
if (code === 6133) {
return false;
} else if (code === 6199) {
return false;
} else if (code === 2695) {
return false;
} else if (code === 7006) {
return false;
}
return true;
}
function translateDiagnostic(diagnostic, resolver) {
if (diagnostic.file === void 0 || diagnostic.start === void 0) {
return null;
}
const fullMapping = getTemplateMapping(
diagnostic.file,
diagnostic.start,
resolver,
true
);
if (fullMapping === null) {
return null;
}
const { sourceLocation, templateSourceMapping, span } = fullMapping;
return makeTemplateDiagnostic(sourceLocation.id, templateSourceMapping, span, diagnostic.category, diagnostic.code, diagnostic.messageText);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/expression.mjs
var import_typescript81 = __toESM(require("typescript"), 1);
var ANY_EXPRESSION = import_typescript81.default.factory.createAsExpression(import_typescript81.default.factory.createNumericLiteral("0"), import_typescript81.default.factory.createKeywordTypeNode(import_typescript81.default.SyntaxKind.AnyKeyword));
var UNDEFINED = import_typescript81.default.factory.createIdentifier("undefined");
var UNARY_OPS = /* @__PURE__ */ new Map([
["+", import_typescript81.default.SyntaxKind.PlusToken],
["-", import_typescript81.default.SyntaxKind.MinusToken]
]);
var BINARY_OPS = /* @__PURE__ */ new Map([
["+", import_typescript81.default.SyntaxKind.PlusToken],
["-", import_typescript81.default.SyntaxKind.MinusToken],
["<", import_typescript81.default.SyntaxKind.LessThanToken],
[">", import_typescript81.default.SyntaxKind.GreaterThanToken],
["<=", import_typescript81.default.SyntaxKind.LessThanEqualsToken],
[">=", import_typescript81.default.SyntaxKind.GreaterThanEqualsToken],
["==", import_typescript81.default.SyntaxKind.EqualsEqualsToken],
["===", import_typescript81.default.SyntaxKind.EqualsEqualsEqualsToken],
["*", import_typescript81.default.SyntaxKind.AsteriskToken],
["/", import_typescript81.default.SyntaxKind.SlashToken],
["%", import_typescript81.default.SyntaxKind.PercentToken],
["!=", import_typescript81.default.SyntaxKind.ExclamationEqualsToken],
["!==", import_typescript81.default.SyntaxKind.ExclamationEqualsEqualsToken],
["||", import_typescript81.default.SyntaxKind.BarBarToken],
["&&", import_typescript81.default.SyntaxKind.AmpersandAmpersandToken],
["&", import_typescript81.default.SyntaxKind.AmpersandToken],
["|", import_typescript81.default.SyntaxKind.BarToken],
["??", import_typescript81.default.SyntaxKind.QuestionQuestionToken]
]);
function astToTypescript(ast, maybeResolve, config) {
const translator = new AstTranslator(maybeResolve, config);
return translator.translate(ast);
}
var AstTranslator = class {
constructor(maybeResolve, config) {
this.maybeResolve = maybeResolve;
this.config = config;
}
translate(ast) {
if (ast instanceof ASTWithSource) {
ast = ast.ast;
}
if (ast instanceof EmptyExpr) {
const res = import_typescript81.default.factory.createIdentifier("undefined");
addParseSpanInfo(res, ast.sourceSpan);
return res;
}
const resolved = this.maybeResolve(ast);
if (resolved !== null) {
return resolved;
}
return ast.visit(this);
}
visitUnary(ast) {
const expr = this.translate(ast.expr);
const op = UNARY_OPS.get(ast.operator);
if (op === void 0) {
throw new Error(`Unsupported Unary.operator: ${ast.operator}`);
}
const node = wrapForDiagnostics(import_typescript81.default.factory.createPrefixUnaryExpression(op, expr));
addParseSpanInfo(node, ast.sourceSpan);
return node;
}
visitBinary(ast) {
const lhs = wrapForDiagnostics(this.translate(ast.left));
const rhs = wrapForDiagnostics(this.translate(ast.right));
const op = BINARY_OPS.get(ast.operation);
if (op === void 0) {
throw new Error(`Unsupported Binary.operation: ${ast.operation}`);
}
const node = import_typescript81.default.factory.createBinaryExpression(lhs, op, rhs);
addParseSpanInfo(node, ast.sourceSpan);
return node;
}
visitChain(ast) {
const elements = ast.expressions.map((expr) => this.translate(expr));
const node = wrapForDiagnostics(import_typescript81.default.factory.createCommaListExpression(elements));
addParseSpanInfo(node, ast.sourceSpan);
return node;
}
visitConditional(ast) {
const condExpr = this.translate(ast.condition);
const trueExpr = this.translate(ast.trueExp);
const falseExpr = wrapForTypeChecker(this.translate(ast.falseExp));
const node = import_typescript81.default.factory.createParenthesizedExpression(import_typescript81.default.factory.createConditionalExpression(condExpr, void 0, trueExpr, void 0, falseExpr));
addParseSpanInfo(node, ast.sourceSpan);
return node;
}
visitImplicitReceiver(ast) {
throw new Error("Method not implemented.");
}
visitThisReceiver(ast) {
throw new Error("Method not implemented.");
}
visitInterpolation(ast) {
return ast.expressions.reduce((lhs, ast2) => import_typescript81.default.factory.createBinaryExpression(lhs, import_typescript81.default.SyntaxKind.PlusToken, wrapForTypeChecker(this.translate(ast2))), import_typescript81.default.factory.createStringLiteral(""));
}
visitKeyedRead(ast) {
const receiver = wrapForDiagnostics(this.translate(ast.receiver));
const key = this.translate(ast.key);
const node = import_typescript81.default.factory.createElementAccessExpression(receiver, key);
addParseSpanInfo(node, ast.sourceSpan);
return node;
}
visitKeyedWrite(ast) {
const receiver = wrapForDiagnostics(this.translate(ast.receiver));
const left = import_typescript81.default.factory.createElementAccessExpression(receiver, this.translate(ast.key));
const right = wrapForTypeChecker(this.translate(ast.value));
const node = wrapForDiagnostics(import_typescript81.default.factory.createBinaryExpression(left, import_typescript81.default.SyntaxKind.EqualsToken, right));
addParseSpanInfo(node, ast.sourceSpan);
return node;
}
visitLiteralArray(ast) {
const elements = ast.expressions.map((expr) => this.translate(expr));
const literal3 = import_typescript81.default.factory.createArrayLiteralExpression(elements);
const node = this.config.strictLiteralTypes ? literal3 : tsCastToAny(literal3);
addParseSpanInfo(node, ast.sourceSpan);
return node;
}
visitLiteralMap(ast) {
const properties = ast.keys.map(({ key }, idx) => {
const value = this.translate(ast.values[idx]);
return import_typescript81.default.factory.createPropertyAssignment(import_typescript81.default.factory.createStringLiteral(key), value);
});
const literal3 = import_typescript81.default.factory.createObjectLiteralExpression(properties, true);
const node = this.config.strictLiteralTypes ? literal3 : tsCastToAny(literal3);
addParseSpanInfo(node, ast.sourceSpan);
return node;
}
visitLiteralPrimitive(ast) {
let node;
if (ast.value === void 0) {
node = import_typescript81.default.factory.createIdentifier("undefined");
} else if (ast.value === null) {
node = import_typescript81.default.factory.createNull();
} else if (typeof ast.value === "string") {
node = import_typescript81.default.factory.createStringLiteral(ast.value);
} else if (typeof ast.value === "number") {
node = tsNumericExpression2(ast.value);
} else if (typeof ast.value === "boolean") {
node = ast.value ? import_typescript81.default.factory.createTrue() : import_typescript81.default.factory.createFalse();
} else {
throw Error(`Unsupported AST value of type ${typeof ast.value}`);
}
addParseSpanInfo(node, ast.sourceSpan);
return node;
}
visitNonNullAssert(ast) {
const expr = wrapForDiagnostics(this.translate(ast.expression));
const node = import_typescript81.default.factory.createNonNullExpression(expr);
addParseSpanInfo(node, ast.sourceSpan);
return node;
}
visitPipe(ast) {
throw new Error("Method not implemented.");
}
visitPrefixNot(ast) {
const expression = wrapForDiagnostics(this.translate(ast.expression));
const node = import_typescript81.default.factory.createLogicalNot(expression);
addParseSpanInfo(node, ast.sourceSpan);
return node;
}
visitPropertyRead(ast) {
const receiver = wrapForDiagnostics(this.translate(ast.receiver));
const name = import_typescript81.default.factory.createPropertyAccessExpression(receiver, ast.name);
addParseSpanInfo(name, ast.nameSpan);
const node = wrapForDiagnostics(name);
addParseSpanInfo(node, ast.sourceSpan);
return node;
}
visitPropertyWrite(ast) {
const receiver = wrapForDiagnostics(this.translate(ast.receiver));
const left = import_typescript81.default.factory.createPropertyAccessExpression(receiver, ast.name);
addParseSpanInfo(left, ast.nameSpan);
const leftWithPath = wrapForDiagnostics(left);
addParseSpanInfo(leftWithPath, ast.sourceSpan);
const right = wrapForTypeChecker(this.translate(ast.value));
const node = wrapForDiagnostics(import_typescript81.default.factory.createBinaryExpression(leftWithPath, import_typescript81.default.SyntaxKind.EqualsToken, right));
addParseSpanInfo(node, ast.sourceSpan);
return node;
}
visitSafePropertyRead(ast) {
let node;
const receiver = wrapForDiagnostics(this.translate(ast.receiver));
if (this.config.strictSafeNavigationTypes) {
const expr = import_typescript81.default.factory.createPropertyAccessExpression(import_typescript81.default.factory.createNonNullExpression(receiver), ast.name);
addParseSpanInfo(expr, ast.nameSpan);
node = import_typescript81.default.factory.createParenthesizedExpression(import_typescript81.default.factory.createConditionalExpression(ANY_EXPRESSION, void 0, expr, void 0, UNDEFINED));
} else if (VeSafeLhsInferenceBugDetector.veWillInferAnyFor(ast)) {
node = import_typescript81.default.factory.createPropertyAccessExpression(tsCastToAny(receiver), ast.name);
} else {
const expr = import_typescript81.default.factory.createPropertyAccessExpression(import_typescript81.default.factory.createNonNullExpression(receiver), ast.name);
addParseSpanInfo(expr, ast.nameSpan);
node = tsCastToAny(expr);
}
addParseSpanInfo(node, ast.sourceSpan);
return node;
}
visitSafeKeyedRead(ast) {
const receiver = wrapForDiagnostics(this.translate(ast.receiver));
const key = this.translate(ast.key);
let node;
if (this.config.strictSafeNavigationTypes) {
const expr = import_typescript81.default.factory.createElementAccessExpression(import_typescript81.default.factory.createNonNullExpression(receiver), key);
addParseSpanInfo(expr, ast.sourceSpan);
node = import_typescript81.default.factory.createParenthesizedExpression(import_typescript81.default.factory.createConditionalExpression(ANY_EXPRESSION, void 0, expr, void 0, UNDEFINED));
} else if (VeSafeLhsInferenceBugDetector.veWillInferAnyFor(ast)) {
node = import_typescript81.default.factory.createElementAccessExpression(tsCastToAny(receiver), key);
} else {
const expr = import_typescript81.default.factory.createElementAccessExpression(import_typescript81.default.factory.createNonNullExpression(receiver), key);
addParseSpanInfo(expr, ast.sourceSpan);
node = tsCastToAny(expr);
}
addParseSpanInfo(node, ast.sourceSpan);
return node;
}
visitCall(ast) {
const args = ast.args.map((expr2) => this.translate(expr2));
let expr;
const receiver = ast.receiver;
if (receiver instanceof PropertyRead) {
const resolved = this.maybeResolve(receiver);
if (resolved !== null) {
expr = resolved;
} else {
const propertyReceiver = wrapForDiagnostics(this.translate(receiver.receiver));
expr = import_typescript81.default.factory.createPropertyAccessExpression(propertyReceiver, receiver.name);
addParseSpanInfo(expr, receiver.nameSpan);
}
} else {
expr = this.translate(receiver);
}
let node;
if (ast.receiver instanceof SafePropertyRead || ast.receiver instanceof SafeKeyedRead) {
node = this.convertToSafeCall(ast, expr, args);
} else {
node = import_typescript81.default.factory.createCallExpression(expr, void 0, args);
}
addParseSpanInfo(node, ast.sourceSpan);
return node;
}
visitSafeCall(ast) {
const args = ast.args.map((expr2) => this.translate(expr2));
const expr = wrapForDiagnostics(this.translate(ast.receiver));
const node = this.convertToSafeCall(ast, expr, args);
addParseSpanInfo(node, ast.sourceSpan);
return node;
}
convertToSafeCall(ast, expr, args) {
if (this.config.strictSafeNavigationTypes) {
const call2 = import_typescript81.default.factory.createCallExpression(import_typescript81.default.factory.createNonNullExpression(expr), void 0, args);
return import_typescript81.default.factory.createParenthesizedExpression(import_typescript81.default.factory.createConditionalExpression(ANY_EXPRESSION, void 0, call2, void 0, UNDEFINED));
}
if (VeSafeLhsInferenceBugDetector.veWillInferAnyFor(ast)) {
return import_typescript81.default.factory.createCallExpression(tsCastToAny(expr), void 0, args);
}
return tsCastToAny(import_typescript81.default.factory.createCallExpression(import_typescript81.default.factory.createNonNullExpression(expr), void 0, args));
}
};
var _VeSafeLhsInferenceBugDetector = class {
static veWillInferAnyFor(ast) {
const visitor = _VeSafeLhsInferenceBugDetector.SINGLETON;
return ast instanceof Call ? ast.visit(visitor) : ast.receiver.visit(visitor);
}
visitUnary(ast) {
return ast.expr.visit(this);
}
visitBinary(ast) {
return ast.left.visit(this) || ast.right.visit(this);
}
visitChain(ast) {
return false;
}
visitConditional(ast) {
return ast.condition.visit(this) || ast.trueExp.visit(this) || ast.falseExp.visit(this);
}
visitCall(ast) {
return true;
}
visitSafeCall(ast) {
return false;
}
visitImplicitReceiver(ast) {
return false;
}
visitThisReceiver(ast) {
return false;
}
visitInterpolation(ast) {
return ast.expressions.some((exp) => exp.visit(this));
}
visitKeyedRead(ast) {
return false;
}
visitKeyedWrite(ast) {
return false;
}
visitLiteralArray(ast) {
return true;
}
visitLiteralMap(ast) {
return true;
}
visitLiteralPrimitive(ast) {
return false;
}
visitPipe(ast) {
return true;
}
visitPrefixNot(ast) {
return ast.expression.visit(this);
}
visitNonNullAssert(ast) {
return ast.expression.visit(this);
}
visitPropertyRead(ast) {
return false;
}
visitPropertyWrite(ast) {
return false;
}
visitSafePropertyRead(ast) {
return false;
}
visitSafeKeyedRead(ast) {
return false;
}
};
var VeSafeLhsInferenceBugDetector = _VeSafeLhsInferenceBugDetector;
(() => {
_VeSafeLhsInferenceBugDetector.SINGLETON = new _VeSafeLhsInferenceBugDetector();
})();
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.mjs
var TcbGenericContextBehavior;
(function(TcbGenericContextBehavior2) {
TcbGenericContextBehavior2[TcbGenericContextBehavior2["UseEmitter"] = 0] = "UseEmitter";
TcbGenericContextBehavior2[TcbGenericContextBehavior2["CopyClassNodes"] = 1] = "CopyClassNodes";
TcbGenericContextBehavior2[TcbGenericContextBehavior2["FallbackToAny"] = 2] = "FallbackToAny";
})(TcbGenericContextBehavior || (TcbGenericContextBehavior = {}));
function generateTypeCheckBlock(env, ref, name, meta, domSchemaChecker, oobRecorder, genericContextBehavior) {
const tcb = new Context2(env, domSchemaChecker, oobRecorder, meta.id, meta.boundTarget, meta.pipes, meta.schemas, meta.isStandalone, meta.preserveWhitespaces);
const scope = Scope3.forNodes(tcb, null, null, tcb.boundTarget.target.template, null);
const ctxRawType = env.referenceType(ref);
if (!import_typescript82.default.isTypeReferenceNode(ctxRawType)) {
throw new Error(`Expected TypeReferenceNode when referencing the ctx param for ${ref.debugName}`);
}
let typeParameters = void 0;
let typeArguments = void 0;
if (ref.node.typeParameters !== void 0) {
if (!env.config.useContextGenericType) {
genericContextBehavior = TcbGenericContextBehavior.FallbackToAny;
}
switch (genericContextBehavior) {
case TcbGenericContextBehavior.UseEmitter:
typeParameters = new TypeParameterEmitter(ref.node.typeParameters, env.reflector).emit((typeRef) => env.referenceType(typeRef));
typeArguments = typeParameters.map((param) => import_typescript82.default.factory.createTypeReferenceNode(param.name));
break;
case TcbGenericContextBehavior.CopyClassNodes:
typeParameters = [...ref.node.typeParameters];
typeArguments = typeParameters.map((param) => import_typescript82.default.factory.createTypeReferenceNode(param.name));
break;
case TcbGenericContextBehavior.FallbackToAny:
typeArguments = ref.node.typeParameters.map(() => import_typescript82.default.factory.createKeywordTypeNode(import_typescript82.default.SyntaxKind.AnyKeyword));
break;
}
}
const paramList = [tcbThisParam(ctxRawType.typeName, typeArguments)];
const scopeStatements = scope.render();
const innerBody = import_typescript82.default.factory.createBlock([...env.getPreludeStatements(), ...scopeStatements]);
const body = import_typescript82.default.factory.createBlock([
import_typescript82.default.factory.createIfStatement(import_typescript82.default.factory.createTrue(), innerBody, void 0)
]);
const fnDecl = import_typescript82.default.factory.createFunctionDeclaration(
void 0,
void 0,
name,
env.config.useContextGenericType ? typeParameters : void 0,
paramList,
void 0,
body
);
addTemplateId(fnDecl, meta.id);
return fnDecl;
}
var TcbOp = class {
circularFallback() {
return INFER_TYPE_FOR_CIRCULAR_OP_EXPR;
}
};
var TcbElementOp = class extends TcbOp {
constructor(tcb, scope, element2) {
super();
this.tcb = tcb;
this.scope = scope;
this.element = element2;
}
get optional() {
return true;
}
execute() {
const id = this.tcb.allocateId();
const initializer = tsCreateElement(this.element.name);
addParseSpanInfo(initializer, this.element.startSourceSpan || this.element.sourceSpan);
this.scope.addStatement(tsCreateVariable(id, initializer));
return id;
}
};
var TcbTemplateVariableOp = class extends TcbOp {
constructor(tcb, scope, template2, variable2) {
super();
this.tcb = tcb;
this.scope = scope;
this.template = template2;
this.variable = variable2;
}
get optional() {
return false;
}
execute() {
const ctx = this.scope.resolve(this.template);
const id = this.tcb.allocateId();
const initializer = import_typescript82.default.factory.createPropertyAccessExpression(
ctx,
this.variable.value || "$implicit"
);
addParseSpanInfo(id, this.variable.keySpan);
let variable2;
if (this.variable.valueSpan !== void 0) {
addParseSpanInfo(initializer, this.variable.valueSpan);
variable2 = tsCreateVariable(id, wrapForTypeChecker(initializer));
} else {
variable2 = tsCreateVariable(id, initializer);
}
addParseSpanInfo(variable2.declarationList.declarations[0], this.variable.sourceSpan);
this.scope.addStatement(variable2);
return id;
}
};
var TcbTemplateContextOp = class extends TcbOp {
constructor(tcb, scope) {
super();
this.tcb = tcb;
this.scope = scope;
this.optional = true;
}
execute() {
const ctx = this.tcb.allocateId();
const type = import_typescript82.default.factory.createKeywordTypeNode(import_typescript82.default.SyntaxKind.AnyKeyword);
this.scope.addStatement(tsDeclareVariable(ctx, type));
return ctx;
}
};
var TcbLetDeclarationOp = class extends TcbOp {
constructor(tcb, scope, node) {
super();
this.tcb = tcb;
this.scope = scope;
this.node = node;
this.optional = false;
}
execute() {
const id = this.tcb.allocateId();
addParseSpanInfo(id, this.node.nameSpan);
const value = tcbExpression(this.node.value, this.tcb, this.scope);
const varStatement = tsCreateVariable(id, wrapForTypeChecker(value), import_typescript82.default.NodeFlags.Const);
addParseSpanInfo(varStatement.declarationList.declarations[0], this.node.sourceSpan);
this.scope.addStatement(varStatement);
return id;
}
};
var TcbTemplateBodyOp = class extends TcbOp {
constructor(tcb, scope, template2) {
super();
this.tcb = tcb;
this.scope = scope;
this.template = template2;
}
get optional() {
return false;
}
execute() {
const directiveGuards = [];
const directives = this.tcb.boundTarget.getDirectivesOfNode(this.template);
if (directives !== null) {
for (const dir of directives) {
const dirInstId = this.scope.resolve(this.template, dir);
const dirId = this.tcb.env.reference(dir.ref);
dir.ngTemplateGuards.forEach((guard2) => {
const boundInput = this.template.inputs.find((i) => i.name === guard2.inputName) || this.template.templateAttrs.find((i) => i instanceof BoundAttribute && i.name === guard2.inputName);
if (boundInput !== void 0) {
const expr = tcbExpression(boundInput.value, this.tcb, this.scope);
markIgnoreDiagnostics(expr);
if (guard2.type === "binding") {
directiveGuards.push(expr);
} else {
const guardInvoke = tsCallMethod(dirId, `ngTemplateGuard_${guard2.inputName}`, [
dirInstId,
expr
]);
addParseSpanInfo(guardInvoke, boundInput.value.sourceSpan);
directiveGuards.push(guardInvoke);
}
}
});
if (dir.hasNgTemplateContextGuard) {
if (this.tcb.env.config.applyTemplateContextGuards) {
const ctx = this.scope.resolve(this.template);
const guardInvoke = tsCallMethod(dirId, "ngTemplateContextGuard", [dirInstId, ctx]);
addParseSpanInfo(guardInvoke, this.template.sourceSpan);
directiveGuards.push(guardInvoke);
} else if (this.template.variables.length > 0 && this.tcb.env.config.suggestionsForSuboptimalTypeInference) {
this.tcb.oobRecorder.suboptimalTypeInference(this.tcb.id, this.template.variables);
}
}
}
}
let guard = null;
if (directiveGuards.length > 0) {
guard = directiveGuards.reduce((expr, dirGuard) => import_typescript82.default.factory.createBinaryExpression(expr, import_typescript82.default.SyntaxKind.AmpersandAmpersandToken, dirGuard), directiveGuards.pop());
}
const tmplScope = Scope3.forNodes(this.tcb, this.scope, this.template, this.template.children, guard);
const statements = tmplScope.render();
if (statements.length === 0) {
return null;
}
let tmplBlock = import_typescript82.default.factory.createBlock(statements);
if (guard !== null) {
tmplBlock = import_typescript82.default.factory.createIfStatement(
guard,
tmplBlock
);
}
this.scope.addStatement(tmplBlock);
return null;
}
};
var TcbExpressionOp = class extends TcbOp {
constructor(tcb, scope, expression) {
super();
this.tcb = tcb;
this.scope = scope;
this.expression = expression;
}
get optional() {
return false;
}
execute() {
const expr = tcbExpression(this.expression, this.tcb, this.scope);
this.scope.addStatement(import_typescript82.default.factory.createExpressionStatement(expr));
return null;
}
};
var TcbDirectiveTypeOpBase = class extends TcbOp {
constructor(tcb, scope, node, dir) {
super();
this.tcb = tcb;
this.scope = scope;
this.node = node;
this.dir = dir;
}
get optional() {
return true;
}
execute() {
const dirRef = this.dir.ref;
const rawType = this.tcb.env.referenceType(this.dir.ref);
let type;
if (this.dir.isGeneric === false || dirRef.node.typeParameters === void 0) {
type = rawType;
} else {
if (!import_typescript82.default.isTypeReferenceNode(rawType)) {
throw new Error(`Expected TypeReferenceNode when referencing the type for ${this.dir.ref.debugName}`);
}
const typeArguments = dirRef.node.typeParameters.map(() => import_typescript82.default.factory.createKeywordTypeNode(import_typescript82.default.SyntaxKind.AnyKeyword));
type = import_typescript82.default.factory.createTypeReferenceNode(rawType.typeName, typeArguments);
}
const id = this.tcb.allocateId();
addExpressionIdentifier(id, ExpressionIdentifier.DIRECTIVE);
addParseSpanInfo(id, this.node.startSourceSpan || this.node.sourceSpan);
this.scope.addStatement(tsDeclareVariable(id, type));
return id;
}
};
var TcbNonGenericDirectiveTypeOp = class extends TcbDirectiveTypeOpBase {
execute() {
const dirRef = this.dir.ref;
if (this.dir.isGeneric) {
throw new Error(`Assertion Error: expected ${dirRef.debugName} not to be generic.`);
}
return super.execute();
}
};
var TcbGenericDirectiveTypeWithAnyParamsOp = class extends TcbDirectiveTypeOpBase {
execute() {
const dirRef = this.dir.ref;
if (dirRef.node.typeParameters === void 0) {
throw new Error(`Assertion Error: expected typeParameters when creating a declaration for ${dirRef.debugName}`);
}
return super.execute();
}
};
var TcbReferenceOp = class extends TcbOp {
constructor(tcb, scope, node, host, target) {
super();
this.tcb = tcb;
this.scope = scope;
this.node = node;
this.host = host;
this.target = target;
this.optional = true;
}
execute() {
const id = this.tcb.allocateId();
let initializer = this.target instanceof Template || this.target instanceof Element ? this.scope.resolve(this.target) : this.scope.resolve(this.host, this.target);
if (this.target instanceof Element && !this.tcb.env.config.checkTypeOfDomReferences || !this.tcb.env.config.checkTypeOfNonDomReferences) {
initializer = import_typescript82.default.factory.createAsExpression(initializer, import_typescript82.default.factory.createKeywordTypeNode(import_typescript82.default.SyntaxKind.AnyKeyword));
} else if (this.target instanceof Template) {
initializer = import_typescript82.default.factory.createAsExpression(initializer, import_typescript82.default.factory.createKeywordTypeNode(import_typescript82.default.SyntaxKind.AnyKeyword));
initializer = import_typescript82.default.factory.createAsExpression(initializer, this.tcb.env.referenceExternalType("@angular/core", "TemplateRef", [DYNAMIC_TYPE]));
initializer = import_typescript82.default.factory.createParenthesizedExpression(initializer);
}
addParseSpanInfo(initializer, this.node.sourceSpan);
addParseSpanInfo(id, this.node.keySpan);
this.scope.addStatement(tsCreateVariable(id, initializer));
return id;
}
};
var TcbInvalidReferenceOp = class extends TcbOp {
constructor(tcb, scope) {
super();
this.tcb = tcb;
this.scope = scope;
this.optional = true;
}
execute() {
const id = this.tcb.allocateId();
this.scope.addStatement(tsCreateVariable(id, ANY_EXPRESSION));
return id;
}
};
var TcbDirectiveCtorOp = class extends TcbOp {
constructor(tcb, scope, node, dir) {
super();
this.tcb = tcb;
this.scope = scope;
this.node = node;
this.dir = dir;
}
get optional() {
return true;
}
execute() {
const id = this.tcb.allocateId();
addExpressionIdentifier(id, ExpressionIdentifier.DIRECTIVE);
addParseSpanInfo(id, this.node.startSourceSpan || this.node.sourceSpan);
const genericInputs = /* @__PURE__ */ new Map();
const boundAttrs = getBoundAttributes(this.dir, this.node);
for (const attr of boundAttrs) {
if (!this.tcb.env.config.checkTypeOfAttributes && attr.attribute instanceof TextAttribute) {
continue;
}
for (const { fieldName, isTwoWayBinding } of attr.inputs) {
if (genericInputs.has(fieldName)) {
continue;
}
const expression = translateInput(attr.attribute, this.tcb, this.scope);
genericInputs.set(fieldName, {
type: "binding",
field: fieldName,
expression,
sourceSpan: attr.attribute.sourceSpan,
isTwoWayBinding
});
}
}
for (const { classPropertyName } of this.dir.inputs) {
if (!genericInputs.has(classPropertyName)) {
genericInputs.set(classPropertyName, { type: "unset", field: classPropertyName });
}
}
const typeCtor = tcbCallTypeCtor(this.dir, this.tcb, Array.from(genericInputs.values()));
markIgnoreDiagnostics(typeCtor);
this.scope.addStatement(tsCreateVariable(id, typeCtor));
return id;
}
circularFallback() {
return new TcbDirectiveCtorCircularFallbackOp(this.tcb, this.scope, this.node, this.dir);
}
};
var TcbDirectiveInputsOp = class extends TcbOp {
constructor(tcb, scope, node, dir) {
super();
this.tcb = tcb;
this.scope = scope;
this.node = node;
this.dir = dir;
}
get optional() {
return false;
}
execute() {
let dirId = null;
const boundAttrs = getBoundAttributes(this.dir, this.node);
const seenRequiredInputs = /* @__PURE__ */ new Set();
for (const attr of boundAttrs) {
const expr = widenBinding(translateInput(attr.attribute, this.tcb, this.scope), this.tcb);
let assignment = wrapForDiagnostics(expr);
for (const { fieldName, required, transformType, isSignal, isTwoWayBinding } of attr.inputs) {
let target;
if (required) {
seenRequiredInputs.add(fieldName);
}
if (this.dir.coercedInputFields.has(fieldName)) {
let type;
if (transformType !== null) {
type = this.tcb.env.referenceTransplantedType(new TransplantedType(transformType));
} else {
const dirTypeRef = this.tcb.env.referenceType(this.dir.ref);
if (!import_typescript82.default.isTypeReferenceNode(dirTypeRef)) {
throw new Error(`Expected TypeReferenceNode from reference to ${this.dir.ref.debugName}`);
}
type = tsCreateTypeQueryForCoercedInput(dirTypeRef.typeName, fieldName);
}
const id = this.tcb.allocateId();
this.scope.addStatement(tsDeclareVariable(id, type));
target = id;
} else if (this.dir.undeclaredInputFields.has(fieldName)) {
continue;
} else if (!this.tcb.env.config.honorAccessModifiersForInputBindings && this.dir.restrictedInputFields.has(fieldName)) {
if (dirId === null) {
dirId = this.scope.resolve(this.node, this.dir);
}
const id = this.tcb.allocateId();
const dirTypeRef = this.tcb.env.referenceType(this.dir.ref);
if (!import_typescript82.default.isTypeReferenceNode(dirTypeRef)) {
throw new Error(`Expected TypeReferenceNode from reference to ${this.dir.ref.debugName}`);
}
const type = import_typescript82.default.factory.createIndexedAccessTypeNode(import_typescript82.default.factory.createTypeQueryNode(dirId), import_typescript82.default.factory.createLiteralTypeNode(import_typescript82.default.factory.createStringLiteral(fieldName)));
const temp = tsDeclareVariable(id, type);
this.scope.addStatement(temp);
target = id;
} else {
if (dirId === null) {
dirId = this.scope.resolve(this.node, this.dir);
}
target = this.dir.stringLiteralInputFields.has(fieldName) ? import_typescript82.default.factory.createElementAccessExpression(dirId, import_typescript82.default.factory.createStringLiteral(fieldName)) : import_typescript82.default.factory.createPropertyAccessExpression(dirId, import_typescript82.default.factory.createIdentifier(fieldName));
}
if (isSignal) {
const inputSignalBrandWriteSymbol = this.tcb.env.referenceExternalSymbol(Identifiers.InputSignalBrandWriteType.moduleName, Identifiers.InputSignalBrandWriteType.name);
if (!import_typescript82.default.isIdentifier(inputSignalBrandWriteSymbol) && !import_typescript82.default.isPropertyAccessExpression(inputSignalBrandWriteSymbol)) {
throw new Error(`Expected identifier or property access for reference to ${Identifiers.InputSignalBrandWriteType.name}`);
}
target = import_typescript82.default.factory.createElementAccessExpression(target, inputSignalBrandWriteSymbol);
}
if (attr.attribute.keySpan !== void 0) {
addParseSpanInfo(target, attr.attribute.keySpan);
}
if (isTwoWayBinding && this.tcb.env.config.allowSignalsInTwoWayBindings) {
assignment = unwrapWritableSignal(assignment, this.tcb);
}
assignment = import_typescript82.default.factory.createBinaryExpression(target, import_typescript82.default.SyntaxKind.EqualsToken, assignment);
}
addParseSpanInfo(assignment, attr.attribute.sourceSpan);
if (!this.tcb.env.config.checkTypeOfAttributes && attr.attribute instanceof TextAttribute) {
markIgnoreDiagnostics(assignment);
}
this.scope.addStatement(import_typescript82.default.factory.createExpressionStatement(assignment));
}
this.checkRequiredInputs(seenRequiredInputs);
return null;
}
checkRequiredInputs(seenRequiredInputs) {
const missing = [];
for (const input of this.dir.inputs) {
if (input.required && !seenRequiredInputs.has(input.classPropertyName)) {
missing.push(input.bindingPropertyName);
}
}
if (missing.length > 0) {
this.tcb.oobRecorder.missingRequiredInputs(this.tcb.id, this.node, this.dir.name, this.dir.isComponent, missing);
}
}
};
var TcbDirectiveCtorCircularFallbackOp = class extends TcbOp {
constructor(tcb, scope, node, dir) {
super();
this.tcb = tcb;
this.scope = scope;
this.node = node;
this.dir = dir;
}
get optional() {
return false;
}
execute() {
const id = this.tcb.allocateId();
const typeCtor = this.tcb.env.typeCtorFor(this.dir);
const circularPlaceholder = import_typescript82.default.factory.createCallExpression(
typeCtor,
void 0,
[import_typescript82.default.factory.createNonNullExpression(import_typescript82.default.factory.createNull())]
);
this.scope.addStatement(tsCreateVariable(id, circularPlaceholder));
return id;
}
};
var TcbDomSchemaCheckerOp = class extends TcbOp {
constructor(tcb, element2, checkElement, claimedInputs) {
super();
this.tcb = tcb;
this.element = element2;
this.checkElement = checkElement;
this.claimedInputs = claimedInputs;
}
get optional() {
return false;
}
execute() {
var _a2;
if (this.checkElement) {
this.tcb.domSchemaChecker.checkElement(this.tcb.id, this.element, this.tcb.schemas, this.tcb.hostIsStandalone);
}
for (const binding of this.element.inputs) {
const isPropertyBinding = binding.type === BindingType.Property || binding.type === BindingType.TwoWay;
if (isPropertyBinding && this.claimedInputs.has(binding.name)) {
continue;
}
if (isPropertyBinding && binding.name !== "style" && binding.name !== "class") {
const propertyName = (_a2 = ATTR_TO_PROP.get(binding.name)) != null ? _a2 : binding.name;
this.tcb.domSchemaChecker.checkProperty(this.tcb.id, this.element, propertyName, binding.sourceSpan, this.tcb.schemas, this.tcb.hostIsStandalone);
}
}
return null;
}
};
var TcbControlFlowContentProjectionOp = class extends TcbOp {
constructor(tcb, element2, ngContentSelectors, componentName) {
super();
this.tcb = tcb;
this.element = element2;
this.ngContentSelectors = ngContentSelectors;
this.componentName = componentName;
this.optional = false;
this.category = tcb.env.config.controlFlowPreventingContentProjection === "error" ? import_typescript82.default.DiagnosticCategory.Error : import_typescript82.default.DiagnosticCategory.Warning;
}
execute() {
const controlFlowToCheck = this.findPotentialControlFlowNodes();
if (controlFlowToCheck.length > 0) {
const matcher = new SelectorMatcher();
for (const selector of this.ngContentSelectors) {
if (selector !== "*") {
matcher.addSelectables(CssSelector.parse(selector), selector);
}
}
for (const root of controlFlowToCheck) {
for (const child of root.children) {
if (child instanceof Element || child instanceof Template) {
matcher.match(createCssSelectorFromNode(child), (_, originalSelector) => {
this.tcb.oobRecorder.controlFlowPreventingContentProjection(this.tcb.id, this.category, child, this.componentName, originalSelector, root, this.tcb.hostPreserveWhitespaces);
});
}
}
}
}
return null;
}
findPotentialControlFlowNodes() {
const result = [];
for (const child of this.element.children) {
if (child instanceof ForLoopBlock) {
if (this.shouldCheck(child)) {
result.push(child);
}
if (child.empty !== null && this.shouldCheck(child.empty)) {
result.push(child.empty);
}
} else if (child instanceof IfBlock) {
for (const branch of child.branches) {
if (this.shouldCheck(branch)) {
result.push(branch);
}
}
} else if (child instanceof SwitchBlock) {
for (const current of child.cases) {
if (this.shouldCheck(current)) {
result.push(current);
}
}
}
}
return result;
}
shouldCheck(node) {
if (node.children.length < 2) {
return false;
}
let hasSeenRootNode = false;
for (const child of node.children) {
if (!(child instanceof Text) || this.tcb.hostPreserveWhitespaces || child.value.trim().length > 0) {
if (hasSeenRootNode) {
return true;
}
hasSeenRootNode = true;
}
}
return false;
}
};
var ATTR_TO_PROP = new Map(Object.entries({
"class": "className",
"for": "htmlFor",
"formaction": "formAction",
"innerHtml": "innerHTML",
"readonly": "readOnly",
"tabindex": "tabIndex"
}));
var TcbUnclaimedInputsOp = class extends TcbOp {
constructor(tcb, scope, element2, claimedInputs) {
super();
this.tcb = tcb;
this.scope = scope;
this.element = element2;
this.claimedInputs = claimedInputs;
}
get optional() {
return false;
}
execute() {
var _a2;
let elId = null;
for (const binding of this.element.inputs) {
const isPropertyBinding = binding.type === BindingType.Property || binding.type === BindingType.TwoWay;
if (isPropertyBinding && this.claimedInputs.has(binding.name)) {
continue;
}
const expr = widenBinding(tcbExpression(binding.value, this.tcb, this.scope), this.tcb);
if (this.tcb.env.config.checkTypeOfDomBindings && isPropertyBinding) {
if (binding.name !== "style" && binding.name !== "class") {
if (elId === null) {
elId = this.scope.resolve(this.element);
}
const propertyName = (_a2 = ATTR_TO_PROP.get(binding.name)) != null ? _a2 : binding.name;
const prop = import_typescript82.default.factory.createElementAccessExpression(elId, import_typescript82.default.factory.createStringLiteral(propertyName));
const stmt = import_typescript82.default.factory.createBinaryExpression(prop, import_typescript82.default.SyntaxKind.EqualsToken, wrapForDiagnostics(expr));
addParseSpanInfo(stmt, binding.sourceSpan);
this.scope.addStatement(import_typescript82.default.factory.createExpressionStatement(stmt));
} else {
this.scope.addStatement(import_typescript82.default.factory.createExpressionStatement(expr));
}
} else {
this.scope.addStatement(import_typescript82.default.factory.createExpressionStatement(expr));
}
}
return null;
}
};
var TcbDirectiveOutputsOp = class extends TcbOp {
constructor(tcb, scope, node, dir) {
super();
this.tcb = tcb;
this.scope = scope;
this.node = node;
this.dir = dir;
}
get optional() {
return false;
}
execute() {
let dirId = null;
const outputs = this.dir.outputs;
for (const output of this.node.outputs) {
if (output.type === ParsedEventType.Animation || !outputs.hasBindingPropertyName(output.name)) {
continue;
}
if (this.tcb.env.config.checkTypeOfOutputEvents && output.name.endsWith("Change")) {
const inputName = output.name.slice(0, -6);
isSplitTwoWayBinding(inputName, output, this.node.inputs, this.tcb);
}
const field = outputs.getByBindingPropertyName(output.name)[0].classPropertyName;
if (dirId === null) {
dirId = this.scope.resolve(this.node, this.dir);
}
const outputField = import_typescript82.default.factory.createElementAccessExpression(dirId, import_typescript82.default.factory.createStringLiteral(field));
addParseSpanInfo(outputField, output.keySpan);
if (this.tcb.env.config.checkTypeOfOutputEvents) {
const handler = tcbCreateEventHandler(output, this.tcb, this.scope, 0);
const subscribeFn = import_typescript82.default.factory.createPropertyAccessExpression(outputField, "subscribe");
const call2 = import_typescript82.default.factory.createCallExpression(subscribeFn, void 0, [
handler
]);
addParseSpanInfo(call2, output.sourceSpan);
this.scope.addStatement(import_typescript82.default.factory.createExpressionStatement(call2));
} else {
this.scope.addStatement(import_typescript82.default.factory.createExpressionStatement(outputField));
const handler = tcbCreateEventHandler(output, this.tcb, this.scope, 1);
this.scope.addStatement(import_typescript82.default.factory.createExpressionStatement(handler));
}
}
return null;
}
};
var TcbUnclaimedOutputsOp = class extends TcbOp {
constructor(tcb, scope, element2, claimedOutputs) {
super();
this.tcb = tcb;
this.scope = scope;
this.element = element2;
this.claimedOutputs = claimedOutputs;
}
get optional() {
return false;
}
execute() {
let elId = null;
for (const output of this.element.outputs) {
if (this.claimedOutputs.has(output.name)) {
continue;
}
if (this.tcb.env.config.checkTypeOfOutputEvents && output.name.endsWith("Change")) {
const inputName = output.name.slice(0, -6);
if (isSplitTwoWayBinding(inputName, output, this.element.inputs, this.tcb)) {
continue;
}
}
if (output.type === ParsedEventType.Animation) {
const eventType = this.tcb.env.config.checkTypeOfAnimationEvents ? this.tcb.env.referenceExternalType("@angular/animations", "AnimationEvent") : 1;
const handler = tcbCreateEventHandler(output, this.tcb, this.scope, eventType);
this.scope.addStatement(import_typescript82.default.factory.createExpressionStatement(handler));
} else if (this.tcb.env.config.checkTypeOfDomEvents) {
const handler = tcbCreateEventHandler(output, this.tcb, this.scope, 0);
if (elId === null) {
elId = this.scope.resolve(this.element);
}
const propertyAccess = import_typescript82.default.factory.createPropertyAccessExpression(elId, "addEventListener");
addParseSpanInfo(propertyAccess, output.keySpan);
const call2 = import_typescript82.default.factory.createCallExpression(
propertyAccess,
void 0,
[import_typescript82.default.factory.createStringLiteral(output.name), handler]
);
addParseSpanInfo(call2, output.sourceSpan);
this.scope.addStatement(import_typescript82.default.factory.createExpressionStatement(call2));
} else {
const handler = tcbCreateEventHandler(output, this.tcb, this.scope, 1);
this.scope.addStatement(import_typescript82.default.factory.createExpressionStatement(handler));
}
}
return null;
}
};
var TcbComponentContextCompletionOp = class extends TcbOp {
constructor(scope) {
super();
this.scope = scope;
this.optional = false;
}
execute() {
const ctx = import_typescript82.default.factory.createThis();
const ctxDot = import_typescript82.default.factory.createPropertyAccessExpression(ctx, "");
markIgnoreDiagnostics(ctxDot);
addExpressionIdentifier(ctxDot, ExpressionIdentifier.COMPONENT_COMPLETION);
this.scope.addStatement(import_typescript82.default.factory.createExpressionStatement(ctxDot));
return null;
}
};
var TcbBlockVariableOp = class extends TcbOp {
constructor(tcb, scope, initializer, variable2) {
super();
this.tcb = tcb;
this.scope = scope;
this.initializer = initializer;
this.variable = variable2;
}
get optional() {
return false;
}
execute() {
const id = this.tcb.allocateId();
addParseSpanInfo(id, this.variable.keySpan);
const variable2 = tsCreateVariable(id, wrapForTypeChecker(this.initializer));
addParseSpanInfo(variable2.declarationList.declarations[0], this.variable.sourceSpan);
this.scope.addStatement(variable2);
return id;
}
};
var TcbBlockImplicitVariableOp = class extends TcbOp {
constructor(tcb, scope, type, variable2) {
super();
this.tcb = tcb;
this.scope = scope;
this.type = type;
this.variable = variable2;
this.optional = true;
}
execute() {
const id = this.tcb.allocateId();
addParseSpanInfo(id, this.variable.keySpan);
const variable2 = tsDeclareVariable(id, this.type);
addParseSpanInfo(variable2.declarationList.declarations[0], this.variable.sourceSpan);
this.scope.addStatement(variable2);
return id;
}
};
var TcbIfOp = class extends TcbOp {
constructor(tcb, scope, block) {
super();
this.tcb = tcb;
this.scope = scope;
this.block = block;
this.expressionScopes = /* @__PURE__ */ new Map();
}
get optional() {
return false;
}
execute() {
const root = this.generateBranch(0);
root && this.scope.addStatement(root);
return null;
}
generateBranch(index) {
const branch = this.block.branches[index];
if (!branch) {
return void 0;
}
if (branch.expression === null) {
const branchScope = this.getBranchScope(this.scope, branch, index);
return import_typescript82.default.factory.createBlock(branchScope.render());
}
const outerScope = Scope3.forNodes(this.tcb, this.scope, branch, [], null);
outerScope.render().forEach((stmt) => this.scope.addStatement(stmt));
this.expressionScopes.set(branch, outerScope);
let expression = tcbExpression(branch.expression, this.tcb, this.scope);
if (branch.expressionAlias !== null) {
expression = import_typescript82.default.factory.createBinaryExpression(import_typescript82.default.factory.createParenthesizedExpression(expression), import_typescript82.default.SyntaxKind.AmpersandAmpersandToken, outerScope.resolve(branch.expressionAlias));
}
const bodyScope = this.getBranchScope(outerScope, branch, index);
return import_typescript82.default.factory.createIfStatement(expression, import_typescript82.default.factory.createBlock(bodyScope.render()), this.generateBranch(index + 1));
}
getBranchScope(parentScope, branch, index) {
const checkBody = this.tcb.env.config.checkControlFlowBodies;
return Scope3.forNodes(this.tcb, parentScope, null, checkBody ? branch.children : [], checkBody ? this.generateBranchGuard(index) : null);
}
generateBranchGuard(index) {
let guard = null;
for (let i = 0; i <= index; i++) {
const branch = this.block.branches[i];
if (branch.expression === null) {
continue;
}
if (!this.expressionScopes.has(branch)) {
throw new Error(`Could not determine expression scope of branch at index ${i}`);
}
const expressionScope = this.expressionScopes.get(branch);
let expression;
expression = tcbExpression(branch.expression, this.tcb, expressionScope);
if (branch.expressionAlias !== null) {
expression = import_typescript82.default.factory.createBinaryExpression(import_typescript82.default.factory.createParenthesizedExpression(expression), import_typescript82.default.SyntaxKind.AmpersandAmpersandToken, expressionScope.resolve(branch.expressionAlias));
}
markIgnoreDiagnostics(expression);
const comparisonExpression = i === index ? expression : import_typescript82.default.factory.createPrefixUnaryExpression(import_typescript82.default.SyntaxKind.ExclamationToken, import_typescript82.default.factory.createParenthesizedExpression(expression));
guard = guard === null ? comparisonExpression : import_typescript82.default.factory.createBinaryExpression(guard, import_typescript82.default.SyntaxKind.AmpersandAmpersandToken, comparisonExpression);
}
return guard;
}
};
var TcbSwitchOp = class extends TcbOp {
constructor(tcb, scope, block) {
super();
this.tcb = tcb;
this.scope = scope;
this.block = block;
}
get optional() {
return false;
}
execute() {
const switchExpression = tcbExpression(this.block.expression, this.tcb, this.scope);
const clauses = this.block.cases.map((current) => {
const checkBody = this.tcb.env.config.checkControlFlowBodies;
const clauseScope = Scope3.forNodes(this.tcb, this.scope, null, checkBody ? current.children : [], checkBody ? this.generateGuard(current, switchExpression) : null);
const statements = [...clauseScope.render(), import_typescript82.default.factory.createBreakStatement()];
return current.expression === null ? import_typescript82.default.factory.createDefaultClause(statements) : import_typescript82.default.factory.createCaseClause(tcbExpression(current.expression, this.tcb, clauseScope), statements);
});
this.scope.addStatement(import_typescript82.default.factory.createSwitchStatement(switchExpression, import_typescript82.default.factory.createCaseBlock(clauses)));
return null;
}
generateGuard(node, switchValue) {
if (node.expression !== null) {
const expression = tcbExpression(node.expression, this.tcb, this.scope);
markIgnoreDiagnostics(expression);
return import_typescript82.default.factory.createBinaryExpression(switchValue, import_typescript82.default.SyntaxKind.EqualsEqualsEqualsToken, expression);
}
let guard = null;
for (const current of this.block.cases) {
if (current.expression === null) {
continue;
}
const expression = tcbExpression(current.expression, this.tcb, this.scope);
markIgnoreDiagnostics(expression);
const comparison = import_typescript82.default.factory.createBinaryExpression(switchValue, import_typescript82.default.SyntaxKind.ExclamationEqualsEqualsToken, expression);
if (guard === null) {
guard = comparison;
} else {
guard = import_typescript82.default.factory.createBinaryExpression(guard, import_typescript82.default.SyntaxKind.AmpersandAmpersandToken, comparison);
}
}
return guard;
}
};
var TcbForOfOp = class extends TcbOp {
constructor(tcb, scope, block) {
super();
this.tcb = tcb;
this.scope = scope;
this.block = block;
}
get optional() {
return false;
}
execute() {
const loopScope = Scope3.forNodes(this.tcb, this.scope, this.block, this.tcb.env.config.checkControlFlowBodies ? this.block.children : [], null);
const initializerId = loopScope.resolve(this.block.item);
if (!import_typescript82.default.isIdentifier(initializerId)) {
throw new Error(`Could not resolve for loop variable ${this.block.item.name} to an identifier`);
}
const initializer = import_typescript82.default.factory.createVariableDeclarationList([import_typescript82.default.factory.createVariableDeclaration(initializerId)], import_typescript82.default.NodeFlags.Const);
addParseSpanInfo(initializer, this.block.item.keySpan);
const expression = import_typescript82.default.factory.createNonNullExpression(tcbExpression(this.block.expression, this.tcb, this.scope));
const trackTranslator = new TcbForLoopTrackTranslator(this.tcb, loopScope, this.block);
const trackExpression = trackTranslator.translate(this.block.trackBy);
const statements = [
...loopScope.render(),
import_typescript82.default.factory.createExpressionStatement(trackExpression)
];
this.scope.addStatement(import_typescript82.default.factory.createForOfStatement(void 0, initializer, expression, import_typescript82.default.factory.createBlock(statements)));
return null;
}
};
var INFER_TYPE_FOR_CIRCULAR_OP_EXPR = import_typescript82.default.factory.createNonNullExpression(import_typescript82.default.factory.createNull());
var Context2 = class {
constructor(env, domSchemaChecker, oobRecorder, id, boundTarget, pipes, schemas, hostIsStandalone, hostPreserveWhitespaces) {
this.env = env;
this.domSchemaChecker = domSchemaChecker;
this.oobRecorder = oobRecorder;
this.id = id;
this.boundTarget = boundTarget;
this.pipes = pipes;
this.schemas = schemas;
this.hostIsStandalone = hostIsStandalone;
this.hostPreserveWhitespaces = hostPreserveWhitespaces;
this.nextId = 1;
}
allocateId() {
return import_typescript82.default.factory.createIdentifier(`_t${this.nextId++}`);
}
getPipeByName(name) {
if (!this.pipes.has(name)) {
return null;
}
return this.pipes.get(name);
}
};
var _Scope = class {
constructor(tcb, parent = null, guard = null) {
this.tcb = tcb;
this.parent = parent;
this.guard = guard;
this.opQueue = [];
this.elementOpMap = /* @__PURE__ */ new Map();
this.directiveOpMap = /* @__PURE__ */ new Map();
this.referenceOpMap = /* @__PURE__ */ new Map();
this.templateCtxOpMap = /* @__PURE__ */ new Map();
this.varMap = /* @__PURE__ */ new Map();
this.letDeclOpMap = /* @__PURE__ */ new Map();
this.statements = [];
}
static forNodes(tcb, parentScope, scopedNode, children, guard) {
const scope = new _Scope(tcb, parentScope, guard);
if (parentScope === null && tcb.env.config.enableTemplateTypeChecker) {
scope.opQueue.push(new TcbComponentContextCompletionOp(scope));
}
if (scopedNode instanceof Template) {
const varMap = /* @__PURE__ */ new Map();
for (const v of scopedNode.variables) {
if (!varMap.has(v.name)) {
varMap.set(v.name, v);
} else {
const firstDecl = varMap.get(v.name);
tcb.oobRecorder.duplicateTemplateVar(tcb.id, v, firstDecl);
}
this.registerVariable(scope, v, new TcbTemplateVariableOp(tcb, scope, scopedNode, v));
}
} else if (scopedNode instanceof IfBlockBranch) {
const { expression, expressionAlias } = scopedNode;
if (expression !== null && expressionAlias !== null) {
this.registerVariable(scope, expressionAlias, new TcbBlockVariableOp(tcb, scope, tcbExpression(expression, tcb, scope), expressionAlias));
}
} else if (scopedNode instanceof ForLoopBlock) {
const loopInitializer = tcb.allocateId();
addParseSpanInfo(loopInitializer, scopedNode.item.sourceSpan);
scope.varMap.set(scopedNode.item, loopInitializer);
for (const variable2 of scopedNode.contextVariables) {
if (!this.forLoopContextVariableTypes.has(variable2.value)) {
throw new Error(`Unrecognized for loop context variable ${variable2.name}`);
}
const type = import_typescript82.default.factory.createKeywordTypeNode(this.forLoopContextVariableTypes.get(variable2.value));
this.registerVariable(scope, variable2, new TcbBlockImplicitVariableOp(tcb, scope, type, variable2));
}
}
for (const node of children) {
scope.appendNode(node);
}
for (const variable2 of scope.varMap.keys()) {
_Scope.checkConflictingLet(scope, variable2);
}
for (const ref of scope.referenceOpMap.keys()) {
_Scope.checkConflictingLet(scope, ref);
}
return scope;
}
static registerVariable(scope, variable2, op) {
const opIndex = scope.opQueue.push(op) - 1;
scope.varMap.set(variable2, opIndex);
}
resolve(node, directive) {
const res = this.resolveLocal(node, directive);
if (res !== null) {
let clone;
if (import_typescript82.default.isIdentifier(res)) {
clone = import_typescript82.default.factory.createIdentifier(res.text);
} else if (import_typescript82.default.isNonNullExpression(res)) {
clone = import_typescript82.default.factory.createNonNullExpression(res.expression);
} else {
throw new Error(`Could not resolve ${node} to an Identifier or a NonNullExpression`);
}
import_typescript82.default.setOriginalNode(clone, res);
clone.parent = clone.parent;
return import_typescript82.default.setSyntheticTrailingComments(clone, []);
} else if (this.parent !== null) {
return this.parent.resolve(node, directive);
} else {
throw new Error(`Could not resolve ${node} / ${directive}`);
}
}
addStatement(stmt) {
this.statements.push(stmt);
}
render() {
for (let i = 0; i < this.opQueue.length; i++) {
const skipOptional = !this.tcb.env.config.enableTemplateTypeChecker;
this.executeOp(i, skipOptional);
}
return this.statements;
}
guards() {
let parentGuards = null;
if (this.parent !== null) {
parentGuards = this.parent.guards();
}
if (this.guard === null) {
return parentGuards;
} else if (parentGuards === null) {
return this.guard;
} else {
return import_typescript82.default.factory.createBinaryExpression(parentGuards, import_typescript82.default.SyntaxKind.AmpersandAmpersandToken, this.guard);
}
}
isLocal(node) {
if (node instanceof Variable) {
return this.varMap.has(node);
}
if (node instanceof LetDeclaration) {
return this.letDeclOpMap.has(node.name);
}
return this.referenceOpMap.has(node);
}
resolveLocal(ref, directive) {
if (ref instanceof Reference && this.referenceOpMap.has(ref)) {
return this.resolveOp(this.referenceOpMap.get(ref));
} else if (ref instanceof LetDeclaration && this.letDeclOpMap.has(ref.name)) {
return this.resolveOp(this.letDeclOpMap.get(ref.name).opIndex);
} else if (ref instanceof Variable && this.varMap.has(ref)) {
const opIndexOrNode = this.varMap.get(ref);
return typeof opIndexOrNode === "number" ? this.resolveOp(opIndexOrNode) : opIndexOrNode;
} else if (ref instanceof Template && directive === void 0 && this.templateCtxOpMap.has(ref)) {
return this.resolveOp(this.templateCtxOpMap.get(ref));
} else if ((ref instanceof Element || ref instanceof Template) && directive !== void 0 && this.directiveOpMap.has(ref)) {
const dirMap = this.directiveOpMap.get(ref);
if (dirMap.has(directive)) {
return this.resolveOp(dirMap.get(directive));
} else {
return null;
}
} else if (ref instanceof Element && this.elementOpMap.has(ref)) {
return this.resolveOp(this.elementOpMap.get(ref));
} else {
return null;
}
}
resolveOp(opIndex) {
const res = this.executeOp(opIndex, false);
if (res === null) {
throw new Error(`Error resolving operation, got null`);
}
return res;
}
executeOp(opIndex, skipOptional) {
const op = this.opQueue[opIndex];
if (!(op instanceof TcbOp)) {
return op;
}
if (skipOptional && op.optional) {
return null;
}
this.opQueue[opIndex] = op.circularFallback();
const res = op.execute();
this.opQueue[opIndex] = res;
return res;
}
appendNode(node) {
if (node instanceof Element) {
const opIndex = this.opQueue.push(new TcbElementOp(this.tcb, this, node)) - 1;
this.elementOpMap.set(node, opIndex);
if (this.tcb.env.config.controlFlowPreventingContentProjection !== "suppress") {
this.appendContentProjectionCheckOp(node);
}
this.appendDirectivesAndInputsOfNode(node);
this.appendOutputsOfNode(node);
this.appendChildren(node);
this.checkAndAppendReferencesOfNode(node);
} else if (node instanceof Template) {
this.appendDirectivesAndInputsOfNode(node);
this.appendOutputsOfNode(node);
const ctxIndex = this.opQueue.push(new TcbTemplateContextOp(this.tcb, this)) - 1;
this.templateCtxOpMap.set(node, ctxIndex);
if (this.tcb.env.config.checkTemplateBodies) {
this.opQueue.push(new TcbTemplateBodyOp(this.tcb, this, node));
} else if (this.tcb.env.config.alwaysCheckSchemaInTemplateBodies) {
this.appendDeepSchemaChecks(node.children);
}
this.checkAndAppendReferencesOfNode(node);
} else if (node instanceof DeferredBlock) {
this.appendDeferredBlock(node);
} else if (node instanceof IfBlock) {
this.opQueue.push(new TcbIfOp(this.tcb, this, node));
} else if (node instanceof SwitchBlock) {
this.opQueue.push(new TcbSwitchOp(this.tcb, this, node));
} else if (node instanceof ForLoopBlock) {
this.opQueue.push(new TcbForOfOp(this.tcb, this, node));
node.empty && this.tcb.env.config.checkControlFlowBodies && this.appendChildren(node.empty);
} else if (node instanceof BoundText) {
this.opQueue.push(new TcbExpressionOp(this.tcb, this, node.value));
} else if (node instanceof Icu) {
this.appendIcuExpressions(node);
} else if (node instanceof Content) {
this.appendChildren(node);
} else if (node instanceof LetDeclaration) {
const opIndex = this.opQueue.push(new TcbLetDeclarationOp(this.tcb, this, node)) - 1;
if (this.isLocal(node)) {
this.tcb.oobRecorder.conflictingDeclaration(this.tcb.id, node);
} else {
this.letDeclOpMap.set(node.name, { opIndex, node });
}
}
}
appendChildren(node) {
for (const child of node.children) {
this.appendNode(child);
}
}
checkAndAppendReferencesOfNode(node) {
for (const ref of node.references) {
const target = this.tcb.boundTarget.getReferenceTarget(ref);
let ctxIndex;
if (target === null) {
this.tcb.oobRecorder.missingReferenceTarget(this.tcb.id, ref);
ctxIndex = this.opQueue.push(new TcbInvalidReferenceOp(this.tcb, this)) - 1;
} else if (target instanceof Template || target instanceof Element) {
ctxIndex = this.opQueue.push(new TcbReferenceOp(this.tcb, this, ref, node, target)) - 1;
} else {
ctxIndex = this.opQueue.push(new TcbReferenceOp(this.tcb, this, ref, node, target.directive)) - 1;
}
this.referenceOpMap.set(ref, ctxIndex);
}
}
appendDirectivesAndInputsOfNode(node) {
const claimedInputs = /* @__PURE__ */ new Set();
const directives = this.tcb.boundTarget.getDirectivesOfNode(node);
if (directives === null || directives.length === 0) {
if (node instanceof Element) {
this.opQueue.push(new TcbUnclaimedInputsOp(this.tcb, this, node, claimedInputs));
this.opQueue.push(new TcbDomSchemaCheckerOp(this.tcb, node, true, claimedInputs));
}
return;
} else {
if (node instanceof Element) {
const isDeferred = this.tcb.boundTarget.isDeferred(node);
if (!isDeferred && directives.some((dirMeta) => dirMeta.isExplicitlyDeferred)) {
this.tcb.oobRecorder.deferredComponentUsedEagerly(this.tcb.id, node);
}
}
}
const dirMap = /* @__PURE__ */ new Map();
for (const dir of directives) {
let directiveOp;
const host = this.tcb.env.reflector;
const dirRef = dir.ref;
if (!dir.isGeneric) {
directiveOp = new TcbNonGenericDirectiveTypeOp(this.tcb, this, node, dir);
} else if (!requiresInlineTypeCtor(dirRef.node, host, this.tcb.env) || this.tcb.env.config.useInlineTypeConstructors) {
directiveOp = new TcbDirectiveCtorOp(this.tcb, this, node, dir);
} else {
directiveOp = new TcbGenericDirectiveTypeWithAnyParamsOp(this.tcb, this, node, dir);
}
const dirIndex = this.opQueue.push(directiveOp) - 1;
dirMap.set(dir, dirIndex);
this.opQueue.push(new TcbDirectiveInputsOp(this.tcb, this, node, dir));
}
this.directiveOpMap.set(node, dirMap);
if (node instanceof Element) {
for (const dir of directives) {
for (const propertyName of dir.inputs.propertyNames) {
claimedInputs.add(propertyName);
}
}
this.opQueue.push(new TcbUnclaimedInputsOp(this.tcb, this, node, claimedInputs));
const checkElement = directives.length === 0;
this.opQueue.push(new TcbDomSchemaCheckerOp(this.tcb, node, checkElement, claimedInputs));
}
}
appendOutputsOfNode(node) {
const claimedOutputs = /* @__PURE__ */ new Set();
const directives = this.tcb.boundTarget.getDirectivesOfNode(node);
if (directives === null || directives.length === 0) {
if (node instanceof Element) {
this.opQueue.push(new TcbUnclaimedOutputsOp(this.tcb, this, node, claimedOutputs));
}
return;
}
for (const dir of directives) {
this.opQueue.push(new TcbDirectiveOutputsOp(this.tcb, this, node, dir));
}
if (node instanceof Element) {
for (const dir of directives) {
for (const outputProperty of dir.outputs.propertyNames) {
claimedOutputs.add(outputProperty);
}
}
this.opQueue.push(new TcbUnclaimedOutputsOp(this.tcb, this, node, claimedOutputs));
}
}
appendDeepSchemaChecks(nodes) {
for (const node of nodes) {
if (!(node instanceof Element || node instanceof Template)) {
continue;
}
if (node instanceof Element) {
const claimedInputs = /* @__PURE__ */ new Set();
const directives = this.tcb.boundTarget.getDirectivesOfNode(node);
let hasDirectives;
if (directives === null || directives.length === 0) {
hasDirectives = false;
} else {
hasDirectives = true;
for (const dir of directives) {
for (const propertyName of dir.inputs.propertyNames) {
claimedInputs.add(propertyName);
}
}
}
this.opQueue.push(new TcbDomSchemaCheckerOp(this.tcb, node, !hasDirectives, claimedInputs));
}
this.appendDeepSchemaChecks(node.children);
}
}
appendIcuExpressions(node) {
for (const variable2 of Object.values(node.vars)) {
this.opQueue.push(new TcbExpressionOp(this.tcb, this, variable2.value));
}
for (const placeholder of Object.values(node.placeholders)) {
if (placeholder instanceof BoundText) {
this.opQueue.push(new TcbExpressionOp(this.tcb, this, placeholder.value));
}
}
}
appendContentProjectionCheckOp(root) {
var _a2;
const meta = ((_a2 = this.tcb.boundTarget.getDirectivesOfNode(root)) == null ? void 0 : _a2.find((meta2) => meta2.isComponent)) || null;
if (meta !== null && meta.ngContentSelectors !== null && meta.ngContentSelectors.length > 0) {
const selectors = meta.ngContentSelectors;
if (selectors.length > 1 || selectors.length === 1 && selectors[0] !== "*") {
this.opQueue.push(new TcbControlFlowContentProjectionOp(this.tcb, root, selectors, meta.name));
}
}
}
appendDeferredBlock(block) {
this.appendDeferredTriggers(block, block.triggers);
this.appendDeferredTriggers(block, block.prefetchTriggers);
this.appendChildren(block);
if (block.placeholder !== null) {
this.appendChildren(block.placeholder);
}
if (block.loading !== null) {
this.appendChildren(block.loading);
}
if (block.error !== null) {
this.appendChildren(block.error);
}
}
appendDeferredTriggers(block, triggers) {
if (triggers.when !== void 0) {
this.opQueue.push(new TcbExpressionOp(this.tcb, this, triggers.when.value));
}
if (triggers.hover !== void 0) {
this.appendReferenceBasedDeferredTrigger(block, triggers.hover);
}
if (triggers.interaction !== void 0) {
this.appendReferenceBasedDeferredTrigger(block, triggers.interaction);
}
if (triggers.viewport !== void 0) {
this.appendReferenceBasedDeferredTrigger(block, triggers.viewport);
}
}
appendReferenceBasedDeferredTrigger(block, trigger) {
if (this.tcb.boundTarget.getDeferredTriggerTarget(block, trigger) === null) {
this.tcb.oobRecorder.inaccessibleDeferredTriggerElement(this.tcb.id, trigger);
}
}
static checkConflictingLet(scope, node) {
if (scope.letDeclOpMap.has(node.name)) {
scope.tcb.oobRecorder.conflictingDeclaration(scope.tcb.id, scope.letDeclOpMap.get(node.name).node);
}
}
};
var Scope3 = _Scope;
(() => {
_Scope.forLoopContextVariableTypes = /* @__PURE__ */ new Map([
["$first", import_typescript82.default.SyntaxKind.BooleanKeyword],
["$last", import_typescript82.default.SyntaxKind.BooleanKeyword],
["$even", import_typescript82.default.SyntaxKind.BooleanKeyword],
["$odd", import_typescript82.default.SyntaxKind.BooleanKeyword],
["$index", import_typescript82.default.SyntaxKind.NumberKeyword],
["$count", import_typescript82.default.SyntaxKind.NumberKeyword]
]);
})();
function tcbThisParam(name, typeArguments) {
return import_typescript82.default.factory.createParameterDeclaration(
void 0,
void 0,
"this",
void 0,
import_typescript82.default.factory.createTypeReferenceNode(name, typeArguments),
void 0
);
}
function tcbExpression(ast, tcb, scope) {
const translator = new TcbExpressionTranslator(tcb, scope);
return translator.translate(ast);
}
var TcbExpressionTranslator = class {
constructor(tcb, scope) {
this.tcb = tcb;
this.scope = scope;
}
translate(ast) {
return astToTypescript(ast, (ast2) => this.resolve(ast2), this.tcb.env.config);
}
resolve(ast) {
if (ast instanceof PropertyRead && ast.receiver instanceof ImplicitReceiver) {
const target = this.tcb.boundTarget.getExpressionTarget(ast);
const targetExpression = target === null ? null : this.getTargetNodeExpression(target, ast);
if (target instanceof LetDeclaration && !this.isValidLetDeclarationAccess(target, ast)) {
this.tcb.oobRecorder.letUsedBeforeDefinition(this.tcb.id, ast, target);
if (targetExpression !== null) {
return import_typescript82.default.factory.createAsExpression(targetExpression, import_typescript82.default.factory.createKeywordTypeNode(import_typescript82.default.SyntaxKind.AnyKeyword));
}
}
return targetExpression;
} else if (ast instanceof PropertyWrite && ast.receiver instanceof ImplicitReceiver) {
const target = this.tcb.boundTarget.getExpressionTarget(ast);
if (target === null) {
return null;
}
const targetExpression = this.getTargetNodeExpression(target, ast);
const expr = this.translate(ast.value);
const result = import_typescript82.default.factory.createParenthesizedExpression(import_typescript82.default.factory.createBinaryExpression(targetExpression, import_typescript82.default.SyntaxKind.EqualsToken, expr));
addParseSpanInfo(result, ast.sourceSpan);
if (target instanceof LetDeclaration) {
markIgnoreDiagnostics(result);
this.tcb.oobRecorder.illegalWriteToLetDeclaration(this.tcb.id, ast, target);
}
return result;
} else if (ast instanceof ImplicitReceiver) {
return import_typescript82.default.factory.createThis();
} else if (ast instanceof BindingPipe) {
const expr = this.translate(ast.exp);
const pipeMeta = this.tcb.getPipeByName(ast.name);
let pipe2;
if (pipeMeta === null) {
this.tcb.oobRecorder.missingPipe(this.tcb.id, ast);
pipe2 = ANY_EXPRESSION;
} else if (pipeMeta.isExplicitlyDeferred && this.tcb.boundTarget.getEagerlyUsedPipes().includes(ast.name)) {
this.tcb.oobRecorder.deferredPipeUsedEagerly(this.tcb.id, ast);
pipe2 = ANY_EXPRESSION;
} else {
pipe2 = this.tcb.env.pipeInst(pipeMeta.ref);
}
const args = ast.args.map((arg) => this.translate(arg));
let methodAccess = import_typescript82.default.factory.createPropertyAccessExpression(pipe2, "transform");
addParseSpanInfo(methodAccess, ast.nameSpan);
if (!this.tcb.env.config.checkTypeOfPipes) {
methodAccess = import_typescript82.default.factory.createAsExpression(methodAccess, import_typescript82.default.factory.createKeywordTypeNode(import_typescript82.default.SyntaxKind.AnyKeyword));
}
const result = import_typescript82.default.factory.createCallExpression(
methodAccess,
void 0,
[expr, ...args]
);
addParseSpanInfo(result, ast.sourceSpan);
return result;
} else if ((ast instanceof Call || ast instanceof SafeCall) && (ast.receiver instanceof PropertyRead || ast.receiver instanceof SafePropertyRead)) {
if (ast.receiver.receiver instanceof ImplicitReceiver && !(ast.receiver.receiver instanceof ThisReceiver) && ast.receiver.name === "$any" && ast.args.length === 1) {
const expr = this.translate(ast.args[0]);
const exprAsAny = import_typescript82.default.factory.createAsExpression(expr, import_typescript82.default.factory.createKeywordTypeNode(import_typescript82.default.SyntaxKind.AnyKeyword));
const result = import_typescript82.default.factory.createParenthesizedExpression(exprAsAny);
addParseSpanInfo(result, ast.sourceSpan);
return result;
}
const target = this.tcb.boundTarget.getExpressionTarget(ast);
if (target === null) {
return null;
}
const receiver = this.getTargetNodeExpression(target, ast);
const method = wrapForDiagnostics(receiver);
addParseSpanInfo(method, ast.receiver.nameSpan);
const args = ast.args.map((arg) => this.translate(arg));
const node = import_typescript82.default.factory.createCallExpression(method, void 0, args);
addParseSpanInfo(node, ast.sourceSpan);
return node;
} else {
return null;
}
}
getTargetNodeExpression(targetNode, expressionNode) {
const expr = this.scope.resolve(targetNode);
addParseSpanInfo(expr, expressionNode.sourceSpan);
return expr;
}
isValidLetDeclarationAccess(target, ast) {
const targetStart = target.sourceSpan.start.offset;
const targetEnd = target.sourceSpan.end.offset;
const astStart = ast.sourceSpan.start;
return targetStart < astStart && astStart > targetEnd || !this.scope.isLocal(target);
}
};
function tcbCallTypeCtor(dir, tcb, inputs) {
const typeCtor = tcb.env.typeCtorFor(dir);
const members = inputs.map((input) => {
const propertyName = import_typescript82.default.factory.createStringLiteral(input.field);
if (input.type === "binding") {
let expr = widenBinding(input.expression, tcb);
if (input.isTwoWayBinding && tcb.env.config.allowSignalsInTwoWayBindings) {
expr = unwrapWritableSignal(expr, tcb);
}
const assignment = import_typescript82.default.factory.createPropertyAssignment(propertyName, wrapForDiagnostics(expr));
addParseSpanInfo(assignment, input.sourceSpan);
return assignment;
} else {
return import_typescript82.default.factory.createPropertyAssignment(propertyName, ANY_EXPRESSION);
}
});
return import_typescript82.default.factory.createCallExpression(
typeCtor,
void 0,
[import_typescript82.default.factory.createObjectLiteralExpression(members)]
);
}
function getBoundAttributes(directive, node) {
const boundInputs = [];
const processAttribute = (attr) => {
if (attr instanceof BoundAttribute && attr.type !== BindingType.Property && attr.type !== BindingType.TwoWay) {
return;
}
const inputs = directive.inputs.getByBindingPropertyName(attr.name);
if (inputs !== null) {
boundInputs.push({
attribute: attr,
inputs: inputs.map((input) => {
var _a2;
return {
fieldName: input.classPropertyName,
required: input.required,
transformType: ((_a2 = input.transform) == null ? void 0 : _a2.type) || null,
isSignal: input.isSignal,
isTwoWayBinding: attr instanceof BoundAttribute && attr.type === BindingType.TwoWay
};
})
});
}
};
node.inputs.forEach(processAttribute);
node.attributes.forEach(processAttribute);
if (node instanceof Template) {
node.templateAttrs.forEach(processAttribute);
}
return boundInputs;
}
function translateInput(attr, tcb, scope) {
if (attr instanceof BoundAttribute) {
return tcbExpression(attr.value, tcb, scope);
} else {
return import_typescript82.default.factory.createStringLiteral(attr.value);
}
}
function widenBinding(expr, tcb) {
if (!tcb.env.config.checkTypeOfInputBindings) {
return tsCastToAny(expr);
} else if (!tcb.env.config.strictNullInputBindings) {
if (import_typescript82.default.isObjectLiteralExpression(expr) || import_typescript82.default.isArrayLiteralExpression(expr)) {
return expr;
} else {
return import_typescript82.default.factory.createNonNullExpression(expr);
}
} else {
return expr;
}
}
function unwrapWritableSignal(expression, tcb) {
const unwrapRef = tcb.env.referenceExternalSymbol(Identifiers.unwrapWritableSignal.moduleName, Identifiers.unwrapWritableSignal.name);
return import_typescript82.default.factory.createCallExpression(unwrapRef, void 0, [expression]);
}
var EVENT_PARAMETER = "$event";
function tcbCreateEventHandler(event, tcb, scope, eventType) {
const handler = tcbEventHandlerExpression(event.handler, tcb, scope);
let eventParamType;
if (eventType === 0) {
eventParamType = void 0;
} else if (eventType === 1) {
eventParamType = import_typescript82.default.factory.createKeywordTypeNode(import_typescript82.default.SyntaxKind.AnyKeyword);
} else {
eventParamType = eventType;
}
const guards = scope.guards();
let body = import_typescript82.default.factory.createExpressionStatement(handler);
if (guards !== null) {
body = import_typescript82.default.factory.createIfStatement(guards, body);
}
const eventParam = import_typescript82.default.factory.createParameterDeclaration(
void 0,
void 0,
EVENT_PARAMETER,
void 0,
eventParamType
);
addExpressionIdentifier(eventParam, ExpressionIdentifier.EVENT_PARAMETER);
return import_typescript82.default.factory.createArrowFunction(
void 0,
void 0,
[eventParam],
import_typescript82.default.factory.createKeywordTypeNode(import_typescript82.default.SyntaxKind.AnyKeyword),
void 0,
import_typescript82.default.factory.createBlock([body])
);
}
function tcbEventHandlerExpression(ast, tcb, scope) {
const translator = new TcbEventHandlerTranslator(tcb, scope);
return translator.translate(ast);
}
function isSplitTwoWayBinding(inputName, output, inputs, tcb) {
const input = inputs.find((input2) => input2.name === inputName);
if (input === void 0 || input.sourceSpan !== output.sourceSpan) {
return false;
}
const inputConsumer = tcb.boundTarget.getConsumerOfBinding(input);
const outputConsumer = tcb.boundTarget.getConsumerOfBinding(output);
if (outputConsumer === null || inputConsumer.ref === void 0 || outputConsumer instanceof Template) {
return false;
}
if (outputConsumer instanceof Element) {
tcb.oobRecorder.splitTwoWayBinding(tcb.id, input, output, inputConsumer.ref.node, outputConsumer);
return true;
} else if (outputConsumer.ref !== inputConsumer.ref) {
tcb.oobRecorder.splitTwoWayBinding(tcb.id, input, output, inputConsumer.ref.node, outputConsumer.ref.node);
return true;
}
return false;
}
var TcbEventHandlerTranslator = class extends TcbExpressionTranslator {
resolve(ast) {
if (ast instanceof PropertyRead && ast.receiver instanceof ImplicitReceiver && !(ast.receiver instanceof ThisReceiver) && ast.name === EVENT_PARAMETER) {
const event = import_typescript82.default.factory.createIdentifier(EVENT_PARAMETER);
addParseSpanInfo(event, ast.nameSpan);
return event;
}
return super.resolve(ast);
}
isValidLetDeclarationAccess() {
return true;
}
};
var TcbForLoopTrackTranslator = class extends TcbExpressionTranslator {
constructor(tcb, scope, block) {
super(tcb, scope);
this.block = block;
this.allowedVariables = /* @__PURE__ */ new Set([block.item]);
for (const variable2 of block.contextVariables) {
if (variable2.value === "$index") {
this.allowedVariables.add(variable2);
}
}
}
resolve(ast) {
if (ast instanceof PropertyRead && ast.receiver instanceof ImplicitReceiver) {
const target = this.tcb.boundTarget.getExpressionTarget(ast);
if (target !== null && (!(target instanceof Variable) || !this.allowedVariables.has(target))) {
this.tcb.oobRecorder.illegalForLoopTrackAccess(this.tcb.id, this.block, ast);
}
}
return super.resolve(ast);
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_file.mjs
var import_typescript83 = __toESM(require("typescript"), 1);
var TypeCheckFile = class extends Environment {
constructor(fileName, config, refEmitter, reflector, compilerHost) {
super(config, new ImportManager({
forceGenerateNamespacesForNewImports: true,
shouldUseSingleQuotes: () => true
}), refEmitter, reflector, import_typescript83.default.createSourceFile(compilerHost.getCanonicalFileName(fileName), "", import_typescript83.default.ScriptTarget.Latest, true));
this.fileName = fileName;
this.nextTcbId = 1;
this.tcbStatements = [];
}
addTypeCheckBlock(ref, meta, domSchemaChecker, oobRecorder, genericContextBehavior) {
const fnId = import_typescript83.default.factory.createIdentifier(`_tcb${this.nextTcbId++}`);
const fn2 = generateTypeCheckBlock(this, ref, fnId, meta, domSchemaChecker, oobRecorder, genericContextBehavior);
this.tcbStatements.push(fn2);
}
render(removeComments) {
ensureTypeCheckFilePreparationImports(this);
const importChanges = this.importManager.finalize();
if (importChanges.updatedImports.size > 0) {
throw new Error("AssertionError: Expected no imports to be updated for a new type check file.");
}
const printer = import_typescript83.default.createPrinter({ removeComments });
let source = "";
const newImports = importChanges.newImports.get(this.contextFile.fileName);
if (newImports !== void 0) {
source += newImports.map((i) => printer.printNode(import_typescript83.default.EmitHint.Unspecified, i, this.contextFile)).join("\n");
}
source += "\n";
for (const stmt of this.pipeInstStatements) {
source += printer.printNode(import_typescript83.default.EmitHint.Unspecified, stmt, this.contextFile) + "\n";
}
for (const stmt of this.typeCtorStatements) {
source += printer.printNode(import_typescript83.default.EmitHint.Unspecified, stmt, this.contextFile) + "\n";
}
source += "\n";
for (const stmt of this.tcbStatements) {
source += printer.printNode(import_typescript83.default.EmitHint.Unspecified, stmt, this.contextFile) + "\n";
}
source += "\nexport const IS_A_MODULE = true;\n";
return source;
}
getPreludeStatements() {
return [];
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/context.mjs
var InliningMode;
(function(InliningMode2) {
InliningMode2[InliningMode2["InlineOps"] = 0] = "InlineOps";
InliningMode2[InliningMode2["Error"] = 1] = "Error";
})(InliningMode || (InliningMode = {}));
var TypeCheckContextImpl = class {
constructor(config, compilerHost, refEmitter, reflector, host, inlining, perf) {
this.config = config;
this.compilerHost = compilerHost;
this.refEmitter = refEmitter;
this.reflector = reflector;
this.host = host;
this.inlining = inlining;
this.perf = perf;
this.fileMap = /* @__PURE__ */ new Map();
this.opMap = /* @__PURE__ */ new Map();
this.typeCtorPending = /* @__PURE__ */ new Set();
if (inlining === InliningMode.Error && config.useInlineTypeConstructors) {
throw new Error(`AssertionError: invalid inlining configuration.`);
}
}
addTemplate(ref, binder, template2, pipes, schemas, sourceMapping, file, parseErrors, isStandalone, preserveWhitespaces) {
if (!this.host.shouldCheckComponent(ref.node)) {
return;
}
const fileData = this.dataForFile(ref.node.getSourceFile());
const shimData = this.pendingShimForComponent(ref.node);
const templateId = fileData.sourceManager.getTemplateId(ref.node);
const templateDiagnostics = [];
if (parseErrors !== null) {
templateDiagnostics.push(...getTemplateDiagnostics(parseErrors, templateId, sourceMapping));
}
const boundTarget = binder.bind({ template: template2 });
if (this.inlining === InliningMode.InlineOps) {
for (const dir of boundTarget.getUsedDirectives()) {
const dirRef = dir.ref;
const dirNode = dirRef.node;
if (!dir.isGeneric || !requiresInlineTypeCtor(dirNode, this.reflector, shimData.file)) {
continue;
}
this.addInlineTypeCtor(fileData, dirNode.getSourceFile(), dirRef, {
fnName: "ngTypeCtor",
body: !dirNode.getSourceFile().isDeclarationFile,
fields: {
inputs: dir.inputs,
queries: dir.queries
},
coercedInputFields: dir.coercedInputFields
});
}
}
shimData.templates.set(templateId, {
template: template2,
boundTarget,
templateDiagnostics
});
const usedPipes = [];
for (const name of boundTarget.getUsedPipes()) {
if (!pipes.has(name)) {
continue;
}
usedPipes.push(pipes.get(name).ref);
}
const inliningRequirement = requiresInlineTypeCheckBlock(ref, shimData.file, usedPipes, this.reflector);
if (this.inlining === InliningMode.Error && inliningRequirement === TcbInliningRequirement.MustInline) {
shimData.oobRecorder.requiresInlineTcb(templateId, ref.node);
this.perf.eventCount(PerfEvent.SkipGenerateTcbNoInline);
return;
}
const meta = {
id: fileData.sourceManager.captureSource(ref.node, sourceMapping, file),
boundTarget,
pipes,
schemas,
isStandalone,
preserveWhitespaces
};
this.perf.eventCount(PerfEvent.GenerateTcb);
if (inliningRequirement !== TcbInliningRequirement.None && this.inlining === InliningMode.InlineOps) {
this.addInlineTypeCheckBlock(fileData, shimData, ref, meta);
} else if (inliningRequirement === TcbInliningRequirement.ShouldInlineForGenericBounds && this.inlining === InliningMode.Error) {
shimData.file.addTypeCheckBlock(ref, meta, shimData.domSchemaChecker, shimData.oobRecorder, TcbGenericContextBehavior.FallbackToAny);
} else {
shimData.file.addTypeCheckBlock(ref, meta, shimData.domSchemaChecker, shimData.oobRecorder, TcbGenericContextBehavior.UseEmitter);
}
}
addInlineTypeCtor(fileData, sf, ref, ctorMeta) {
if (this.typeCtorPending.has(ref.node)) {
return;
}
this.typeCtorPending.add(ref.node);
if (!this.opMap.has(sf)) {
this.opMap.set(sf, []);
}
const ops = this.opMap.get(sf);
ops.push(new TypeCtorOp(ref, this.reflector, ctorMeta));
fileData.hasInlines = true;
}
transform(sf) {
if (!this.opMap.has(sf)) {
return null;
}
const printer = import_typescript84.default.createPrinter({ omitTrailingSemicolon: true });
const importManager = new ImportManager({
forceGenerateNamespacesForNewImports: true,
shouldUseSingleQuotes: () => true
});
const updates = this.opMap.get(sf).map((op) => {
return {
pos: op.splitPoint,
text: op.execute(importManager, sf, this.refEmitter, printer)
};
});
const { newImports, updatedImports } = importManager.finalize();
if (newImports.has(sf.fileName)) {
newImports.get(sf.fileName).forEach((newImport) => {
updates.push({
pos: 0,
text: printer.printNode(import_typescript84.default.EmitHint.Unspecified, newImport, sf)
});
});
}
for (const [oldBindings, newBindings] of updatedImports.entries()) {
if (oldBindings.getSourceFile() !== sf) {
throw new Error("Unexpected updates to unrelated source files.");
}
updates.push({
pos: oldBindings.getStart(),
deletePos: oldBindings.getEnd(),
text: printer.printNode(import_typescript84.default.EmitHint.Unspecified, newBindings, sf)
});
}
const result = new MagicString(sf.text, { filename: sf.fileName });
for (const update of updates) {
if (update.deletePos !== void 0) {
result.remove(update.pos, update.deletePos);
}
result.appendLeft(update.pos, update.text);
}
return result.toString();
}
finalize() {
const updates = /* @__PURE__ */ new Map();
for (const originalSf of this.opMap.keys()) {
const newText = this.transform(originalSf);
if (newText !== null) {
updates.set(absoluteFromSourceFile(originalSf), {
newText,
originalFile: originalSf
});
}
}
for (const [sfPath, pendingFileData] of this.fileMap) {
for (const pendingShimData of pendingFileData.shimData.values()) {
this.host.recordShimData(sfPath, {
genesisDiagnostics: [
...pendingShimData.domSchemaChecker.diagnostics,
...pendingShimData.oobRecorder.diagnostics
],
hasInlines: pendingFileData.hasInlines,
path: pendingShimData.file.fileName,
templates: pendingShimData.templates
});
const sfText = pendingShimData.file.render(false);
updates.set(pendingShimData.file.fileName, {
newText: sfText,
originalFile: null
});
}
}
return updates;
}
addInlineTypeCheckBlock(fileData, shimData, ref, tcbMeta) {
const sf = ref.node.getSourceFile();
if (!this.opMap.has(sf)) {
this.opMap.set(sf, []);
}
const ops = this.opMap.get(sf);
ops.push(new InlineTcbOp(ref, tcbMeta, this.config, this.reflector, shimData.domSchemaChecker, shimData.oobRecorder));
fileData.hasInlines = true;
}
pendingShimForComponent(node) {
const fileData = this.dataForFile(node.getSourceFile());
const shimPath = TypeCheckShimGenerator.shimFor(absoluteFromSourceFile(node.getSourceFile()));
if (!fileData.shimData.has(shimPath)) {
fileData.shimData.set(shimPath, {
domSchemaChecker: new RegistryDomSchemaChecker(fileData.sourceManager),
oobRecorder: new OutOfBandDiagnosticRecorderImpl(fileData.sourceManager),
file: new TypeCheckFile(shimPath, this.config, this.refEmitter, this.reflector, this.compilerHost),
templates: /* @__PURE__ */ new Map()
});
}
return fileData.shimData.get(shimPath);
}
dataForFile(sf) {
const sfPath = absoluteFromSourceFile(sf);
if (!this.fileMap.has(sfPath)) {
const data = {
hasInlines: false,
sourceManager: this.host.getSourceManager(sfPath),
shimData: /* @__PURE__ */ new Map()
};
this.fileMap.set(sfPath, data);
}
return this.fileMap.get(sfPath);
}
};
function getTemplateDiagnostics(parseErrors, templateId, sourceMapping) {
return parseErrors.map((error) => {
const span = error.span;
if (span.start.offset === span.end.offset) {
span.end.offset++;
}
return makeTemplateDiagnostic(templateId, sourceMapping, span, import_typescript84.default.DiagnosticCategory.Error, ngErrorCode(ErrorCode.TEMPLATE_PARSE_ERROR), error.msg);
});
}
var InlineTcbOp = class {
constructor(ref, meta, config, reflector, domSchemaChecker, oobRecorder) {
this.ref = ref;
this.meta = meta;
this.config = config;
this.reflector = reflector;
this.domSchemaChecker = domSchemaChecker;
this.oobRecorder = oobRecorder;
}
get splitPoint() {
return this.ref.node.end + 1;
}
execute(im, sf, refEmitter, printer) {
const env = new Environment(this.config, im, refEmitter, this.reflector, sf);
const fnName = import_typescript84.default.factory.createIdentifier(`_tcb_${this.ref.node.pos}`);
const fn2 = generateTypeCheckBlock(env, this.ref, fnName, this.meta, this.domSchemaChecker, this.oobRecorder, TcbGenericContextBehavior.CopyClassNodes);
return printer.printNode(import_typescript84.default.EmitHint.Unspecified, fn2, sf);
}
};
var TypeCtorOp = class {
constructor(ref, reflector, meta) {
this.ref = ref;
this.reflector = reflector;
this.meta = meta;
}
get splitPoint() {
return this.ref.node.end - 1;
}
execute(im, sf, refEmitter, printer) {
const emitEnv = new ReferenceEmitEnvironment(im, refEmitter, this.reflector, sf);
const tcb = generateInlineTypeCtor(emitEnv, this.ref.node, this.meta);
return printer.printNode(import_typescript84.default.EmitHint.Unspecified, tcb, sf);
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/line_mappings.mjs
var LF_CHAR = 10;
var CR_CHAR = 13;
var LINE_SEP_CHAR = 8232;
var PARAGRAPH_CHAR = 8233;
function getLineAndCharacterFromPosition(lineStartsMap, position) {
const lineIndex = findClosestLineStartPosition(lineStartsMap, position);
return { character: position - lineStartsMap[lineIndex], line: lineIndex };
}
function computeLineStartsMap(text2) {
const result = [0];
let pos = 0;
while (pos < text2.length) {
const char = text2.charCodeAt(pos++);
if (char === CR_CHAR) {
if (text2.charCodeAt(pos) === LF_CHAR) {
pos++;
}
result.push(pos);
} else if (char === LF_CHAR || char === LINE_SEP_CHAR || char === PARAGRAPH_CHAR) {
result.push(pos);
}
}
result.push(pos);
return result;
}
function findClosestLineStartPosition(linesMap, position, low = 0, high = linesMap.length - 1) {
while (low <= high) {
const pivotIdx = Math.floor((low + high) / 2);
const pivotEl = linesMap[pivotIdx];
if (pivotEl === position) {
return pivotIdx;
} else if (position > pivotEl) {
low = pivotIdx + 1;
} else {
high = pivotIdx - 1;
}
}
return low - 1;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/source.mjs
var TemplateSource = class {
constructor(mapping, file) {
this.mapping = mapping;
this.file = file;
this.lineStarts = null;
}
toParseSourceSpan(start, end) {
const startLoc = this.toParseLocation(start);
const endLoc = this.toParseLocation(end);
return new ParseSourceSpan(startLoc, endLoc);
}
toParseLocation(position) {
const lineStarts = this.acquireLineStarts();
const { line, character } = getLineAndCharacterFromPosition(lineStarts, position);
return new ParseLocation(this.file, position, line, character);
}
acquireLineStarts() {
if (this.lineStarts === null) {
this.lineStarts = computeLineStartsMap(this.file.content);
}
return this.lineStarts;
}
};
var TemplateSourceManager = class {
constructor() {
this.templateSources = /* @__PURE__ */ new Map();
}
getTemplateId(node) {
return getTemplateId(node);
}
captureSource(node, mapping, file) {
const id = getTemplateId(node);
this.templateSources.set(id, new TemplateSource(mapping, file));
return id;
}
getSourceMapping(id) {
if (!this.templateSources.has(id)) {
throw new Error(`Unexpected unknown template ID: ${id}`);
}
return this.templateSources.get(id).mapping;
}
toParseSourceSpan(id, span) {
if (!this.templateSources.has(id)) {
return null;
}
const templateSource = this.templateSources.get(id);
return templateSource.toParseSourceSpan(span.start, span.end);
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/template_symbol_builder.mjs
var import_typescript85 = __toESM(require("typescript"), 1);
var SymbolBuilder = class {
constructor(tcbPath, tcbIsShim, typeCheckBlock, templateData, componentScopeReader, getTypeChecker) {
this.tcbPath = tcbPath;
this.tcbIsShim = tcbIsShim;
this.typeCheckBlock = typeCheckBlock;
this.templateData = templateData;
this.componentScopeReader = componentScopeReader;
this.getTypeChecker = getTypeChecker;
this.symbolCache = /* @__PURE__ */ new Map();
}
getSymbol(node) {
if (this.symbolCache.has(node)) {
return this.symbolCache.get(node);
}
let symbol = null;
if (node instanceof BoundAttribute || node instanceof TextAttribute) {
symbol = this.getSymbolOfInputBinding(node);
} else if (node instanceof BoundEvent) {
symbol = this.getSymbolOfBoundEvent(node);
} else if (node instanceof Element) {
symbol = this.getSymbolOfElement(node);
} else if (node instanceof Template) {
symbol = this.getSymbolOfAstTemplate(node);
} else if (node instanceof Variable) {
symbol = this.getSymbolOfVariable(node);
} else if (node instanceof LetDeclaration) {
symbol = this.getSymbolOfLetDeclaration(node);
} else if (node instanceof Reference) {
symbol = this.getSymbolOfReference(node);
} else if (node instanceof BindingPipe) {
symbol = this.getSymbolOfPipe(node);
} else if (node instanceof AST) {
symbol = this.getSymbolOfTemplateExpression(node);
} else {
}
this.symbolCache.set(node, symbol);
return symbol;
}
getSymbolOfAstTemplate(template2) {
const directives = this.getDirectivesOfNode(template2);
return { kind: SymbolKind.Template, directives, templateNode: template2 };
}
getSymbolOfElement(element2) {
var _a2;
const elementSourceSpan = (_a2 = element2.startSourceSpan) != null ? _a2 : element2.sourceSpan;
const node = findFirstMatchingNode(this.typeCheckBlock, {
withSpan: elementSourceSpan,
filter: import_typescript85.default.isVariableDeclaration
});
if (node === null) {
return null;
}
const symbolFromDeclaration = this.getSymbolOfTsNode(node);
if (symbolFromDeclaration === null || symbolFromDeclaration.tsSymbol === null) {
return null;
}
const directives = this.getDirectivesOfNode(element2);
return __spreadProps(__spreadValues({}, symbolFromDeclaration), {
kind: SymbolKind.Element,
directives,
templateNode: element2
});
}
getDirectivesOfNode(element2) {
var _a2;
const elementSourceSpan = (_a2 = element2.startSourceSpan) != null ? _a2 : element2.sourceSpan;
const tcbSourceFile = this.typeCheckBlock.getSourceFile();
const isDirectiveDeclaration = (node) => (import_typescript85.default.isTypeNode(node) || import_typescript85.default.isIdentifier(node)) && import_typescript85.default.isVariableDeclaration(node.parent) && hasExpressionIdentifier(tcbSourceFile, node, ExpressionIdentifier.DIRECTIVE);
const nodes = findAllMatchingNodes(this.typeCheckBlock, {
withSpan: elementSourceSpan,
filter: isDirectiveDeclaration
});
const symbols = [];
for (const node of nodes) {
const symbol = this.getSymbolOfTsNode(node.parent);
if (symbol === null || !isSymbolWithValueDeclaration(symbol.tsSymbol) || !import_typescript85.default.isClassDeclaration(symbol.tsSymbol.valueDeclaration)) {
continue;
}
const meta = this.getDirectiveMeta(element2, symbol.tsSymbol.valueDeclaration);
if (meta !== null && meta.selector !== null) {
const ref = new Reference2(symbol.tsSymbol.valueDeclaration);
if (meta.hostDirectives !== null) {
this.addHostDirectiveSymbols(element2, meta.hostDirectives, symbols);
}
const directiveSymbol = __spreadProps(__spreadValues({}, symbol), {
ref,
tsSymbol: symbol.tsSymbol,
selector: meta.selector,
isComponent: meta.isComponent,
ngModule: this.getDirectiveModule(symbol.tsSymbol.valueDeclaration),
kind: SymbolKind.Directive,
isStructural: meta.isStructural,
isInScope: true,
isHostDirective: false
});
symbols.push(directiveSymbol);
}
}
return symbols;
}
addHostDirectiveSymbols(host, hostDirectives, symbols) {
for (const current of hostDirectives) {
if (!isHostDirectiveMetaForGlobalMode(current)) {
throw new Error("Impossible state: typecheck code path in local compilation mode.");
}
if (!import_typescript85.default.isClassDeclaration(current.directive.node)) {
continue;
}
const symbol = this.getSymbolOfTsNode(current.directive.node);
const meta = this.getDirectiveMeta(host, current.directive.node);
if (meta !== null && symbol !== null && isSymbolWithValueDeclaration(symbol.tsSymbol)) {
if (meta.hostDirectives !== null) {
this.addHostDirectiveSymbols(host, meta.hostDirectives, symbols);
}
const directiveSymbol = __spreadProps(__spreadValues({}, symbol), {
isHostDirective: true,
ref: current.directive,
tsSymbol: symbol.tsSymbol,
exposedInputs: current.inputs,
exposedOutputs: current.outputs,
selector: meta.selector,
isComponent: meta.isComponent,
ngModule: this.getDirectiveModule(current.directive.node),
kind: SymbolKind.Directive,
isStructural: meta.isStructural,
isInScope: true
});
symbols.push(directiveSymbol);
}
}
}
getDirectiveMeta(host, directiveDeclaration) {
var _a2;
let directives = this.templateData.boundTarget.getDirectivesOfNode(host);
const firstChild = host.children[0];
if (firstChild instanceof Element) {
const isMicrosyntaxTemplate = host instanceof Template && sourceSpanEqual(firstChild.sourceSpan, host.sourceSpan);
if (isMicrosyntaxTemplate) {
const firstChildDirectives = this.templateData.boundTarget.getDirectivesOfNode(firstChild);
if (firstChildDirectives !== null && directives !== null) {
directives = directives.concat(firstChildDirectives);
} else {
directives = directives != null ? directives : firstChildDirectives;
}
}
}
if (directives === null) {
return null;
}
return (_a2 = directives.find((m) => m.ref.node === directiveDeclaration)) != null ? _a2 : null;
}
getDirectiveModule(declaration) {
const scope = this.componentScopeReader.getScopeForComponent(declaration);
if (scope === null || scope.kind !== ComponentScopeKind.NgModule) {
return null;
}
return scope.ngModule;
}
getSymbolOfBoundEvent(eventBinding) {
const consumer = this.templateData.boundTarget.getConsumerOfBinding(eventBinding);
if (consumer === null) {
return null;
}
let expectedAccess;
if (consumer instanceof Template || consumer instanceof Element) {
expectedAccess = "addEventListener";
} else {
const bindingPropertyNames = consumer.outputs.getByBindingPropertyName(eventBinding.name);
if (bindingPropertyNames === null || bindingPropertyNames.length === 0) {
return null;
}
expectedAccess = bindingPropertyNames[0].classPropertyName;
}
function filter(n2) {
if (!isAccessExpression2(n2)) {
return false;
}
if (import_typescript85.default.isPropertyAccessExpression(n2)) {
return n2.name.getText() === expectedAccess;
} else {
return import_typescript85.default.isStringLiteral(n2.argumentExpression) && n2.argumentExpression.text === expectedAccess;
}
}
const outputFieldAccesses = findAllMatchingNodes(this.typeCheckBlock, {
withSpan: eventBinding.keySpan,
filter
});
const bindings = [];
for (const outputFieldAccess of outputFieldAccesses) {
if (consumer instanceof Template || consumer instanceof Element) {
if (!import_typescript85.default.isPropertyAccessExpression(outputFieldAccess)) {
continue;
}
const addEventListener = outputFieldAccess.name;
const tsSymbol = this.getTypeChecker().getSymbolAtLocation(addEventListener);
const tsType = this.getTypeChecker().getTypeAtLocation(addEventListener);
const positionInFile = this.getTcbPositionForNode(addEventListener);
const target = this.getSymbol(consumer);
if (target === null || tsSymbol === void 0) {
continue;
}
bindings.push({
kind: SymbolKind.Binding,
tsSymbol,
tsType,
target,
tcbLocation: {
tcbPath: this.tcbPath,
isShimFile: this.tcbIsShim,
positionInFile
}
});
} else {
if (!import_typescript85.default.isElementAccessExpression(outputFieldAccess)) {
continue;
}
const tsSymbol = this.getTypeChecker().getSymbolAtLocation(outputFieldAccess.argumentExpression);
if (tsSymbol === void 0) {
continue;
}
const target = this.getDirectiveSymbolForAccessExpression(outputFieldAccess, consumer);
if (target === null) {
continue;
}
const positionInFile = this.getTcbPositionForNode(outputFieldAccess);
const tsType = this.getTypeChecker().getTypeAtLocation(outputFieldAccess);
bindings.push({
kind: SymbolKind.Binding,
tsSymbol,
tsType,
target,
tcbLocation: {
tcbPath: this.tcbPath,
isShimFile: this.tcbIsShim,
positionInFile
}
});
}
}
if (bindings.length === 0) {
return null;
}
return { kind: SymbolKind.Output, bindings };
}
getSymbolOfInputBinding(binding) {
const consumer = this.templateData.boundTarget.getConsumerOfBinding(binding);
if (consumer === null) {
return null;
}
if (consumer instanceof Element || consumer instanceof Template) {
const host = this.getSymbol(consumer);
return host !== null ? { kind: SymbolKind.DomBinding, host } : null;
}
const nodes = findAllMatchingNodes(this.typeCheckBlock, {
withSpan: binding.sourceSpan,
filter: isAssignment
});
const bindings = [];
for (const node of nodes) {
if (!isAccessExpression2(node.left)) {
continue;
}
const signalInputAssignment = unwrapSignalInputWriteTAccessor(node.left);
let fieldAccessExpr;
let symbolInfo = null;
if (signalInputAssignment !== null) {
if (import_typescript85.default.isIdentifier(signalInputAssignment.fieldExpr)) {
continue;
}
const fieldSymbol = this.getSymbolOfTsNode(signalInputAssignment.fieldExpr);
const typeSymbol = this.getSymbolOfTsNode(signalInputAssignment.typeExpr);
fieldAccessExpr = signalInputAssignment.fieldExpr;
symbolInfo = fieldSymbol === null || typeSymbol === null ? null : {
tcbLocation: fieldSymbol.tcbLocation,
tsSymbol: fieldSymbol.tsSymbol,
tsType: typeSymbol.tsType
};
} else {
fieldAccessExpr = node.left;
symbolInfo = this.getSymbolOfTsNode(node.left);
}
if (symbolInfo === null || symbolInfo.tsSymbol === null) {
continue;
}
const target = this.getDirectiveSymbolForAccessExpression(fieldAccessExpr, consumer);
if (target === null) {
continue;
}
bindings.push(__spreadProps(__spreadValues({}, symbolInfo), {
tsSymbol: symbolInfo.tsSymbol,
kind: SymbolKind.Binding,
target
}));
}
if (bindings.length === 0) {
return null;
}
return { kind: SymbolKind.Input, bindings };
}
getDirectiveSymbolForAccessExpression(fieldAccessExpr, { isComponent, selector, isStructural }) {
var _a2;
const tsSymbol = this.getTypeChecker().getSymbolAtLocation(fieldAccessExpr.expression);
if ((tsSymbol == null ? void 0 : tsSymbol.declarations) === void 0 || tsSymbol.declarations.length === 0 || selector === null) {
return null;
}
const [declaration] = tsSymbol.declarations;
if (!import_typescript85.default.isVariableDeclaration(declaration) || !hasExpressionIdentifier(
declaration.getSourceFile(),
(_a2 = declaration.type) != null ? _a2 : declaration.name,
ExpressionIdentifier.DIRECTIVE
)) {
return null;
}
const symbol = this.getSymbolOfTsNode(declaration);
if (symbol === null || !isSymbolWithValueDeclaration(symbol.tsSymbol) || !import_typescript85.default.isClassDeclaration(symbol.tsSymbol.valueDeclaration)) {
return null;
}
const ref = new Reference2(symbol.tsSymbol.valueDeclaration);
const ngModule = this.getDirectiveModule(symbol.tsSymbol.valueDeclaration);
return {
ref,
kind: SymbolKind.Directive,
tsSymbol: symbol.tsSymbol,
tsType: symbol.tsType,
tcbLocation: symbol.tcbLocation,
isComponent,
isStructural,
selector,
ngModule,
isHostDirective: false,
isInScope: true
};
}
getSymbolOfVariable(variable2) {
const node = findFirstMatchingNode(this.typeCheckBlock, {
withSpan: variable2.sourceSpan,
filter: import_typescript85.default.isVariableDeclaration
});
if (node === null) {
return null;
}
let nodeValueSymbol = null;
if (import_typescript85.default.isForOfStatement(node.parent.parent)) {
nodeValueSymbol = this.getSymbolOfTsNode(node);
} else if (node.initializer !== void 0) {
nodeValueSymbol = this.getSymbolOfTsNode(node.initializer);
}
if (nodeValueSymbol === null) {
return null;
}
return {
tsType: nodeValueSymbol.tsType,
tsSymbol: nodeValueSymbol.tsSymbol,
initializerLocation: nodeValueSymbol.tcbLocation,
kind: SymbolKind.Variable,
declaration: variable2,
localVarLocation: {
tcbPath: this.tcbPath,
isShimFile: this.tcbIsShim,
positionInFile: this.getTcbPositionForNode(node.name)
}
};
}
getSymbolOfReference(ref) {
const target = this.templateData.boundTarget.getReferenceTarget(ref);
let node = findFirstMatchingNode(this.typeCheckBlock, {
withSpan: ref.sourceSpan,
filter: import_typescript85.default.isVariableDeclaration
});
if (node === null || target === null || node.initializer === void 0) {
return null;
}
const originalDeclaration = import_typescript85.default.isParenthesizedExpression(node.initializer) && import_typescript85.default.isAsExpression(node.initializer.expression) ? this.getTypeChecker().getSymbolAtLocation(node.name) : this.getTypeChecker().getSymbolAtLocation(node.initializer);
if (originalDeclaration === void 0 || originalDeclaration.valueDeclaration === void 0) {
return null;
}
const symbol = this.getSymbolOfTsNode(originalDeclaration.valueDeclaration);
if (symbol === null || symbol.tsSymbol === null) {
return null;
}
const referenceVarTcbLocation = {
tcbPath: this.tcbPath,
isShimFile: this.tcbIsShim,
positionInFile: this.getTcbPositionForNode(node)
};
if (target instanceof Template || target instanceof Element) {
return {
kind: SymbolKind.Reference,
tsSymbol: symbol.tsSymbol,
tsType: symbol.tsType,
target,
declaration: ref,
targetLocation: symbol.tcbLocation,
referenceVarLocation: referenceVarTcbLocation
};
} else {
if (!import_typescript85.default.isClassDeclaration(target.directive.ref.node)) {
return null;
}
return {
kind: SymbolKind.Reference,
tsSymbol: symbol.tsSymbol,
tsType: symbol.tsType,
declaration: ref,
target: target.directive.ref.node,
targetLocation: symbol.tcbLocation,
referenceVarLocation: referenceVarTcbLocation
};
}
}
getSymbolOfLetDeclaration(decl) {
const node = findFirstMatchingNode(this.typeCheckBlock, {
withSpan: decl.sourceSpan,
filter: import_typescript85.default.isVariableDeclaration
});
if (node === null) {
return null;
}
const nodeValueSymbol = this.getSymbolOfTsNode(node.initializer);
if (nodeValueSymbol === null) {
return null;
}
return {
tsType: nodeValueSymbol.tsType,
tsSymbol: nodeValueSymbol.tsSymbol,
initializerLocation: nodeValueSymbol.tcbLocation,
kind: SymbolKind.LetDeclaration,
declaration: decl,
localVarLocation: {
tcbPath: this.tcbPath,
isShimFile: this.tcbIsShim,
positionInFile: this.getTcbPositionForNode(node.name)
}
};
}
getSymbolOfPipe(expression) {
const methodAccess = findFirstMatchingNode(this.typeCheckBlock, {
withSpan: expression.nameSpan,
filter: import_typescript85.default.isPropertyAccessExpression
});
if (methodAccess === null) {
return null;
}
const pipeVariableNode = methodAccess.expression;
const pipeDeclaration = this.getTypeChecker().getSymbolAtLocation(pipeVariableNode);
if (pipeDeclaration === void 0 || pipeDeclaration.valueDeclaration === void 0) {
return null;
}
const pipeInstance = this.getSymbolOfTsNode(pipeDeclaration.valueDeclaration);
if (pipeInstance === null || !isSymbolWithValueDeclaration(pipeInstance.tsSymbol)) {
return null;
}
const symbolInfo = this.getSymbolOfTsNode(methodAccess);
if (symbolInfo === null) {
return null;
}
return __spreadProps(__spreadValues({
kind: SymbolKind.Pipe
}, symbolInfo), {
classSymbol: __spreadProps(__spreadValues({}, pipeInstance), {
tsSymbol: pipeInstance.tsSymbol
})
});
}
getSymbolOfTemplateExpression(expression) {
if (expression instanceof ASTWithSource) {
expression = expression.ast;
}
const expressionTarget = this.templateData.boundTarget.getExpressionTarget(expression);
if (expressionTarget !== null) {
return this.getSymbol(expressionTarget);
}
let withSpan = expression.sourceSpan;
if (expression instanceof PropertyWrite) {
withSpan = expression.nameSpan;
}
let node = null;
if (expression instanceof PropertyRead) {
node = findFirstMatchingNode(this.typeCheckBlock, {
withSpan,
filter: import_typescript85.default.isPropertyAccessExpression
});
}
if (node === null) {
node = findFirstMatchingNode(this.typeCheckBlock, { withSpan, filter: anyNodeFilter });
}
if (node === null) {
return null;
}
while (import_typescript85.default.isParenthesizedExpression(node)) {
node = node.expression;
}
if (expression instanceof SafePropertyRead && import_typescript85.default.isConditionalExpression(node)) {
const whenTrueSymbol = this.getSymbolOfTsNode(node.whenTrue);
if (whenTrueSymbol === null) {
return null;
}
return __spreadProps(__spreadValues({}, whenTrueSymbol), {
kind: SymbolKind.Expression,
tsType: this.getTypeChecker().getTypeAtLocation(node)
});
} else {
const symbolInfo = this.getSymbolOfTsNode(node);
return symbolInfo === null ? null : __spreadProps(__spreadValues({}, symbolInfo), { kind: SymbolKind.Expression });
}
}
getSymbolOfTsNode(node) {
var _a2;
while (import_typescript85.default.isParenthesizedExpression(node)) {
node = node.expression;
}
let tsSymbol;
if (import_typescript85.default.isPropertyAccessExpression(node)) {
tsSymbol = this.getTypeChecker().getSymbolAtLocation(node.name);
} else {
tsSymbol = this.getTypeChecker().getSymbolAtLocation(node);
}
const positionInFile = this.getTcbPositionForNode(node);
const type = this.getTypeChecker().getTypeAtLocation(node);
return {
tsSymbol: (_a2 = tsSymbol != null ? tsSymbol : type.symbol) != null ? _a2 : null,
tsType: type,
tcbLocation: {
tcbPath: this.tcbPath,
isShimFile: this.tcbIsShim,
positionInFile
}
};
}
getTcbPositionForNode(node) {
if (import_typescript85.default.isTypeReferenceNode(node)) {
return this.getTcbPositionForNode(node.typeName);
} else if (import_typescript85.default.isQualifiedName(node)) {
return node.right.getStart();
} else if (import_typescript85.default.isPropertyAccessExpression(node)) {
return node.name.getStart();
} else if (import_typescript85.default.isElementAccessExpression(node)) {
return node.argumentExpression.getStart();
} else {
return node.getStart();
}
}
};
function anyNodeFilter(n2) {
return true;
}
function sourceSpanEqual(a, b) {
return a.start.offset === b.start.offset && a.end.offset === b.end.offset;
}
function unwrapSignalInputWriteTAccessor(expr) {
if (!import_typescript85.default.isElementAccessExpression(expr) || !import_typescript85.default.isPropertyAccessExpression(expr.argumentExpression)) {
return null;
}
if (!import_typescript85.default.isIdentifier(expr.argumentExpression.name) || expr.argumentExpression.name.text !== Identifiers.InputSignalBrandWriteType.name) {
return null;
}
if (!import_typescript85.default.isPropertyAccessExpression(expr.expression) && !import_typescript85.default.isElementAccessExpression(expr.expression) && !import_typescript85.default.isIdentifier(expr.expression)) {
throw new Error("Unexpected expression for signal input write type.");
}
return {
fieldExpr: expr.expression,
typeExpr: expr
};
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/checker.mjs
var REGISTRY2 = new DomElementSchemaRegistry();
var TemplateTypeCheckerImpl = class {
constructor(originalProgram, programDriver, typeCheckAdapter, config, refEmitter, reflector, compilerHost, priorBuild, metaReader, localMetaReader, ngModuleIndex, componentScopeReader, typeCheckScopeRegistry, perf) {
this.originalProgram = originalProgram;
this.programDriver = programDriver;
this.typeCheckAdapter = typeCheckAdapter;
this.config = config;
this.refEmitter = refEmitter;
this.reflector = reflector;
this.compilerHost = compilerHost;
this.priorBuild = priorBuild;
this.metaReader = metaReader;
this.localMetaReader = localMetaReader;
this.ngModuleIndex = ngModuleIndex;
this.componentScopeReader = componentScopeReader;
this.typeCheckScopeRegistry = typeCheckScopeRegistry;
this.perf = perf;
this.state = /* @__PURE__ */ new Map();
this.completionCache = /* @__PURE__ */ new Map();
this.symbolBuilderCache = /* @__PURE__ */ new Map();
this.scopeCache = /* @__PURE__ */ new Map();
this.elementTagCache = /* @__PURE__ */ new Map();
this.isComplete = false;
}
getTemplate(component) {
const { data } = this.getLatestComponentState(component);
if (data === null) {
return null;
}
return data.template;
}
getUsedDirectives(component) {
var _a2;
return ((_a2 = this.getLatestComponentState(component).data) == null ? void 0 : _a2.boundTarget.getUsedDirectives()) || null;
}
getUsedPipes(component) {
var _a2;
return ((_a2 = this.getLatestComponentState(component).data) == null ? void 0 : _a2.boundTarget.getUsedPipes()) || null;
}
getLatestComponentState(component) {
this.ensureShimForComponent(component);
const sf = component.getSourceFile();
const sfPath = absoluteFromSourceFile(sf);
const shimPath = TypeCheckShimGenerator.shimFor(sfPath);
const fileRecord = this.getFileData(sfPath);
if (!fileRecord.shimData.has(shimPath)) {
return { data: null, tcb: null, tcbPath: shimPath, tcbIsShim: true };
}
const templateId = fileRecord.sourceManager.getTemplateId(component);
const shimRecord = fileRecord.shimData.get(shimPath);
const id = fileRecord.sourceManager.getTemplateId(component);
const program = this.programDriver.getProgram();
const shimSf = getSourceFileOrNull(program, shimPath);
if (shimSf === null || !fileRecord.shimData.has(shimPath)) {
throw new Error(`Error: no shim file in program: ${shimPath}`);
}
let tcb = findTypeCheckBlock(shimSf, id, false);
let tcbPath = shimPath;
if (tcb === null) {
const inlineSf = getSourceFileOrError(program, sfPath);
tcb = findTypeCheckBlock(inlineSf, id, false);
if (tcb !== null) {
tcbPath = sfPath;
}
}
let data = null;
if (shimRecord.templates.has(templateId)) {
data = shimRecord.templates.get(templateId);
}
return { data, tcb, tcbPath, tcbIsShim: tcbPath === shimPath };
}
isTrackedTypeCheckFile(filePath) {
return this.getFileAndShimRecordsForPath(filePath) !== null;
}
getFileRecordForTcbLocation({ tcbPath, isShimFile }) {
if (!isShimFile) {
if (this.state.has(tcbPath)) {
return this.state.get(tcbPath);
} else {
return null;
}
}
const records = this.getFileAndShimRecordsForPath(tcbPath);
if (records !== null) {
return records.fileRecord;
} else {
return null;
}
}
getFileAndShimRecordsForPath(shimPath) {
for (const fileRecord of this.state.values()) {
if (fileRecord.shimData.has(shimPath)) {
return { fileRecord, shimRecord: fileRecord.shimData.get(shimPath) };
}
}
return null;
}
getTemplateMappingAtTcbLocation(tcbLocation) {
const fileRecord = this.getFileRecordForTcbLocation(tcbLocation);
if (fileRecord === null) {
return null;
}
const shimSf = this.programDriver.getProgram().getSourceFile(tcbLocation.tcbPath);
if (shimSf === void 0) {
return null;
}
return getTemplateMapping(
shimSf,
tcbLocation.positionInFile,
fileRecord.sourceManager,
false
);
}
generateAllTypeCheckBlocks() {
this.ensureAllShimsForAllFiles();
}
getDiagnosticsForFile(sf, optimizeFor) {
switch (optimizeFor) {
case OptimizeFor.WholeProgram:
this.ensureAllShimsForAllFiles();
break;
case OptimizeFor.SingleFile:
this.ensureAllShimsForOneFile(sf);
break;
}
return this.perf.inPhase(PerfPhase.TtcDiagnostics, () => {
const sfPath = absoluteFromSourceFile(sf);
const fileRecord = this.state.get(sfPath);
const typeCheckProgram = this.programDriver.getProgram();
const diagnostics = [];
if (fileRecord.hasInlines) {
const inlineSf = getSourceFileOrError(typeCheckProgram, sfPath);
diagnostics.push(...typeCheckProgram.getSemanticDiagnostics(inlineSf).map((diag) => convertDiagnostic(diag, fileRecord.sourceManager)));
}
for (const [shimPath, shimRecord] of fileRecord.shimData) {
const shimSf = getSourceFileOrError(typeCheckProgram, shimPath);
diagnostics.push(...typeCheckProgram.getSemanticDiagnostics(shimSf).map((diag) => convertDiagnostic(diag, fileRecord.sourceManager)));
diagnostics.push(...shimRecord.genesisDiagnostics);
for (const templateData of shimRecord.templates.values()) {
diagnostics.push(...templateData.templateDiagnostics);
}
}
return diagnostics.filter((diag) => diag !== null);
});
}
getDiagnosticsForComponent(component) {
this.ensureShimForComponent(component);
return this.perf.inPhase(PerfPhase.TtcDiagnostics, () => {
const sf = component.getSourceFile();
const sfPath = absoluteFromSourceFile(sf);
const shimPath = TypeCheckShimGenerator.shimFor(sfPath);
const fileRecord = this.getFileData(sfPath);
if (!fileRecord.shimData.has(shimPath)) {
return [];
}
const templateId = fileRecord.sourceManager.getTemplateId(component);
const shimRecord = fileRecord.shimData.get(shimPath);
const typeCheckProgram = this.programDriver.getProgram();
const diagnostics = [];
if (shimRecord.hasInlines) {
const inlineSf = getSourceFileOrError(typeCheckProgram, sfPath);
diagnostics.push(...typeCheckProgram.getSemanticDiagnostics(inlineSf).map((diag) => convertDiagnostic(diag, fileRecord.sourceManager)));
}
const shimSf = getSourceFileOrError(typeCheckProgram, shimPath);
diagnostics.push(...typeCheckProgram.getSemanticDiagnostics(shimSf).map((diag) => convertDiagnostic(diag, fileRecord.sourceManager)));
diagnostics.push(...shimRecord.genesisDiagnostics);
for (const templateData of shimRecord.templates.values()) {
diagnostics.push(...templateData.templateDiagnostics);
}
return diagnostics.filter((diag) => diag !== null && diag.templateId === templateId);
});
}
getTypeCheckBlock(component) {
return this.getLatestComponentState(component).tcb;
}
getGlobalCompletions(context, component, node) {
const engine = this.getOrCreateCompletionEngine(component);
if (engine === null) {
return null;
}
return this.perf.inPhase(PerfPhase.TtcAutocompletion, () => engine.getGlobalCompletions(context, node));
}
getExpressionCompletionLocation(ast, component) {
const engine = this.getOrCreateCompletionEngine(component);
if (engine === null) {
return null;
}
return this.perf.inPhase(PerfPhase.TtcAutocompletion, () => engine.getExpressionCompletionLocation(ast));
}
getLiteralCompletionLocation(node, component) {
const engine = this.getOrCreateCompletionEngine(component);
if (engine === null) {
return null;
}
return this.perf.inPhase(PerfPhase.TtcAutocompletion, () => engine.getLiteralCompletionLocation(node));
}
invalidateClass(clazz) {
this.completionCache.delete(clazz);
this.symbolBuilderCache.delete(clazz);
this.scopeCache.delete(clazz);
this.elementTagCache.delete(clazz);
const sf = clazz.getSourceFile();
const sfPath = absoluteFromSourceFile(sf);
const shimPath = TypeCheckShimGenerator.shimFor(sfPath);
const fileData = this.getFileData(sfPath);
const templateId = fileData.sourceManager.getTemplateId(clazz);
fileData.shimData.delete(shimPath);
fileData.isComplete = false;
this.isComplete = false;
}
getExpressionTarget(expression, clazz) {
var _a2;
return ((_a2 = this.getLatestComponentState(clazz).data) == null ? void 0 : _a2.boundTarget.getExpressionTarget(expression)) || null;
}
makeTemplateDiagnostic(clazz, sourceSpan, category, errorCode, message, relatedInformation) {
const sfPath = absoluteFromSourceFile(clazz.getSourceFile());
const fileRecord = this.state.get(sfPath);
const templateId = fileRecord.sourceManager.getTemplateId(clazz);
const mapping = fileRecord.sourceManager.getSourceMapping(templateId);
return __spreadProps(__spreadValues({}, makeTemplateDiagnostic(templateId, mapping, sourceSpan, category, ngErrorCode(errorCode), message, relatedInformation)), {
__ngCode: errorCode
});
}
getOrCreateCompletionEngine(component) {
if (this.completionCache.has(component)) {
return this.completionCache.get(component);
}
const { tcb, data, tcbPath, tcbIsShim } = this.getLatestComponentState(component);
if (tcb === null || data === null) {
return null;
}
const engine = new CompletionEngine(tcb, data, tcbPath, tcbIsShim);
this.completionCache.set(component, engine);
return engine;
}
maybeAdoptPriorResultsForFile(sf) {
const sfPath = absoluteFromSourceFile(sf);
if (this.state.has(sfPath)) {
const existingResults = this.state.get(sfPath);
if (existingResults.isComplete) {
return;
}
}
const previousResults = this.priorBuild.priorTypeCheckingResultsFor(sf);
if (previousResults === null || !previousResults.isComplete) {
return;
}
this.perf.eventCount(PerfEvent.ReuseTypeCheckFile);
this.state.set(sfPath, previousResults);
}
ensureAllShimsForAllFiles() {
if (this.isComplete) {
return;
}
this.perf.inPhase(PerfPhase.TcbGeneration, () => {
const host = new WholeProgramTypeCheckingHost(this);
const ctx = this.newContext(host);
for (const sf of this.originalProgram.getSourceFiles()) {
if (sf.isDeclarationFile || isShim(sf)) {
continue;
}
this.maybeAdoptPriorResultsForFile(sf);
const sfPath = absoluteFromSourceFile(sf);
const fileData = this.getFileData(sfPath);
if (fileData.isComplete) {
continue;
}
this.typeCheckAdapter.typeCheck(sf, ctx);
fileData.isComplete = true;
}
this.updateFromContext(ctx);
this.isComplete = true;
});
}
ensureAllShimsForOneFile(sf) {
this.perf.inPhase(PerfPhase.TcbGeneration, () => {
this.maybeAdoptPriorResultsForFile(sf);
const sfPath = absoluteFromSourceFile(sf);
const fileData = this.getFileData(sfPath);
if (fileData.isComplete) {
return;
}
const host = new SingleFileTypeCheckingHost(sfPath, fileData, this);
const ctx = this.newContext(host);
this.typeCheckAdapter.typeCheck(sf, ctx);
fileData.isComplete = true;
this.updateFromContext(ctx);
});
}
ensureShimForComponent(component) {
const sf = component.getSourceFile();
const sfPath = absoluteFromSourceFile(sf);
const shimPath = TypeCheckShimGenerator.shimFor(sfPath);
this.maybeAdoptPriorResultsForFile(sf);
const fileData = this.getFileData(sfPath);
if (fileData.shimData.has(shimPath)) {
return;
}
const host = new SingleShimTypeCheckingHost(sfPath, fileData, this, shimPath);
const ctx = this.newContext(host);
this.typeCheckAdapter.typeCheck(sf, ctx);
this.updateFromContext(ctx);
}
newContext(host) {
const inlining = this.programDriver.supportsInlineOperations ? InliningMode.InlineOps : InliningMode.Error;
return new TypeCheckContextImpl(this.config, this.compilerHost, this.refEmitter, this.reflector, host, inlining, this.perf);
}
clearAllShimDataUsingInlines() {
for (const fileData of this.state.values()) {
if (!fileData.hasInlines) {
continue;
}
for (const [shimFile, shimData] of fileData.shimData.entries()) {
if (shimData.hasInlines) {
fileData.shimData.delete(shimFile);
}
}
fileData.hasInlines = false;
fileData.isComplete = false;
this.isComplete = false;
}
}
updateFromContext(ctx) {
const updates = ctx.finalize();
return this.perf.inPhase(PerfPhase.TcbUpdateProgram, () => {
if (updates.size > 0) {
this.perf.eventCount(PerfEvent.UpdateTypeCheckProgram);
}
this.programDriver.updateFiles(updates, UpdateMode.Incremental);
this.priorBuild.recordSuccessfulTypeCheck(this.state);
this.perf.memory(PerfCheckpoint.TtcUpdateProgram);
});
}
getFileData(path4) {
if (!this.state.has(path4)) {
this.state.set(path4, {
hasInlines: false,
sourceManager: new TemplateSourceManager(),
isComplete: false,
shimData: /* @__PURE__ */ new Map()
});
}
return this.state.get(path4);
}
getSymbolOfNode(node, component) {
const builder = this.getOrCreateSymbolBuilder(component);
if (builder === null) {
return null;
}
return this.perf.inPhase(PerfPhase.TtcSymbol, () => builder.getSymbol(node));
}
getOrCreateSymbolBuilder(component) {
if (this.symbolBuilderCache.has(component)) {
return this.symbolBuilderCache.get(component);
}
const { tcb, data, tcbPath, tcbIsShim } = this.getLatestComponentState(component);
if (tcb === null || data === null) {
return null;
}
const builder = new SymbolBuilder(tcbPath, tcbIsShim, tcb, data, this.componentScopeReader, () => this.programDriver.getProgram().getTypeChecker());
this.symbolBuilderCache.set(component, builder);
return builder;
}
getPotentialTemplateDirectives(component) {
var _a2, _b2;
const typeChecker = this.programDriver.getProgram().getTypeChecker();
const inScopeDirectives = (_b2 = (_a2 = this.getScopeData(component)) == null ? void 0 : _a2.directives) != null ? _b2 : [];
const resultingDirectives = /* @__PURE__ */ new Map();
for (const d of inScopeDirectives) {
resultingDirectives.set(d.ref.node, d);
}
for (const directiveClass of this.localMetaReader.getKnown(MetaKind.Directive)) {
const directiveMeta = this.metaReader.getDirectiveMetadata(new Reference2(directiveClass));
if (directiveMeta === null)
continue;
if (resultingDirectives.has(directiveClass))
continue;
const withScope = this.scopeDataOfDirectiveMeta(typeChecker, directiveMeta);
if (withScope === null)
continue;
resultingDirectives.set(directiveClass, __spreadProps(__spreadValues({}, withScope), { isInScope: false }));
}
return Array.from(resultingDirectives.values());
}
getPotentialPipes(component) {
var _a2, _b2;
const typeChecker = this.programDriver.getProgram().getTypeChecker();
const inScopePipes = (_b2 = (_a2 = this.getScopeData(component)) == null ? void 0 : _a2.pipes) != null ? _b2 : [];
const resultingPipes = /* @__PURE__ */ new Map();
for (const p2 of inScopePipes) {
resultingPipes.set(p2.ref.node, p2);
}
for (const pipeClass of this.localMetaReader.getKnown(MetaKind.Pipe)) {
const pipeMeta = this.metaReader.getPipeMetadata(new Reference2(pipeClass));
if (pipeMeta === null)
continue;
if (resultingPipes.has(pipeClass))
continue;
const withScope = this.scopeDataOfPipeMeta(typeChecker, pipeMeta);
if (withScope === null)
continue;
resultingPipes.set(pipeClass, __spreadProps(__spreadValues({}, withScope), { isInScope: false }));
}
return Array.from(resultingPipes.values());
}
getDirectiveMetadata(dir) {
if (!isNamedClassDeclaration(dir)) {
return null;
}
return this.typeCheckScopeRegistry.getTypeCheckDirectiveMetadata(new Reference2(dir));
}
getNgModuleMetadata(module2) {
if (!isNamedClassDeclaration(module2)) {
return null;
}
return this.metaReader.getNgModuleMetadata(new Reference2(module2));
}
getPipeMetadata(pipe2) {
if (!isNamedClassDeclaration(pipe2)) {
return null;
}
return this.metaReader.getPipeMetadata(new Reference2(pipe2));
}
getPotentialElementTags(component) {
if (this.elementTagCache.has(component)) {
return this.elementTagCache.get(component);
}
const tagMap = /* @__PURE__ */ new Map();
for (const tag of REGISTRY2.allKnownElementNames()) {
tagMap.set(tag, null);
}
const potentialDirectives = this.getPotentialTemplateDirectives(component);
for (const directive of potentialDirectives) {
if (directive.selector === null) {
continue;
}
for (const selector of CssSelector.parse(directive.selector)) {
if (selector.element === null || tagMap.has(selector.element)) {
continue;
}
tagMap.set(selector.element, directive);
}
}
this.elementTagCache.set(component, tagMap);
return tagMap;
}
getPotentialDomBindings(tagName) {
const attributes = REGISTRY2.allKnownAttributesOfElement(tagName);
return attributes.map((attribute2) => ({
attribute: attribute2,
property: REGISTRY2.getMappedPropName(attribute2)
}));
}
getPotentialDomEvents(tagName) {
return REGISTRY2.allKnownEventsOfElement(tagName);
}
getPrimaryAngularDecorator(target) {
this.ensureAllShimsForOneFile(target.getSourceFile());
if (!isNamedClassDeclaration(target)) {
return null;
}
const ref = new Reference2(target);
const dirMeta = this.metaReader.getDirectiveMetadata(ref);
if (dirMeta !== null) {
return dirMeta.decorator;
}
const pipeMeta = this.metaReader.getPipeMetadata(ref);
if (pipeMeta !== null) {
return pipeMeta.decorator;
}
const ngModuleMeta = this.metaReader.getNgModuleMetadata(ref);
if (ngModuleMeta !== null) {
return ngModuleMeta.decorator;
}
return null;
}
getOwningNgModule(component) {
if (!isNamedClassDeclaration(component)) {
return null;
}
const dirMeta = this.metaReader.getDirectiveMetadata(new Reference2(component));
if (dirMeta !== null && dirMeta.isStandalone) {
return null;
}
const scope = this.componentScopeReader.getScopeForComponent(component);
if (scope === null || scope.kind !== ComponentScopeKind.NgModule || !isNamedClassDeclaration(scope.ngModule)) {
return null;
}
return scope.ngModule;
}
emit(kind, refTo, inContext) {
var _a2, _b2;
const emittedRef = this.refEmitter.emit(refTo, inContext.getSourceFile());
if (emittedRef.kind === 1) {
return null;
}
const emitted = emittedRef.expression;
if (emitted instanceof WrappedNodeExpr) {
if (refTo.node === inContext) {
return null;
}
let isForwardReference = false;
if (emitted.node.getStart() > inContext.getStart()) {
const declaration = (_b2 = (_a2 = this.programDriver.getProgram().getTypeChecker().getTypeAtLocation(emitted.node).getSymbol()) == null ? void 0 : _a2.declarations) == null ? void 0 : _b2[0];
if (declaration && declaration.getSourceFile() === inContext.getSourceFile()) {
isForwardReference = true;
}
}
return { kind, symbolName: emitted.node.text, isForwardReference };
} else if (emitted instanceof ExternalExpr && emitted.value.moduleName !== null && emitted.value.name !== null) {
return {
kind,
moduleSpecifier: emitted.value.moduleName,
symbolName: emitted.value.name,
isForwardReference: false
};
}
return null;
}
getPotentialImportsFor(toImport, inContext, importMode) {
var _a2;
const imports = [];
const meta = (_a2 = this.metaReader.getDirectiveMetadata(toImport)) != null ? _a2 : this.metaReader.getPipeMetadata(toImport);
if (meta === null) {
return imports;
}
if (meta.isStandalone || importMode === PotentialImportMode.ForceDirect) {
const emitted = this.emit(PotentialImportKind.Standalone, toImport, inContext);
if (emitted !== null) {
imports.push(emitted);
}
}
const exportingNgModules = this.ngModuleIndex.getNgModulesExporting(meta.ref.node);
if (exportingNgModules !== null) {
for (const exporter of exportingNgModules) {
const emittedRef = this.emit(PotentialImportKind.NgModule, exporter, inContext);
if (emittedRef !== null) {
imports.push(emittedRef);
}
}
}
return imports;
}
getScopeData(component) {
if (this.scopeCache.has(component)) {
return this.scopeCache.get(component);
}
if (!isNamedClassDeclaration(component)) {
throw new Error(`AssertionError: components must have names`);
}
const scope = this.componentScopeReader.getScopeForComponent(component);
if (scope === null) {
return null;
}
const dependencies = scope.kind === ComponentScopeKind.NgModule ? scope.compilation.dependencies : scope.dependencies;
const data = {
directives: [],
pipes: [],
isPoisoned: scope.kind === ComponentScopeKind.NgModule ? scope.compilation.isPoisoned : scope.isPoisoned
};
const typeChecker = this.programDriver.getProgram().getTypeChecker();
for (const dep of dependencies) {
if (dep.kind === MetaKind.Directive) {
const dirScope = this.scopeDataOfDirectiveMeta(typeChecker, dep);
if (dirScope === null)
continue;
data.directives.push(__spreadProps(__spreadValues({}, dirScope), { isInScope: true }));
} else if (dep.kind === MetaKind.Pipe) {
const pipeScope = this.scopeDataOfPipeMeta(typeChecker, dep);
if (pipeScope === null)
continue;
data.pipes.push(__spreadProps(__spreadValues({}, pipeScope), { isInScope: true }));
}
}
this.scopeCache.set(component, data);
return data;
}
scopeDataOfDirectiveMeta(typeChecker, dep) {
if (dep.selector === null) {
return null;
}
const tsSymbol = typeChecker.getSymbolAtLocation(dep.ref.node.name);
if (!isSymbolWithValueDeclaration(tsSymbol)) {
return null;
}
let ngModule = null;
const moduleScopeOfDir = this.componentScopeReader.getScopeForComponent(dep.ref.node);
if (moduleScopeOfDir !== null && moduleScopeOfDir.kind === ComponentScopeKind.NgModule) {
ngModule = moduleScopeOfDir.ngModule;
}
return {
ref: dep.ref,
isComponent: dep.isComponent,
isStructural: dep.isStructural,
selector: dep.selector,
tsSymbol,
ngModule
};
}
scopeDataOfPipeMeta(typeChecker, dep) {
const tsSymbol = typeChecker.getSymbolAtLocation(dep.ref.node.name);
if (tsSymbol === void 0) {
return null;
}
return {
ref: dep.ref,
name: dep.name,
tsSymbol
};
}
};
function convertDiagnostic(diag, sourceResolver) {
if (!shouldReportDiagnostic(diag)) {
return null;
}
return translateDiagnostic(diag, sourceResolver);
}
var WholeProgramTypeCheckingHost = class {
constructor(impl) {
this.impl = impl;
}
getSourceManager(sfPath) {
return this.impl.getFileData(sfPath).sourceManager;
}
shouldCheckComponent(node) {
const sfPath = absoluteFromSourceFile(node.getSourceFile());
const shimPath = TypeCheckShimGenerator.shimFor(sfPath);
const fileData = this.impl.getFileData(sfPath);
return !fileData.shimData.has(shimPath);
}
recordShimData(sfPath, data) {
const fileData = this.impl.getFileData(sfPath);
fileData.shimData.set(data.path, data);
if (data.hasInlines) {
fileData.hasInlines = true;
}
}
recordComplete(sfPath) {
this.impl.getFileData(sfPath).isComplete = true;
}
};
var SingleFileTypeCheckingHost = class {
constructor(sfPath, fileData, impl) {
this.sfPath = sfPath;
this.fileData = fileData;
this.impl = impl;
this.seenInlines = false;
}
assertPath(sfPath) {
if (this.sfPath !== sfPath) {
throw new Error(`AssertionError: querying TypeCheckingHost outside of assigned file`);
}
}
getSourceManager(sfPath) {
this.assertPath(sfPath);
return this.fileData.sourceManager;
}
shouldCheckComponent(node) {
if (this.sfPath !== absoluteFromSourceFile(node.getSourceFile())) {
return false;
}
const shimPath = TypeCheckShimGenerator.shimFor(this.sfPath);
return !this.fileData.shimData.has(shimPath);
}
recordShimData(sfPath, data) {
this.assertPath(sfPath);
if (data.hasInlines && !this.seenInlines) {
this.impl.clearAllShimDataUsingInlines();
this.seenInlines = true;
}
this.fileData.shimData.set(data.path, data);
if (data.hasInlines) {
this.fileData.hasInlines = true;
}
}
recordComplete(sfPath) {
this.assertPath(sfPath);
this.fileData.isComplete = true;
}
};
var SingleShimTypeCheckingHost = class extends SingleFileTypeCheckingHost {
constructor(sfPath, fileData, impl, shimPath) {
super(sfPath, fileData, impl);
this.shimPath = shimPath;
}
shouldCheckNode(node) {
if (this.sfPath !== absoluteFromSourceFile(node.getSourceFile())) {
return false;
}
const shimPath = TypeCheckShimGenerator.shimFor(this.sfPath);
if (shimPath !== this.shimPath) {
return false;
}
return !this.fileData.shimData.has(shimPath);
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/component/src/handler.mjs
var EMPTY_ARRAY2 = [];
var isUsedDirective = (decl) => decl.kind === R3TemplateDependencyKind.Directive;
var isUsedPipe = (decl) => decl.kind === R3TemplateDependencyKind.Pipe;
var ComponentDecoratorHandler = class {
constructor(reflector, evaluator, metaRegistry, metaReader, scopeReader, dtsScopeReader, scopeRegistry, typeCheckScopeRegistry, resourceRegistry, isCore, strictCtorDeps, resourceLoader, rootDirs, defaultPreserveWhitespaces, i18nUseExternalIds, enableI18nLegacyMessageIdFormat, usePoisonedData, i18nNormalizeLineEndingsInICUs, moduleResolver, cycleAnalyzer, cycleHandlingStrategy, refEmitter, referencesRegistry, depTracker, injectableRegistry, semanticDepGraphUpdater, annotateForClosureCompiler, perf, hostDirectivesResolver, importTracker, includeClassMetadata, compilationMode, deferredSymbolTracker, forbidOrphanRendering, enableBlockSyntax, enableLetSyntax, localCompilationExtraImportsTracker, jitDeclarationRegistry, i18nPreserveSignificantWhitespace) {
this.reflector = reflector;
this.evaluator = evaluator;
this.metaRegistry = metaRegistry;
this.metaReader = metaReader;
this.scopeReader = scopeReader;
this.dtsScopeReader = dtsScopeReader;
this.scopeRegistry = scopeRegistry;
this.typeCheckScopeRegistry = typeCheckScopeRegistry;
this.resourceRegistry = resourceRegistry;
this.isCore = isCore;
this.strictCtorDeps = strictCtorDeps;
this.resourceLoader = resourceLoader;
this.rootDirs = rootDirs;
this.defaultPreserveWhitespaces = defaultPreserveWhitespaces;
this.i18nUseExternalIds = i18nUseExternalIds;
this.enableI18nLegacyMessageIdFormat = enableI18nLegacyMessageIdFormat;
this.usePoisonedData = usePoisonedData;
this.i18nNormalizeLineEndingsInICUs = i18nNormalizeLineEndingsInICUs;
this.moduleResolver = moduleResolver;
this.cycleAnalyzer = cycleAnalyzer;
this.cycleHandlingStrategy = cycleHandlingStrategy;
this.refEmitter = refEmitter;
this.referencesRegistry = referencesRegistry;
this.depTracker = depTracker;
this.injectableRegistry = injectableRegistry;
this.semanticDepGraphUpdater = semanticDepGraphUpdater;
this.annotateForClosureCompiler = annotateForClosureCompiler;
this.perf = perf;
this.hostDirectivesResolver = hostDirectivesResolver;
this.importTracker = importTracker;
this.includeClassMetadata = includeClassMetadata;
this.compilationMode = compilationMode;
this.deferredSymbolTracker = deferredSymbolTracker;
this.forbidOrphanRendering = forbidOrphanRendering;
this.enableBlockSyntax = enableBlockSyntax;
this.enableLetSyntax = enableLetSyntax;
this.localCompilationExtraImportsTracker = localCompilationExtraImportsTracker;
this.jitDeclarationRegistry = jitDeclarationRegistry;
this.i18nPreserveSignificantWhitespace = i18nPreserveSignificantWhitespace;
this.literalCache = /* @__PURE__ */ new Map();
this.elementSchemaRegistry = new DomElementSchemaRegistry();
this.preanalyzeTemplateCache = /* @__PURE__ */ new Map();
this.preanalyzeStylesCache = /* @__PURE__ */ new Map();
this.precedence = HandlerPrecedence.PRIMARY;
this.name = "ComponentDecoratorHandler";
this.extractTemplateOptions = {
enableI18nLegacyMessageIdFormat: this.enableI18nLegacyMessageIdFormat,
i18nNormalizeLineEndingsInICUs: this.i18nNormalizeLineEndingsInICUs,
usePoisonedData: this.usePoisonedData,
enableBlockSyntax: this.enableBlockSyntax,
enableLetSyntax: this.enableLetSyntax,
preserveSignificantWhitespace: this.i18nPreserveSignificantWhitespace
};
}
detect(node, decorators) {
if (!decorators) {
return void 0;
}
const decorator = findAngularDecorator(decorators, "Component", this.isCore);
if (decorator !== void 0) {
return {
trigger: decorator.node,
decorator,
metadata: decorator
};
} else {
return void 0;
}
}
preanalyze(node, decorator) {
if (!this.resourceLoader.canPreload) {
return void 0;
}
const meta = resolveLiteral(decorator, this.literalCache);
const component = reflectObjectLiteral(meta);
const containingFile = node.getSourceFile().fileName;
const resolveStyleUrl = (styleUrl) => {
try {
const resourceUrl = this.resourceLoader.resolve(styleUrl, containingFile);
return this.resourceLoader.preload(resourceUrl, { type: "style", containingFile });
} catch (e) {
return void 0;
}
};
const templateAndTemplateStyleResources = preloadAndParseTemplate(this.evaluator, this.resourceLoader, this.depTracker, this.preanalyzeTemplateCache, node, decorator, component, containingFile, this.defaultPreserveWhitespaces, this.extractTemplateOptions, this.compilationMode).then((template2) => {
if (template2 === null) {
return void 0;
}
return Promise.all(template2.styleUrls.map((styleUrl) => resolveStyleUrl(styleUrl))).then(() => void 0);
});
const componentStyleUrls = extractComponentStyleUrls(this.evaluator, component);
let inlineStyles;
if (component.has("styles")) {
const litStyles = parseDirectiveStyles(component, this.evaluator, this.compilationMode);
if (litStyles === null) {
this.preanalyzeStylesCache.set(node, null);
} else {
inlineStyles = Promise.all(litStyles.map((style) => this.resourceLoader.preprocessInline(style, { type: "style", containingFile }))).then((styles) => {
this.preanalyzeStylesCache.set(node, styles);
});
}
} else {
this.preanalyzeStylesCache.set(node, null);
}
return Promise.all([
templateAndTemplateStyleResources,
inlineStyles,
...componentStyleUrls.map((styleUrl) => resolveStyleUrl(styleUrl.url))
]).then(() => void 0);
}
analyze(node, decorator) {
var _a2, _b2, _c2, _d2, _e2;
this.perf.eventCount(PerfEvent.AnalyzeComponent);
const containingFile = node.getSourceFile().fileName;
this.literalCache.delete(decorator);
let diagnostics;
let isPoisoned = false;
const directiveResult = extractDirectiveMetadata(node, decorator, this.reflector, this.importTracker, this.evaluator, this.refEmitter, this.referencesRegistry, this.isCore, this.annotateForClosureCompiler, this.compilationMode, this.elementSchemaRegistry.getDefaultComponentElementName());
if (directiveResult.jitForced) {
this.jitDeclarationRegistry.jitDeclarations.add(node);
return {};
}
const { decorator: component, metadata, inputs, outputs, hostDirectives, rawHostDirectives } = directiveResult;
const encapsulation = (_a2 = this.compilationMode !== CompilationMode.LOCAL ? resolveEnumValue(this.evaluator, component, "encapsulation", "ViewEncapsulation") : resolveEncapsulationEnumValueLocally(component.get("encapsulation"))) != null ? _a2 : ViewEncapsulation.Emulated;
let changeDetection = null;
if (this.compilationMode !== CompilationMode.LOCAL) {
changeDetection = resolveEnumValue(this.evaluator, component, "changeDetection", "ChangeDetectionStrategy");
} else if (component.has("changeDetection")) {
changeDetection = new output_ast_exports.WrappedNodeExpr(component.get("changeDetection"));
}
let animations = null;
let animationTriggerNames = null;
if (component.has("animations")) {
const animationExpression = component.get("animations");
animations = new output_ast_exports.WrappedNodeExpr(animationExpression);
const animationsValue = this.evaluator.evaluate(animationExpression, animationTriggerResolver);
animationTriggerNames = { includesDynamicAnimations: false, staticTriggerNames: [] };
collectAnimationNames(animationsValue, animationTriggerNames);
}
const relativeContextFilePath = this.rootDirs.reduce((previous, rootDir) => {
const candidate = relative(absoluteFrom(rootDir), absoluteFrom(containingFile));
if (previous === void 0 || candidate.length < previous.length) {
return candidate;
} else {
return previous;
}
}, void 0);
let viewProvidersRequiringFactory = null;
let providersRequiringFactory = null;
let wrappedViewProviders = null;
if (component.has("viewProviders")) {
const viewProviders = component.get("viewProviders");
viewProvidersRequiringFactory = resolveProvidersRequiringFactory(viewProviders, this.reflector, this.evaluator);
wrappedViewProviders = new output_ast_exports.WrappedNodeExpr(this.annotateForClosureCompiler ? wrapFunctionExpressionsInParens(viewProviders) : viewProviders);
}
if (component.has("providers")) {
providersRequiringFactory = resolveProvidersRequiringFactory(component.get("providers"), this.reflector, this.evaluator);
}
let resolvedImports = null;
let resolvedDeferredImports = null;
let rawImports = (_b2 = component.get("imports")) != null ? _b2 : null;
let rawDeferredImports = (_c2 = component.get("deferredImports")) != null ? _c2 : null;
if ((rawImports || rawDeferredImports) && !metadata.isStandalone) {
if (diagnostics === void 0) {
diagnostics = [];
}
const importsField = rawImports ? "imports" : "deferredImports";
diagnostics.push(makeDiagnostic(ErrorCode.COMPONENT_NOT_STANDALONE, component.get(importsField), `'${importsField}' is only valid on a component that is standalone.`, [
makeRelatedInformation(node.name, `Did you forget to add 'standalone: true' to this @Component?`)
]));
isPoisoned = true;
} else if (this.compilationMode !== CompilationMode.LOCAL && (rawImports || rawDeferredImports)) {
const importResolvers = combineResolvers([
createModuleWithProvidersResolver(this.reflector, this.isCore),
forwardRefResolver
]);
const importDiagnostics = [];
if (rawImports) {
const expr = rawImports;
const imported = this.evaluator.evaluate(expr, importResolvers);
const { imports: flattened, diagnostics: diagnostics2 } = validateAndFlattenComponentImports(imported, expr, false);
importDiagnostics.push(...diagnostics2);
resolvedImports = flattened;
rawImports = expr;
}
if (rawDeferredImports) {
const expr = rawDeferredImports;
const imported = this.evaluator.evaluate(expr, importResolvers);
const { imports: flattened, diagnostics: diagnostics2 } = validateAndFlattenComponentImports(imported, expr, true);
importDiagnostics.push(...diagnostics2);
resolvedDeferredImports = flattened;
rawDeferredImports = expr;
}
if (importDiagnostics.length > 0) {
isPoisoned = true;
if (diagnostics === void 0) {
diagnostics = [];
}
diagnostics.push(...importDiagnostics);
}
}
let schemas = null;
if (component.has("schemas") && !metadata.isStandalone) {
if (diagnostics === void 0) {
diagnostics = [];
}
diagnostics.push(makeDiagnostic(ErrorCode.COMPONENT_NOT_STANDALONE, component.get("schemas"), `'schemas' is only valid on a component that is standalone.`));
} else if (this.compilationMode !== CompilationMode.LOCAL && component.has("schemas")) {
schemas = extractSchemas(component.get("schemas"), this.evaluator, "Component");
} else if (metadata.isStandalone) {
schemas = [];
}
let template2;
if (this.preanalyzeTemplateCache.has(node)) {
const preanalyzed = this.preanalyzeTemplateCache.get(node);
this.preanalyzeTemplateCache.delete(node);
template2 = preanalyzed;
} else {
const templateDecl = parseTemplateDeclaration(node, decorator, component, containingFile, this.evaluator, this.depTracker, this.resourceLoader, this.defaultPreserveWhitespaces);
template2 = extractTemplate(node, templateDecl, this.evaluator, this.depTracker, this.resourceLoader, {
enableI18nLegacyMessageIdFormat: this.enableI18nLegacyMessageIdFormat,
i18nNormalizeLineEndingsInICUs: this.i18nNormalizeLineEndingsInICUs,
usePoisonedData: this.usePoisonedData,
enableBlockSyntax: this.enableBlockSyntax,
enableLetSyntax: this.enableLetSyntax,
preserveSignificantWhitespace: this.i18nPreserveSignificantWhitespace
}, this.compilationMode);
if (this.compilationMode === CompilationMode.LOCAL && template2.errors && template2.errors.length > 0) {
if (diagnostics === void 0) {
diagnostics = [];
}
diagnostics.push(...getTemplateDiagnostics(
template2.errors,
"",
template2.sourceMapping
));
}
}
const templateResource = template2.declaration.isInline ? { path: null, expression: component.get("template") } : {
path: absoluteFrom(template2.declaration.resolvedTemplateUrl),
expression: template2.sourceMapping.node
};
let styles = [];
const styleResources = extractStyleResources(this.resourceLoader, component, containingFile);
const styleUrls = [
...extractComponentStyleUrls(this.evaluator, component),
..._extractTemplateStyleUrls(template2)
];
for (const styleUrl of styleUrls) {
try {
const resourceUrl = this.resourceLoader.resolve(styleUrl.url, containingFile);
const resourceStr = this.resourceLoader.load(resourceUrl);
styles.push(resourceStr);
if (this.depTracker !== null) {
this.depTracker.addResourceDependency(node.getSourceFile(), absoluteFrom(resourceUrl));
}
} catch (e) {
if (this.depTracker !== null) {
this.depTracker.recordDependencyAnalysisFailure(node.getSourceFile());
}
if (diagnostics === void 0) {
diagnostics = [];
}
const resourceType = styleUrl.source === 2 ? 2 : 1;
diagnostics.push(makeResourceNotFoundError(styleUrl.url, styleUrl.nodeForError, resourceType).toDiagnostic());
}
}
if (encapsulation === ViewEncapsulation.ShadowDom && metadata.selector !== null) {
const selectorError = checkCustomElementSelectorForErrors(metadata.selector);
if (selectorError !== null) {
if (diagnostics === void 0) {
diagnostics = [];
}
diagnostics.push(makeDiagnostic(ErrorCode.COMPONENT_INVALID_SHADOW_DOM_SELECTOR, component.get("selector"), selectorError));
}
}
let inlineStyles = null;
if (this.preanalyzeStylesCache.has(node)) {
inlineStyles = this.preanalyzeStylesCache.get(node);
this.preanalyzeStylesCache.delete(node);
if (inlineStyles !== null) {
styles.push(...inlineStyles);
}
} else {
if (this.resourceLoader.canPreprocess) {
throw new Error("Inline resource processing requires asynchronous preanalyze.");
}
if (component.has("styles")) {
const litStyles = parseDirectiveStyles(component, this.evaluator, this.compilationMode);
if (litStyles !== null) {
inlineStyles = [...litStyles];
styles.push(...litStyles);
}
}
}
if (template2.styles.length > 0) {
styles.push(...template2.styles);
}
let explicitlyDeferredTypes = null;
if (metadata.isStandalone && rawDeferredImports !== null) {
const deferredTypes = this.collectExplicitlyDeferredSymbols(rawDeferredImports);
for (const [deferredType, importDetails] of deferredTypes) {
explicitlyDeferredTypes != null ? explicitlyDeferredTypes : explicitlyDeferredTypes = [];
explicitlyDeferredTypes.push({
symbolName: importDetails.name,
importPath: importDetails.from,
isDefaultImport: isDefaultImport(importDetails.node)
});
this.deferredSymbolTracker.markAsDeferrableCandidate(deferredType, importDetails.node, node, true);
}
}
const output = {
analysis: {
baseClass: readBaseClass(node, this.reflector, this.evaluator),
inputs,
inputFieldNamesFromMetadataArray: directiveResult.inputFieldNamesFromMetadataArray,
outputs,
hostDirectives,
rawHostDirectives,
meta: __spreadProps(__spreadValues({}, metadata), {
template: template2,
encapsulation,
changeDetection,
interpolation: (_d2 = template2.interpolationConfig) != null ? _d2 : DEFAULT_INTERPOLATION_CONFIG,
styles,
animations,
viewProviders: wrappedViewProviders,
i18nUseExternalIds: this.i18nUseExternalIds,
relativeContextFilePath,
rawImports: rawImports !== null ? new output_ast_exports.WrappedNodeExpr(rawImports) : void 0
}),
typeCheckMeta: extractDirectiveTypeCheckMeta(node, inputs, this.reflector),
classMetadata: this.includeClassMetadata ? extractClassMetadata(node, this.reflector, this.isCore, this.annotateForClosureCompiler, (dec) => transformDecoratorResources(dec, component, styles, template2)) : null,
classDebugInfo: extractClassDebugInfo(
node,
this.reflector,
this.rootDirs,
this.forbidOrphanRendering
),
template: template2,
providersRequiringFactory,
viewProvidersRequiringFactory,
inlineStyles,
styleUrls,
resources: {
styles: styleResources,
template: templateResource
},
isPoisoned,
animationTriggerNames,
rawImports,
resolvedImports,
rawDeferredImports,
resolvedDeferredImports,
explicitlyDeferredTypes,
schemas,
decorator: (_e2 = decorator == null ? void 0 : decorator.node) != null ? _e2 : null
},
diagnostics
};
return output;
}
symbol(node, analysis) {
const typeParameters = extractSemanticTypeParameters(node);
return new ComponentSymbol(node, analysis.meta.selector, analysis.inputs, analysis.outputs, analysis.meta.exportAs, analysis.typeCheckMeta, typeParameters);
}
register(node, analysis) {
var _a2;
const ref = new Reference2(node);
this.metaRegistry.registerDirectiveMetadata(__spreadProps(__spreadValues({
kind: MetaKind.Directive,
matchSource: MatchSource.Selector,
ref,
name: node.name.text,
selector: analysis.meta.selector,
exportAs: analysis.meta.exportAs,
inputs: analysis.inputs,
inputFieldNamesFromMetadataArray: analysis.inputFieldNamesFromMetadataArray,
outputs: analysis.outputs,
queries: analysis.meta.queries.map((query) => query.propertyName),
isComponent: true,
baseClass: analysis.baseClass,
hostDirectives: analysis.hostDirectives
}, analysis.typeCheckMeta), {
isPoisoned: analysis.isPoisoned,
isStructural: false,
isStandalone: analysis.meta.isStandalone,
isSignal: analysis.meta.isSignal,
imports: analysis.resolvedImports,
deferredImports: analysis.resolvedDeferredImports,
animationTriggerNames: analysis.animationTriggerNames,
schemas: analysis.schemas,
decorator: analysis.decorator,
assumedToExportProviders: false,
ngContentSelectors: analysis.template.ngContentSelectors,
preserveWhitespaces: (_a2 = analysis.template.preserveWhitespaces) != null ? _a2 : false,
isExplicitlyDeferred: false
}));
this.resourceRegistry.registerResources(analysis.resources, node);
this.injectableRegistry.registerInjectable(node, {
ctorDeps: analysis.meta.deps
});
}
index(context, node, analysis) {
if (analysis.isPoisoned && !this.usePoisonedData) {
return null;
}
const scope = this.scopeReader.getScopeForComponent(node);
const selector = analysis.meta.selector;
const matcher = new SelectorMatcher();
if (scope !== null) {
let { dependencies, isPoisoned } = scope.kind === ComponentScopeKind.NgModule ? scope.compilation : scope;
if ((isPoisoned || scope.kind === ComponentScopeKind.NgModule && scope.exported.isPoisoned) && !this.usePoisonedData) {
return null;
}
for (const dep of dependencies) {
if (dep.kind === MetaKind.Directive && dep.selector !== null) {
matcher.addSelectables(CssSelector.parse(dep.selector), [
...this.hostDirectivesResolver.resolve(dep),
dep
]);
}
}
}
const binder = new R3TargetBinder(matcher);
const boundTemplate = binder.bind({ template: analysis.template.diagNodes });
context.addComponent({
declaration: node,
selector,
boundTemplate,
templateMeta: {
isInline: analysis.template.declaration.isInline,
file: analysis.template.file
}
});
return null;
}
typeCheck(ctx, node, meta) {
var _a2;
if (this.typeCheckScopeRegistry === null || !import_typescript88.default.isClassDeclaration(node)) {
return;
}
if (meta.isPoisoned && !this.usePoisonedData) {
return;
}
const scope = this.typeCheckScopeRegistry.getTypeCheckScope(node);
if (scope.isPoisoned && !this.usePoisonedData) {
return;
}
const binder = new R3TargetBinder(scope.matcher);
ctx.addTemplate(new Reference2(node), binder, meta.template.diagNodes, scope.pipes, scope.schemas, meta.template.sourceMapping, meta.template.file, meta.template.errors, meta.meta.isStandalone, (_a2 = meta.meta.template.preserveWhitespaces) != null ? _a2 : false);
}
extendedTemplateCheck(component, extendedTemplateChecker) {
return extendedTemplateChecker.getDiagnosticsForComponent(component);
}
templateSemanticsCheck(component, templateSemanticsChecker) {
return templateSemanticsChecker.getDiagnosticsForComponent(component);
}
resolve(node, analysis, symbol) {
var _a2, _b2;
const metadata = analysis.meta;
const diagnostics = [];
const context = getSourceFile(node);
const nonRemovableImports = this.deferredSymbolTracker.getNonRemovableDeferredImports(context, node);
if (nonRemovableImports.length > 0) {
for (const importDecl of nonRemovableImports) {
const diagnostic = makeDiagnostic(ErrorCode.DEFERRED_DEPENDENCY_IMPORTED_EAGERLY, importDecl, `This import contains symbols that are used both inside and outside of the \`@Component.deferredImports\` fields in the file. This renders all these defer imports useless as this import remains and its module is eagerly loaded. To fix this, make sure that all symbols from the import are *only* used within \`@Component.deferredImports\` arrays and there are no other references to those symbols present in this file.`);
diagnostics.push(diagnostic);
}
return { diagnostics };
}
let data;
if (this.compilationMode === CompilationMode.LOCAL) {
data = {
declarations: EMPTY_ARRAY2,
declarationListEmitMode: !analysis.meta.isStandalone || analysis.rawImports !== null ? 3 : 0,
deferPerBlockDependencies: this.locateDeferBlocksWithoutScope(analysis.template),
deferBlockDepsEmitMode: 1,
deferrableDeclToImportDecl: /* @__PURE__ */ new Map(),
deferPerComponentDependencies: (_a2 = analysis.explicitlyDeferredTypes) != null ? _a2 : []
};
if (this.localCompilationExtraImportsTracker === null) {
return { data };
}
} else {
data = {
declarations: EMPTY_ARRAY2,
declarationListEmitMode: 0,
deferPerBlockDependencies: /* @__PURE__ */ new Map(),
deferBlockDepsEmitMode: 0,
deferrableDeclToImportDecl: /* @__PURE__ */ new Map(),
deferPerComponentDependencies: []
};
}
if (this.semanticDepGraphUpdater !== null && analysis.baseClass instanceof Reference2) {
symbol.baseClass = this.semanticDepGraphUpdater.getSymbol(analysis.baseClass.node);
}
if (analysis.isPoisoned && !this.usePoisonedData) {
return {};
}
const scope = this.scopeReader.getScopeForComponent(node);
if (scope !== null) {
const isModuleScope = scope.kind === ComponentScopeKind.NgModule;
const dependencies = isModuleScope ? scope.compilation.dependencies : scope.dependencies;
const explicitlyDeferredDependencies = getExplicitlyDeferredDeps(scope);
if (isModuleScope && context.fileName !== getSourceFile(scope.ngModule).fileName) {
(_b2 = this.localCompilationExtraImportsTracker) == null ? void 0 : _b2.markFileForExtraImportGeneration(context);
}
if (metadata.isStandalone && analysis.rawDeferredImports !== null && explicitlyDeferredDependencies.length > 0) {
const diagnostic = validateNoImportOverlap(dependencies, explicitlyDeferredDependencies, analysis.rawDeferredImports);
if (diagnostic !== null) {
diagnostics.push(diagnostic);
}
}
const binder = createTargetBinder(dependencies);
const pipes = extractPipes(dependencies);
let allDependencies = dependencies;
let deferBlockBinder = binder;
if (explicitlyDeferredDependencies.length > 0) {
allDependencies = [...explicitlyDeferredDependencies, ...dependencies];
deferBlockBinder = createTargetBinder(allDependencies);
}
const bound = binder.bind({ template: metadata.template.nodes });
const deferBlocks = /* @__PURE__ */ new Map();
for (const deferBlock of bound.getDeferBlocks()) {
deferBlocks.set(deferBlock, deferBlockBinder.bind({ template: deferBlock.children }));
}
const eagerlyUsed = /* @__PURE__ */ new Set();
for (const dir of bound.getEagerlyUsedDirectives()) {
eagerlyUsed.add(dir.ref.node);
}
for (const name of bound.getEagerlyUsedPipes()) {
if (!pipes.has(name)) {
continue;
}
eagerlyUsed.add(pipes.get(name).ref.node);
}
const wholeTemplateUsed = new Set(eagerlyUsed);
for (const bound2 of deferBlocks.values()) {
for (const dir of bound2.getEagerlyUsedDirectives()) {
wholeTemplateUsed.add(dir.ref.node);
}
for (const name of bound2.getEagerlyUsedPipes()) {
if (!pipes.has(name)) {
continue;
}
wholeTemplateUsed.add(pipes.get(name).ref.node);
}
}
const declarations = /* @__PURE__ */ new Map();
for (const dep of allDependencies) {
if (declarations.has(dep.ref.node)) {
continue;
}
switch (dep.kind) {
case MetaKind.Directive:
if (!wholeTemplateUsed.has(dep.ref.node) || dep.matchSource !== MatchSource.Selector) {
continue;
}
const dirType = this.refEmitter.emit(dep.ref, context);
assertSuccessfulReferenceEmit(dirType, node.name, dep.isComponent ? "component" : "directive");
declarations.set(dep.ref.node, {
kind: R3TemplateDependencyKind.Directive,
ref: dep.ref,
type: dirType.expression,
importedFile: dirType.importedFile,
selector: dep.selector,
inputs: dep.inputs.propertyNames,
outputs: dep.outputs.propertyNames,
exportAs: dep.exportAs,
isComponent: dep.isComponent
});
break;
case MetaKind.Pipe:
if (!wholeTemplateUsed.has(dep.ref.node)) {
continue;
}
const pipeType = this.refEmitter.emit(dep.ref, context);
assertSuccessfulReferenceEmit(pipeType, node.name, "pipe");
declarations.set(dep.ref.node, {
kind: R3TemplateDependencyKind.Pipe,
type: pipeType.expression,
name: dep.name,
ref: dep.ref,
importedFile: pipeType.importedFile
});
break;
case MetaKind.NgModule:
const ngModuleType = this.refEmitter.emit(dep.ref, context);
assertSuccessfulReferenceEmit(ngModuleType, node.name, "NgModule");
declarations.set(dep.ref.node, {
kind: R3TemplateDependencyKind.NgModule,
type: ngModuleType.expression,
importedFile: ngModuleType.importedFile
});
break;
}
}
const getSemanticReference = (decl) => this.semanticDepGraphUpdater.getSemanticReference(decl.ref.node, decl.type);
if (this.semanticDepGraphUpdater !== null) {
symbol.usedDirectives = Array.from(declarations.values()).filter(isUsedDirective).map(getSemanticReference);
symbol.usedPipes = Array.from(declarations.values()).filter(isUsedPipe).map(getSemanticReference);
}
const eagerDeclarations = Array.from(declarations.values()).filter((decl) => decl.kind === R3TemplateDependencyKind.NgModule || eagerlyUsed.has(decl.ref.node));
if (this.compilationMode !== CompilationMode.LOCAL) {
this.resolveDeferBlocks(node, deferBlocks, declarations, data, analysis, eagerlyUsed);
}
const cyclesFromDirectives = /* @__PURE__ */ new Map();
const cyclesFromPipes = /* @__PURE__ */ new Map();
if (!metadata.isStandalone) {
for (const usedDep of eagerDeclarations) {
const cycle = this._checkForCyclicImport(usedDep.importedFile, usedDep.type, context);
if (cycle !== null) {
switch (usedDep.kind) {
case R3TemplateDependencyKind.Directive:
cyclesFromDirectives.set(usedDep, cycle);
break;
case R3TemplateDependencyKind.Pipe:
cyclesFromPipes.set(usedDep, cycle);
break;
}
}
}
}
const standaloneImportMayBeForwardDeclared = analysis.resolvedImports !== null && analysis.resolvedImports.some((ref) => ref.synthetic);
const cycleDetected = cyclesFromDirectives.size !== 0 || cyclesFromPipes.size !== 0;
if (!cycleDetected) {
for (const { type, importedFile } of eagerDeclarations) {
this.maybeRecordSyntheticImport(importedFile, type, context);
}
const declarationIsForwardDeclared = eagerDeclarations.some((decl) => isExpressionForwardReference(decl.type, node.name, context));
if (this.compilationMode !== CompilationMode.LOCAL && (declarationIsForwardDeclared || standaloneImportMayBeForwardDeclared)) {
data.declarationListEmitMode = 1;
}
data.declarations = eagerDeclarations;
if (this.compilationMode === CompilationMode.LOCAL && this.localCompilationExtraImportsTracker !== null) {
for (const { type } of eagerDeclarations) {
if (type instanceof ExternalExpr && type.value.moduleName) {
this.localCompilationExtraImportsTracker.addImportForFile(context, type.value.moduleName);
}
}
}
} else {
if (this.cycleHandlingStrategy === 0) {
this.scopeRegistry.setComponentRemoteScope(node, eagerDeclarations.filter(isUsedDirective).map((dir) => dir.ref), eagerDeclarations.filter(isUsedPipe).map((pipe2) => pipe2.ref));
symbol.isRemotelyScoped = true;
if (this.semanticDepGraphUpdater !== null && scope.kind === ComponentScopeKind.NgModule && scope.ngModule !== null) {
const moduleSymbol = this.semanticDepGraphUpdater.getSymbol(scope.ngModule);
if (!(moduleSymbol instanceof NgModuleSymbol)) {
throw new Error(`AssertionError: Expected ${scope.ngModule.name} to be an NgModuleSymbol.`);
}
moduleSymbol.addRemotelyScopedComponent(symbol, symbol.usedDirectives, symbol.usedPipes);
}
} else {
const relatedMessages = [];
for (const [dir, cycle] of cyclesFromDirectives) {
relatedMessages.push(makeCyclicImportInfo(dir.ref, dir.isComponent ? "component" : "directive", cycle));
}
for (const [pipe2, cycle] of cyclesFromPipes) {
relatedMessages.push(makeCyclicImportInfo(pipe2.ref, "pipe", cycle));
}
throw new FatalDiagnosticError(ErrorCode.IMPORT_CYCLE_DETECTED, node, "One or more import cycles would need to be created to compile this component, which is not supported by the current compiler configuration.", relatedMessages);
}
}
} else {
data.deferPerBlockDependencies = this.locateDeferBlocksWithoutScope(metadata.template);
}
if (this.compilationMode !== CompilationMode.LOCAL) {
if (analysis.resolvedImports !== null && analysis.rawImports !== null) {
const importDiagnostics = validateStandaloneImports(analysis.resolvedImports, analysis.rawImports, this.metaReader, this.scopeReader, false);
diagnostics.push(...importDiagnostics);
}
if (analysis.resolvedDeferredImports !== null && analysis.rawDeferredImports !== null) {
const importDiagnostics = validateStandaloneImports(analysis.resolvedDeferredImports, analysis.rawDeferredImports, this.metaReader, this.scopeReader, true);
diagnostics.push(...importDiagnostics);
}
if (analysis.providersRequiringFactory !== null && analysis.meta.providers instanceof output_ast_exports.WrappedNodeExpr) {
const providerDiagnostics = getProviderDiagnostics(analysis.providersRequiringFactory, analysis.meta.providers.node, this.injectableRegistry);
diagnostics.push(...providerDiagnostics);
}
if (analysis.viewProvidersRequiringFactory !== null && analysis.meta.viewProviders instanceof output_ast_exports.WrappedNodeExpr) {
const viewProviderDiagnostics = getProviderDiagnostics(analysis.viewProvidersRequiringFactory, analysis.meta.viewProviders.node, this.injectableRegistry);
diagnostics.push(...viewProviderDiagnostics);
}
const directiveDiagnostics = getDirectiveDiagnostics(node, this.injectableRegistry, this.evaluator, this.reflector, this.scopeRegistry, this.strictCtorDeps, "Component");
if (directiveDiagnostics !== null) {
diagnostics.push(...directiveDiagnostics);
}
const hostDirectivesDiagnostics = analysis.hostDirectives && analysis.rawHostDirectives ? validateHostDirectives(analysis.rawHostDirectives, analysis.hostDirectives, this.metaReader) : null;
if (hostDirectivesDiagnostics !== null) {
diagnostics.push(...hostDirectivesDiagnostics);
}
}
if (diagnostics.length > 0) {
return { diagnostics };
}
return { data };
}
xi18n(ctx, node, analysis) {
var _a2;
ctx.updateFromTemplate(analysis.template.content, analysis.template.declaration.resolvedTemplateUrl, (_a2 = analysis.template.interpolationConfig) != null ? _a2 : DEFAULT_INTERPOLATION_CONFIG);
}
updateResources(node, analysis) {
const containingFile = node.getSourceFile().fileName;
const templateDecl = analysis.template.declaration;
if (!templateDecl.isInline) {
analysis.template = extractTemplate(node, templateDecl, this.evaluator, this.depTracker, this.resourceLoader, this.extractTemplateOptions, this.compilationMode);
}
let styles = [];
if (analysis.styleUrls !== null) {
for (const styleUrl of analysis.styleUrls) {
try {
const resolvedStyleUrl = this.resourceLoader.resolve(styleUrl.url, containingFile);
const styleText = this.resourceLoader.load(resolvedStyleUrl);
styles.push(styleText);
} catch (e) {
}
}
}
if (analysis.inlineStyles !== null) {
for (const styleText of analysis.inlineStyles) {
styles.push(styleText);
}
}
for (const styleText of analysis.template.styles) {
styles.push(styleText);
}
analysis.meta.styles = styles.filter((s) => s.trim().length > 0);
}
compileFull(node, analysis, resolution, pool) {
if (analysis.template.errors !== null && analysis.template.errors.length > 0) {
return [];
}
const perComponentDeferredDeps = this.resolveAllDeferredDependencies(resolution);
const meta = __spreadProps(__spreadValues(__spreadValues({}, analysis.meta), resolution), {
defer: this.compileDeferBlocks(resolution)
});
const fac = compileNgFactoryDefField(toFactoryMetadata(meta, FactoryTarget.Component));
removeDeferrableTypesFromComponentDecorator(analysis, perComponentDeferredDeps);
const def = compileComponentFromMetadata(meta, pool, makeBindingParser());
const inputTransformFields = compileInputTransformFields(analysis.inputs);
const classMetadata = analysis.classMetadata !== null ? compileComponentClassMetadata(analysis.classMetadata, perComponentDeferredDeps).toStmt() : null;
const debugInfo = analysis.classDebugInfo !== null ? compileClassDebugInfo(analysis.classDebugInfo).toStmt() : null;
const deferrableImports = this.deferredSymbolTracker.getDeferrableImportDecls();
return compileResults(fac, def, classMetadata, "\u0275cmp", inputTransformFields, deferrableImports, debugInfo);
}
compilePartial(node, analysis, resolution) {
if (analysis.template.errors !== null && analysis.template.errors.length > 0) {
return [];
}
const templateInfo = {
content: analysis.template.content,
sourceUrl: analysis.template.declaration.resolvedTemplateUrl,
isInline: analysis.template.declaration.isInline,
inlineTemplateLiteralExpression: analysis.template.sourceMapping.type === "direct" ? new output_ast_exports.WrappedNodeExpr(analysis.template.sourceMapping.node) : null
};
const perComponentDeferredDeps = this.resolveAllDeferredDependencies(resolution);
const meta = __spreadProps(__spreadValues(__spreadValues({}, analysis.meta), resolution), {
defer: this.compileDeferBlocks(resolution)
});
const fac = compileDeclareFactory(toFactoryMetadata(meta, FactoryTarget.Component));
const inputTransformFields = compileInputTransformFields(analysis.inputs);
const def = compileDeclareComponentFromMetadata(meta, analysis.template, templateInfo);
const classMetadata = analysis.classMetadata !== null ? compileComponentDeclareClassMetadata(analysis.classMetadata, perComponentDeferredDeps).toStmt() : null;
const deferrableImports = this.deferredSymbolTracker.getDeferrableImportDecls();
return compileResults(fac, def, classMetadata, "\u0275cmp", inputTransformFields, deferrableImports);
}
compileLocal(node, analysis, resolution, pool) {
const deferrableTypes = analysis.explicitlyDeferredTypes;
const meta = __spreadProps(__spreadValues(__spreadValues({}, analysis.meta), resolution), {
defer: this.compileDeferBlocks(resolution)
});
if (analysis.explicitlyDeferredTypes !== null) {
removeDeferrableTypesFromComponentDecorator(analysis, analysis.explicitlyDeferredTypes);
}
const fac = compileNgFactoryDefField(toFactoryMetadata(meta, FactoryTarget.Component));
const def = compileComponentFromMetadata(meta, pool, makeBindingParser());
const inputTransformFields = compileInputTransformFields(analysis.inputs);
const classMetadata = analysis.classMetadata !== null ? compileComponentClassMetadata(analysis.classMetadata, deferrableTypes).toStmt() : null;
const debugInfo = analysis.classDebugInfo !== null ? compileClassDebugInfo(analysis.classDebugInfo).toStmt() : null;
const deferrableImports = this.deferredSymbolTracker.getDeferrableImportDecls();
return compileResults(fac, def, classMetadata, "\u0275cmp", inputTransformFields, deferrableImports, debugInfo);
}
locateDeferBlocksWithoutScope(template2) {
const deferBlocks = /* @__PURE__ */ new Map();
const directivelessBinder = new R3TargetBinder(new SelectorMatcher());
const bound = directivelessBinder.bind({ template: template2.nodes });
const deferredBlocks = bound.getDeferBlocks();
for (const block of deferredBlocks) {
deferBlocks.set(block, []);
}
return deferBlocks;
}
resolveAllDeferredDependencies(resolution) {
var _a2;
const deferrableTypes = [];
for (const [_, deps] of resolution.deferPerBlockDependencies) {
for (const deferBlockDep of deps) {
const importDecl = (_a2 = resolution.deferrableDeclToImportDecl.get(deferBlockDep.declaration.node)) != null ? _a2 : null;
if (importDecl !== null && this.deferredSymbolTracker.canDefer(importDecl)) {
deferBlockDep.isDeferrable = true;
deferBlockDep.importPath = importDecl.moduleSpecifier.text;
deferBlockDep.isDefaultImport = isDefaultImport(importDecl);
deferrableTypes.push(deferBlockDep);
}
}
}
return deferrableTypes;
}
collectExplicitlyDeferredSymbols(rawDeferredImports) {
const deferredTypes = /* @__PURE__ */ new Map();
if (!import_typescript88.default.isArrayLiteralExpression(rawDeferredImports)) {
return deferredTypes;
}
for (const element2 of rawDeferredImports.elements) {
const node = tryUnwrapForwardRef(element2, this.reflector) || element2;
if (!import_typescript88.default.isIdentifier(node)) {
continue;
}
const imp = this.reflector.getImportOfIdentifier(node);
if (imp !== null) {
deferredTypes.set(node, imp);
}
}
return deferredTypes;
}
_checkForCyclicImport(importedFile, expr, origin) {
const imported = resolveImportedFile(this.moduleResolver, importedFile, expr, origin);
if (imported === null) {
return null;
}
return this.cycleAnalyzer.wouldCreateCycle(origin, imported);
}
maybeRecordSyntheticImport(importedFile, expr, origin) {
const imported = resolveImportedFile(this.moduleResolver, importedFile, expr, origin);
if (imported === null) {
return;
}
this.cycleAnalyzer.recordSyntheticImport(origin, imported);
}
resolveDeferBlocks(componentClassDecl, deferBlocks, deferrableDecls, resolutionData, analysisData, eagerlyUsedDecls) {
const allDeferredDecls = /* @__PURE__ */ new Set();
for (const [deferBlock, bound] of deferBlocks) {
const usedDirectives = new Set(bound.getEagerlyUsedDirectives().map((d) => d.ref.node));
const usedPipes = new Set(bound.getEagerlyUsedPipes());
let deps;
if (resolutionData.deferPerBlockDependencies.has(deferBlock)) {
deps = resolutionData.deferPerBlockDependencies.get(deferBlock);
} else {
deps = [];
resolutionData.deferPerBlockDependencies.set(deferBlock, deps);
}
for (const decl of Array.from(deferrableDecls.values())) {
if (decl.kind === R3TemplateDependencyKind.NgModule) {
continue;
}
if (decl.kind === R3TemplateDependencyKind.Directive && !usedDirectives.has(decl.ref.node)) {
continue;
}
if (decl.kind === R3TemplateDependencyKind.Pipe && !usedPipes.has(decl.name)) {
continue;
}
deps.push({
typeReference: decl.type,
symbolName: decl.ref.node.name.text,
isDeferrable: false,
importPath: null,
isDefaultImport: false,
declaration: decl.ref
});
allDeferredDecls.add(decl.ref.node);
}
}
if (analysisData.meta.isStandalone) {
if (analysisData.rawImports !== null) {
this.registerDeferrableCandidates(componentClassDecl, analysisData.rawImports, false, allDeferredDecls, eagerlyUsedDecls, resolutionData);
}
if (analysisData.rawDeferredImports !== null) {
this.registerDeferrableCandidates(componentClassDecl, analysisData.rawDeferredImports, true, allDeferredDecls, eagerlyUsedDecls, resolutionData);
}
}
}
registerDeferrableCandidates(componentClassDecl, importsExpr, isDeferredImport, allDeferredDecls, eagerlyUsedDecls, resolutionData) {
if (!import_typescript88.default.isArrayLiteralExpression(importsExpr)) {
return;
}
for (const element2 of importsExpr.elements) {
const node = tryUnwrapForwardRef(element2, this.reflector) || element2;
if (!import_typescript88.default.isIdentifier(node)) {
continue;
}
const imp = this.reflector.getImportOfIdentifier(node);
if (imp === null) {
continue;
}
const decl = this.reflector.getDeclarationOfIdentifier(node);
if (decl === null) {
continue;
}
if (!isNamedClassDeclaration(decl.node)) {
continue;
}
if (!allDeferredDecls.has(decl.node)) {
continue;
}
if (eagerlyUsedDecls.has(decl.node)) {
continue;
}
const dirMeta = this.metaReader.getDirectiveMetadata(new Reference2(decl.node));
if (dirMeta !== null && !dirMeta.isStandalone) {
continue;
}
const pipeMeta = this.metaReader.getPipeMetadata(new Reference2(decl.node));
if (pipeMeta !== null && !pipeMeta.isStandalone) {
continue;
}
if (dirMeta === null && pipeMeta === null) {
continue;
}
resolutionData.deferrableDeclToImportDecl.set(decl.node, imp.node);
this.deferredSymbolTracker.markAsDeferrableCandidate(node, imp.node, componentClassDecl, isDeferredImport);
}
}
compileDeferBlocks(resolution) {
const { deferBlockDepsEmitMode: mode, deferPerBlockDependencies: perBlockDeps, deferPerComponentDependencies: perComponentDeps } = resolution;
if (mode === 0) {
if (!perBlockDeps) {
throw new Error("Internal error: deferPerBlockDependencies must be present when compiling in PerBlock mode");
}
const blocks = /* @__PURE__ */ new Map();
for (const [block, dependencies] of perBlockDeps) {
blocks.set(block, dependencies.length === 0 ? null : compileDeferResolverFunction({ mode, dependencies }));
}
return { mode, blocks };
}
if (mode === 1) {
if (!perComponentDeps) {
throw new Error("Internal error: deferPerComponentDependencies must be present in PerComponent mode");
}
return {
mode,
dependenciesFn: perComponentDeps.length === 0 ? null : compileDeferResolverFunction({ mode, dependencies: perComponentDeps })
};
}
throw new Error(`Invalid deferBlockDepsEmitMode. Cannot compile deferred block metadata.`);
}
};
function createTargetBinder(dependencies) {
const matcher = new SelectorMatcher();
for (const dep of dependencies) {
if (dep.kind === MetaKind.Directive && dep.selector !== null) {
matcher.addSelectables(CssSelector.parse(dep.selector), [dep]);
}
}
return new R3TargetBinder(matcher);
}
function getExplicitlyDeferredDeps(scope) {
return scope.kind === ComponentScopeKind.NgModule ? [] : scope.deferredDependencies;
}
function extractPipes(dependencies) {
const pipes = /* @__PURE__ */ new Map();
for (const dep of dependencies) {
if (dep.kind === MetaKind.Pipe) {
pipes.set(dep.name, dep);
}
}
return pipes;
}
function removeDeferrableTypesFromComponentDecorator(analysis, deferrableTypes) {
if (analysis.classMetadata) {
const deferrableSymbols = new Set(deferrableTypes.map((t) => t.symbolName));
const rewrittenDecoratorsNode = removeIdentifierReferences(analysis.classMetadata.decorators.node, deferrableSymbols);
analysis.classMetadata.decorators = new output_ast_exports.WrappedNodeExpr(rewrittenDecoratorsNode);
}
}
function validateNoImportOverlap(eagerDeps, deferredDeps, rawDeferredImports) {
let diagnostic = null;
const eagerDepsSet = /* @__PURE__ */ new Set();
for (const eagerDep of eagerDeps) {
eagerDepsSet.add(eagerDep.ref.node);
}
for (const deferredDep of deferredDeps) {
if (eagerDepsSet.has(deferredDep.ref.node)) {
const classInfo = deferredDep.ref.debugName ? `The \`${deferredDep.ref.debugName}\`` : "One of the dependencies";
diagnostic = makeDiagnostic(ErrorCode.DEFERRED_DEPENDENCY_IMPORTED_EAGERLY, getDiagnosticNode(deferredDep.ref, rawDeferredImports), `\`${classInfo}\` is imported via both \`@Component.imports\` and \`@Component.deferredImports\`. To fix this, make sure that dependencies are imported only once.`);
break;
}
}
return diagnostic;
}
function validateStandaloneImports(importRefs, importExpr2, metaReader, scopeReader, isDeferredImport) {
const diagnostics = [];
for (const ref of importRefs) {
const dirMeta = metaReader.getDirectiveMetadata(ref);
if (dirMeta !== null) {
if (!dirMeta.isStandalone) {
diagnostics.push(makeNotStandaloneDiagnostic(scopeReader, ref, importExpr2, dirMeta.isComponent ? "component" : "directive"));
}
continue;
}
const pipeMeta = metaReader.getPipeMetadata(ref);
if (pipeMeta !== null) {
if (!pipeMeta.isStandalone) {
diagnostics.push(makeNotStandaloneDiagnostic(scopeReader, ref, importExpr2, "pipe"));
}
continue;
}
const ngModuleMeta = metaReader.getNgModuleMetadata(ref);
if (!isDeferredImport && ngModuleMeta !== null) {
continue;
}
const error = isDeferredImport ? makeUnknownComponentDeferredImportDiagnostic(ref, importExpr2) : makeUnknownComponentImportDiagnostic(ref, importExpr2);
diagnostics.push(error);
}
return diagnostics;
}
function isDefaultImport(node) {
return node.importClause !== void 0 && node.importClause.namedBindings === void 0;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/src/injectable.mjs
var import_typescript90 = __toESM(require("typescript"), 1);
var InjectableDecoratorHandler = class {
constructor(reflector, evaluator, isCore, strictCtorDeps, injectableRegistry, perf, includeClassMetadata, compilationMode, errorOnDuplicateProv = true) {
this.reflector = reflector;
this.evaluator = evaluator;
this.isCore = isCore;
this.strictCtorDeps = strictCtorDeps;
this.injectableRegistry = injectableRegistry;
this.perf = perf;
this.includeClassMetadata = includeClassMetadata;
this.compilationMode = compilationMode;
this.errorOnDuplicateProv = errorOnDuplicateProv;
this.precedence = HandlerPrecedence.SHARED;
this.name = "InjectableDecoratorHandler";
}
detect(node, decorators) {
if (!decorators) {
return void 0;
}
const decorator = findAngularDecorator(decorators, "Injectable", this.isCore);
if (decorator !== void 0) {
return {
trigger: decorator.node,
decorator,
metadata: decorator
};
} else {
return void 0;
}
}
analyze(node, decorator) {
this.perf.eventCount(PerfEvent.AnalyzeInjectable);
const meta = extractInjectableMetadata(node, decorator, this.reflector);
const decorators = this.reflector.getDecoratorsOfDeclaration(node);
return {
analysis: {
meta,
ctorDeps: extractInjectableCtorDeps(node, meta, decorator, this.reflector, this.isCore, this.strictCtorDeps),
classMetadata: this.includeClassMetadata ? extractClassMetadata(node, this.reflector, this.isCore) : null,
needsFactory: !decorators || decorators.every((current) => !isAngularCore(current) || current.name === "Injectable")
}
};
}
symbol() {
return null;
}
register(node, analysis) {
if (this.compilationMode === CompilationMode.LOCAL) {
return;
}
this.injectableRegistry.registerInjectable(node, {
ctorDeps: analysis.ctorDeps
});
}
resolve(node, analysis) {
if (this.compilationMode === CompilationMode.LOCAL) {
return {};
}
if (requiresValidCtor(analysis.meta)) {
const diagnostic = checkInheritanceOfInjectable(node, this.injectableRegistry, this.reflector, this.evaluator, this.strictCtorDeps, "Injectable");
if (diagnostic !== null) {
return {
diagnostics: [diagnostic]
};
}
}
return {};
}
compileFull(node, analysis) {
return this.compile(compileNgFactoryDefField, (meta) => compileInjectable(meta, false), compileClassMetadata, node, analysis);
}
compilePartial(node, analysis) {
return this.compile(compileDeclareFactory, compileDeclareInjectableFromMetadata, compileDeclareClassMetadata, node, analysis);
}
compileLocal(node, analysis) {
return this.compile(compileNgFactoryDefField, (meta) => compileInjectable(meta, false), compileClassMetadata, node, analysis);
}
compile(compileFactoryFn, compileInjectableFn, compileClassMetadataFn, node, analysis) {
const results = [];
if (analysis.needsFactory) {
const meta = analysis.meta;
const factoryRes = compileFactoryFn(toFactoryMetadata(__spreadProps(__spreadValues({}, meta), { deps: analysis.ctorDeps }), FactoryTarget.Injectable));
if (analysis.classMetadata !== null) {
factoryRes.statements.push(compileClassMetadataFn(analysis.classMetadata).toStmt());
}
results.push(factoryRes);
}
const \u0275prov = this.reflector.getMembersOfClass(node).find((member) => member.name === "\u0275prov");
if (\u0275prov !== void 0 && this.errorOnDuplicateProv) {
throw new FatalDiagnosticError(ErrorCode.INJECTABLE_DUPLICATE_PROV, \u0275prov.nameNode || \u0275prov.node || node, "Injectables cannot contain a static \u0275prov property, because the compiler is going to generate one.");
}
if (\u0275prov === void 0) {
const res = compileInjectableFn(analysis.meta);
results.push({
name: "\u0275prov",
initializer: res.expression,
statements: res.statements,
type: res.type,
deferrableImports: null
});
}
return results;
}
};
function extractInjectableMetadata(clazz, decorator, reflector) {
const name = clazz.name.text;
const type = wrapTypeReference(reflector, clazz);
const typeArgumentCount = reflector.getGenericArityOfClass(clazz) || 0;
if (decorator.args === null) {
throw new FatalDiagnosticError(ErrorCode.DECORATOR_NOT_CALLED, decorator.node, "@Injectable must be called");
}
if (decorator.args.length === 0) {
return {
name,
type,
typeArgumentCount,
providedIn: createMayBeForwardRefExpression(new LiteralExpr(null), 0)
};
} else if (decorator.args.length === 1) {
const metaNode = decorator.args[0];
if (!import_typescript90.default.isObjectLiteralExpression(metaNode)) {
throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARG_NOT_LITERAL, metaNode, `@Injectable argument must be an object literal`);
}
const meta = reflectObjectLiteral(metaNode);
const providedIn = meta.has("providedIn") ? getProviderExpression(meta.get("providedIn"), reflector) : createMayBeForwardRefExpression(new LiteralExpr(null), 0);
let deps = void 0;
if ((meta.has("useClass") || meta.has("useFactory")) && meta.has("deps")) {
const depsExpr = meta.get("deps");
if (!import_typescript90.default.isArrayLiteralExpression(depsExpr)) {
throw new FatalDiagnosticError(ErrorCode.VALUE_NOT_LITERAL, depsExpr, `@Injectable deps metadata must be an inline array`);
}
deps = depsExpr.elements.map((dep) => getDep(dep, reflector));
}
const result = { name, type, typeArgumentCount, providedIn };
if (meta.has("useValue")) {
result.useValue = getProviderExpression(meta.get("useValue"), reflector);
} else if (meta.has("useExisting")) {
result.useExisting = getProviderExpression(meta.get("useExisting"), reflector);
} else if (meta.has("useClass")) {
result.useClass = getProviderExpression(meta.get("useClass"), reflector);
result.deps = deps;
} else if (meta.has("useFactory")) {
result.useFactory = new WrappedNodeExpr(meta.get("useFactory"));
result.deps = deps;
}
return result;
} else {
throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, decorator.args[2], "Too many arguments to @Injectable");
}
}
function getProviderExpression(expression, reflector) {
const forwardRefValue = tryUnwrapForwardRef(expression, reflector);
return createMayBeForwardRefExpression(new WrappedNodeExpr(forwardRefValue != null ? forwardRefValue : expression), forwardRefValue !== null ? 2 : 0);
}
function extractInjectableCtorDeps(clazz, meta, decorator, reflector, isCore, strictCtorDeps) {
if (decorator.args === null) {
throw new FatalDiagnosticError(ErrorCode.DECORATOR_NOT_CALLED, decorator.node, "@Injectable must be called");
}
let ctorDeps = null;
if (decorator.args.length === 0) {
if (strictCtorDeps && !isAbstractClassDeclaration(clazz)) {
ctorDeps = getValidConstructorDependencies(clazz, reflector, isCore);
} else {
ctorDeps = unwrapConstructorDependencies(getConstructorDependencies(clazz, reflector, isCore));
}
return ctorDeps;
} else if (decorator.args.length === 1) {
const rawCtorDeps = getConstructorDependencies(clazz, reflector, isCore);
if (strictCtorDeps && !isAbstractClassDeclaration(clazz) && requiresValidCtor(meta)) {
ctorDeps = validateConstructorDependencies(clazz, rawCtorDeps);
} else {
ctorDeps = unwrapConstructorDependencies(rawCtorDeps);
}
}
return ctorDeps;
}
function requiresValidCtor(meta) {
return meta.useValue === void 0 && meta.useExisting === void 0 && meta.useClass === void 0 && meta.useFactory === void 0;
}
function getDep(dep, reflector) {
const meta = {
token: new WrappedNodeExpr(dep),
attributeNameType: null,
host: false,
optional: false,
self: false,
skipSelf: false
};
function maybeUpdateDecorator(dec, reflector2, token) {
const source = reflector2.getImportOfIdentifier(dec);
if (source === null || source.from !== "@angular/core") {
return false;
}
switch (source.name) {
case "Inject":
if (token !== void 0) {
meta.token = new WrappedNodeExpr(token);
}
break;
case "Optional":
meta.optional = true;
break;
case "SkipSelf":
meta.skipSelf = true;
break;
case "Self":
meta.self = true;
break;
default:
return false;
}
return true;
}
if (import_typescript90.default.isArrayLiteralExpression(dep)) {
dep.elements.forEach((el) => {
let isDecorator = false;
if (import_typescript90.default.isIdentifier(el)) {
isDecorator = maybeUpdateDecorator(el, reflector);
} else if (import_typescript90.default.isNewExpression(el) && import_typescript90.default.isIdentifier(el.expression)) {
const token = el.arguments && el.arguments.length > 0 && el.arguments[0] || void 0;
isDecorator = maybeUpdateDecorator(el.expression, reflector, token);
}
if (!isDecorator) {
meta.token = new WrappedNodeExpr(el);
}
});
}
return meta;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/src/pipe.mjs
var import_typescript91 = __toESM(require("typescript"), 1);
var PipeSymbol = class extends SemanticSymbol {
constructor(decl, name) {
super(decl);
this.name = name;
}
isPublicApiAffected(previousSymbol) {
if (!(previousSymbol instanceof PipeSymbol)) {
return true;
}
return this.name !== previousSymbol.name;
}
isTypeCheckApiAffected(previousSymbol) {
return this.isPublicApiAffected(previousSymbol);
}
};
var PipeDecoratorHandler = class {
constructor(reflector, evaluator, metaRegistry, scopeRegistry, injectableRegistry, isCore, perf, includeClassMetadata, compilationMode, generateExtraImportsInLocalMode) {
this.reflector = reflector;
this.evaluator = evaluator;
this.metaRegistry = metaRegistry;
this.scopeRegistry = scopeRegistry;
this.injectableRegistry = injectableRegistry;
this.isCore = isCore;
this.perf = perf;
this.includeClassMetadata = includeClassMetadata;
this.compilationMode = compilationMode;
this.generateExtraImportsInLocalMode = generateExtraImportsInLocalMode;
this.precedence = HandlerPrecedence.PRIMARY;
this.name = "PipeDecoratorHandler";
}
detect(node, decorators) {
if (!decorators) {
return void 0;
}
const decorator = findAngularDecorator(decorators, "Pipe", this.isCore);
if (decorator !== void 0) {
return {
trigger: decorator.node,
decorator,
metadata: decorator
};
} else {
return void 0;
}
}
analyze(clazz, decorator) {
var _a2;
this.perf.eventCount(PerfEvent.AnalyzePipe);
const name = clazz.name.text;
const type = wrapTypeReference(this.reflector, clazz);
if (decorator.args === null) {
throw new FatalDiagnosticError(ErrorCode.DECORATOR_NOT_CALLED, decorator.node, `@Pipe must be called`);
}
if (decorator.args.length !== 1) {
throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, decorator.node, "@Pipe must have exactly one argument");
}
const meta = unwrapExpression(decorator.args[0]);
if (!import_typescript91.default.isObjectLiteralExpression(meta)) {
throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARG_NOT_LITERAL, meta, "@Pipe must have a literal argument");
}
const pipe2 = reflectObjectLiteral(meta);
if (!pipe2.has("name")) {
throw new FatalDiagnosticError(ErrorCode.PIPE_MISSING_NAME, meta, `@Pipe decorator is missing name field`);
}
const pipeNameExpr = pipe2.get("name");
const pipeName = this.evaluator.evaluate(pipeNameExpr);
if (typeof pipeName !== "string") {
throw createValueHasWrongTypeError(pipeNameExpr, pipeName, `@Pipe.name must be a string`);
}
let pure = true;
if (pipe2.has("pure")) {
const expr = pipe2.get("pure");
const pureValue = this.evaluator.evaluate(expr);
if (typeof pureValue !== "boolean") {
throw createValueHasWrongTypeError(expr, pureValue, `@Pipe.pure must be a boolean`);
}
pure = pureValue;
}
let isStandalone = false;
if (pipe2.has("standalone")) {
const expr = pipe2.get("standalone");
const resolved = this.evaluator.evaluate(expr);
if (typeof resolved !== "boolean") {
throw createValueHasWrongTypeError(expr, resolved, `standalone flag must be a boolean`);
}
isStandalone = resolved;
}
return {
analysis: {
meta: {
name,
type,
typeArgumentCount: this.reflector.getGenericArityOfClass(clazz) || 0,
pipeName,
deps: getValidConstructorDependencies(clazz, this.reflector, this.isCore),
pure,
isStandalone
},
classMetadata: this.includeClassMetadata ? extractClassMetadata(clazz, this.reflector, this.isCore) : null,
pipeNameExpr,
decorator: (_a2 = decorator == null ? void 0 : decorator.node) != null ? _a2 : null
}
};
}
symbol(node, analysis) {
return new PipeSymbol(node, analysis.meta.pipeName);
}
register(node, analysis) {
const ref = new Reference2(node);
this.metaRegistry.registerPipeMetadata({
kind: MetaKind.Pipe,
ref,
name: analysis.meta.pipeName,
nameExpr: analysis.pipeNameExpr,
isStandalone: analysis.meta.isStandalone,
decorator: analysis.decorator,
isExplicitlyDeferred: false
});
this.injectableRegistry.registerInjectable(node, {
ctorDeps: analysis.meta.deps
});
}
resolve(node) {
if (this.compilationMode === CompilationMode.LOCAL) {
return {};
}
const duplicateDeclData = this.scopeRegistry.getDuplicateDeclarations(node);
if (duplicateDeclData !== null) {
return {
diagnostics: [makeDuplicateDeclarationError(node, duplicateDeclData, "Pipe")]
};
}
return {};
}
compileFull(node, analysis) {
const fac = compileNgFactoryDefField(toFactoryMetadata(analysis.meta, FactoryTarget.Pipe));
const def = compilePipeFromMetadata(analysis.meta);
const classMetadata = analysis.classMetadata !== null ? compileClassMetadata(analysis.classMetadata).toStmt() : null;
return compileResults(fac, def, classMetadata, "\u0275pipe", null, null);
}
compilePartial(node, analysis) {
const fac = compileDeclareFactory(toFactoryMetadata(analysis.meta, FactoryTarget.Pipe));
const def = compileDeclarePipeFromMetadata(analysis.meta);
const classMetadata = analysis.classMetadata !== null ? compileDeclareClassMetadata(analysis.classMetadata).toStmt() : null;
return compileResults(fac, def, classMetadata, "\u0275pipe", null, null);
}
compileLocal(node, analysis) {
const fac = compileNgFactoryDefField(toFactoryMetadata(analysis.meta, FactoryTarget.Pipe));
const def = compilePipeFromMetadata(analysis.meta);
const classMetadata = analysis.classMetadata !== null ? compileClassMetadata(analysis.classMetadata).toStmt() : null;
return compileResults(fac, def, classMetadata, "\u0275pipe", null, null);
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/transform/jit/src/initializer_api_transforms/transform_api.mjs
var import_typescript92 = __toESM(require("typescript"), 1);
function createSyntheticAngularCoreDecoratorAccess(factory11, importManager, ngClassDecorator, sourceFile, decoratorName) {
const classDecoratorIdentifier = import_typescript92.default.isIdentifier(ngClassDecorator.identifier) ? ngClassDecorator.identifier : ngClassDecorator.identifier.expression;
return factory11.createPropertyAccessExpression(
importManager.addImport({
exportModuleSpecifier: "@angular/core",
exportSymbolName: null,
requestedFile: sourceFile
}),
import_typescript92.default.setOriginalNode(factory11.createIdentifier(decoratorName), classDecoratorIdentifier)
);
}
function castAsAny(factory11, expr) {
return factory11.createAsExpression(expr, factory11.createKeywordTypeNode(import_typescript92.default.SyntaxKind.AnyKeyword));
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/transform/jit/src/initializer_api_transforms/input_function.mjs
var signalInputsTransform = (member, sourceFile, host, factory11, importTracker, importManager, classDecorator, isCore) => {
var _a2, _b2;
if ((_a2 = host.getDecoratorsOfDeclaration(member.node)) == null ? void 0 : _a2.some((d) => isAngularDecorator2(d, "Input", isCore))) {
return member.node;
}
const inputMapping = tryParseSignalInputMapping(member, host, importTracker);
if (inputMapping === null) {
return member.node;
}
const fields = {
"isSignal": factory11.createTrue(),
"alias": factory11.createStringLiteral(inputMapping.bindingPropertyName),
"required": inputMapping.required ? factory11.createTrue() : factory11.createFalse(),
"transform": factory11.createIdentifier("undefined")
};
const newDecorator = factory11.createDecorator(factory11.createCallExpression(createSyntheticAngularCoreDecoratorAccess(factory11, importManager, classDecorator, sourceFile, "Input"), void 0, [
castAsAny(factory11, factory11.createObjectLiteralExpression(Object.entries(fields).map(([name, value]) => factory11.createPropertyAssignment(name, value))))
]));
return factory11.updatePropertyDeclaration(member.node, [newDecorator, ...(_b2 = member.node.modifiers) != null ? _b2 : []], member.name, member.node.questionToken, member.node.type, member.node.initializer);
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/transform/jit/src/initializer_api_transforms/model_function.mjs
var import_typescript93 = __toESM(require("typescript"), 1);
var signalModelTransform = (member, sourceFile, host, factory11, importTracker, importManager, classDecorator, isCore) => {
var _a2, _b2;
if ((_a2 = host.getDecoratorsOfDeclaration(member.node)) == null ? void 0 : _a2.some((d) => {
return isAngularDecorator2(d, "Input", isCore) || isAngularDecorator2(d, "Output", isCore);
})) {
return member.node;
}
const modelMapping = tryParseSignalModelMapping(member, host, importTracker);
if (modelMapping === null) {
return member.node;
}
const inputConfig = factory11.createObjectLiteralExpression([
factory11.createPropertyAssignment("isSignal", modelMapping.input.isSignal ? factory11.createTrue() : factory11.createFalse()),
factory11.createPropertyAssignment("alias", factory11.createStringLiteral(modelMapping.input.bindingPropertyName)),
factory11.createPropertyAssignment("required", modelMapping.input.required ? factory11.createTrue() : factory11.createFalse())
]);
const inputDecorator = createDecorator(
"Input",
factory11.createAsExpression(inputConfig, factory11.createKeywordTypeNode(import_typescript93.default.SyntaxKind.AnyKeyword)),
classDecorator,
factory11,
sourceFile,
importManager
);
const outputDecorator = createDecorator("Output", factory11.createStringLiteral(modelMapping.output.bindingPropertyName), classDecorator, factory11, sourceFile, importManager);
return factory11.updatePropertyDeclaration(member.node, [inputDecorator, outputDecorator, ...(_b2 = member.node.modifiers) != null ? _b2 : []], member.node.name, member.node.questionToken, member.node.type, member.node.initializer);
};
function createDecorator(name, config, classDecorator, factory11, sourceFile, importManager) {
const callTarget = createSyntheticAngularCoreDecoratorAccess(factory11, importManager, classDecorator, sourceFile, name);
return factory11.createDecorator(factory11.createCallExpression(callTarget, void 0, [config]));
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/transform/jit/src/initializer_api_transforms/output_function.mjs
var initializerApiOutputTransform = (member, sourceFile, host, factory11, importTracker, importManager, classDecorator, isCore) => {
var _a2, _b2;
if ((_a2 = host.getDecoratorsOfDeclaration(member.node)) == null ? void 0 : _a2.some((d) => isAngularDecorator2(d, "Output", isCore))) {
return member.node;
}
const output = tryParseInitializerBasedOutput(member, host, importTracker);
if (output === null) {
return member.node;
}
const newDecorator = factory11.createDecorator(factory11.createCallExpression(createSyntheticAngularCoreDecoratorAccess(factory11, importManager, classDecorator, sourceFile, "Output"), void 0, [factory11.createStringLiteral(output.metadata.bindingPropertyName)]));
return factory11.updatePropertyDeclaration(member.node, [newDecorator, ...(_b2 = member.node.modifiers) != null ? _b2 : []], member.node.name, member.node.questionToken, member.node.type, member.node.initializer);
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/transform/jit/src/initializer_api_transforms/query_functions.mjs
var queryFunctionToDecorator = {
viewChild: "ViewChild",
viewChildren: "ViewChildren",
contentChild: "ContentChild",
contentChildren: "ContentChildren"
};
var queryFunctionsTransforms = (member, sourceFile, host, factory11, importTracker, importManager, classDecorator, isCore) => {
var _a2;
const decorators = host.getDecoratorsOfDeclaration(member.node);
const queryDecorators = decorators && getAngularDecorators(decorators, queryDecoratorNames, isCore);
if (queryDecorators !== null && queryDecorators.length > 0) {
return member.node;
}
const queryDefinition = tryParseSignalQueryFromInitializer(member, host, importTracker);
if (queryDefinition === null) {
return member.node;
}
const callArgs = queryDefinition.call.arguments;
const newDecorator = factory11.createDecorator(factory11.createCallExpression(
createSyntheticAngularCoreDecoratorAccess(factory11, importManager, classDecorator, sourceFile, queryFunctionToDecorator[queryDefinition.name]),
void 0,
[
queryDefinition.call.arguments[0],
castAsAny(factory11, factory11.createObjectLiteralExpression([
...callArgs.length > 1 ? [factory11.createSpreadAssignment(callArgs[1])] : [],
factory11.createPropertyAssignment("isSignal", factory11.createTrue())
]))
]
));
return factory11.updatePropertyDeclaration(member.node, [newDecorator, ...(_a2 = member.node.modifiers) != null ? _a2 : []], member.node.name, member.node.questionToken, member.node.type, member.node.initializer);
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/transform/jit/src/initializer_api_transforms/transform.mjs
var decoratorsWithInputs = ["Directive", "Component"];
var propertyTransforms = [
signalInputsTransform,
initializerApiOutputTransform,
queryFunctionsTransforms,
signalModelTransform
];
function getInitializerApiJitTransform(host, importTracker, isCore, shouldTransformClass) {
return (ctx) => {
return (sourceFile) => {
const importManager = new ImportManager();
sourceFile = import_typescript94.default.visitNode(sourceFile, createTransformVisitor(ctx, host, importManager, importTracker, isCore, shouldTransformClass), import_typescript94.default.isSourceFile);
return importManager.transformTsFile(ctx, sourceFile);
};
};
}
function createTransformVisitor(ctx, host, importManager, importTracker, isCore, shouldTransformClass) {
const visitor = (node) => {
var _a2;
if (import_typescript94.default.isClassDeclaration(node) && node.name !== void 0) {
const originalNode = import_typescript94.default.getOriginalNode(node, import_typescript94.default.isClassDeclaration);
const angularDecorator = (_a2 = host.getDecoratorsOfDeclaration(originalNode)) == null ? void 0 : _a2.find((d) => decoratorsWithInputs.some((name) => isAngularDecorator2(d, name, isCore)));
if (angularDecorator !== void 0 && (shouldTransformClass === void 0 || shouldTransformClass(node))) {
let hasChanged = false;
const sourceFile = originalNode.getSourceFile();
const members = node.members.map((memberNode) => {
if (!import_typescript94.default.isPropertyDeclaration(memberNode)) {
return memberNode;
}
const member = reflectClassMember(memberNode);
if (member === null) {
return memberNode;
}
for (const transform2 of propertyTransforms) {
const newNode = transform2(__spreadProps(__spreadValues({}, member), { node: memberNode }), sourceFile, host, ctx.factory, importTracker, importManager, angularDecorator, isCore);
if (newNode !== member.node) {
hasChanged = true;
return newNode;
}
}
return memberNode;
});
if (hasChanged) {
return ctx.factory.updateClassDeclaration(node, node.modifiers, node.name, node.typeParameters, node.heritageClauses, members);
}
}
}
return import_typescript94.default.visitEachChild(node, visitor, ctx);
};
return visitor;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/transform/jit/src/index.mjs
function angularJitApplicationTransform(program, isCore = false, shouldTransformClass) {
const typeChecker = program.getTypeChecker();
const reflectionHost = new TypeScriptReflectionHost(typeChecker);
const importTracker = new ImportedSymbolsTracker();
const downlevelDecoratorTransform = getDownlevelDecoratorsTransform(
typeChecker,
reflectionHost,
[],
isCore,
false,
shouldTransformClass
);
const initializerApisJitTransform = getInitializerApiJitTransform(reflectionHost, importTracker, isCore, shouldTransformClass);
return (ctx) => {
return (sourceFile) => {
sourceFile = initializerApisJitTransform(ctx)(sourceFile);
sourceFile = downlevelDecoratorTransform(ctx)(sourceFile);
return sourceFile;
};
};
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/transformers/api.mjs
var EmitFlags;
(function(EmitFlags2) {
EmitFlags2[EmitFlags2["DTS"] = 1] = "DTS";
EmitFlags2[EmitFlags2["JS"] = 2] = "JS";
EmitFlags2[EmitFlags2["Metadata"] = 4] = "Metadata";
EmitFlags2[EmitFlags2["I18nBundle"] = 8] = "I18nBundle";
EmitFlags2[EmitFlags2["Codegen"] = 16] = "Codegen";
EmitFlags2[EmitFlags2["Default"] = 19] = "Default";
EmitFlags2[EmitFlags2["All"] = 31] = "All";
})(EmitFlags || (EmitFlags = {}));
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/transformers/compiler_host.mjs
var import_typescript96 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/program.mjs
var import_typescript124 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/transformers/i18n.mjs
var path2 = __toESM(require("path"), 1);
function i18nGetExtension(formatName) {
const format = formatName.toLowerCase();
switch (format) {
case "xmb":
return "xmb";
case "xlf":
case "xlif":
case "xliff":
case "xlf2":
case "xliff2":
return "xlf";
}
throw new Error(`Unsupported format "${formatName}"`);
}
function i18nExtract(formatName, outFile, host, options, bundle, pathResolve = path2.resolve) {
formatName = formatName || "xlf";
const ext = i18nGetExtension(formatName);
const content = i18nSerialize(bundle, formatName, options);
const dstFile = outFile || `messages.${ext}`;
const dstPath = pathResolve(options.outDir || options.basePath, dstFile);
host.writeFile(dstPath, content, false, void 0, []);
return [dstPath];
}
function i18nSerialize(bundle, formatName, options) {
const format = formatName.toLowerCase();
let serializer2;
switch (format) {
case "xmb":
serializer2 = new Xmb(
options.i18nPreserveWhitespaceForLegacyExtraction
);
break;
case "xliff2":
case "xlf2":
serializer2 = new Xliff2();
break;
case "xlf":
case "xliff":
default:
serializer2 = new Xliff();
}
return bundle.write(serializer2, getPathNormalizer(options.basePath));
}
function getPathNormalizer(basePath) {
return (sourcePath) => {
sourcePath = basePath ? path2.relative(basePath, sourcePath) : sourcePath;
return sourcePath.split(path2.sep).join("/");
};
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/typescript_support.mjs
var import_typescript97 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/version_helpers.mjs
function toNumbers(value) {
const suffixIndex = value.lastIndexOf("-");
return value.slice(0, suffixIndex === -1 ? value.length : suffixIndex).split(".").map((segment) => {
const parsed = parseInt(segment, 10);
if (isNaN(parsed)) {
throw Error(`Unable to parse version string ${value}.`);
}
return parsed;
});
}
function compareNumbers(a, b) {
const max = Math.max(a.length, b.length);
const min = Math.min(a.length, b.length);
for (let i = 0; i < min; i++) {
if (a[i] > b[i])
return 1;
if (a[i] < b[i])
return -1;
}
if (min !== max) {
const longestArray = a.length === max ? a : b;
const comparisonResult = a.length === max ? 1 : -1;
for (let i = min; i < max; i++) {
if (longestArray[i] > 0) {
return comparisonResult;
}
}
}
return 0;
}
function compareVersions(v1, v2) {
return compareNumbers(toNumbers(v1), toNumbers(v2));
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/typescript_support.mjs
var MIN_TS_VERSION = "5.4.0";
var MAX_TS_VERSION = "5.6.0";
var tsVersion = import_typescript97.default.version;
function checkVersion(version, minVersion, maxVersion) {
if (compareVersions(version, minVersion) < 0 || compareVersions(version, maxVersion) >= 0) {
throw new Error(`The Angular Compiler requires TypeScript >=${minVersion} and <${maxVersion} but ${version} was found instead.`);
}
}
function verifySupportedTypeScriptVersion() {
checkVersion(tsVersion, MIN_TS_VERSION, MAX_TS_VERSION);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/core/src/compiler.mjs
var import_typescript120 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/cycles/src/analyzer.mjs
var CycleAnalyzer = class {
constructor(importGraph) {
this.importGraph = importGraph;
this.cachedResults = null;
}
wouldCreateCycle(from, to) {
if (this.cachedResults === null || this.cachedResults.from !== from) {
this.cachedResults = new CycleResults(from, this.importGraph);
}
return this.cachedResults.wouldBeCyclic(to) ? new Cycle(this.importGraph, from, to) : null;
}
recordSyntheticImport(from, to) {
this.cachedResults = null;
this.importGraph.addSyntheticImport(from, to);
}
};
var NgCyclicResult = Symbol("NgCyclicResult");
var CycleResults = class {
constructor(from, importGraph) {
this.from = from;
this.importGraph = importGraph;
this.cyclic = {};
this.acyclic = {};
}
wouldBeCyclic(sf) {
const cached = this.getCachedResult(sf);
if (cached !== null) {
return cached;
}
if (sf === this.from) {
return true;
}
this.markAcyclic(sf);
const imports = this.importGraph.importsOf(sf);
for (const imported of imports) {
if (this.wouldBeCyclic(imported)) {
this.markCyclic(sf);
return true;
}
}
return false;
}
getCachedResult(sf) {
const result = sf[NgCyclicResult];
if (result === this.cyclic) {
return true;
} else if (result === this.acyclic) {
return false;
} else {
return null;
}
}
markCyclic(sf) {
sf[NgCyclicResult] = this.cyclic;
}
markAcyclic(sf) {
sf[NgCyclicResult] = this.acyclic;
}
};
var Cycle = class {
constructor(importGraph, from, to) {
this.importGraph = importGraph;
this.from = from;
this.to = to;
}
getPath() {
return [this.from, ...this.importGraph.findPath(this.to, this.from)];
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/cycles/src/imports.mjs
var import_typescript98 = __toESM(require("typescript"), 1);
var ImportGraph = class {
constructor(checker, perf) {
this.checker = checker;
this.perf = perf;
this.imports = /* @__PURE__ */ new Map();
}
importsOf(sf) {
if (!this.imports.has(sf)) {
this.imports.set(sf, this.scanImports(sf));
}
return this.imports.get(sf);
}
findPath(start, end) {
if (start === end) {
return [start];
}
const found = /* @__PURE__ */ new Set([start]);
const queue = [new Found(start, null)];
while (queue.length > 0) {
const current = queue.shift();
const imports = this.importsOf(current.sourceFile);
for (const importedFile of imports) {
if (!found.has(importedFile)) {
const next = new Found(importedFile, current);
if (next.sourceFile === end) {
return next.toPath();
}
found.add(importedFile);
queue.push(next);
}
}
}
return null;
}
addSyntheticImport(sf, imported) {
if (isLocalFile(imported)) {
this.importsOf(sf).add(imported);
}
}
scanImports(sf) {
return this.perf.inPhase(PerfPhase.CycleDetection, () => {
const imports = /* @__PURE__ */ new Set();
for (const stmt of sf.statements) {
if (!import_typescript98.default.isImportDeclaration(stmt) && !import_typescript98.default.isExportDeclaration(stmt) || stmt.moduleSpecifier === void 0) {
continue;
}
if (import_typescript98.default.isImportDeclaration(stmt) && stmt.importClause !== void 0 && isTypeOnlyImportClause(stmt.importClause)) {
continue;
}
const symbol = this.checker.getSymbolAtLocation(stmt.moduleSpecifier);
if (symbol === void 0 || symbol.valueDeclaration === void 0) {
continue;
}
const moduleFile = symbol.valueDeclaration;
if (import_typescript98.default.isSourceFile(moduleFile) && isLocalFile(moduleFile)) {
imports.add(moduleFile);
}
}
return imports;
});
}
};
function isLocalFile(sf) {
return !sf.isDeclarationFile;
}
function isTypeOnlyImportClause(node) {
if (node.isTypeOnly) {
return true;
}
if (node.namedBindings !== void 0 && import_typescript98.default.isNamedImports(node.namedBindings) && node.namedBindings.elements.every((specifier) => specifier.isTypeOnly)) {
return true;
}
return false;
}
var Found = class {
constructor(sourceFile, parent) {
this.sourceFile = sourceFile;
this.parent = parent;
}
toPath() {
const array = [];
let current = this;
while (current !== null) {
array.push(current.sourceFile);
current = current.parent;
}
return array.reverse();
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/docs/src/extractor.mjs
var import_typescript108 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/docs/src/class_extractor.mjs
var import_typescript102 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/docs/src/entities.mjs
var EntryType;
(function(EntryType2) {
EntryType2["Block"] = "block";
EntryType2["Component"] = "component";
EntryType2["Constant"] = "constant";
EntryType2["Decorator"] = "decorator";
EntryType2["Directive"] = "directive";
EntryType2["Element"] = "element";
EntryType2["Enum"] = "enum";
EntryType2["Function"] = "function";
EntryType2["Interface"] = "interface";
EntryType2["NgModule"] = "ng_module";
EntryType2["Pipe"] = "pipe";
EntryType2["TypeAlias"] = "type_alias";
EntryType2["UndecoratedClass"] = "undecorated_class";
EntryType2["InitializerApiFunction"] = "initializer_api_function";
})(EntryType || (EntryType = {}));
var MemberType;
(function(MemberType2) {
MemberType2["Property"] = "property";
MemberType2["Method"] = "method";
MemberType2["Getter"] = "getter";
MemberType2["Setter"] = "setter";
MemberType2["EnumItem"] = "enum_item";
})(MemberType || (MemberType = {}));
var DecoratorType;
(function(DecoratorType2) {
DecoratorType2["Class"] = "class";
DecoratorType2["Member"] = "member";
DecoratorType2["Parameter"] = "parameter";
})(DecoratorType || (DecoratorType = {}));
var MemberTags;
(function(MemberTags2) {
MemberTags2["Abstract"] = "abstract";
MemberTags2["Static"] = "static";
MemberTags2["Readonly"] = "readonly";
MemberTags2["Protected"] = "protected";
MemberTags2["Optional"] = "optional";
MemberTags2["Input"] = "input";
MemberTags2["Output"] = "output";
MemberTags2["Inherited"] = "override";
})(MemberTags || (MemberTags = {}));
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/docs/src/filters.mjs
function isAngularPrivateName(name) {
var _a2;
const firstChar = (_a2 = name[0]) != null ? _a2 : "";
return firstChar === "\u0275" || firstChar === "_";
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/docs/src/function_extractor.mjs
var import_typescript100 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/docs/src/generics_extractor.mjs
function extractGenerics(declaration) {
var _a2, _b2;
return (_b2 = (_a2 = declaration.typeParameters) == null ? void 0 : _a2.map((typeParam) => {
var _a3, _b3;
return {
name: typeParam.name.getText(),
constraint: (_a3 = typeParam.constraint) == null ? void 0 : _a3.getText(),
default: (_b3 = typeParam.default) == null ? void 0 : _b3.getText()
};
})) != null ? _b2 : [];
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/docs/src/jsdoc_extractor.mjs
var import_typescript99 = __toESM(require("typescript"), 1);
var decoratorExpression = /@(?=(Injectable|Component|Directive|Pipe|NgModule|Input|Output|HostBinding|HostListener|Inject|Optional|Self|Host|SkipSelf|ViewChild|ViewChildren|ContentChild|ContentChildren))/g;
function extractJsDocTags(node) {
const escapedNode = getEscapedNode(node);
return import_typescript99.default.getJSDocTags(escapedNode).map((t) => {
var _a2;
return {
name: t.tagName.getText(),
comment: unescapeAngularDecorators((_a2 = import_typescript99.default.getTextOfJSDocComment(t.comment)) != null ? _a2 : "")
};
});
}
function extractJsDocDescription(node) {
var _a2, _b2;
const escapedNode = getEscapedNode(node);
const commentOrTag = import_typescript99.default.getJSDocCommentsAndTags(escapedNode).find((d) => {
return import_typescript99.default.isJSDoc(d) || import_typescript99.default.isJSDocParameterTag(d);
});
const comment = (_a2 = commentOrTag == null ? void 0 : commentOrTag.comment) != null ? _a2 : "";
const description = typeof comment === "string" ? comment : (_b2 = import_typescript99.default.getTextOfJSDocComment(comment)) != null ? _b2 : "";
return unescapeAngularDecorators(description);
}
function extractRawJsDoc(node) {
var _a2, _b2;
const comment = (_b2 = (_a2 = import_typescript99.default.getJSDocCommentsAndTags(node).find(import_typescript99.default.isJSDoc)) == null ? void 0 : _a2.getFullText()) != null ? _b2 : "";
return unescapeAngularDecorators(comment);
}
function getEscapedNode(node) {
if (import_typescript99.default.isParameter(node)) {
return node;
}
const rawComment = extractRawJsDoc(node);
const escaped = escapeAngularDecorators(rawComment);
const file = import_typescript99.default.createSourceFile("x.ts", `${escaped}class X {}`, import_typescript99.default.ScriptTarget.ES2020, true);
return file.statements.find((s) => import_typescript99.default.isClassDeclaration(s));
}
function escapeAngularDecorators(comment) {
return comment.replace(decoratorExpression, "_NG_AT_");
}
function unescapeAngularDecorators(comment) {
return comment.replace(/_NG_AT_/g, "@");
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/docs/src/type_extractor.mjs
function extractResolvedTypeString(node, checker) {
return checker.typeToString(checker.getTypeAtLocation(node));
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/docs/src/function_extractor.mjs
var FunctionExtractor = class {
constructor(name, exportDeclaration, typeChecker) {
this.name = name;
this.exportDeclaration = exportDeclaration;
this.typeChecker = typeChecker;
}
extract() {
var _a2, _b2;
const signature = this.typeChecker.getSignatureFromDeclaration(this.exportDeclaration);
const returnType = signature ? this.typeChecker.typeToString(
this.typeChecker.getReturnTypeOfSignature(signature),
void 0,
import_typescript100.default.TypeFormatFlags.NoTypeReduction | import_typescript100.default.TypeFormatFlags.NoTruncation
) : "unknown";
const implementation = (_a2 = findImplementationOfFunction(this.exportDeclaration, this.typeChecker)) != null ? _a2 : this.exportDeclaration;
const type = this.typeChecker.getTypeAtLocation(this.exportDeclaration);
const overloads = extractCallSignatures(this.name, this.typeChecker, type);
const jsdocsTags = extractJsDocTags(implementation);
const description = extractJsDocDescription(implementation);
return {
name: this.name,
signatures: overloads,
implementation: {
params: extractAllParams(implementation.parameters, this.typeChecker),
isNewType: import_typescript100.default.isConstructSignatureDeclaration(implementation),
returnType,
returnDescription: (_b2 = jsdocsTags.find((tag) => tag.name === "returns")) == null ? void 0 : _b2.comment,
generics: extractGenerics(implementation),
name: this.name,
description,
entryType: EntryType.Function,
jsdocTags: jsdocsTags,
rawComment: extractRawJsDoc(implementation)
},
entryType: EntryType.Function,
description,
jsdocTags: jsdocsTags,
rawComment: extractRawJsDoc(implementation)
};
}
};
function extractAllParams(params, typeChecker) {
return params.map((param) => ({
name: param.name.getText(),
description: extractJsDocDescription(param),
type: extractResolvedTypeString(param, typeChecker),
isOptional: !!(param.questionToken || param.initializer),
isRestParam: !!param.dotDotDotToken
}));
}
function filterSignatureDeclarations(signatures) {
const result = [];
for (const signature of signatures) {
const decl = signature.getDeclaration();
if (import_typescript100.default.isFunctionDeclaration(decl) || import_typescript100.default.isCallSignatureDeclaration(decl) || import_typescript100.default.isMethodDeclaration(decl)) {
result.push({ signature, decl });
}
}
return result;
}
function extractCallSignatures(name, typeChecker, type) {
return filterSignatureDeclarations(type.getCallSignatures()).map(({ decl, signature }) => ({
name,
entryType: EntryType.Function,
description: extractJsDocDescription(decl),
generics: extractGenerics(decl),
isNewType: false,
jsdocTags: extractJsDocTags(decl),
params: extractAllParams(decl.parameters, typeChecker),
rawComment: extractRawJsDoc(decl),
returnType: typeChecker.typeToString(
typeChecker.getReturnTypeOfSignature(signature),
void 0,
import_typescript100.default.TypeFormatFlags.NoTypeReduction | import_typescript100.default.TypeFormatFlags.NoTruncation
)
}));
}
function findImplementationOfFunction(node, typeChecker) {
var _a2;
if (node.body !== void 0 || node.name === void 0) {
return node;
}
const symbol = typeChecker.getSymbolAtLocation(node.name);
const implementation = (_a2 = symbol == null ? void 0 : symbol.declarations) == null ? void 0 : _a2.find((s) => import_typescript100.default.isFunctionDeclaration(s) && s.body !== void 0);
return implementation;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/docs/src/internal.mjs
var import_typescript101 = __toESM(require("typescript"), 1);
function isInternal(member) {
return extractJsDocTags(member).some((tag) => tag.name === "internal") || hasLeadingInternalComment(member);
}
function hasLeadingInternalComment(member) {
var _a2;
const memberText = member.getSourceFile().text;
return (_a2 = import_typescript101.default.reduceEachLeadingCommentRange(
memberText,
member.getFullStart(),
(pos, end, kind, hasTrailingNewLine, containsInternal) => {
return containsInternal || memberText.slice(pos, end).includes("@internal");
},
false,
false
)) != null ? _a2 : false;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/docs/src/class_extractor.mjs
var ClassExtractor = class {
constructor(declaration, typeChecker) {
this.declaration = declaration;
this.typeChecker = typeChecker;
}
extract() {
return {
name: this.declaration.name.text,
isAbstract: this.isAbstract(),
entryType: import_typescript102.default.isInterfaceDeclaration(this.declaration) ? EntryType.Interface : EntryType.UndecoratedClass,
members: this.extractSignatures().concat(this.extractAllClassMembers()),
generics: extractGenerics(this.declaration),
description: extractJsDocDescription(this.declaration),
jsdocTags: extractJsDocTags(this.declaration),
rawComment: extractRawJsDoc(this.declaration),
extends: this.extractInheritance(this.declaration),
implements: this.extractInterfaceConformance(this.declaration)
};
}
extractAllClassMembers() {
const members = [];
for (const member of this.getMemberDeclarations()) {
if (this.isMemberExcluded(member))
continue;
const memberEntry = this.extractClassMember(member);
if (memberEntry) {
members.push(memberEntry);
}
}
return members;
}
extractClassMember(memberDeclaration) {
if (this.isMethod(memberDeclaration)) {
return this.extractMethod(memberDeclaration);
} else if (this.isProperty(memberDeclaration)) {
return this.extractClassProperty(memberDeclaration);
} else if (import_typescript102.default.isAccessor(memberDeclaration)) {
return this.extractGetterSetter(memberDeclaration);
}
return void 0;
}
extractSignatures() {
return this.computeAllSignatureDeclarations().map((s) => this.extractSignature(s));
}
extractMethod(methodDeclaration) {
const functionExtractor = new FunctionExtractor(methodDeclaration.name.getText(), methodDeclaration, this.typeChecker);
return __spreadProps(__spreadValues({}, functionExtractor.extract()), {
memberType: MemberType.Method,
memberTags: this.getMemberTags(methodDeclaration)
});
}
extractSignature(signature) {
const functionExtractor = new FunctionExtractor(import_typescript102.default.isConstructSignatureDeclaration(signature) ? "new" : "", signature, this.typeChecker);
return __spreadProps(__spreadValues({}, functionExtractor.extract()), {
memberType: MemberType.Method,
memberTags: []
});
}
extractClassProperty(propertyDeclaration) {
return {
name: propertyDeclaration.name.getText(),
type: extractResolvedTypeString(propertyDeclaration, this.typeChecker),
memberType: MemberType.Property,
memberTags: this.getMemberTags(propertyDeclaration),
description: extractJsDocDescription(propertyDeclaration),
jsdocTags: extractJsDocTags(propertyDeclaration)
};
}
extractGetterSetter(accessor) {
return __spreadProps(__spreadValues({}, this.extractClassProperty(accessor)), {
memberType: import_typescript102.default.isGetAccessor(accessor) ? MemberType.Getter : MemberType.Setter
});
}
extractInheritance(declaration) {
if (!declaration.heritageClauses) {
return void 0;
}
for (const clause of declaration.heritageClauses) {
if (clause.token === import_typescript102.default.SyntaxKind.ExtendsKeyword) {
const types = clause.types;
if (types.length > 0) {
const baseClass = types[0];
return baseClass.getText();
}
}
}
return void 0;
}
extractInterfaceConformance(declaration) {
var _a2, _b2;
const implementClause = (_a2 = declaration.heritageClauses) == null ? void 0 : _a2.find((clause) => clause.token === import_typescript102.default.SyntaxKind.ImplementsKeyword);
return (_b2 = implementClause == null ? void 0 : implementClause.types.map((m) => m.getText())) != null ? _b2 : [];
}
getMemberTags(member) {
var _a2;
const tags = this.getMemberTagsFromModifiers((_a2 = member.modifiers) != null ? _a2 : []);
if (member.questionToken) {
tags.push(MemberTags.Optional);
}
if (member.parent !== this.declaration) {
tags.push(MemberTags.Inherited);
}
return tags;
}
computeAllSignatureDeclarations() {
const type = this.typeChecker.getTypeAtLocation(this.declaration);
const signatures = [...type.getCallSignatures(), ...type.getConstructSignatures()];
const result = [];
for (const signature of signatures) {
const decl = signature.getDeclaration();
if (this.isDocumentableSignature(decl) && this.isDocumentableMember(decl)) {
result.push(decl);
}
}
return result;
}
getMemberDeclarations() {
var _a2;
const type = this.typeChecker.getTypeAtLocation(this.declaration);
const members = type.getProperties();
const typeOfConstructor = this.typeChecker.getTypeOfSymbol(type.symbol);
const staticMembers = typeOfConstructor.getProperties();
const result = [];
for (const member of [...members, ...staticMembers]) {
const memberDeclarations = this.filterMethodOverloads((_a2 = member.getDeclarations()) != null ? _a2 : []);
for (const memberDeclaration of memberDeclarations) {
if (this.isDocumentableMember(memberDeclaration)) {
result.push(memberDeclaration);
}
}
}
return result;
}
filterMethodOverloads(declarations) {
return declarations.filter((declaration) => {
if (import_typescript102.default.isFunctionDeclaration(declaration) || import_typescript102.default.isMethodDeclaration(declaration)) {
return !!declaration.body || import_typescript102.default.getCombinedModifierFlags(declaration) & import_typescript102.default.ModifierFlags.Abstract;
}
return true;
});
}
getMemberTagsFromModifiers(mods) {
const tags = [];
for (const mod of mods) {
const tag = this.getTagForMemberModifier(mod);
if (tag)
tags.push(tag);
}
return tags;
}
getTagForMemberModifier(mod) {
switch (mod.kind) {
case import_typescript102.default.SyntaxKind.StaticKeyword:
return MemberTags.Static;
case import_typescript102.default.SyntaxKind.ReadonlyKeyword:
return MemberTags.Readonly;
case import_typescript102.default.SyntaxKind.ProtectedKeyword:
return MemberTags.Protected;
case import_typescript102.default.SyntaxKind.AbstractKeyword:
return MemberTags.Abstract;
default:
return void 0;
}
}
isMemberExcluded(member) {
var _a2;
return !member.name || !this.isDocumentableMember(member) || !import_typescript102.default.isCallSignatureDeclaration(member) && ((_a2 = member.modifiers) == null ? void 0 : _a2.some((mod) => mod.kind === import_typescript102.default.SyntaxKind.PrivateKeyword)) || member.name.getText() === "prototype" || isAngularPrivateName(member.name.getText()) || isInternal(member);
}
isDocumentableMember(member) {
return this.isMethod(member) || this.isProperty(member) || import_typescript102.default.isAccessor(member) || import_typescript102.default.isCallSignatureDeclaration(member);
}
isPublicConstructorParameterProperty(node) {
if (import_typescript102.default.isParameterPropertyDeclaration(node, node.parent) && node.modifiers) {
return node.modifiers.some((modifier) => modifier.kind === import_typescript102.default.SyntaxKind.PublicKeyword);
}
return false;
}
isProperty(member) {
return import_typescript102.default.isPropertyDeclaration(member) || import_typescript102.default.isPropertySignature(member) || this.isPublicConstructorParameterProperty(member);
}
isMethod(member) {
return import_typescript102.default.isMethodDeclaration(member) || import_typescript102.default.isMethodSignature(member);
}
isDocumentableSignature(signature) {
return import_typescript102.default.isConstructSignatureDeclaration(signature) || import_typescript102.default.isCallSignatureDeclaration(signature);
}
isAbstract() {
var _a2;
const modifiers = (_a2 = this.declaration.modifiers) != null ? _a2 : [];
return modifiers.some((mod) => mod.kind === import_typescript102.default.SyntaxKind.AbstractKeyword);
}
};
var DirectiveExtractor = class extends ClassExtractor {
constructor(declaration, reference2, metadata, checker) {
super(declaration, checker);
this.reference = reference2;
this.metadata = metadata;
}
extract() {
var _a2, _b2;
return __spreadProps(__spreadValues({}, super.extract()), {
isStandalone: this.metadata.isStandalone,
selector: (_a2 = this.metadata.selector) != null ? _a2 : "",
exportAs: (_b2 = this.metadata.exportAs) != null ? _b2 : [],
entryType: this.metadata.isComponent ? EntryType.Component : EntryType.Directive
});
}
extractClassProperty(propertyDeclaration) {
const entry = super.extractClassProperty(propertyDeclaration);
const inputMetadata = this.getInputMetadata(propertyDeclaration);
if (inputMetadata) {
entry.memberTags.push(MemberTags.Input);
entry.inputAlias = inputMetadata.bindingPropertyName;
entry.isRequiredInput = inputMetadata.required;
}
const outputMetadata = this.getOutputMetadata(propertyDeclaration);
if (outputMetadata) {
entry.memberTags.push(MemberTags.Output);
entry.outputAlias = outputMetadata.bindingPropertyName;
}
return entry;
}
getInputMetadata(prop) {
var _a2, _b2;
const propName = prop.name.getText();
return (_b2 = (_a2 = this.metadata.inputs) == null ? void 0 : _a2.getByClassPropertyName(propName)) != null ? _b2 : void 0;
}
getOutputMetadata(prop) {
var _a2, _b2, _c2;
const propName = prop.name.getText();
return (_c2 = (_b2 = (_a2 = this.metadata) == null ? void 0 : _a2.outputs) == null ? void 0 : _b2.getByClassPropertyName(propName)) != null ? _c2 : void 0;
}
};
var PipeExtractor = class extends ClassExtractor {
constructor(declaration, reference2, metadata, typeChecker) {
super(declaration, typeChecker);
this.reference = reference2;
this.metadata = metadata;
}
extract() {
return __spreadProps(__spreadValues({}, super.extract()), {
pipeName: this.metadata.name,
entryType: EntryType.Pipe,
isStandalone: this.metadata.isStandalone
});
}
};
var NgModuleExtractor = class extends ClassExtractor {
constructor(declaration, reference2, metadata, typeChecker) {
super(declaration, typeChecker);
this.reference = reference2;
this.metadata = metadata;
}
extract() {
return __spreadProps(__spreadValues({}, super.extract()), {
entryType: EntryType.NgModule
});
}
};
function extractClass(classDeclaration, metadataReader, typeChecker) {
const ref = new Reference2(classDeclaration);
let extractor;
let directiveMetadata = metadataReader.getDirectiveMetadata(ref);
let pipeMetadata = metadataReader.getPipeMetadata(ref);
let ngModuleMetadata = metadataReader.getNgModuleMetadata(ref);
if (directiveMetadata) {
extractor = new DirectiveExtractor(classDeclaration, ref, directiveMetadata, typeChecker);
} else if (pipeMetadata) {
extractor = new PipeExtractor(classDeclaration, ref, pipeMetadata, typeChecker);
} else if (ngModuleMetadata) {
extractor = new NgModuleExtractor(classDeclaration, ref, ngModuleMetadata, typeChecker);
} else {
extractor = new ClassExtractor(classDeclaration, typeChecker);
}
return extractor.extract();
}
function extractInterface(declaration, typeChecker) {
const extractor = new ClassExtractor(declaration, typeChecker);
return extractor.extract();
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/docs/src/constant_extractor.mjs
var import_typescript103 = __toESM(require("typescript"), 1);
var LITERAL_AS_ENUM_TAG = "object-literal-as-enum";
function extractConstant(declaration, typeChecker) {
const resolvedType = typeChecker.getBaseTypeOfLiteralType(typeChecker.getTypeAtLocation(declaration));
const rawComment = extractRawJsDoc(declaration.parent.parent);
const jsdocTags = extractJsDocTags(declaration);
const description = extractJsDocDescription(declaration);
const name = declaration.name.getText();
if (jsdocTags.some((tag) => tag.name === LITERAL_AS_ENUM_TAG)) {
return {
name,
entryType: EntryType.Enum,
members: extractLiteralPropertiesAsEnumMembers(declaration),
rawComment,
description,
jsdocTags: jsdocTags.filter((tag) => tag.name !== LITERAL_AS_ENUM_TAG)
};
}
return {
name,
type: typeChecker.typeToString(resolvedType),
entryType: EntryType.Constant,
rawComment,
description,
jsdocTags
};
}
function isSyntheticAngularConstant(declaration) {
return declaration.name.getText() === "USED_FOR_NG_TYPE_CHECKING";
}
function extractLiteralPropertiesAsEnumMembers(declaration) {
let initializer = declaration.initializer;
while (initializer && (import_typescript103.default.isAsExpression(initializer) || import_typescript103.default.isParenthesizedExpression(initializer))) {
initializer = initializer.expression;
}
if (initializer === void 0 || !import_typescript103.default.isObjectLiteralExpression(initializer)) {
throw new Error(`Declaration tagged with "${LITERAL_AS_ENUM_TAG}" must be initialized to an object literal, but received ${initializer ? import_typescript103.default.SyntaxKind[initializer.kind] : "undefined"}`);
}
return initializer.properties.map((prop) => {
if (!import_typescript103.default.isPropertyAssignment(prop) || !import_typescript103.default.isIdentifier(prop.name)) {
throw new Error(`Property in declaration tagged with "${LITERAL_AS_ENUM_TAG}" must be a property assignment with a static name`);
}
if (!import_typescript103.default.isNumericLiteral(prop.initializer) && !import_typescript103.default.isStringLiteralLike(prop.initializer)) {
throw new Error(`Property in declaration tagged with "${LITERAL_AS_ENUM_TAG}" must be initialized to a number or string literal`);
}
return {
name: prop.name.text,
type: `${declaration.name.getText()}.${prop.name.text}`,
value: prop.initializer.getText(),
memberType: MemberType.EnumItem,
jsdocTags: extractJsDocTags(prop),
description: extractJsDocDescription(prop),
memberTags: []
};
});
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/docs/src/decorator_extractor.mjs
var import_typescript104 = __toESM(require("typescript"), 1);
function extractorDecorator(declaration, typeChecker) {
const documentedNode = getDecoratorJsDocNode(declaration);
const decoratorType = getDecoratorType(declaration);
if (!decoratorType) {
throw new Error(`"${declaration.name.getText()} is not a decorator."`);
}
return {
name: declaration.name.getText(),
decoratorType,
entryType: EntryType.Decorator,
rawComment: extractRawJsDoc(documentedNode),
description: extractJsDocDescription(documentedNode),
jsdocTags: extractJsDocTags(documentedNode),
members: getDecoratorOptions(declaration, typeChecker)
};
}
function isDecoratorDeclaration(declaration) {
return !!getDecoratorType(declaration);
}
function isDecoratorOptionsInterface(declaration) {
return declaration.getSourceFile().statements.some((s) => import_typescript104.default.isVariableStatement(s) && s.declarationList.declarations.some((d) => isDecoratorDeclaration(d) && d.name.getText() === declaration.name.getText()));
}
function getDecoratorType(declaration) {
var _a2, _b2;
const initializer = (_b2 = (_a2 = declaration.initializer) == null ? void 0 : _a2.getFullText()) != null ? _b2 : "";
if (initializer.includes("makeDecorator"))
return DecoratorType.Class;
if (initializer.includes("makePropDecorator"))
return DecoratorType.Member;
if (initializer.includes("makeParamDecorator"))
return DecoratorType.Parameter;
return void 0;
}
function getDecoratorOptions(declaration, typeChecker) {
var _a2, _b2;
const name = declaration.name.getText();
const optionsDeclaration = declaration.getSourceFile().statements.find((node) => {
return (import_typescript104.default.isInterfaceDeclaration(node) || import_typescript104.default.isTypeAliasDeclaration(node)) && node.name.getText() === name;
});
if (!optionsDeclaration) {
throw new Error(`Decorator "${name}" has no corresponding options interface.`);
}
let optionsInterface;
if (import_typescript104.default.isTypeAliasDeclaration(optionsDeclaration)) {
const aliasedType = typeChecker.getTypeAtLocation(optionsDeclaration.type);
optionsInterface = ((_b2 = (_a2 = aliasedType.getSymbol()) == null ? void 0 : _a2.getDeclarations()) != null ? _b2 : []).find((d) => import_typescript104.default.isInterfaceDeclaration(d));
} else {
optionsInterface = optionsDeclaration;
}
if (!optionsInterface || !import_typescript104.default.isInterfaceDeclaration(optionsInterface)) {
throw new Error(`Options for decorator "${name}" is not an interface.`);
}
return extractInterface(optionsInterface, typeChecker).members;
}
function getDecoratorJsDocNode(declaration) {
const name = declaration.name.getText();
const decoratorInterface = declaration.getSourceFile().statements.find((s) => {
return import_typescript104.default.isInterfaceDeclaration(s) && s.name.getText() === `${name}Decorator`;
});
if (!decoratorInterface || !import_typescript104.default.isInterfaceDeclaration(decoratorInterface)) {
throw new Error(`No interface "${name}Decorator" found.`);
}
const callSignature = decoratorInterface.members.find((node) => {
return import_typescript104.default.isCallSignatureDeclaration(node) && extractRawJsDoc(node);
});
if (!callSignature || !import_typescript104.default.isCallSignatureDeclaration(callSignature)) {
throw new Error(`No call signature with JsDoc on "${name}Decorator"`);
}
return callSignature;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/docs/src/enum_extractor.mjs
var import_typescript105 = __toESM(require("typescript"), 1);
function extractEnum(declaration, typeChecker) {
return {
name: declaration.name.getText(),
entryType: EntryType.Enum,
members: extractEnumMembers(declaration, typeChecker),
rawComment: extractRawJsDoc(declaration),
description: extractJsDocDescription(declaration),
jsdocTags: extractJsDocTags(declaration)
};
}
function extractEnumMembers(declaration, checker) {
return declaration.members.map((member) => ({
name: member.name.getText(),
type: extractResolvedTypeString(member, checker),
value: getEnumMemberValue(member),
memberType: MemberType.EnumItem,
jsdocTags: extractJsDocTags(member),
description: extractJsDocDescription(member),
memberTags: []
}));
}
function getEnumMemberValue(memberNode) {
var _a2;
const literal3 = memberNode.getChildren().find((n2) => {
return import_typescript105.default.isNumericLiteral(n2) || import_typescript105.default.isStringLiteral(n2) || import_typescript105.default.isPrefixUnaryExpression(n2) && n2.operator === import_typescript105.default.SyntaxKind.MinusToken && import_typescript105.default.isNumericLiteral(n2.operand);
});
return (_a2 = literal3 == null ? void 0 : literal3.getText()) != null ? _a2 : "";
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/docs/src/initializer_api_function_extractor.mjs
var import_typescript106 = __toESM(require("typescript"), 1);
var initializerApiTag = "initializerApiFunction";
function isInitializerApiFunction(node, typeChecker) {
if (import_typescript106.default.isFunctionDeclaration(node) && node.name !== void 0 && node.body === void 0) {
const implementation = findImplementationOfFunction(node, typeChecker);
if (implementation !== void 0) {
node = implementation;
}
}
if (!import_typescript106.default.isFunctionDeclaration(node) && !import_typescript106.default.isVariableDeclaration(node)) {
return false;
}
let tagContainer = import_typescript106.default.isFunctionDeclaration(node) ? node : getContainerVariableStatement(node);
if (tagContainer === null) {
return false;
}
const tags = import_typescript106.default.getJSDocTags(tagContainer);
return tags.some((t) => t.tagName.text === initializerApiTag);
}
function extractInitializerApiFunction(node, typeChecker) {
var _a2;
if (node.name === void 0 || !import_typescript106.default.isIdentifier(node.name)) {
throw new Error(`Initializer API: Expected literal variable name.`);
}
const container = import_typescript106.default.isFunctionDeclaration(node) ? node : getContainerVariableStatement(node);
if (container === null) {
throw new Error("Initializer API: Could not find container AST node of variable.");
}
const name = node.name.text;
const type = typeChecker.getTypeAtLocation(node);
const callFunction = extractFunctionWithOverloads(name, type, typeChecker);
const subFunctions = [];
for (const property2 of type.getProperties()) {
const subName = property2.getName();
const subDecl = (_a2 = property2.getDeclarations()) == null ? void 0 : _a2[0];
if (subDecl === void 0 || !import_typescript106.default.isPropertySignature(subDecl)) {
throw new Error(`Initializer API: Could not resolve declaration of sub-property: ${name}.${subName}`);
}
const subType = typeChecker.getTypeAtLocation(subDecl);
subFunctions.push(extractFunctionWithOverloads(subName, subType, typeChecker));
}
let jsdocTags;
let description;
let rawComment;
if (import_typescript106.default.isFunctionDeclaration(node)) {
const implementation = findImplementationOfFunction(node, typeChecker);
if (implementation === void 0) {
throw new Error(`Initializer API: Could not find implementation of function: ${name}`);
}
callFunction.implementation = {
name,
entryType: EntryType.Function,
isNewType: false,
description: extractJsDocDescription(implementation),
generics: extractGenerics(implementation),
jsdocTags: extractJsDocTags(implementation),
params: extractAllParams(implementation.parameters, typeChecker),
rawComment: extractRawJsDoc(implementation),
returnType: typeChecker.typeToString(typeChecker.getReturnTypeOfSignature(typeChecker.getSignatureFromDeclaration(implementation)))
};
jsdocTags = callFunction.implementation.jsdocTags;
description = callFunction.implementation.description;
rawComment = callFunction.implementation.description;
} else {
jsdocTags = extractJsDocTags(container);
description = extractJsDocDescription(container);
rawComment = extractRawJsDoc(container);
}
const metadataTag = jsdocTags.find((t) => t.name === initializerApiTag);
if (metadataTag === void 0) {
throw new Error(`Initializer API: Detected initializer API function does not have "@initializerApiFunction" tag: ${name}`);
}
let parsedMetadata = void 0;
if (metadataTag.comment.trim() !== "") {
try {
parsedMetadata = JSON.parse(metadataTag.comment);
} catch (e) {
throw new Error(`Could not parse initializer API function metadata: ${e}`);
}
}
return {
entryType: EntryType.InitializerApiFunction,
name,
description,
jsdocTags,
rawComment,
callFunction,
subFunctions,
__docsMetadata__: parsedMetadata
};
}
function getContainerVariableStatement(node) {
if (!import_typescript106.default.isVariableDeclarationList(node.parent)) {
return null;
}
if (!import_typescript106.default.isVariableStatement(node.parent.parent)) {
return null;
}
return node.parent.parent;
}
function extractFunctionWithOverloads(name, type, typeChecker) {
return {
name,
signatures: extractCallSignatures(name, typeChecker, type),
implementation: null
};
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/docs/src/type_alias_extractor.mjs
function extractTypeAlias(declaration) {
return {
name: declaration.name.getText(),
type: declaration.type.getText(),
entryType: EntryType.TypeAlias,
rawComment: extractRawJsDoc(declaration),
description: extractJsDocDescription(declaration),
jsdocTags: extractJsDocTags(declaration)
};
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/docs/src/import_extractor.mjs
var import_typescript107 = __toESM(require("typescript"), 1);
function getImportedSymbols(sourceFile) {
const importSpecifiers = /* @__PURE__ */ new Map();
function visit2(node) {
var _a2;
if (import_typescript107.default.isImportDeclaration(node)) {
let moduleSpecifier = node.moduleSpecifier.getText(sourceFile).replace(/['"]/g, "");
if (moduleSpecifier.startsWith("@angular/")) {
const namedBindings = (_a2 = node.importClause) == null ? void 0 : _a2.namedBindings;
if (namedBindings && import_typescript107.default.isNamedImports(namedBindings)) {
namedBindings.elements.forEach((importSpecifier) => {
const importName = importSpecifier.name.text;
const importAlias = importSpecifier.propertyName ? importSpecifier.propertyName.text : void 0;
importSpecifiers.set(importAlias != null ? importAlias : importName, moduleSpecifier);
});
}
}
}
import_typescript107.default.forEachChild(node, visit2);
}
visit2(sourceFile);
return importSpecifiers;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/docs/src/extractor.mjs
var DocsExtractor = class {
constructor(typeChecker, metadataReader) {
this.typeChecker = typeChecker;
this.metadataReader = metadataReader;
}
extractAll(sourceFile, rootDir, privateModules) {
const entries = [];
const symbols = /* @__PURE__ */ new Map();
const exportedDeclarations = this.getExportedDeclarations(sourceFile);
for (const [exportName, node] of exportedDeclarations) {
if (isAngularPrivateName(exportName)) {
continue;
}
const entry = this.extractDeclaration(node);
if (entry && !isIgnoredDocEntry(entry)) {
const realSourceFile = node.getSourceFile();
const importedSymbols = getImportedSymbols(realSourceFile);
importedSymbols.forEach((moduleName, symbolName) => {
if (symbolName.startsWith("\u0275") || privateModules.has(moduleName)) {
return;
}
if (symbols.has(symbolName) && symbols.get(symbolName) !== moduleName) {
throw new Error(`Ambigous symbol \`${symbolName}\` exported by both ${symbols.get(symbolName)} & ${moduleName}`);
}
symbols.set(symbolName, moduleName);
});
entry.source = {
filePath: getRelativeFilePath(realSourceFile, rootDir),
startLine: import_typescript108.default.getLineAndCharacterOfPosition(realSourceFile, node.getStart()).line + 1,
endLine: import_typescript108.default.getLineAndCharacterOfPosition(realSourceFile, node.getEnd()).line + 1
};
entries.push(__spreadProps(__spreadValues({}, entry), { name: exportName }));
}
}
return { entries, symbols };
}
extractDeclaration(node) {
if (isNamedClassDeclaration(node)) {
return extractClass(node, this.metadataReader, this.typeChecker);
}
if (isInitializerApiFunction(node, this.typeChecker)) {
return extractInitializerApiFunction(node, this.typeChecker);
}
if (import_typescript108.default.isInterfaceDeclaration(node) && !isIgnoredInterface(node)) {
return extractInterface(node, this.typeChecker);
}
if (import_typescript108.default.isFunctionDeclaration(node)) {
const functionExtractor = new FunctionExtractor(node.name.getText(), node, this.typeChecker);
return functionExtractor.extract();
}
if (import_typescript108.default.isVariableDeclaration(node) && !isSyntheticAngularConstant(node)) {
return isDecoratorDeclaration(node) ? extractorDecorator(node, this.typeChecker) : extractConstant(node, this.typeChecker);
}
if (import_typescript108.default.isTypeAliasDeclaration(node)) {
return extractTypeAlias(node);
}
if (import_typescript108.default.isEnumDeclaration(node)) {
return extractEnum(node, this.typeChecker);
}
return null;
}
getExportedDeclarations(sourceFile) {
var _a2;
const reflector = new TypeScriptReflectionHost(this.typeChecker);
const exportedDeclarationMap = reflector.getExportsOfModule(sourceFile);
let exportedDeclarations = Array.from((_a2 = exportedDeclarationMap == null ? void 0 : exportedDeclarationMap.entries()) != null ? _a2 : []).map(([exportName, declaration]) => [exportName, declaration.node]);
return exportedDeclarations.sort(([a, declarationA], [b, declarationB]) => declarationA.pos - declarationB.pos);
}
};
function isIgnoredInterface(node) {
return node.name.getText().endsWith("Decorator") || isDecoratorOptionsInterface(node);
}
function isIgnoredDocEntry(entry) {
const isDocsPrivate = entry.jsdocTags.find((e) => e.name === "docsPrivate");
if (isDocsPrivate !== void 0 && isDocsPrivate.comment === "") {
throw new Error(`Docs extraction: Entry "${entry.name}" is marked as "@docsPrivate" but without reasoning.`);
}
return isDocsPrivate !== void 0;
}
function getRelativeFilePath(sourceFile, rootDir) {
const fullPath = sourceFile.fileName;
const relativePath = fullPath.replace(rootDir, "");
return relativePath;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/entry_point/src/generator.mjs
var import_typescript109 = __toESM(require("typescript"), 1);
var FlatIndexGenerator = class {
constructor(entryPoint, relativeFlatIndexPath, moduleName) {
this.entryPoint = entryPoint;
this.moduleName = moduleName;
this.shouldEmit = true;
this.flatIndexPath = join(dirname(entryPoint), relativeFlatIndexPath).replace(/\.js$/, "") + ".ts";
}
makeTopLevelShim() {
const relativeEntryPoint = relativePathBetween(this.flatIndexPath, this.entryPoint);
const contents = `/**
* Generated bundle index. Do not edit.
*/
export * from '${relativeEntryPoint}';
`;
const genFile = import_typescript109.default.createSourceFile(this.flatIndexPath, contents, import_typescript109.default.ScriptTarget.ES2015, true, import_typescript109.default.ScriptKind.TS);
if (this.moduleName !== null) {
genFile.moduleName = this.moduleName;
}
return genFile;
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/entry_point/src/logic.mjs
function findFlatIndexEntryPoint(rootFiles) {
const tsFiles = rootFiles.filter((file) => isNonDeclarationTsPath(file));
let resolvedEntryPoint = null;
if (tsFiles.length === 1) {
resolvedEntryPoint = tsFiles[0];
} else {
for (const tsFile of tsFiles) {
if (getFileSystem().basename(tsFile) === "index.ts" && (resolvedEntryPoint === null || tsFile.length <= resolvedEntryPoint.length)) {
resolvedEntryPoint = tsFile;
}
}
}
return resolvedEntryPoint;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/entry_point/src/private_export_checker.mjs
var import_typescript111 = __toESM(require("typescript"), 1);
function checkForPrivateExports(entryPoint, checker, refGraph) {
const diagnostics = [];
const topLevelExports = /* @__PURE__ */ new Set();
const moduleSymbol = checker.getSymbolAtLocation(entryPoint);
if (moduleSymbol === void 0) {
throw new Error(`Internal error: failed to get symbol for entrypoint`);
}
const exportedSymbols = checker.getExportsOfModule(moduleSymbol);
exportedSymbols.forEach((symbol) => {
if (symbol.flags & import_typescript111.default.SymbolFlags.Alias) {
symbol = checker.getAliasedSymbol(symbol);
}
const decl = symbol.valueDeclaration;
if (decl !== void 0) {
topLevelExports.add(decl);
}
});
const checkedSet = /* @__PURE__ */ new Set();
topLevelExports.forEach((mainExport) => {
refGraph.transitiveReferencesOf(mainExport).forEach((transitiveReference) => {
if (checkedSet.has(transitiveReference)) {
return;
}
checkedSet.add(transitiveReference);
if (!topLevelExports.has(transitiveReference)) {
const descriptor = getDescriptorOfDeclaration(transitiveReference);
const name = getNameOfDeclaration(transitiveReference);
let visibleVia = "NgModule exports";
const transitivePath = refGraph.pathFrom(mainExport, transitiveReference);
if (transitivePath !== null) {
visibleVia = transitivePath.map((seg) => getNameOfDeclaration(seg)).join(" -> ");
}
const diagnostic = __spreadProps(__spreadValues({
category: import_typescript111.default.DiagnosticCategory.Error,
code: ngErrorCode(ErrorCode.SYMBOL_NOT_EXPORTED),
file: transitiveReference.getSourceFile()
}, getPosOfDeclaration(transitiveReference)), {
messageText: `Unsupported private ${descriptor} ${name}. This ${descriptor} is visible to consumers via ${visibleVia}, but is not exported from the top-level library entrypoint.`
});
diagnostics.push(diagnostic);
}
});
});
return diagnostics;
}
function getPosOfDeclaration(decl) {
const node = getIdentifierOfDeclaration(decl) || decl;
return {
start: node.getStart(),
length: node.getEnd() + 1 - node.getStart()
};
}
function getIdentifierOfDeclaration(decl) {
if ((import_typescript111.default.isClassDeclaration(decl) || import_typescript111.default.isVariableDeclaration(decl) || import_typescript111.default.isFunctionDeclaration(decl)) && decl.name !== void 0 && import_typescript111.default.isIdentifier(decl.name)) {
return decl.name;
} else {
return null;
}
}
function getNameOfDeclaration(decl) {
const id = getIdentifierOfDeclaration(decl);
return id !== null ? id.text : "(unnamed)";
}
function getDescriptorOfDeclaration(decl) {
switch (decl.kind) {
case import_typescript111.default.SyntaxKind.ClassDeclaration:
return "class";
case import_typescript111.default.SyntaxKind.FunctionDeclaration:
return "function";
case import_typescript111.default.SyntaxKind.VariableDeclaration:
return "variable";
case import_typescript111.default.SyntaxKind.EnumDeclaration:
return "enum";
default:
return "declaration";
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/entry_point/src/reference_graph.mjs
var ReferenceGraph = class {
constructor() {
this.references = /* @__PURE__ */ new Map();
}
add(from, to) {
if (!this.references.has(from)) {
this.references.set(from, /* @__PURE__ */ new Set());
}
this.references.get(from).add(to);
}
transitiveReferencesOf(target) {
const set = /* @__PURE__ */ new Set();
this.collectTransitiveReferences(set, target);
return set;
}
pathFrom(source, target) {
return this.collectPathFrom(source, target, /* @__PURE__ */ new Set());
}
collectPathFrom(source, target, seen) {
if (source === target) {
return [target];
} else if (seen.has(source)) {
return null;
}
seen.add(source);
if (!this.references.has(source)) {
return null;
} else {
let candidatePath = null;
this.references.get(source).forEach((edge) => {
if (candidatePath !== null) {
return;
}
const partialPath = this.collectPathFrom(edge, target, seen);
if (partialPath !== null) {
candidatePath = [source, ...partialPath];
}
});
return candidatePath;
}
}
collectTransitiveReferences(set, decl) {
if (this.references.has(decl)) {
this.references.get(decl).forEach((ref) => {
if (!set.has(ref)) {
set.add(ref);
this.collectTransitiveReferences(set, ref);
}
});
}
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/incremental/src/dependency_tracking.mjs
var FileDependencyGraph = class {
constructor() {
this.nodes = /* @__PURE__ */ new Map();
}
addDependency(from, on) {
this.nodeFor(from).dependsOn.add(absoluteFromSourceFile(on));
}
addResourceDependency(from, resource) {
this.nodeFor(from).usesResources.add(resource);
}
recordDependencyAnalysisFailure(file) {
this.nodeFor(file).failedAnalysis = true;
}
getResourceDependencies(from) {
const node = this.nodes.get(from);
return node ? [...node.usesResources] : [];
}
updateWithPhysicalChanges(previous, changedTsPaths, deletedTsPaths, changedResources) {
const logicallyChanged = /* @__PURE__ */ new Set();
for (const sf of previous.nodes.keys()) {
const sfPath = absoluteFromSourceFile(sf);
const node = previous.nodeFor(sf);
if (isLogicallyChanged(sf, node, changedTsPaths, deletedTsPaths, changedResources)) {
logicallyChanged.add(sfPath);
} else if (!deletedTsPaths.has(sfPath)) {
this.nodes.set(sf, {
dependsOn: new Set(node.dependsOn),
usesResources: new Set(node.usesResources),
failedAnalysis: false
});
}
}
return logicallyChanged;
}
nodeFor(sf) {
if (!this.nodes.has(sf)) {
this.nodes.set(sf, {
dependsOn: /* @__PURE__ */ new Set(),
usesResources: /* @__PURE__ */ new Set(),
failedAnalysis: false
});
}
return this.nodes.get(sf);
}
};
function isLogicallyChanged(sf, node, changedTsPaths, deletedTsPaths, changedResources) {
if (node.failedAnalysis) {
return true;
}
const sfPath = absoluteFromSourceFile(sf);
if (changedTsPaths.has(sfPath) || deletedTsPaths.has(sfPath)) {
return true;
}
for (const dep of node.dependsOn) {
if (changedTsPaths.has(dep) || deletedTsPaths.has(dep)) {
return true;
}
}
for (const dep of node.usesResources) {
if (changedResources.has(dep)) {
return true;
}
}
return false;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/incremental/src/state.mjs
var IncrementalStateKind;
(function(IncrementalStateKind2) {
IncrementalStateKind2[IncrementalStateKind2["Fresh"] = 0] = "Fresh";
IncrementalStateKind2[IncrementalStateKind2["Delta"] = 1] = "Delta";
IncrementalStateKind2[IncrementalStateKind2["Analyzed"] = 2] = "Analyzed";
})(IncrementalStateKind || (IncrementalStateKind = {}));
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/incremental/src/incremental.mjs
var PhaseKind;
(function(PhaseKind2) {
PhaseKind2[PhaseKind2["Analysis"] = 0] = "Analysis";
PhaseKind2[PhaseKind2["TypeCheckAndEmit"] = 1] = "TypeCheckAndEmit";
})(PhaseKind || (PhaseKind = {}));
var IncrementalCompilation = class {
constructor(state, depGraph, versions, step) {
this.depGraph = depGraph;
this.versions = versions;
this.step = step;
this._state = state;
this.phase = {
kind: PhaseKind.Analysis,
semanticDepGraphUpdater: new SemanticDepGraphUpdater(step !== null ? step.priorState.semanticDepGraph : null)
};
}
static fresh(program, versions) {
const state = {
kind: IncrementalStateKind.Fresh
};
return new IncrementalCompilation(state, new FileDependencyGraph(), versions, null);
}
static incremental(program, newVersions, oldProgram, oldState, modifiedResourceFiles, perf) {
return perf.inPhase(PerfPhase.Reconciliation, () => {
const physicallyChangedTsFiles = /* @__PURE__ */ new Set();
const changedResourceFiles = new Set(modifiedResourceFiles != null ? modifiedResourceFiles : []);
let priorAnalysis;
switch (oldState.kind) {
case IncrementalStateKind.Fresh:
return IncrementalCompilation.fresh(program, newVersions);
case IncrementalStateKind.Analyzed:
priorAnalysis = oldState;
break;
case IncrementalStateKind.Delta:
priorAnalysis = oldState.lastAnalyzedState;
for (const sfPath of oldState.physicallyChangedTsFiles) {
physicallyChangedTsFiles.add(sfPath);
}
for (const resourcePath of oldState.changedResourceFiles) {
changedResourceFiles.add(resourcePath);
}
break;
}
const oldVersions = priorAnalysis.versions;
const oldFilesArray = oldProgram.getSourceFiles().map(toOriginalSourceFile);
const oldFiles = new Set(oldFilesArray);
const deletedTsFiles = new Set(oldFilesArray.map((sf) => absoluteFromSourceFile(sf)));
for (const possiblyRedirectedNewFile of program.getSourceFiles()) {
const sf = toOriginalSourceFile(possiblyRedirectedNewFile);
const sfPath = absoluteFromSourceFile(sf);
deletedTsFiles.delete(sfPath);
if (oldFiles.has(sf)) {
if (oldVersions === null || newVersions === null) {
continue;
}
if (oldVersions.has(sfPath) && newVersions.has(sfPath) && oldVersions.get(sfPath) === newVersions.get(sfPath)) {
continue;
}
}
if (sf.isDeclarationFile) {
return IncrementalCompilation.fresh(program, newVersions);
}
physicallyChangedTsFiles.add(sfPath);
}
for (const deletedFileName of deletedTsFiles) {
physicallyChangedTsFiles.delete(resolve(deletedFileName));
}
const depGraph = new FileDependencyGraph();
const logicallyChangedTsFiles = depGraph.updateWithPhysicalChanges(priorAnalysis.depGraph, physicallyChangedTsFiles, deletedTsFiles, changedResourceFiles);
for (const sfPath of physicallyChangedTsFiles) {
logicallyChangedTsFiles.add(sfPath);
}
const state = {
kind: IncrementalStateKind.Delta,
physicallyChangedTsFiles,
changedResourceFiles,
lastAnalyzedState: priorAnalysis
};
return new IncrementalCompilation(state, depGraph, newVersions, {
priorState: priorAnalysis,
logicallyChangedTsFiles
});
});
}
get state() {
return this._state;
}
get semanticDepGraphUpdater() {
if (this.phase.kind !== PhaseKind.Analysis) {
throw new Error(`AssertionError: Cannot update the SemanticDepGraph after analysis completes`);
}
return this.phase.semanticDepGraphUpdater;
}
recordSuccessfulAnalysis(traitCompiler) {
if (this.phase.kind !== PhaseKind.Analysis) {
throw new Error(`AssertionError: Incremental compilation in phase ${PhaseKind[this.phase.kind]}, expected Analysis`);
}
const { needsEmit, needsTypeCheckEmit, newGraph } = this.phase.semanticDepGraphUpdater.finalize();
let emitted;
if (this.step === null) {
emitted = /* @__PURE__ */ new Set();
} else {
emitted = new Set(this.step.priorState.emitted);
for (const sfPath of this.step.logicallyChangedTsFiles) {
emitted.delete(sfPath);
}
for (const sfPath of needsEmit) {
emitted.delete(sfPath);
}
}
this._state = {
kind: IncrementalStateKind.Analyzed,
versions: this.versions,
depGraph: this.depGraph,
semanticDepGraph: newGraph,
priorAnalysis: traitCompiler.getAnalyzedRecords(),
typeCheckResults: null,
emitted
};
this.phase = {
kind: PhaseKind.TypeCheckAndEmit,
needsEmit,
needsTypeCheckEmit
};
}
recordSuccessfulTypeCheck(results) {
if (this._state.kind !== IncrementalStateKind.Analyzed) {
throw new Error(`AssertionError: Expected successfully analyzed compilation.`);
} else if (this.phase.kind !== PhaseKind.TypeCheckAndEmit) {
throw new Error(`AssertionError: Incremental compilation in phase ${PhaseKind[this.phase.kind]}, expected TypeCheck`);
}
this._state.typeCheckResults = results;
}
recordSuccessfulEmit(sf) {
if (this._state.kind !== IncrementalStateKind.Analyzed) {
throw new Error(`AssertionError: Expected successfully analyzed compilation.`);
}
this._state.emitted.add(absoluteFromSourceFile(sf));
}
priorAnalysisFor(sf) {
if (this.step === null) {
return null;
}
const sfPath = absoluteFromSourceFile(sf);
if (this.step.logicallyChangedTsFiles.has(sfPath)) {
return null;
}
const priorAnalysis = this.step.priorState.priorAnalysis;
if (!priorAnalysis.has(sf)) {
return null;
}
return priorAnalysis.get(sf);
}
priorTypeCheckingResultsFor(sf) {
if (this.phase.kind !== PhaseKind.TypeCheckAndEmit) {
throw new Error(`AssertionError: Expected successfully analyzed compilation.`);
}
if (this.step === null) {
return null;
}
const sfPath = absoluteFromSourceFile(sf);
if (this.step.logicallyChangedTsFiles.has(sfPath) || this.phase.needsTypeCheckEmit.has(sfPath)) {
return null;
}
if (this.step.priorState.typeCheckResults === null || !this.step.priorState.typeCheckResults.has(sfPath)) {
return null;
}
const priorResults = this.step.priorState.typeCheckResults.get(sfPath);
if (priorResults.hasInlines) {
return null;
}
return priorResults;
}
safeToSkipEmit(sf) {
if (this.step === null) {
return false;
}
const sfPath = absoluteFromSourceFile(sf);
if (this.step.logicallyChangedTsFiles.has(sfPath)) {
return false;
}
if (this.phase.kind !== PhaseKind.TypeCheckAndEmit) {
throw new Error(`AssertionError: Expected successful analysis before attempting to emit files`);
}
if (this.phase.needsEmit.has(sfPath)) {
return false;
}
return this.step.priorState.emitted.has(sfPath);
}
};
function toOriginalSourceFile(sf) {
const unredirectedSf = toUnredirectedSourceFile(sf);
const originalFile = unredirectedSf[NgOriginalFile];
if (originalFile !== void 0) {
return originalFile;
} else {
return unredirectedSf;
}
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/incremental/src/strategy.mjs
var TrackedIncrementalBuildStrategy = class {
constructor() {
this.state = null;
this.isSet = false;
}
getIncrementalState() {
return this.state;
}
setIncrementalState(state) {
this.state = state;
this.isSet = true;
}
toNextBuildStrategy() {
const strategy = new TrackedIncrementalBuildStrategy();
strategy.state = this.isSet ? this.state : null;
return strategy;
}
};
var SYM_INCREMENTAL_STATE = Symbol("NgIncrementalState");
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/indexer/src/api.mjs
var IdentifierKind;
(function(IdentifierKind2) {
IdentifierKind2[IdentifierKind2["Property"] = 0] = "Property";
IdentifierKind2[IdentifierKind2["Method"] = 1] = "Method";
IdentifierKind2[IdentifierKind2["Element"] = 2] = "Element";
IdentifierKind2[IdentifierKind2["Template"] = 3] = "Template";
IdentifierKind2[IdentifierKind2["Attribute"] = 4] = "Attribute";
IdentifierKind2[IdentifierKind2["Reference"] = 5] = "Reference";
IdentifierKind2[IdentifierKind2["Variable"] = 6] = "Variable";
IdentifierKind2[IdentifierKind2["LetDeclaration"] = 7] = "LetDeclaration";
})(IdentifierKind || (IdentifierKind = {}));
var AbsoluteSourceSpan2 = class {
constructor(start, end) {
this.start = start;
this.end = end;
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/indexer/src/context.mjs
var IndexingContext = class {
constructor() {
this.components = /* @__PURE__ */ new Set();
}
addComponent(info) {
this.components.add(info);
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/indexer/src/template.mjs
var ExpressionVisitor = class extends RecursiveAstVisitor2 {
constructor(expressionStr, absoluteOffset, boundTemplate, targetToIdentifier) {
super();
this.expressionStr = expressionStr;
this.absoluteOffset = absoluteOffset;
this.boundTemplate = boundTemplate;
this.targetToIdentifier = targetToIdentifier;
this.identifiers = [];
this.errors = [];
}
static getIdentifiers(ast, source, absoluteOffset, boundTemplate, targetToIdentifier) {
const visitor = new ExpressionVisitor(source, absoluteOffset, boundTemplate, targetToIdentifier);
visitor.visit(ast);
return { identifiers: visitor.identifiers, errors: visitor.errors };
}
visit(ast) {
ast.visit(this);
}
visitPropertyRead(ast, context) {
this.visitIdentifier(ast, IdentifierKind.Property);
super.visitPropertyRead(ast, context);
}
visitPropertyWrite(ast, context) {
this.visitIdentifier(ast, IdentifierKind.Property);
super.visitPropertyWrite(ast, context);
}
visitIdentifier(ast, kind) {
if (!(ast.receiver instanceof ImplicitReceiver)) {
return;
}
let identifierStart = ast.sourceSpan.start - this.absoluteOffset;
if (ast instanceof PropertyRead || ast instanceof PropertyWrite) {
identifierStart = ast.nameSpan.start - this.absoluteOffset;
}
if (!this.expressionStr.substring(identifierStart).startsWith(ast.name)) {
this.errors.push(new Error(`Impossible state: "${ast.name}" not found in "${this.expressionStr}" at location ${identifierStart}`));
return;
}
const absoluteStart = this.absoluteOffset + identifierStart;
const span = new AbsoluteSourceSpan2(absoluteStart, absoluteStart + ast.name.length);
const targetAst = this.boundTemplate.getExpressionTarget(ast);
const target = targetAst ? this.targetToIdentifier(targetAst) : null;
const identifier = {
name: ast.name,
span,
kind,
target
};
this.identifiers.push(identifier);
}
};
var TemplateVisitor = class extends RecursiveVisitor {
constructor(boundTemplate) {
super();
this.boundTemplate = boundTemplate;
this.identifiers = /* @__PURE__ */ new Set();
this.errors = [];
this.targetIdentifierCache = /* @__PURE__ */ new Map();
this.elementAndTemplateIdentifierCache = /* @__PURE__ */ new Map();
}
visit(node) {
node.visit(this);
}
visitAll(nodes) {
nodes.forEach((node) => this.visit(node));
}
visitElement(element2) {
const elementIdentifier = this.elementOrTemplateToIdentifier(element2);
if (elementIdentifier !== null) {
this.identifiers.add(elementIdentifier);
}
this.visitAll(element2.references);
this.visitAll(element2.inputs);
this.visitAll(element2.attributes);
this.visitAll(element2.children);
this.visitAll(element2.outputs);
}
visitTemplate(template2) {
const templateIdentifier = this.elementOrTemplateToIdentifier(template2);
if (templateIdentifier !== null) {
this.identifiers.add(templateIdentifier);
}
this.visitAll(template2.variables);
this.visitAll(template2.attributes);
this.visitAll(template2.templateAttrs);
this.visitAll(template2.children);
this.visitAll(template2.references);
}
visitBoundAttribute(attribute2) {
if (attribute2.valueSpan === void 0) {
return;
}
const { identifiers, errors } = ExpressionVisitor.getIdentifiers(attribute2.value, attribute2.valueSpan.toString(), attribute2.valueSpan.start.offset, this.boundTemplate, this.targetToIdentifier.bind(this));
identifiers.forEach((id) => this.identifiers.add(id));
this.errors.push(...errors);
}
visitBoundEvent(attribute2) {
this.visitExpression(attribute2.handler);
}
visitBoundText(text2) {
this.visitExpression(text2.value);
}
visitReference(reference2) {
const referenceIdentifier = this.targetToIdentifier(reference2);
if (referenceIdentifier === null) {
return;
}
this.identifiers.add(referenceIdentifier);
}
visitVariable(variable2) {
const variableIdentifier = this.targetToIdentifier(variable2);
if (variableIdentifier === null) {
return;
}
this.identifiers.add(variableIdentifier);
}
visitDeferredBlock(deferred) {
deferred.visitAll(this);
}
visitDeferredBlockPlaceholder(block) {
this.visitAll(block.children);
}
visitDeferredBlockError(block) {
this.visitAll(block.children);
}
visitDeferredBlockLoading(block) {
this.visitAll(block.children);
}
visitDeferredTrigger(trigger) {
if (trigger instanceof BoundDeferredTrigger) {
this.visitExpression(trigger.value);
}
}
visitSwitchBlock(block) {
this.visitExpression(block.expression);
this.visitAll(block.cases);
}
visitSwitchBlockCase(block) {
block.expression && this.visitExpression(block.expression);
this.visitAll(block.children);
}
visitForLoopBlock(block) {
var _a2;
block.item.visit(this);
this.visitAll(block.contextVariables);
this.visitExpression(block.expression);
this.visitAll(block.children);
(_a2 = block.empty) == null ? void 0 : _a2.visit(this);
}
visitForLoopBlockEmpty(block) {
this.visitAll(block.children);
}
visitIfBlock(block) {
this.visitAll(block.branches);
}
visitIfBlockBranch(block) {
var _a2;
block.expression && this.visitExpression(block.expression);
(_a2 = block.expressionAlias) == null ? void 0 : _a2.visit(this);
this.visitAll(block.children);
}
visitLetDeclaration(decl) {
const identifier = this.targetToIdentifier(decl);
if (identifier !== null) {
this.identifiers.add(identifier);
}
this.visitExpression(decl.value);
}
elementOrTemplateToIdentifier(node) {
var _a2;
if (this.elementAndTemplateIdentifierCache.has(node)) {
return this.elementAndTemplateIdentifierCache.get(node);
}
let name;
let kind;
if (node instanceof Template) {
name = (_a2 = node.tagName) != null ? _a2 : "ng-template";
kind = IdentifierKind.Template;
} else {
name = node.name;
kind = IdentifierKind.Element;
}
if (name.startsWith(":")) {
name = name.split(":").pop();
}
const sourceSpan = node.startSourceSpan;
const start = this.getStartLocation(name, sourceSpan);
if (start === null) {
return null;
}
const absoluteSpan = new AbsoluteSourceSpan2(start, start + name.length);
const attributes = node.attributes.map(({ name: name2, sourceSpan: sourceSpan2 }) => {
return {
name: name2,
span: new AbsoluteSourceSpan2(sourceSpan2.start.offset, sourceSpan2.end.offset),
kind: IdentifierKind.Attribute
};
});
const usedDirectives = this.boundTemplate.getDirectivesOfNode(node) || [];
const identifier = {
name,
span: absoluteSpan,
kind,
attributes: new Set(attributes),
usedDirectives: new Set(usedDirectives.map((dir) => {
return {
node: dir.ref.node,
selector: dir.selector
};
}))
};
this.elementAndTemplateIdentifierCache.set(node, identifier);
return identifier;
}
targetToIdentifier(node) {
if (this.targetIdentifierCache.has(node)) {
return this.targetIdentifierCache.get(node);
}
const { name, sourceSpan } = node;
const start = this.getStartLocation(name, sourceSpan);
if (start === null) {
return null;
}
const span = new AbsoluteSourceSpan2(start, start + name.length);
let identifier;
if (node instanceof Reference) {
const refTarget = this.boundTemplate.getReferenceTarget(node);
let target = null;
if (refTarget) {
let node2 = null;
let directive = null;
if (refTarget instanceof Element || refTarget instanceof Template) {
node2 = this.elementOrTemplateToIdentifier(refTarget);
} else {
node2 = this.elementOrTemplateToIdentifier(refTarget.node);
directive = refTarget.directive.ref.node;
}
if (node2 === null) {
return null;
}
target = {
node: node2,
directive
};
}
identifier = {
name,
span,
kind: IdentifierKind.Reference,
target
};
} else if (node instanceof Variable) {
identifier = {
name,
span,
kind: IdentifierKind.Variable
};
} else {
identifier = {
name,
span,
kind: IdentifierKind.LetDeclaration
};
}
this.targetIdentifierCache.set(node, identifier);
return identifier;
}
getStartLocation(name, context) {
const localStr = context.toString();
if (!localStr.includes(name)) {
this.errors.push(new Error(`Impossible state: "${name}" not found in "${localStr}"`));
return null;
}
return context.start.offset + localStr.indexOf(name);
}
visitExpression(ast) {
if (ast instanceof ASTWithSource && ast.source !== null) {
const targetToIdentifier = this.targetToIdentifier.bind(this);
const absoluteOffset = ast.sourceSpan.start;
const { identifiers, errors } = ExpressionVisitor.getIdentifiers(ast, ast.source, absoluteOffset, this.boundTemplate, targetToIdentifier);
identifiers.forEach((id) => this.identifiers.add(id));
this.errors.push(...errors);
}
}
};
function getTemplateIdentifiers(boundTemplate) {
const visitor = new TemplateVisitor(boundTemplate);
if (boundTemplate.target.template !== void 0) {
visitor.visitAll(boundTemplate.target.template);
}
return { identifiers: visitor.identifiers, errors: visitor.errors };
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/indexer/src/transform.mjs
function generateAnalysis(context) {
const analysis = /* @__PURE__ */ new Map();
context.components.forEach(({ declaration, selector, boundTemplate, templateMeta }) => {
const name = declaration.name.getText();
const usedComponents = /* @__PURE__ */ new Set();
const usedDirs = boundTemplate.getUsedDirectives();
usedDirs.forEach((dir) => {
if (dir.isComponent) {
usedComponents.add(dir.ref.node);
}
});
const componentFile = new ParseSourceFile(declaration.getSourceFile().getFullText(), declaration.getSourceFile().fileName);
let templateFile;
if (templateMeta.isInline) {
templateFile = componentFile;
} else {
templateFile = templateMeta.file;
}
const { identifiers, errors } = getTemplateIdentifiers(boundTemplate);
analysis.set(declaration, {
name,
selector,
file: componentFile,
template: {
identifiers,
usedComponents,
isInline: templateMeta.isInline,
file: templateFile
},
errors
});
});
return analysis;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/metadata/src/ng_module_index.mjs
var NgModuleIndexImpl = class {
constructor(metaReader, localReader) {
this.metaReader = metaReader;
this.localReader = localReader;
this.ngModuleAuthoritativeReference = /* @__PURE__ */ new Map();
this.typeToExportingModules = /* @__PURE__ */ new Map();
this.indexed = false;
}
updateWith(cache, key, elem) {
if (cache.has(key)) {
cache.get(key).add(elem);
} else {
const set = /* @__PURE__ */ new Set();
set.add(elem);
cache.set(key, set);
}
}
index() {
const seenTypesWithReexports = /* @__PURE__ */ new Map();
const locallyDeclaredDirsAndNgModules = [
...this.localReader.getKnown(MetaKind.NgModule),
...this.localReader.getKnown(MetaKind.Directive)
];
for (const decl of locallyDeclaredDirsAndNgModules) {
this.indexTrait(new Reference2(decl), seenTypesWithReexports);
}
this.indexed = true;
}
indexTrait(ref, seenTypesWithReexports) {
var _a2, _b2, _c2;
if (seenTypesWithReexports.has(ref.node)) {
return;
}
seenTypesWithReexports.set(ref.node, /* @__PURE__ */ new Set());
const meta = (_a2 = this.metaReader.getDirectiveMetadata(ref)) != null ? _a2 : this.metaReader.getNgModuleMetadata(ref);
if (meta === null) {
return;
}
if (meta.imports !== null) {
for (const childRef of meta.imports) {
this.indexTrait(childRef, seenTypesWithReexports);
}
}
if (meta.kind === MetaKind.NgModule) {
if (!this.ngModuleAuthoritativeReference.has(ref.node)) {
this.ngModuleAuthoritativeReference.set(ref.node, ref);
}
for (const childRef of meta.exports) {
this.indexTrait(childRef, seenTypesWithReexports);
const childMeta = (_c2 = (_b2 = this.metaReader.getDirectiveMetadata(childRef)) != null ? _b2 : this.metaReader.getPipeMetadata(childRef)) != null ? _c2 : this.metaReader.getNgModuleMetadata(childRef);
if (childMeta === null) {
continue;
}
switch (childMeta.kind) {
case MetaKind.Directive:
case MetaKind.Pipe:
this.updateWith(this.typeToExportingModules, childRef.node, ref.node);
this.updateWith(seenTypesWithReexports, ref.node, childRef.node);
break;
case MetaKind.NgModule:
if (seenTypesWithReexports.has(childRef.node)) {
for (const reexported of seenTypesWithReexports.get(childRef.node)) {
this.updateWith(this.typeToExportingModules, reexported, ref.node);
this.updateWith(seenTypesWithReexports, ref.node, reexported);
}
}
break;
}
}
}
}
getNgModulesExporting(directiveOrPipe) {
if (!this.indexed) {
this.index();
}
if (!this.typeToExportingModules.has(directiveOrPipe)) {
return [];
}
const refs = [];
for (const ngModule of this.typeToExportingModules.get(directiveOrPipe)) {
if (this.ngModuleAuthoritativeReference.has(ngModule)) {
refs.push(this.ngModuleAuthoritativeReference.get(ngModule));
}
}
return refs;
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/resource/src/loader.mjs
var import_typescript113 = __toESM(require("typescript"), 1);
var CSS_PREPROCESSOR_EXT = /(\.scss|\.sass|\.less|\.styl)$/;
var RESOURCE_MARKER = ".$ngresource$";
var RESOURCE_MARKER_TS = RESOURCE_MARKER + ".ts";
var AdapterResourceLoader = class {
constructor(adapter, options) {
this.adapter = adapter;
this.options = options;
this.cache = /* @__PURE__ */ new Map();
this.fetching = /* @__PURE__ */ new Map();
this.lookupResolutionHost = createLookupResolutionHost(this.adapter);
this.canPreload = !!this.adapter.readResource;
this.canPreprocess = !!this.adapter.transformResource;
}
resolve(url, fromFile) {
let resolvedUrl = null;
if (this.adapter.resourceNameToFileName) {
resolvedUrl = this.adapter.resourceNameToFileName(url, fromFile, (url2, fromFile2) => this.fallbackResolve(url2, fromFile2));
} else {
resolvedUrl = this.fallbackResolve(url, fromFile);
}
if (resolvedUrl === null) {
throw new Error(`HostResourceResolver: could not resolve ${url} in context of ${fromFile})`);
}
return resolvedUrl;
}
preload(resolvedUrl, context) {
if (!this.adapter.readResource) {
throw new Error("HostResourceLoader: the CompilerHost provided does not support pre-loading resources.");
}
if (this.cache.has(resolvedUrl)) {
return void 0;
} else if (this.fetching.has(resolvedUrl)) {
return this.fetching.get(resolvedUrl);
}
let result = this.adapter.readResource(resolvedUrl);
if (this.adapter.transformResource && context.type === "style") {
const resourceContext = {
type: "style",
containingFile: context.containingFile,
resourceFile: resolvedUrl
};
result = Promise.resolve(result).then((str) => __async(this, null, function* () {
const transformResult = yield this.adapter.transformResource(str, resourceContext);
return transformResult === null ? str : transformResult.content;
}));
}
if (typeof result === "string") {
this.cache.set(resolvedUrl, result);
return void 0;
} else {
const fetchCompletion = result.then((str) => {
this.fetching.delete(resolvedUrl);
this.cache.set(resolvedUrl, str);
});
this.fetching.set(resolvedUrl, fetchCompletion);
return fetchCompletion;
}
}
preprocessInline(data, context) {
return __async(this, null, function* () {
if (!this.adapter.transformResource || context.type !== "style") {
return data;
}
const transformResult = yield this.adapter.transformResource(data, {
type: "style",
containingFile: context.containingFile,
resourceFile: null
});
if (transformResult === null) {
return data;
}
return transformResult.content;
});
}
load(resolvedUrl) {
if (this.cache.has(resolvedUrl)) {
return this.cache.get(resolvedUrl);
}
const result = this.adapter.readResource ? this.adapter.readResource(resolvedUrl) : this.adapter.readFile(resolvedUrl);
if (typeof result !== "string") {
throw new Error(`HostResourceLoader: loader(${resolvedUrl}) returned a Promise`);
}
this.cache.set(resolvedUrl, result);
return result;
}
invalidate() {
this.cache.clear();
}
fallbackResolve(url, fromFile) {
let candidateLocations;
if (url.startsWith("/")) {
candidateLocations = this.getRootedCandidateLocations(url);
} else {
if (!url.startsWith(".")) {
url = `./${url}`;
}
candidateLocations = this.getResolvedCandidateLocations(url, fromFile);
}
for (const candidate of candidateLocations) {
if (this.adapter.fileExists(candidate)) {
return candidate;
} else if (CSS_PREPROCESSOR_EXT.test(candidate)) {
const cssFallbackUrl = candidate.replace(CSS_PREPROCESSOR_EXT, ".css");
if (this.adapter.fileExists(cssFallbackUrl)) {
return cssFallbackUrl;
}
}
}
return null;
}
getRootedCandidateLocations(url) {
const segment = "." + url;
return this.adapter.rootDirs.map((rootDir) => join(rootDir, segment));
}
getResolvedCandidateLocations(url, fromFile) {
const failedLookup = import_typescript113.default.resolveModuleName(url + RESOURCE_MARKER, fromFile, this.options, this.lookupResolutionHost);
if (failedLookup.failedLookupLocations === void 0) {
throw new Error(`Internal error: expected to find failedLookupLocations during resolution of resource '${url}' in context of ${fromFile}`);
}
return failedLookup.failedLookupLocations.filter((candidate) => candidate.endsWith(RESOURCE_MARKER_TS)).map((candidate) => candidate.slice(0, -RESOURCE_MARKER_TS.length));
}
};
function createLookupResolutionHost(adapter) {
var _a2, _b2, _c2;
return {
directoryExists(directoryName) {
if (directoryName.includes(RESOURCE_MARKER)) {
return false;
} else if (adapter.directoryExists !== void 0) {
return adapter.directoryExists(directoryName);
} else {
return true;
}
},
fileExists(fileName) {
if (fileName.includes(RESOURCE_MARKER)) {
return false;
} else {
return adapter.fileExists(fileName);
}
},
readFile: adapter.readFile.bind(adapter),
getCurrentDirectory: adapter.getCurrentDirectory.bind(adapter),
getDirectories: (_a2 = adapter.getDirectories) == null ? void 0 : _a2.bind(adapter),
realpath: (_b2 = adapter.realpath) == null ? void 0 : _b2.bind(adapter),
trace: (_c2 = adapter.trace) == null ? void 0 : _c2.bind(adapter),
useCaseSensitiveFileNames: typeof adapter.useCaseSensitiveFileNames === "function" ? adapter.useCaseSensitiveFileNames.bind(adapter) : adapter.useCaseSensitiveFileNames
};
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/scope/src/standalone.mjs
var StandaloneComponentScopeReader = class {
constructor(metaReader, localModuleReader, dtsModuleReader) {
this.metaReader = metaReader;
this.localModuleReader = localModuleReader;
this.dtsModuleReader = dtsModuleReader;
this.cache = /* @__PURE__ */ new Map();
}
getScopeForComponent(clazz) {
var _a2;
if (!this.cache.has(clazz)) {
const clazzRef = new Reference2(clazz);
const clazzMeta = this.metaReader.getDirectiveMetadata(clazzRef);
if (clazzMeta === null || !clazzMeta.isComponent || !clazzMeta.isStandalone) {
this.cache.set(clazz, null);
return null;
}
const dependencies = /* @__PURE__ */ new Set([clazzMeta]);
const deferredDependencies = /* @__PURE__ */ new Set();
const seen = /* @__PURE__ */ new Set([clazz]);
let isPoisoned = clazzMeta.isPoisoned;
if (clazzMeta.imports !== null) {
for (const ref of clazzMeta.imports) {
if (seen.has(ref.node)) {
continue;
}
seen.add(ref.node);
const dirMeta = this.metaReader.getDirectiveMetadata(ref);
if (dirMeta !== null) {
dependencies.add(__spreadProps(__spreadValues({}, dirMeta), { ref }));
isPoisoned = isPoisoned || dirMeta.isPoisoned || !dirMeta.isStandalone;
continue;
}
const pipeMeta = this.metaReader.getPipeMetadata(ref);
if (pipeMeta !== null) {
dependencies.add(__spreadProps(__spreadValues({}, pipeMeta), { ref }));
isPoisoned = isPoisoned || !pipeMeta.isStandalone;
continue;
}
const ngModuleMeta = this.metaReader.getNgModuleMetadata(ref);
if (ngModuleMeta !== null) {
dependencies.add(__spreadProps(__spreadValues({}, ngModuleMeta), { ref }));
let ngModuleScope;
if (ref.node.getSourceFile().isDeclarationFile) {
ngModuleScope = this.dtsModuleReader.resolve(ref);
} else {
ngModuleScope = this.localModuleReader.getScopeOfModule(ref.node);
}
if (ngModuleScope === null) {
isPoisoned = true;
continue;
}
isPoisoned = isPoisoned || ngModuleScope.exported.isPoisoned;
for (const dep of ngModuleScope.exported.dependencies) {
if (!seen.has(dep.ref.node)) {
seen.add(dep.ref.node);
dependencies.add(dep);
}
}
continue;
}
isPoisoned = true;
}
}
if (clazzMeta.deferredImports !== null) {
for (const ref of clazzMeta.deferredImports) {
const dirMeta = this.metaReader.getDirectiveMetadata(ref);
if (dirMeta !== null) {
deferredDependencies.add(__spreadProps(__spreadValues({}, dirMeta), { ref, isExplicitlyDeferred: true }));
isPoisoned = isPoisoned || dirMeta.isPoisoned || !dirMeta.isStandalone;
continue;
}
const pipeMeta = this.metaReader.getPipeMetadata(ref);
if (pipeMeta !== null) {
deferredDependencies.add(__spreadProps(__spreadValues({}, pipeMeta), { ref, isExplicitlyDeferred: true }));
isPoisoned = isPoisoned || !pipeMeta.isStandalone;
continue;
}
}
}
this.cache.set(clazz, {
kind: ComponentScopeKind.Standalone,
component: clazz,
dependencies: Array.from(dependencies),
deferredDependencies: Array.from(deferredDependencies),
isPoisoned,
schemas: (_a2 = clazzMeta.schemas) != null ? _a2 : []
});
}
return this.cache.get(clazz);
}
getRemoteScope() {
return null;
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/symbol_util.mjs
var import_typescript114 = __toESM(require("typescript"), 1);
var SIGNAL_FNS = /* @__PURE__ */ new Set([
"WritableSignal",
"Signal",
"InputSignal",
"InputSignalWithTransform",
"ModelSignal"
]);
function isSignalReference(symbol) {
return (symbol.kind === SymbolKind.Expression || symbol.kind === SymbolKind.Variable || symbol.kind === SymbolKind.LetDeclaration) && (symbol.tsType.symbol !== void 0 && isSignalSymbol(symbol.tsType.symbol) || symbol.tsType.aliasSymbol !== void 0 && isSignalSymbol(symbol.tsType.aliasSymbol));
}
function isSignalSymbol(symbol) {
const declarations = symbol.getDeclarations();
return declarations !== void 0 && declarations.some((decl) => {
const fileName = decl.getSourceFile().fileName;
return (import_typescript114.default.isInterfaceDeclaration(decl) || import_typescript114.default.isTypeAliasDeclaration(decl)) && SIGNAL_FNS.has(decl.name.text) && (fileName.includes("@angular/core") || fileName.includes("angular2/rc/packages/core"));
});
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/extended/api/api.mjs
var TemplateCheckWithVisitor = class {
constructor() {
this.canVisitStructuralAttributes = true;
}
run(ctx, component, template2) {
const visitor = new TemplateVisitor2(ctx, component, this);
return visitor.getDiagnostics(template2);
}
};
var TemplateVisitor2 = class extends RecursiveAstVisitor2 {
constructor(ctx, component, check) {
super();
this.ctx = ctx;
this.component = component;
this.check = check;
this.diagnostics = [];
}
visit(node, context) {
this.diagnostics.push(...this.check.visitNode(this.ctx, this.component, node));
node.visit(this);
}
visitAllNodes(nodes) {
for (const node of nodes) {
this.visit(node);
}
}
visitAst(ast) {
if (ast instanceof ASTWithSource) {
ast = ast.ast;
}
this.visit(ast);
}
visitElement(element2) {
this.visitAllNodes(element2.attributes);
this.visitAllNodes(element2.inputs);
this.visitAllNodes(element2.outputs);
this.visitAllNodes(element2.references);
this.visitAllNodes(element2.children);
}
visitTemplate(template2) {
const isInlineTemplate = template2.tagName === "ng-template";
this.visitAllNodes(template2.attributes);
if (isInlineTemplate) {
this.visitAllNodes(template2.inputs);
this.visitAllNodes(template2.outputs);
}
if (this.check.canVisitStructuralAttributes || isInlineTemplate) {
this.visitAllNodes(template2.templateAttrs);
}
this.visitAllNodes(template2.variables);
this.visitAllNodes(template2.references);
this.visitAllNodes(template2.children);
}
visitContent(content) {
this.visitAllNodes(content.children);
}
visitVariable(variable2) {
}
visitReference(reference2) {
}
visitTextAttribute(attribute2) {
}
visitUnknownBlock(block) {
}
visitBoundAttribute(attribute2) {
this.visitAst(attribute2.value);
}
visitBoundEvent(attribute2) {
this.visitAst(attribute2.handler);
}
visitText(text2) {
}
visitBoundText(text2) {
this.visitAst(text2.value);
}
visitIcu(icu) {
Object.keys(icu.vars).forEach((key) => this.visit(icu.vars[key]));
Object.keys(icu.placeholders).forEach((key) => this.visit(icu.placeholders[key]));
}
visitDeferredBlock(deferred) {
deferred.visitAll(this);
}
visitDeferredTrigger(trigger) {
if (trigger instanceof BoundDeferredTrigger) {
this.visitAst(trigger.value);
}
}
visitDeferredBlockPlaceholder(block) {
this.visitAllNodes(block.children);
}
visitDeferredBlockError(block) {
this.visitAllNodes(block.children);
}
visitDeferredBlockLoading(block) {
this.visitAllNodes(block.children);
}
visitSwitchBlock(block) {
this.visitAst(block.expression);
this.visitAllNodes(block.cases);
}
visitSwitchBlockCase(block) {
block.expression && this.visitAst(block.expression);
this.visitAllNodes(block.children);
}
visitForLoopBlock(block) {
var _a2;
block.item.visit(this);
this.visitAllNodes(block.contextVariables);
this.visitAst(block.expression);
this.visitAllNodes(block.children);
(_a2 = block.empty) == null ? void 0 : _a2.visit(this);
}
visitForLoopBlockEmpty(block) {
this.visitAllNodes(block.children);
}
visitIfBlock(block) {
this.visitAllNodes(block.branches);
}
visitIfBlockBranch(block) {
var _a2;
block.expression && this.visitAst(block.expression);
(_a2 = block.expressionAlias) == null ? void 0 : _a2.visit(this);
this.visitAllNodes(block.children);
}
visitLetDeclaration(decl) {
this.visitAst(decl.value);
}
getDiagnostics(template2) {
this.diagnostics = [];
this.visitAllNodes(template2);
return this.diagnostics;
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/interpolated_signal_not_invoked/index.mjs
var SIGNAL_INSTANCE_PROPERTIES = /* @__PURE__ */ new Set(["set", "update", "asReadonly"]);
var FUNCTION_INSTANCE_PROPERTIES = /* @__PURE__ */ new Set(["name", "length", "prototype"]);
var InterpolatedSignalCheck = class extends TemplateCheckWithVisitor {
constructor() {
super(...arguments);
this.code = ErrorCode.INTERPOLATED_SIGNAL_NOT_INVOKED;
}
visitNode(ctx, component, node) {
if (node instanceof Interpolation) {
return node.expressions.filter((item) => item instanceof PropertyRead).flatMap((item) => buildDiagnosticForSignal(ctx, item, component));
} else if (node instanceof BoundAttribute) {
const usedDirectives = ctx.templateTypeChecker.getUsedDirectives(component);
if (usedDirectives !== null && usedDirectives.some((dir) => dir.inputs.getByBindingPropertyName(node.name) !== null)) {
return [];
}
if ((node.type === BindingType.Property || node.type === BindingType.Class || node.type === BindingType.Style || node.type === BindingType.Attribute || node.type === BindingType.Animation) && node.value instanceof ASTWithSource && node.value.ast instanceof PropertyRead) {
return buildDiagnosticForSignal(ctx, node.value.ast, component);
}
}
return [];
}
};
function isFunctionInstanceProperty(name) {
return FUNCTION_INSTANCE_PROPERTIES.has(name);
}
function isSignalInstanceProperty(name) {
return SIGNAL_INSTANCE_PROPERTIES.has(name);
}
function buildDiagnosticForSignal(ctx, node, component) {
const symbol = ctx.templateTypeChecker.getSymbolOfNode(node, component);
if (symbol !== null && symbol.kind === SymbolKind.Expression && isSignalReference(symbol)) {
const templateMapping = ctx.templateTypeChecker.getTemplateMappingAtTcbLocation(symbol.tcbLocation);
const errorString = `${node.name} is a function and should be invoked: ${node.name}()`;
const diagnostic = ctx.makeTemplateDiagnostic(templateMapping.span, errorString);
return [diagnostic];
}
const symbolOfReceiver = ctx.templateTypeChecker.getSymbolOfNode(node.receiver, component);
if ((isFunctionInstanceProperty(node.name) || isSignalInstanceProperty(node.name)) && symbolOfReceiver !== null && symbolOfReceiver.kind === SymbolKind.Expression && isSignalReference(symbolOfReceiver)) {
const templateMapping = ctx.templateTypeChecker.getTemplateMappingAtTcbLocation(symbolOfReceiver.tcbLocation);
const errorString = `${node.receiver.name} is a function and should be invoked: ${node.receiver.name}()`;
const diagnostic = ctx.makeTemplateDiagnostic(templateMapping.span, errorString);
return [diagnostic];
}
return [];
}
var factory = {
code: ErrorCode.INTERPOLATED_SIGNAL_NOT_INVOKED,
name: ExtendedTemplateDiagnosticName.INTERPOLATED_SIGNAL_NOT_INVOKED,
create: () => new InterpolatedSignalCheck()
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/invalid_banana_in_box/index.mjs
var InvalidBananaInBoxCheck = class extends TemplateCheckWithVisitor {
constructor() {
super(...arguments);
this.code = ErrorCode.INVALID_BANANA_IN_BOX;
}
visitNode(ctx, component, node) {
if (!(node instanceof BoundEvent))
return [];
const name = node.name;
if (!name.startsWith("[") || !name.endsWith("]"))
return [];
const boundSyntax = node.sourceSpan.toString();
const expectedBoundSyntax = boundSyntax.replace(`(${name})`, `[(${name.slice(1, -1)})]`);
const diagnostic = ctx.makeTemplateDiagnostic(node.sourceSpan, `In the two-way binding syntax the parentheses should be inside the brackets, ex. '${expectedBoundSyntax}'.
Find more at https://angular.dev/guide/templates/two-way-binding`);
return [diagnostic];
}
};
var factory2 = {
code: ErrorCode.INVALID_BANANA_IN_BOX,
name: ExtendedTemplateDiagnosticName.INVALID_BANANA_IN_BOX,
create: () => new InvalidBananaInBoxCheck()
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/missing_control_flow_directive/index.mjs
var KNOWN_CONTROL_FLOW_DIRECTIVES = /* @__PURE__ */ new Map([
["ngIf", { directive: "NgIf", builtIn: "@if" }],
["ngFor", { directive: "NgFor", builtIn: "@for" }],
["ngSwitchCase", { directive: "NgSwitchCase", builtIn: "@switch with @case" }],
["ngSwitchDefault", { directive: "NgSwitchDefault", builtIn: "@switch with @default" }]
]);
var MissingControlFlowDirectiveCheck = class extends TemplateCheckWithVisitor {
constructor() {
super(...arguments);
this.code = ErrorCode.MISSING_CONTROL_FLOW_DIRECTIVE;
}
run(ctx, component, template2) {
const componentMetadata = ctx.templateTypeChecker.getDirectiveMetadata(component);
if (!componentMetadata || !componentMetadata.isStandalone) {
return [];
}
return super.run(ctx, component, template2);
}
visitNode(ctx, component, node) {
if (!(node instanceof Template))
return [];
const controlFlowAttr = node.templateAttrs.find((attr) => KNOWN_CONTROL_FLOW_DIRECTIVES.has(attr.name));
if (!controlFlowAttr)
return [];
const symbol = ctx.templateTypeChecker.getSymbolOfNode(node, component);
if (symbol === null || symbol.directives.length > 0) {
return [];
}
const sourceSpan = controlFlowAttr.keySpan || controlFlowAttr.sourceSpan;
const directiveAndBuiltIn = KNOWN_CONTROL_FLOW_DIRECTIVES.get(controlFlowAttr.name);
const errorMessage = `The \`*${controlFlowAttr.name}\` directive was used in the template, but neither the \`${directiveAndBuiltIn == null ? void 0 : directiveAndBuiltIn.directive}\` directive nor the \`CommonModule\` was imported. Use Angular's built-in control flow ${directiveAndBuiltIn == null ? void 0 : directiveAndBuiltIn.builtIn} or make sure that either the \`${directiveAndBuiltIn == null ? void 0 : directiveAndBuiltIn.directive}\` directive or the \`CommonModule\` is included in the \`@Component.imports\` array of this component.`;
const diagnostic = ctx.makeTemplateDiagnostic(sourceSpan, errorMessage);
return [diagnostic];
}
};
var factory3 = {
code: ErrorCode.MISSING_CONTROL_FLOW_DIRECTIVE,
name: ExtendedTemplateDiagnosticName.MISSING_CONTROL_FLOW_DIRECTIVE,
create: (options) => {
return new MissingControlFlowDirectiveCheck();
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/missing_ngforof_let/index.mjs
var MissingNgForOfLetCheck = class extends TemplateCheckWithVisitor {
constructor() {
super(...arguments);
this.code = ErrorCode.MISSING_NGFOROF_LET;
}
visitNode(ctx, component, node) {
const isTemplate = node instanceof Template;
if (!(node instanceof Template)) {
return [];
}
if (node.templateAttrs.length === 0) {
return [];
}
const attr = node.templateAttrs.find((x) => x.name === "ngFor");
if (attr === void 0) {
return [];
}
if (node.variables.length > 0) {
return [];
}
const errorString = "Your ngFor is missing a value. Did you forget to add the `let` keyword?";
const diagnostic = ctx.makeTemplateDiagnostic(attr.sourceSpan, errorString);
return [diagnostic];
}
};
var factory4 = {
code: ErrorCode.MISSING_NGFOROF_LET,
name: ExtendedTemplateDiagnosticName.MISSING_NGFOROF_LET,
create: () => new MissingNgForOfLetCheck()
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/nullish_coalescing_not_nullable/index.mjs
var import_typescript115 = __toESM(require("typescript"), 1);
var NullishCoalescingNotNullableCheck = class extends TemplateCheckWithVisitor {
constructor() {
super(...arguments);
this.canVisitStructuralAttributes = false;
this.code = ErrorCode.NULLISH_COALESCING_NOT_NULLABLE;
}
visitNode(ctx, component, node) {
if (!(node instanceof Binary) || node.operation !== "??")
return [];
const symbolLeft = ctx.templateTypeChecker.getSymbolOfNode(node.left, component);
if (symbolLeft === null || symbolLeft.kind !== SymbolKind.Expression) {
return [];
}
const typeLeft = symbolLeft.tsType;
if (typeLeft.flags & (import_typescript115.default.TypeFlags.Any | import_typescript115.default.TypeFlags.Unknown)) {
return [];
}
if (typeLeft.getNonNullableType() !== typeLeft)
return [];
const symbol = ctx.templateTypeChecker.getSymbolOfNode(node, component);
if (symbol.kind !== SymbolKind.Expression) {
return [];
}
const templateMapping = ctx.templateTypeChecker.getTemplateMappingAtTcbLocation(symbol.tcbLocation);
if (templateMapping === null) {
return [];
}
const diagnostic = ctx.makeTemplateDiagnostic(templateMapping.span, `The left side of this nullish coalescing operation does not include 'null' or 'undefined' in its type, therefore the '??' operator can be safely removed.`);
return [diagnostic];
}
};
var factory5 = {
code: ErrorCode.NULLISH_COALESCING_NOT_NULLABLE,
name: ExtendedTemplateDiagnosticName.NULLISH_COALESCING_NOT_NULLABLE,
create: (options) => {
const strictNullChecks = options.strictNullChecks === void 0 ? !!options.strict : !!options.strictNullChecks;
if (!strictNullChecks) {
return null;
}
return new NullishCoalescingNotNullableCheck();
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/optional_chain_not_nullable/index.mjs
var import_typescript116 = __toESM(require("typescript"), 1);
var OptionalChainNotNullableCheck = class extends TemplateCheckWithVisitor {
constructor() {
super(...arguments);
this.canVisitStructuralAttributes = false;
this.code = ErrorCode.OPTIONAL_CHAIN_NOT_NULLABLE;
}
visitNode(ctx, component, node) {
if (!(node instanceof SafeCall) && !(node instanceof SafePropertyRead) && !(node instanceof SafeKeyedRead))
return [];
const symbolLeft = ctx.templateTypeChecker.getSymbolOfNode(node.receiver, component);
if (symbolLeft === null || symbolLeft.kind !== SymbolKind.Expression) {
return [];
}
const typeLeft = symbolLeft.tsType;
if (typeLeft.flags & (import_typescript116.default.TypeFlags.Any | import_typescript116.default.TypeFlags.Unknown)) {
return [];
}
if (typeLeft.getNonNullableType() !== typeLeft)
return [];
const symbol = ctx.templateTypeChecker.getSymbolOfNode(node, component);
if (symbol.kind !== SymbolKind.Expression) {
return [];
}
const templateMapping = ctx.templateTypeChecker.getTemplateMappingAtTcbLocation(symbol.tcbLocation);
if (templateMapping === null) {
return [];
}
const advice = node instanceof SafePropertyRead ? `the '?.' operator can be replaced with the '.' operator` : `the '?.' operator can be safely removed`;
const diagnostic = ctx.makeTemplateDiagnostic(templateMapping.span, `The left side of this optional chain operation does not include 'null' or 'undefined' in its type, therefore ${advice}.`);
return [diagnostic];
}
};
var factory6 = {
code: ErrorCode.OPTIONAL_CHAIN_NOT_NULLABLE,
name: ExtendedTemplateDiagnosticName.OPTIONAL_CHAIN_NOT_NULLABLE,
create: (options) => {
const strictNullChecks = options.strictNullChecks === void 0 ? !!options.strict : !!options.strictNullChecks;
if (!strictNullChecks) {
return null;
}
return new OptionalChainNotNullableCheck();
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/suffix_not_supported/index.mjs
var STYLE_SUFFIXES = ["px", "%", "em"];
var SuffixNotSupportedCheck = class extends TemplateCheckWithVisitor {
constructor() {
super(...arguments);
this.code = ErrorCode.SUFFIX_NOT_SUPPORTED;
}
visitNode(ctx, component, node) {
if (!(node instanceof BoundAttribute))
return [];
if (!node.keySpan.toString().startsWith("attr.") || !STYLE_SUFFIXES.some((suffix) => node.name.endsWith(`.${suffix}`))) {
return [];
}
const diagnostic = ctx.makeTemplateDiagnostic(node.keySpan, `The ${STYLE_SUFFIXES.map((suffix) => `'.${suffix}'`).join(", ")} suffixes are only supported on style bindings.`);
return [diagnostic];
}
};
var factory7 = {
code: ErrorCode.SUFFIX_NOT_SUPPORTED,
name: ExtendedTemplateDiagnosticName.SUFFIX_NOT_SUPPORTED,
create: () => new SuffixNotSupportedCheck()
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/text_attribute_not_binding/index.mjs
var TextAttributeNotBindingSpec = class extends TemplateCheckWithVisitor {
constructor() {
super(...arguments);
this.code = ErrorCode.TEXT_ATTRIBUTE_NOT_BINDING;
}
visitNode(ctx, component, node) {
if (!(node instanceof TextAttribute))
return [];
const name = node.name;
if (!name.startsWith("attr.") && !name.startsWith("style.") && !name.startsWith("class.")) {
return [];
}
let errorString;
if (name.startsWith("attr.")) {
const staticAttr = name.replace("attr.", "");
errorString = `Static attributes should be written without the 'attr.' prefix.`;
if (node.value) {
errorString += ` For example, ${staticAttr}="${node.value}".`;
}
} else {
const expectedKey = `[${name}]`;
const expectedValue = node.value === "true" || node.value === "false" ? node.value : `'${node.value}'`;
errorString = "Attribute, style, and class bindings should be enclosed with square braces.";
if (node.value) {
errorString += ` For example, '${expectedKey}="${expectedValue}"'.`;
}
}
const diagnostic = ctx.makeTemplateDiagnostic(node.sourceSpan, errorString);
return [diagnostic];
}
};
var factory8 = {
code: ErrorCode.TEXT_ATTRIBUTE_NOT_BINDING,
name: ExtendedTemplateDiagnosticName.TEXT_ATTRIBUTE_NOT_BINDING,
create: () => new TextAttributeNotBindingSpec()
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/uninvoked_function_in_event_binding/index.mjs
var UninvokedFunctionInEventBindingSpec = class extends TemplateCheckWithVisitor {
constructor() {
super(...arguments);
this.code = ErrorCode.UNINVOKED_FUNCTION_IN_EVENT_BINDING;
}
visitNode(ctx, component, node) {
if (!(node instanceof BoundEvent))
return [];
if (node.type !== ParsedEventType.Regular && node.type !== ParsedEventType.Animation)
return [];
if (!(node.handler instanceof ASTWithSource))
return [];
const sourceExpressionText = node.handler.source || "";
if (node.handler.ast instanceof Chain) {
return node.handler.ast.expressions.flatMap((expression) => assertExpressionInvoked(expression, component, node, sourceExpressionText, ctx));
}
if (node.handler.ast instanceof Conditional) {
const { trueExp, falseExp } = node.handler.ast;
return [trueExp, falseExp].flatMap((expression) => assertExpressionInvoked(expression, component, node, sourceExpressionText, ctx));
}
return assertExpressionInvoked(node.handler.ast, component, node, sourceExpressionText, ctx);
}
};
function assertExpressionInvoked(expression, component, node, expressionText, ctx) {
var _a2;
if (expression instanceof Call || expression instanceof SafeCall) {
return [];
}
if (!(expression instanceof PropertyRead) && !(expression instanceof SafePropertyRead)) {
return [];
}
const symbol = ctx.templateTypeChecker.getSymbolOfNode(expression, component);
if (symbol !== null && symbol.kind === SymbolKind.Expression) {
if (((_a2 = symbol.tsType.getCallSignatures()) == null ? void 0 : _a2.length) > 0) {
const fullExpressionText = generateStringFromExpression(expression, expressionText);
const errorString = `Function in event binding should be invoked: ${fullExpressionText}()`;
return [ctx.makeTemplateDiagnostic(node.sourceSpan, errorString)];
}
}
return [];
}
function generateStringFromExpression(expression, source) {
return source.substring(expression.span.start, expression.span.end);
}
var factory9 = {
code: ErrorCode.UNINVOKED_FUNCTION_IN_EVENT_BINDING,
name: ExtendedTemplateDiagnosticName.UNINVOKED_FUNCTION_IN_EVENT_BINDING,
create: () => new UninvokedFunctionInEventBindingSpec()
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/unused_let_declaration/index.mjs
var UnusedLetDeclarationCheck = class extends TemplateCheckWithVisitor {
constructor() {
super(...arguments);
this.code = ErrorCode.UNUSED_LET_DECLARATION;
this.analysis = /* @__PURE__ */ new Map();
}
run(ctx, component, template2) {
super.run(ctx, component, template2);
const diagnostics = [];
const { allLetDeclarations, usedLetDeclarations } = this.getAnalysis(component);
for (const decl of allLetDeclarations) {
if (!usedLetDeclarations.has(decl)) {
diagnostics.push(ctx.makeTemplateDiagnostic(decl.sourceSpan, `@let ${decl.name} is declared but its value is never read.`));
}
}
this.analysis.clear();
return diagnostics;
}
visitNode(ctx, component, node) {
if (node instanceof LetDeclaration) {
this.getAnalysis(component).allLetDeclarations.add(node);
} else if (node instanceof AST) {
const unwrappedNode = node instanceof ASTWithSource ? node.ast : node;
const target = ctx.templateTypeChecker.getExpressionTarget(unwrappedNode, component);
if (target !== null && target instanceof LetDeclaration) {
this.getAnalysis(component).usedLetDeclarations.add(target);
}
}
return [];
}
getAnalysis(node) {
if (!this.analysis.has(node)) {
this.analysis.set(node, { allLetDeclarations: /* @__PURE__ */ new Set(), usedLetDeclarations: /* @__PURE__ */ new Set() });
}
return this.analysis.get(node);
}
};
var factory10 = {
code: ErrorCode.UNUSED_LET_DECLARATION,
name: ExtendedTemplateDiagnosticName.UNUSED_LET_DECLARATION,
create: () => new UnusedLetDeclarationCheck()
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/extended/src/extended_template_checker.mjs
var import_typescript117 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/core/api/src/public_options.mjs
var DiagnosticCategoryLabel;
(function(DiagnosticCategoryLabel2) {
DiagnosticCategoryLabel2["Warning"] = "warning";
DiagnosticCategoryLabel2["Error"] = "error";
DiagnosticCategoryLabel2["Suppress"] = "suppress";
})(DiagnosticCategoryLabel || (DiagnosticCategoryLabel = {}));
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/extended/src/extended_template_checker.mjs
var ExtendedTemplateCheckerImpl = class {
constructor(templateTypeChecker, typeChecker, templateCheckFactories, options) {
var _a2, _b2, _c2, _d2, _e2;
this.partialCtx = { templateTypeChecker, typeChecker };
this.templateChecks = /* @__PURE__ */ new Map();
for (const factory11 of templateCheckFactories) {
const category = diagnosticLabelToCategory((_e2 = (_d2 = (_b2 = (_a2 = options == null ? void 0 : options.extendedDiagnostics) == null ? void 0 : _a2.checks) == null ? void 0 : _b2[factory11.name]) != null ? _d2 : (_c2 = options == null ? void 0 : options.extendedDiagnostics) == null ? void 0 : _c2.defaultCategory) != null ? _e2 : DiagnosticCategoryLabel.Warning);
if (category === null) {
continue;
}
const check = factory11.create(options);
if (check === null) {
continue;
}
this.templateChecks.set(check, category);
}
}
getDiagnosticsForComponent(component) {
const template2 = this.partialCtx.templateTypeChecker.getTemplate(component);
if (template2 === null) {
return [];
}
const diagnostics = [];
for (const [check, category] of this.templateChecks.entries()) {
const ctx = __spreadProps(__spreadValues({}, this.partialCtx), {
makeTemplateDiagnostic: (span, message, relatedInformation) => {
return this.partialCtx.templateTypeChecker.makeTemplateDiagnostic(component, span, category, check.code, message, relatedInformation);
}
});
diagnostics.push(...check.run(ctx, component, template2));
}
return diagnostics;
}
};
function diagnosticLabelToCategory(label) {
switch (label) {
case DiagnosticCategoryLabel.Warning:
return import_typescript117.default.DiagnosticCategory.Warning;
case DiagnosticCategoryLabel.Error:
return import_typescript117.default.DiagnosticCategory.Error;
case DiagnosticCategoryLabel.Suppress:
return null;
default:
return assertNever(label);
}
}
function assertNever(value) {
throw new Error(`Unexpected call to 'assertNever()' with value:
${value}`);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/extended/index.mjs
var ALL_DIAGNOSTIC_FACTORIES = [
factory2,
factory5,
factory6,
factory3,
factory8,
factory4,
factory7,
factory,
factory9,
factory10
];
var SUPPORTED_DIAGNOSTIC_NAMES = /* @__PURE__ */ new Set([
ExtendedTemplateDiagnosticName.CONTROL_FLOW_PREVENTING_CONTENT_PROJECTION,
...ALL_DIAGNOSTIC_FACTORIES.map((factory11) => factory11.name)
]);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/template_semantics/src/template_semantics_checker.mjs
var import_typescript118 = __toESM(require("typescript"), 1);
var TemplateSemanticsCheckerImpl = class {
constructor(templateTypeChecker) {
this.templateTypeChecker = templateTypeChecker;
}
getDiagnosticsForComponent(component) {
const template2 = this.templateTypeChecker.getTemplate(component);
return template2 !== null ? TemplateSemanticsVisitor.visit(template2, component, this.templateTypeChecker) : [];
}
};
var TemplateSemanticsVisitor = class extends RecursiveVisitor {
constructor(expressionVisitor) {
super();
this.expressionVisitor = expressionVisitor;
}
static visit(nodes, component, templateTypeChecker) {
const diagnostics = [];
const expressionVisitor = new ExpressionsSemanticsVisitor(templateTypeChecker, component, diagnostics);
const templateVisitor = new TemplateSemanticsVisitor(expressionVisitor);
nodes.forEach((node) => node.visit(templateVisitor));
return diagnostics;
}
visitBoundEvent(event) {
super.visitBoundEvent(event);
event.handler.visit(this.expressionVisitor, event);
}
};
var ExpressionsSemanticsVisitor = class extends RecursiveAstVisitor2 {
constructor(templateTypeChecker, component, diagnostics) {
super();
this.templateTypeChecker = templateTypeChecker;
this.component = component;
this.diagnostics = diagnostics;
}
visitPropertyWrite(ast, context) {
super.visitPropertyWrite(ast, context);
this.checkForIllegalWriteInEventBinding(ast, context);
}
visitPropertyRead(ast, context) {
super.visitPropertyRead(ast, context);
this.checkForIllegalWriteInTwoWayBinding(ast, context);
}
checkForIllegalWriteInEventBinding(ast, context) {
if (!(context instanceof BoundEvent) || !(ast.receiver instanceof ImplicitReceiver)) {
return;
}
const target = this.templateTypeChecker.getExpressionTarget(ast, this.component);
if (target instanceof Variable) {
const errorMessage = `Cannot use variable '${target.name}' as the left-hand side of an assignment expression. Template variables are read-only.`;
this.diagnostics.push(this.makeIllegalTemplateVarDiagnostic(target, context, errorMessage));
}
}
checkForIllegalWriteInTwoWayBinding(ast, context) {
if (!(context instanceof BoundEvent) || context.type !== ParsedEventType.TwoWay || !(ast.receiver instanceof ImplicitReceiver) || ast !== unwrapAstWithSource(context.handler)) {
return;
}
const target = this.templateTypeChecker.getExpressionTarget(ast, this.component);
const isVariable2 = target instanceof Variable;
const isLet = target instanceof LetDeclaration;
if (!isVariable2 && !isLet) {
return;
}
const symbol = this.templateTypeChecker.getSymbolOfNode(target, this.component);
if (symbol !== null && !isSignalReference(symbol)) {
let errorMessage;
if (isVariable2) {
errorMessage = `Cannot use a non-signal variable '${target.name}' in a two-way binding expression. Template variables are read-only.`;
} else {
errorMessage = `Cannot use non-signal @let declaration '${target.name}' in a two-way binding expression. @let declarations are read-only.`;
}
this.diagnostics.push(this.makeIllegalTemplateVarDiagnostic(target, context, errorMessage));
}
}
makeIllegalTemplateVarDiagnostic(target, expressionNode, errorMessage) {
const span = target instanceof Variable ? target.valueSpan || target.sourceSpan : target.sourceSpan;
return this.templateTypeChecker.makeTemplateDiagnostic(this.component, expressionNode.handlerSpan, import_typescript118.default.DiagnosticCategory.Error, ngErrorCode(ErrorCode.WRITE_TO_READ_ONLY_VARIABLE), errorMessage, [
{
text: `'${target.name}' is declared here.`,
start: span.start.offset,
end: span.end.offset,
sourceFile: this.component.getSourceFile()
}
]);
}
};
function unwrapAstWithSource(ast) {
return ast instanceof ASTWithSource ? ast.ast : ast;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/validation/src/rules/initializer_api_usage_rule.mjs
var import_typescript119 = __toESM(require("typescript"), 1);
var APIS_TO_CHECK = [
INPUT_INITIALIZER_FN,
MODEL_INITIALIZER_FN,
...OUTPUT_INITIALIZER_FNS,
...QUERY_INITIALIZER_FNS
];
var InitializerApiUsageRule = class {
constructor(reflector, importedSymbolsTracker) {
this.reflector = reflector;
this.importedSymbolsTracker = importedSymbolsTracker;
}
shouldCheck(sourceFile) {
return APIS_TO_CHECK.some(({ functionName, owningModule: owningModule2 }) => {
return this.importedSymbolsTracker.hasNamedImport(sourceFile, functionName, owningModule2) || this.importedSymbolsTracker.hasNamespaceImport(sourceFile, owningModule2);
});
}
checkNode(node) {
if (!import_typescript119.default.isCallExpression(node)) {
return null;
}
while (node.parent && (import_typescript119.default.isParenthesizedExpression(node.parent) || import_typescript119.default.isAsExpression(node.parent))) {
node = node.parent;
}
if (!node.parent || !import_typescript119.default.isCallExpression(node)) {
return null;
}
const identifiedInitializer = tryParseInitializerApi(APIS_TO_CHECK, node, this.reflector, this.importedSymbolsTracker);
if (identifiedInitializer === null) {
return null;
}
const functionName = identifiedInitializer.api.functionName + (identifiedInitializer.isRequired ? ".required" : "");
if (import_typescript119.default.isPropertyDeclaration(node.parent) && node.parent.initializer === node) {
let closestClass = node.parent;
while (closestClass && !import_typescript119.default.isClassDeclaration(closestClass)) {
closestClass = closestClass.parent;
}
if (closestClass && import_typescript119.default.isClassDeclaration(closestClass)) {
const decorators = this.reflector.getDecoratorsOfDeclaration(closestClass);
const isComponentOrDirective = decorators !== null && decorators.some((decorator) => {
var _a2;
return ((_a2 = decorator.import) == null ? void 0 : _a2.from) === "@angular/core" && (decorator.name === "Component" || decorator.name === "Directive");
});
return isComponentOrDirective ? null : makeDiagnostic(ErrorCode.UNSUPPORTED_INITIALIZER_API_USAGE, node, `Unsupported call to the ${functionName} function. This function can only be used as the initializer of a property on a @Component or @Directive class.`);
}
}
return makeDiagnostic(ErrorCode.UNSUPPORTED_INITIALIZER_API_USAGE, node, `Unsupported call to the ${functionName} function. This function can only be called in the initializer of a class member.`);
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/validation/src/source_file_validator.mjs
var SourceFileValidator = class {
constructor(reflector, importedSymbolsTracker) {
this.rules = [new InitializerApiUsageRule(reflector, importedSymbolsTracker)];
}
getDiagnosticsForFile(sourceFile) {
if (sourceFile.isDeclarationFile || sourceFile.fileName.endsWith(".ngtypecheck.ts")) {
return null;
}
let rulesToRun = null;
for (const rule of this.rules) {
if (rule.shouldCheck(sourceFile)) {
rulesToRun != null ? rulesToRun : rulesToRun = [];
rulesToRun.push(rule);
}
}
if (rulesToRun === null) {
return null;
}
let fileDiagnostics = null;
sourceFile.forEachChild(function walk(node) {
for (const rule of rulesToRun) {
const nodeDiagnostics = rule.checkNode(node);
if (nodeDiagnostics !== null) {
fileDiagnostics != null ? fileDiagnostics : fileDiagnostics = [];
if (Array.isArray(nodeDiagnostics)) {
fileDiagnostics.push(...nodeDiagnostics);
} else {
fileDiagnostics.push(nodeDiagnostics);
}
}
}
node.forEachChild(walk);
});
return fileDiagnostics;
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/core/src/core_version.mjs
function coreHasSymbol(program, symbol) {
const checker = program.getTypeChecker();
for (const sf of program.getSourceFiles().filter(isMaybeCore)) {
const sym = checker.getSymbolAtLocation(sf);
if (sym === void 0 || sym.exports === void 0) {
continue;
}
if (!sym.exports.has("\u0275\u0275template")) {
continue;
}
return sym.exports.has(symbol.name);
}
return null;
}
function isMaybeCore(sf) {
return sf.isDeclarationFile && sf.fileName.includes("@angular/core") && sf.fileName.endsWith("index.d.ts");
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/core/src/feature_detection.mjs
var import_semver = __toESM(require_semver2(), 1);
function coreVersionSupportsFeature(coreVersion, minVersion) {
if (coreVersion === `0.0.0-${"PLACEHOLDER"}`) {
return true;
}
return import_semver.default.satisfies(coreVersion, minVersion);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/core/src/compiler.mjs
var CompilationTicketKind;
(function(CompilationTicketKind2) {
CompilationTicketKind2[CompilationTicketKind2["Fresh"] = 0] = "Fresh";
CompilationTicketKind2[CompilationTicketKind2["IncrementalTypeScript"] = 1] = "IncrementalTypeScript";
CompilationTicketKind2[CompilationTicketKind2["IncrementalResource"] = 2] = "IncrementalResource";
})(CompilationTicketKind || (CompilationTicketKind = {}));
function freshCompilationTicket(tsProgram, options, incrementalBuildStrategy, programDriver, perfRecorder, enableTemplateTypeChecker, usePoisonedData) {
return {
kind: CompilationTicketKind.Fresh,
tsProgram,
options,
incrementalBuildStrategy,
programDriver,
enableTemplateTypeChecker,
usePoisonedData,
perfRecorder: perfRecorder != null ? perfRecorder : ActivePerfRecorder.zeroedToNow()
};
}
function incrementalFromCompilerTicket(oldCompiler, newProgram, incrementalBuildStrategy, programDriver, modifiedResourceFiles, perfRecorder) {
const oldProgram = oldCompiler.getCurrentProgram();
const oldState = oldCompiler.incrementalStrategy.getIncrementalState(oldProgram);
if (oldState === null) {
return freshCompilationTicket(newProgram, oldCompiler.options, incrementalBuildStrategy, programDriver, perfRecorder, oldCompiler.enableTemplateTypeChecker, oldCompiler.usePoisonedData);
}
if (perfRecorder === null) {
perfRecorder = ActivePerfRecorder.zeroedToNow();
}
const incrementalCompilation = IncrementalCompilation.incremental(newProgram, versionMapFromProgram(newProgram, programDriver), oldProgram, oldState, modifiedResourceFiles, perfRecorder);
return {
kind: CompilationTicketKind.IncrementalTypeScript,
enableTemplateTypeChecker: oldCompiler.enableTemplateTypeChecker,
usePoisonedData: oldCompiler.usePoisonedData,
options: oldCompiler.options,
incrementalBuildStrategy,
incrementalCompilation,
programDriver,
newProgram,
perfRecorder
};
}
var NgCompiler = class {
static fromTicket(ticket, adapter) {
switch (ticket.kind) {
case CompilationTicketKind.Fresh:
return new NgCompiler(adapter, ticket.options, ticket.tsProgram, ticket.programDriver, ticket.incrementalBuildStrategy, IncrementalCompilation.fresh(ticket.tsProgram, versionMapFromProgram(ticket.tsProgram, ticket.programDriver)), ticket.enableTemplateTypeChecker, ticket.usePoisonedData, ticket.perfRecorder);
case CompilationTicketKind.IncrementalTypeScript:
return new NgCompiler(adapter, ticket.options, ticket.newProgram, ticket.programDriver, ticket.incrementalBuildStrategy, ticket.incrementalCompilation, ticket.enableTemplateTypeChecker, ticket.usePoisonedData, ticket.perfRecorder);
case CompilationTicketKind.IncrementalResource:
const compiler = ticket.compiler;
compiler.updateWithChangedResources(ticket.modifiedResourceFiles, ticket.perfRecorder);
return compiler;
}
}
constructor(adapter, options, inputProgram, programDriver, incrementalStrategy, incrementalCompilation, enableTemplateTypeChecker, usePoisonedData, livePerfRecorder) {
var _a2, _b2, _c2;
this.adapter = adapter;
this.options = options;
this.inputProgram = inputProgram;
this.programDriver = programDriver;
this.incrementalStrategy = incrementalStrategy;
this.incrementalCompilation = incrementalCompilation;
this.usePoisonedData = usePoisonedData;
this.livePerfRecorder = livePerfRecorder;
this.compilation = null;
this.constructionDiagnostics = [];
this.nonTemplateDiagnostics = null;
this.delegatingPerfRecorder = new DelegatingPerfRecorder(this.perfRecorder);
this.usePoisonedData = usePoisonedData || !!options._compilePoisonedComponents;
this.enableTemplateTypeChecker = enableTemplateTypeChecker || !!options._enableTemplateTypeChecker;
this.enableBlockSyntax = (_a2 = options["_enableBlockSyntax"]) != null ? _a2 : true;
this.enableLetSyntax = (_b2 = options["_enableLetSyntax"]) != null ? _b2 : true;
this.angularCoreVersion = (_c2 = options["_angularCoreVersion"]) != null ? _c2 : null;
this.constructionDiagnostics.push(...this.adapter.constructionDiagnostics, ...verifyCompatibleTypeCheckOptions(this.options));
this.currentProgram = inputProgram;
this.closureCompilerEnabled = !!this.options.annotateForClosureCompiler;
this.entryPoint = adapter.entryPoint !== null ? getSourceFileOrNull(inputProgram, adapter.entryPoint) : null;
const moduleResolutionCache = import_typescript120.default.createModuleResolutionCache(
this.adapter.getCurrentDirectory(),
this.adapter.getCanonicalFileName.bind(this.adapter)
);
this.moduleResolver = new ModuleResolver(inputProgram, this.options, this.adapter, moduleResolutionCache);
this.resourceManager = new AdapterResourceLoader(adapter, this.options);
this.cycleAnalyzer = new CycleAnalyzer(new ImportGraph(inputProgram.getTypeChecker(), this.delegatingPerfRecorder));
this.incrementalStrategy.setIncrementalState(this.incrementalCompilation.state, inputProgram);
this.ignoreForDiagnostics = new Set(inputProgram.getSourceFiles().filter((sf) => this.adapter.isShim(sf)));
this.ignoreForEmit = this.adapter.ignoreForEmit;
let dtsFileCount = 0;
let nonDtsFileCount = 0;
for (const sf of inputProgram.getSourceFiles()) {
if (sf.isDeclarationFile) {
dtsFileCount++;
} else {
nonDtsFileCount++;
}
}
livePerfRecorder.eventCount(PerfEvent.InputDtsFile, dtsFileCount);
livePerfRecorder.eventCount(PerfEvent.InputTsFile, nonDtsFileCount);
}
get perfRecorder() {
return this.livePerfRecorder;
}
updateWithChangedResources(changedResources, perfRecorder) {
this.livePerfRecorder = perfRecorder;
this.delegatingPerfRecorder.target = perfRecorder;
perfRecorder.inPhase(PerfPhase.ResourceUpdate, () => {
if (this.compilation === null) {
return;
}
this.resourceManager.invalidate();
const classesToUpdate = /* @__PURE__ */ new Set();
for (const resourceFile of changedResources) {
for (const templateClass of this.getComponentsWithTemplateFile(resourceFile)) {
classesToUpdate.add(templateClass);
}
for (const styleClass of this.getComponentsWithStyleFile(resourceFile)) {
classesToUpdate.add(styleClass);
}
}
for (const clazz of classesToUpdate) {
this.compilation.traitCompiler.updateResources(clazz);
if (!import_typescript120.default.isClassDeclaration(clazz)) {
continue;
}
this.compilation.templateTypeChecker.invalidateClass(clazz);
}
});
}
getResourceDependencies(file) {
this.ensureAnalyzed();
return this.incrementalCompilation.depGraph.getResourceDependencies(file);
}
getDiagnostics() {
const diagnostics = [...this.getNonTemplateDiagnostics()];
try {
diagnostics.push(...this.getTemplateDiagnostics(), ...this.runAdditionalChecks());
} catch (err) {
if (!isFatalDiagnosticError(err)) {
throw err;
}
diagnostics.push(err.toDiagnostic());
}
return this.addMessageTextDetails(diagnostics);
}
getDiagnosticsForFile(file, optimizeFor) {
const diagnostics = [
...this.getNonTemplateDiagnostics().filter((diag) => diag.file === file)
];
try {
diagnostics.push(...this.getTemplateDiagnosticsForFile(file, optimizeFor), ...this.runAdditionalChecks(file));
} catch (err) {
if (!isFatalDiagnosticError(err)) {
throw err;
}
diagnostics.push(err.toDiagnostic());
}
return this.addMessageTextDetails(diagnostics);
}
getDiagnosticsForComponent(component) {
const compilation = this.ensureAnalyzed();
const ttc = compilation.templateTypeChecker;
const diagnostics = [];
try {
diagnostics.push(...ttc.getDiagnosticsForComponent(component));
const { extendedTemplateChecker, templateSemanticsChecker } = compilation;
if (templateSemanticsChecker !== null) {
diagnostics.push(...templateSemanticsChecker.getDiagnosticsForComponent(component));
}
if (this.options.strictTemplates && extendedTemplateChecker !== null) {
diagnostics.push(...extendedTemplateChecker.getDiagnosticsForComponent(component));
}
} catch (err) {
if (!isFatalDiagnosticError(err)) {
throw err;
}
diagnostics.push(err.toDiagnostic());
}
return this.addMessageTextDetails(diagnostics);
}
addMessageTextDetails(diagnostics) {
return diagnostics.map((diag) => {
if (diag.code && COMPILER_ERRORS_WITH_GUIDES.has(ngErrorCode(diag.code))) {
return __spreadProps(__spreadValues({}, diag), {
messageText: diag.messageText + `. Find more at ${ERROR_DETAILS_PAGE_BASE_URL}/NG${ngErrorCode(diag.code)}`
});
}
return diag;
});
}
getOptionDiagnostics() {
return this.constructionDiagnostics;
}
getCurrentProgram() {
return this.currentProgram;
}
getTemplateTypeChecker() {
if (!this.enableTemplateTypeChecker) {
throw new Error("The `TemplateTypeChecker` does not work without `enableTemplateTypeChecker`.");
}
return this.ensureAnalyzed().templateTypeChecker;
}
getComponentsWithTemplateFile(templateFilePath) {
const { resourceRegistry } = this.ensureAnalyzed();
return resourceRegistry.getComponentsWithTemplate(resolve(templateFilePath));
}
getComponentsWithStyleFile(styleFilePath) {
const { resourceRegistry } = this.ensureAnalyzed();
return resourceRegistry.getComponentsWithStyle(resolve(styleFilePath));
}
getComponentResources(classDecl) {
if (!isNamedClassDeclaration(classDecl)) {
return null;
}
const { resourceRegistry } = this.ensureAnalyzed();
const styles = resourceRegistry.getStyles(classDecl);
const template2 = resourceRegistry.getTemplate(classDecl);
if (template2 === null) {
return null;
}
return { styles, template: template2 };
}
getMeta(classDecl) {
var _a2;
if (!isNamedClassDeclaration(classDecl)) {
return null;
}
const ref = new Reference2(classDecl);
const { metaReader } = this.ensureAnalyzed();
const meta = (_a2 = metaReader.getPipeMetadata(ref)) != null ? _a2 : metaReader.getDirectiveMetadata(ref);
if (meta === null) {
return null;
}
return meta;
}
analyzeAsync() {
return __async(this, null, function* () {
if (this.compilation !== null) {
return;
}
yield this.perfRecorder.inPhase(PerfPhase.Analysis, () => __async(this, null, function* () {
this.compilation = this.makeCompilation();
const promises = [];
for (const sf of this.inputProgram.getSourceFiles()) {
if (sf.isDeclarationFile) {
continue;
}
let analysisPromise = this.compilation.traitCompiler.analyzeAsync(sf);
if (analysisPromise !== void 0) {
promises.push(analysisPromise);
}
}
yield Promise.all(promises);
this.perfRecorder.memory(PerfCheckpoint.Analysis);
this.resolveCompilation(this.compilation.traitCompiler);
}));
});
}
prepareEmit() {
const compilation = this.ensureAnalyzed();
untagAllTsFiles(this.inputProgram);
const coreImportsFrom = compilation.isCore ? getR3SymbolsFile(this.inputProgram) : null;
let importRewriter;
if (coreImportsFrom !== null) {
importRewriter = new R3SymbolsImportRewriter(coreImportsFrom.fileName);
} else {
importRewriter = new NoopImportRewriter();
}
const defaultImportTracker = new DefaultImportTracker();
const before = [
ivyTransformFactory(compilation.traitCompiler, compilation.reflector, importRewriter, defaultImportTracker, compilation.localCompilationExtraImportsTracker, this.delegatingPerfRecorder, compilation.isCore, this.closureCompilerEnabled),
aliasTransformFactory(compilation.traitCompiler.exportStatements),
defaultImportTracker.importPreservingTransformer()
];
if (compilation.supportJitMode && compilation.jitDeclarationRegistry.jitDeclarations.size > 0) {
const { jitDeclarations } = compilation.jitDeclarationRegistry;
const jitDeclarationsArray = Array.from(jitDeclarations);
const jitDeclarationOriginalNodes = new Set(jitDeclarationsArray.map((d) => import_typescript120.default.getOriginalNode(d)));
const sourceFilesWithJit = new Set(jitDeclarationsArray.map((d) => d.getSourceFile().fileName));
before.push((ctx) => {
const reflectionHost = new TypeScriptReflectionHost(this.inputProgram.getTypeChecker());
const jitTransform = angularJitApplicationTransform(this.inputProgram, compilation.isCore, (node) => {
node = import_typescript120.default.getOriginalNode(node, import_typescript120.default.isClassDeclaration);
return reflectionHost.isClass(node) && jitDeclarationOriginalNodes.has(node);
})(ctx);
return (sourceFile) => {
if (!sourceFilesWithJit.has(sourceFile.fileName)) {
return sourceFile;
}
return jitTransform(sourceFile);
};
});
}
const afterDeclarations = [];
if (this.options.compilationMode !== "experimental-local" && compilation.dtsTransforms !== null) {
afterDeclarations.push(declarationTransformFactory(compilation.dtsTransforms, compilation.reflector, compilation.refEmitter, importRewriter));
}
if (compilation.aliasingHost !== null && compilation.aliasingHost.aliasExportsInDts) {
afterDeclarations.push(aliasTransformFactory(compilation.traitCompiler.exportStatements));
}
return { transformers: { before, afterDeclarations } };
}
getIndexedComponents() {
const compilation = this.ensureAnalyzed();
const context = new IndexingContext();
compilation.traitCompiler.index(context);
return generateAnalysis(context);
}
getApiDocumentation(entryPoint, privateModules) {
const compilation = this.ensureAnalyzed();
const checker = this.inputProgram.getTypeChecker();
const docsExtractor = new DocsExtractor(checker, compilation.metaReader);
const entryPointSourceFile = this.inputProgram.getSourceFiles().find((sourceFile) => {
return sourceFile.fileName.includes(entryPoint);
});
if (!entryPointSourceFile) {
throw new Error(`Entry point "${entryPoint}" not found in program sources.`);
}
const rootDir = this.inputProgram.getCurrentDirectory();
return docsExtractor.extractAll(entryPointSourceFile, rootDir, privateModules);
}
xi18n(ctx) {
const compilation = this.ensureAnalyzed();
compilation.traitCompiler.xi18n(ctx);
}
ensureAnalyzed() {
if (this.compilation === null) {
this.analyzeSync();
}
return this.compilation;
}
analyzeSync() {
this.perfRecorder.inPhase(PerfPhase.Analysis, () => {
this.compilation = this.makeCompilation();
for (const sf of this.inputProgram.getSourceFiles()) {
if (sf.isDeclarationFile) {
continue;
}
this.compilation.traitCompiler.analyzeSync(sf);
}
this.perfRecorder.memory(PerfCheckpoint.Analysis);
this.resolveCompilation(this.compilation.traitCompiler);
});
}
resolveCompilation(traitCompiler) {
this.perfRecorder.inPhase(PerfPhase.Resolve, () => {
traitCompiler.resolve();
this.incrementalCompilation.recordSuccessfulAnalysis(traitCompiler);
this.perfRecorder.memory(PerfCheckpoint.Resolve);
});
}
get fullTemplateTypeCheck() {
const strictTemplates = !!this.options.strictTemplates;
return strictTemplates || !!this.options.fullTemplateTypeCheck;
}
getTypeCheckingConfig() {
var _a2, _b2, _c2, _d2, _e2;
const strictTemplates = !!this.options.strictTemplates;
const useInlineTypeConstructors = this.programDriver.supportsInlineOperations;
let allowSignalsInTwoWayBindings = (_a2 = coreHasSymbol(this.inputProgram, Identifiers.unwrapWritableSignal)) != null ? _a2 : this.angularCoreVersion === null || coreVersionSupportsFeature(this.angularCoreVersion, ">= 17.2.0-0");
let typeCheckingConfig;
if (this.fullTemplateTypeCheck) {
typeCheckingConfig = {
applyTemplateContextGuards: strictTemplates,
checkQueries: false,
checkTemplateBodies: true,
alwaysCheckSchemaInTemplateBodies: true,
checkTypeOfInputBindings: strictTemplates,
honorAccessModifiersForInputBindings: false,
checkControlFlowBodies: true,
strictNullInputBindings: strictTemplates,
checkTypeOfAttributes: strictTemplates,
checkTypeOfDomBindings: false,
checkTypeOfOutputEvents: strictTemplates,
checkTypeOfAnimationEvents: strictTemplates,
checkTypeOfDomEvents: strictTemplates,
checkTypeOfDomReferences: strictTemplates,
checkTypeOfNonDomReferences: true,
checkTypeOfPipes: true,
strictSafeNavigationTypes: strictTemplates,
useContextGenericType: strictTemplates,
strictLiteralTypes: true,
enableTemplateTypeChecker: this.enableTemplateTypeChecker,
useInlineTypeConstructors,
suggestionsForSuboptimalTypeInference: this.enableTemplateTypeChecker && !strictTemplates,
controlFlowPreventingContentProjection: ((_b2 = this.options.extendedDiagnostics) == null ? void 0 : _b2.defaultCategory) || DiagnosticCategoryLabel.Warning,
allowSignalsInTwoWayBindings
};
} else {
typeCheckingConfig = {
applyTemplateContextGuards: false,
checkQueries: false,
checkTemplateBodies: false,
checkControlFlowBodies: false,
alwaysCheckSchemaInTemplateBodies: this.closureCompilerEnabled,
checkTypeOfInputBindings: false,
strictNullInputBindings: false,
honorAccessModifiersForInputBindings: false,
checkTypeOfAttributes: false,
checkTypeOfDomBindings: false,
checkTypeOfOutputEvents: false,
checkTypeOfAnimationEvents: false,
checkTypeOfDomEvents: false,
checkTypeOfDomReferences: false,
checkTypeOfNonDomReferences: false,
checkTypeOfPipes: false,
strictSafeNavigationTypes: false,
useContextGenericType: false,
strictLiteralTypes: false,
enableTemplateTypeChecker: this.enableTemplateTypeChecker,
useInlineTypeConstructors,
suggestionsForSuboptimalTypeInference: false,
controlFlowPreventingContentProjection: ((_c2 = this.options.extendedDiagnostics) == null ? void 0 : _c2.defaultCategory) || DiagnosticCategoryLabel.Warning,
allowSignalsInTwoWayBindings
};
}
if (this.options.strictInputTypes !== void 0) {
typeCheckingConfig.checkTypeOfInputBindings = this.options.strictInputTypes;
typeCheckingConfig.applyTemplateContextGuards = this.options.strictInputTypes;
}
if (this.options.strictInputAccessModifiers !== void 0) {
typeCheckingConfig.honorAccessModifiersForInputBindings = this.options.strictInputAccessModifiers;
}
if (this.options.strictNullInputTypes !== void 0) {
typeCheckingConfig.strictNullInputBindings = this.options.strictNullInputTypes;
}
if (this.options.strictOutputEventTypes !== void 0) {
typeCheckingConfig.checkTypeOfOutputEvents = this.options.strictOutputEventTypes;
typeCheckingConfig.checkTypeOfAnimationEvents = this.options.strictOutputEventTypes;
}
if (this.options.strictDomEventTypes !== void 0) {
typeCheckingConfig.checkTypeOfDomEvents = this.options.strictDomEventTypes;
}
if (this.options.strictSafeNavigationTypes !== void 0) {
typeCheckingConfig.strictSafeNavigationTypes = this.options.strictSafeNavigationTypes;
}
if (this.options.strictDomLocalRefTypes !== void 0) {
typeCheckingConfig.checkTypeOfDomReferences = this.options.strictDomLocalRefTypes;
}
if (this.options.strictAttributeTypes !== void 0) {
typeCheckingConfig.checkTypeOfAttributes = this.options.strictAttributeTypes;
}
if (this.options.strictContextGenerics !== void 0) {
typeCheckingConfig.useContextGenericType = this.options.strictContextGenerics;
}
if (this.options.strictLiteralTypes !== void 0) {
typeCheckingConfig.strictLiteralTypes = this.options.strictLiteralTypes;
}
if (((_e2 = (_d2 = this.options.extendedDiagnostics) == null ? void 0 : _d2.checks) == null ? void 0 : _e2.controlFlowPreventingContentProjection) !== void 0) {
typeCheckingConfig.controlFlowPreventingContentProjection = this.options.extendedDiagnostics.checks.controlFlowPreventingContentProjection;
}
return typeCheckingConfig;
}
getTemplateDiagnostics() {
const compilation = this.ensureAnalyzed();
const diagnostics = [];
for (const sf of this.inputProgram.getSourceFiles()) {
if (sf.isDeclarationFile || this.adapter.isShim(sf)) {
continue;
}
diagnostics.push(...compilation.templateTypeChecker.getDiagnosticsForFile(sf, OptimizeFor.WholeProgram));
}
const program = this.programDriver.getProgram();
this.incrementalStrategy.setIncrementalState(this.incrementalCompilation.state, program);
this.currentProgram = program;
return diagnostics;
}
getTemplateDiagnosticsForFile(sf, optimizeFor) {
const compilation = this.ensureAnalyzed();
const diagnostics = [];
if (!sf.isDeclarationFile && !this.adapter.isShim(sf)) {
diagnostics.push(...compilation.templateTypeChecker.getDiagnosticsForFile(sf, optimizeFor));
}
const program = this.programDriver.getProgram();
this.incrementalStrategy.setIncrementalState(this.incrementalCompilation.state, program);
this.currentProgram = program;
return diagnostics;
}
getNonTemplateDiagnostics() {
if (this.nonTemplateDiagnostics === null) {
const compilation = this.ensureAnalyzed();
this.nonTemplateDiagnostics = [...compilation.traitCompiler.diagnostics];
if (this.entryPoint !== null && compilation.exportReferenceGraph !== null) {
this.nonTemplateDiagnostics.push(...checkForPrivateExports(this.entryPoint, this.inputProgram.getTypeChecker(), compilation.exportReferenceGraph));
}
}
return this.nonTemplateDiagnostics;
}
runAdditionalChecks(sf) {
const diagnostics = [];
const compilation = this.ensureAnalyzed();
const { extendedTemplateChecker, templateSemanticsChecker, sourceFileValidator } = compilation;
const files = sf ? [sf] : this.inputProgram.getSourceFiles();
for (const sf2 of files) {
if (sourceFileValidator !== null) {
const sourceFileDiagnostics = sourceFileValidator.getDiagnosticsForFile(sf2);
if (sourceFileDiagnostics !== null) {
diagnostics.push(...sourceFileDiagnostics);
}
}
if (templateSemanticsChecker !== null) {
diagnostics.push(...compilation.traitCompiler.runAdditionalChecks(sf2, (clazz, handler) => {
var _a2;
return ((_a2 = handler.templateSemanticsCheck) == null ? void 0 : _a2.call(handler, clazz, templateSemanticsChecker)) || null;
}));
}
if (this.options.strictTemplates && extendedTemplateChecker !== null) {
diagnostics.push(...compilation.traitCompiler.runAdditionalChecks(sf2, (clazz, handler) => {
var _a2;
return ((_a2 = handler.extendedTemplateCheck) == null ? void 0 : _a2.call(handler, clazz, extendedTemplateChecker)) || null;
}));
}
}
return diagnostics;
}
makeCompilation() {
var _a2, _b2, _c2, _d2, _e2;
const isCore = isAngularCorePackage(this.inputProgram);
let compilationMode = CompilationMode.FULL;
if (!isCore) {
switch (this.options.compilationMode) {
case "full":
compilationMode = CompilationMode.FULL;
break;
case "partial":
compilationMode = CompilationMode.PARTIAL;
break;
case "experimental-local":
compilationMode = CompilationMode.LOCAL;
break;
}
}
const checker = this.inputProgram.getTypeChecker();
const reflector = new TypeScriptReflectionHost(checker, compilationMode === CompilationMode.LOCAL);
let refEmitter;
let aliasingHost = null;
if (this.adapter.unifiedModulesHost === null || !this.options["_useHostForImportGeneration"] && !this.options["_useHostForImportAndAliasGeneration"]) {
let localImportStrategy;
if (this.options.rootDir !== void 0 || this.options.rootDirs !== void 0 && this.options.rootDirs.length > 0) {
localImportStrategy = new LogicalProjectStrategy(reflector, new LogicalFileSystem([...this.adapter.rootDirs], this.adapter));
} else {
localImportStrategy = new RelativePathStrategy(reflector);
}
refEmitter = new ReferenceEmitter([
new LocalIdentifierStrategy(),
new AbsoluteModuleStrategy(this.inputProgram, checker, this.moduleResolver, reflector),
localImportStrategy
]);
if (this.entryPoint === null && this.options.generateDeepReexports === true) {
aliasingHost = new PrivateExportAliasingHost(reflector);
}
} else {
refEmitter = new ReferenceEmitter([
new LocalIdentifierStrategy(),
...this.options["_useHostForImportAndAliasGeneration"] ? [new AliasStrategy()] : [],
new UnifiedModulesStrategy(reflector, this.adapter.unifiedModulesHost)
]);
if (this.options["_useHostForImportAndAliasGeneration"]) {
aliasingHost = new UnifiedModulesAliasingHost(this.adapter.unifiedModulesHost);
}
}
const evaluator = new PartialEvaluator(reflector, checker, this.incrementalCompilation.depGraph);
const dtsReader = new DtsMetadataReader(checker, reflector);
const localMetaRegistry = new LocalMetadataRegistry();
const localMetaReader = localMetaRegistry;
const depScopeReader = new MetadataDtsModuleScopeResolver(dtsReader, aliasingHost);
const metaReader = new CompoundMetadataReader([localMetaReader, dtsReader]);
const ngModuleIndex = new NgModuleIndexImpl(metaReader, localMetaReader);
const ngModuleScopeRegistry = new LocalModuleScopeRegistry(localMetaReader, metaReader, depScopeReader, refEmitter, aliasingHost);
const standaloneScopeReader = new StandaloneComponentScopeReader(metaReader, ngModuleScopeRegistry, depScopeReader);
const scopeReader = new CompoundComponentScopeReader([
ngModuleScopeRegistry,
standaloneScopeReader
]);
const semanticDepGraphUpdater = this.incrementalCompilation.semanticDepGraphUpdater;
const metaRegistry = new CompoundMetadataRegistry([localMetaRegistry, ngModuleScopeRegistry]);
const injectableRegistry = new InjectableClassRegistry(reflector, isCore);
const hostDirectivesResolver = new HostDirectivesResolver(metaReader);
const exportedProviderStatusResolver = new ExportedProviderStatusResolver(metaReader);
const importTracker = new ImportedSymbolsTracker();
const typeCheckScopeRegistry = new TypeCheckScopeRegistry(scopeReader, metaReader, hostDirectivesResolver);
let referencesRegistry;
let exportReferenceGraph = null;
if (this.entryPoint !== null) {
exportReferenceGraph = new ReferenceGraph();
referencesRegistry = new ReferenceGraphAdapter(exportReferenceGraph);
} else {
referencesRegistry = new NoopReferencesRegistry();
}
const dtsTransforms = new DtsTransformRegistry();
const resourceRegistry = new ResourceRegistry();
const deferredSymbolsTracker = new DeferredSymbolTracker(this.inputProgram.getTypeChecker(), (_a2 = this.options.onlyExplicitDeferDependencyImports) != null ? _a2 : false);
let localCompilationExtraImportsTracker = null;
if (compilationMode === CompilationMode.LOCAL && this.options.generateExtraImportsInLocalMode) {
localCompilationExtraImportsTracker = new LocalCompilationExtraImportsTracker(checker);
}
const cycleHandlingStrategy = compilationMode === CompilationMode.PARTIAL ? 1 : 0;
const strictCtorDeps = this.options.strictInjectionParameters || false;
const supportJitMode = (_b2 = this.options["supportJitMode"]) != null ? _b2 : true;
const supportTestBed = (_c2 = this.options["supportTestBed"]) != null ? _c2 : true;
if (supportTestBed === false && compilationMode === CompilationMode.PARTIAL) {
throw new Error('TestBed support ("supportTestBed" option) cannot be disabled in partial compilation mode.');
}
if (supportJitMode === false && compilationMode === CompilationMode.PARTIAL) {
throw new Error('JIT mode support ("supportJitMode" option) cannot be disabled in partial compilation mode.');
}
if (supportJitMode === false && this.options.forbidOrphanComponents) {
throw new Error('JIT mode support ("supportJitMode" option) cannot be disabled when forbidOrphanComponents is set to true');
}
const jitDeclarationRegistry = new JitDeclarationRegistry();
const handlers = [
new ComponentDecoratorHandler(reflector, evaluator, metaRegistry, metaReader, scopeReader, depScopeReader, ngModuleScopeRegistry, typeCheckScopeRegistry, resourceRegistry, isCore, strictCtorDeps, this.resourceManager, this.adapter.rootDirs, this.options.preserveWhitespaces || false, this.options.i18nUseExternalIds !== false, this.options.enableI18nLegacyMessageIdFormat !== false, this.usePoisonedData, this.options.i18nNormalizeLineEndingsInICUs === true, this.moduleResolver, this.cycleAnalyzer, cycleHandlingStrategy, refEmitter, referencesRegistry, this.incrementalCompilation.depGraph, injectableRegistry, semanticDepGraphUpdater, this.closureCompilerEnabled, this.delegatingPerfRecorder, hostDirectivesResolver, importTracker, supportTestBed, compilationMode, deferredSymbolsTracker, !!this.options.forbidOrphanComponents, this.enableBlockSyntax, this.enableLetSyntax, localCompilationExtraImportsTracker, jitDeclarationRegistry, (_d2 = this.options.i18nPreserveWhitespaceForLegacyExtraction) != null ? _d2 : true),
new DirectiveDecoratorHandler(reflector, evaluator, metaRegistry, ngModuleScopeRegistry, metaReader, injectableRegistry, refEmitter, referencesRegistry, isCore, strictCtorDeps, semanticDepGraphUpdater, this.closureCompilerEnabled, this.delegatingPerfRecorder, importTracker, supportTestBed, compilationMode, jitDeclarationRegistry),
new PipeDecoratorHandler(reflector, evaluator, metaRegistry, ngModuleScopeRegistry, injectableRegistry, isCore, this.delegatingPerfRecorder, supportTestBed, compilationMode, !!this.options.generateExtraImportsInLocalMode),
new InjectableDecoratorHandler(reflector, evaluator, isCore, strictCtorDeps, injectableRegistry, this.delegatingPerfRecorder, supportTestBed, compilationMode),
new NgModuleDecoratorHandler(reflector, evaluator, metaReader, metaRegistry, ngModuleScopeRegistry, referencesRegistry, exportedProviderStatusResolver, semanticDepGraphUpdater, isCore, refEmitter, this.closureCompilerEnabled, (_e2 = this.options.onlyPublishPublicTypingsForNgModules) != null ? _e2 : false, injectableRegistry, this.delegatingPerfRecorder, supportTestBed, supportJitMode, compilationMode, localCompilationExtraImportsTracker, jitDeclarationRegistry)
];
const traitCompiler = new TraitCompiler(handlers, reflector, this.delegatingPerfRecorder, this.incrementalCompilation, this.options.compileNonExportedClasses !== false, compilationMode, dtsTransforms, semanticDepGraphUpdater, this.adapter);
const notifyingDriver = new NotifyingProgramDriverWrapper(this.programDriver, (program) => {
this.incrementalStrategy.setIncrementalState(this.incrementalCompilation.state, program);
this.currentProgram = program;
});
const templateTypeChecker = new TemplateTypeCheckerImpl(this.inputProgram, notifyingDriver, traitCompiler, this.getTypeCheckingConfig(), refEmitter, reflector, this.adapter, this.incrementalCompilation, metaReader, localMetaReader, ngModuleIndex, scopeReader, typeCheckScopeRegistry, this.delegatingPerfRecorder);
const extendedTemplateChecker = this.constructionDiagnostics.length === 0 ? new ExtendedTemplateCheckerImpl(templateTypeChecker, checker, ALL_DIAGNOSTIC_FACTORIES, this.options) : null;
const templateSemanticsChecker = this.constructionDiagnostics.length === 0 ? new TemplateSemanticsCheckerImpl(templateTypeChecker) : null;
const sourceFileValidator = this.constructionDiagnostics.length === 0 ? new SourceFileValidator(reflector, importTracker) : null;
return {
isCore,
traitCompiler,
reflector,
scopeRegistry: ngModuleScopeRegistry,
dtsTransforms,
exportReferenceGraph,
metaReader,
typeCheckScopeRegistry,
aliasingHost,
refEmitter,
templateTypeChecker,
resourceRegistry,
extendedTemplateChecker,
localCompilationExtraImportsTracker,
jitDeclarationRegistry,
templateSemanticsChecker,
sourceFileValidator,
supportJitMode
};
}
};
function isAngularCorePackage(program) {
const r3Symbols = getR3SymbolsFile(program);
if (r3Symbols === null) {
return false;
}
return r3Symbols.statements.some((stmt) => {
if (!import_typescript120.default.isVariableStatement(stmt)) {
return false;
}
const modifiers = import_typescript120.default.getModifiers(stmt);
if (modifiers === void 0 || !modifiers.some((mod) => mod.kind === import_typescript120.default.SyntaxKind.ExportKeyword)) {
return false;
}
return stmt.declarationList.declarations.some((decl) => {
if (!import_typescript120.default.isIdentifier(decl.name) || decl.name.text !== "ITS_JUST_ANGULAR") {
return false;
}
if (decl.initializer === void 0 || decl.initializer.kind !== import_typescript120.default.SyntaxKind.TrueKeyword) {
return false;
}
return true;
});
});
}
function getR3SymbolsFile(program) {
return program.getSourceFiles().find((file) => file.fileName.indexOf("r3_symbols.ts") >= 0) || null;
}
function* verifyCompatibleTypeCheckOptions(options) {
var _a2, _b2, _c2;
if (options.fullTemplateTypeCheck === false && options.strictTemplates === true) {
yield makeConfigDiagnostic({
category: import_typescript120.default.DiagnosticCategory.Error,
code: ErrorCode.CONFIG_STRICT_TEMPLATES_IMPLIES_FULL_TEMPLATE_TYPECHECK,
messageText: `
Angular compiler option "strictTemplates" is enabled, however "fullTemplateTypeCheck" is disabled.
Having the "strictTemplates" flag enabled implies that "fullTemplateTypeCheck" is also enabled, so
the latter can not be explicitly disabled.
One of the following actions is required:
1. Remove the "fullTemplateTypeCheck" option.
2. Remove "strictTemplates" or set it to 'false'.
More information about the template type checking compiler options can be found in the documentation:
https://angular.dev/tools/cli/template-typecheck
`.trim()
});
}
if (options.extendedDiagnostics && options.strictTemplates === false) {
yield makeConfigDiagnostic({
category: import_typescript120.default.DiagnosticCategory.Error,
code: ErrorCode.CONFIG_EXTENDED_DIAGNOSTICS_IMPLIES_STRICT_TEMPLATES,
messageText: `
Angular compiler option "extendedDiagnostics" is configured, however "strictTemplates" is disabled.
Using "extendedDiagnostics" requires that "strictTemplates" is also enabled.
One of the following actions is required:
1. Remove "strictTemplates: false" to enable it.
2. Remove "extendedDiagnostics" configuration to disable them.
`.trim()
});
}
const allowedCategoryLabels = Array.from(Object.values(DiagnosticCategoryLabel));
const defaultCategory = (_a2 = options.extendedDiagnostics) == null ? void 0 : _a2.defaultCategory;
if (defaultCategory && !allowedCategoryLabels.includes(defaultCategory)) {
yield makeConfigDiagnostic({
category: import_typescript120.default.DiagnosticCategory.Error,
code: ErrorCode.CONFIG_EXTENDED_DIAGNOSTICS_UNKNOWN_CATEGORY_LABEL,
messageText: `
Angular compiler option "extendedDiagnostics.defaultCategory" has an unknown diagnostic category: "${defaultCategory}".
Allowed diagnostic categories are:
${allowedCategoryLabels.join("\n")}
`.trim()
});
}
for (const [checkName, category] of Object.entries((_c2 = (_b2 = options.extendedDiagnostics) == null ? void 0 : _b2.checks) != null ? _c2 : {})) {
if (!SUPPORTED_DIAGNOSTIC_NAMES.has(checkName)) {
yield makeConfigDiagnostic({
category: import_typescript120.default.DiagnosticCategory.Error,
code: ErrorCode.CONFIG_EXTENDED_DIAGNOSTICS_UNKNOWN_CHECK,
messageText: `
Angular compiler option "extendedDiagnostics.checks" has an unknown check: "${checkName}".
Allowed check names are:
${Array.from(SUPPORTED_DIAGNOSTIC_NAMES).join("\n")}
`.trim()
});
}
if (!allowedCategoryLabels.includes(category)) {
yield makeConfigDiagnostic({
category: import_typescript120.default.DiagnosticCategory.Error,
code: ErrorCode.CONFIG_EXTENDED_DIAGNOSTICS_UNKNOWN_CATEGORY_LABEL,
messageText: `
Angular compiler option "extendedDiagnostics.checks['${checkName}']" has an unknown diagnostic category: "${category}".
Allowed diagnostic categories are:
${allowedCategoryLabels.join("\n")}
`.trim()
});
}
}
}
function makeConfigDiagnostic({ category, code, messageText }) {
return {
category,
code: ngErrorCode(code),
file: void 0,
start: void 0,
length: void 0,
messageText
};
}
var ReferenceGraphAdapter = class {
constructor(graph) {
this.graph = graph;
}
add(source, ...references) {
for (const { node } of references) {
let sourceFile = node.getSourceFile();
if (sourceFile === void 0) {
sourceFile = import_typescript120.default.getOriginalNode(node).getSourceFile();
}
if (sourceFile === void 0 || !isDtsPath(sourceFile.fileName)) {
this.graph.add(source, node);
}
}
}
};
var NotifyingProgramDriverWrapper = class {
constructor(delegate, notifyNewProgram) {
var _a2;
this.delegate = delegate;
this.notifyNewProgram = notifyNewProgram;
this.getSourceFileVersion = (_a2 = this.delegate.getSourceFileVersion) == null ? void 0 : _a2.bind(this);
}
get supportsInlineOperations() {
return this.delegate.supportsInlineOperations;
}
getProgram() {
return this.delegate.getProgram();
}
updateFiles(contents, updateMode) {
this.delegate.updateFiles(contents, updateMode);
this.notifyNewProgram(this.delegate.getProgram());
}
};
function versionMapFromProgram(program, driver) {
if (driver.getSourceFileVersion === void 0) {
return null;
}
const versions = /* @__PURE__ */ new Map();
for (const possiblyRedirectedSourceFile of program.getSourceFiles()) {
const sf = toUnredirectedSourceFile(possiblyRedirectedSourceFile);
versions.set(absoluteFromSourceFile(sf), driver.getSourceFileVersion(sf));
}
return versions;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/core/src/host.mjs
var import_typescript122 = __toESM(require("typescript"), 1);
var DelegatingCompilerHost2 = class {
get jsDocParsingMode() {
return this.delegate.jsDocParsingMode;
}
set jsDocParsingMode(mode) {
this.delegate.jsDocParsingMode = mode;
}
constructor(delegate) {
this.delegate = delegate;
this.createHash = this.delegateMethod("createHash");
this.directoryExists = this.delegateMethod("directoryExists");
this.fileNameToModuleName = this.delegateMethod("fileNameToModuleName");
this.getCancellationToken = this.delegateMethod("getCancellationToken");
this.getCanonicalFileName = this.delegateMethod("getCanonicalFileName");
this.getCurrentDirectory = this.delegateMethod("getCurrentDirectory");
this.getDefaultLibFileName = this.delegateMethod("getDefaultLibFileName");
this.getDefaultLibLocation = this.delegateMethod("getDefaultLibLocation");
this.getDirectories = this.delegateMethod("getDirectories");
this.getEnvironmentVariable = this.delegateMethod("getEnvironmentVariable");
this.getModifiedResourceFiles = this.delegateMethod("getModifiedResourceFiles");
this.getNewLine = this.delegateMethod("getNewLine");
this.getParsedCommandLine = this.delegateMethod("getParsedCommandLine");
this.getSourceFileByPath = this.delegateMethod("getSourceFileByPath");
this.readDirectory = this.delegateMethod("readDirectory");
this.readFile = this.delegateMethod("readFile");
this.readResource = this.delegateMethod("readResource");
this.transformResource = this.delegateMethod("transformResource");
this.realpath = this.delegateMethod("realpath");
this.resolveModuleNames = this.delegateMethod("resolveModuleNames");
this.resolveTypeReferenceDirectives = this.delegateMethod("resolveTypeReferenceDirectives");
this.resourceNameToFileName = this.delegateMethod("resourceNameToFileName");
this.trace = this.delegateMethod("trace");
this.useCaseSensitiveFileNames = this.delegateMethod("useCaseSensitiveFileNames");
this.writeFile = this.delegateMethod("writeFile");
this.getModuleResolutionCache = this.delegateMethod("getModuleResolutionCache");
this.hasInvalidatedResolutions = this.delegateMethod("hasInvalidatedResolutions");
this.resolveModuleNameLiterals = this.delegateMethod("resolveModuleNameLiterals");
this.resolveTypeReferenceDirectiveReferences = this.delegateMethod("resolveTypeReferenceDirectiveReferences");
}
delegateMethod(name) {
return this.delegate[name] !== void 0 ? this.delegate[name].bind(this.delegate) : void 0;
}
};
var NgCompilerHost = class extends DelegatingCompilerHost2 {
constructor(delegate, inputFiles, rootDirs, shimAdapter, shimTagger, entryPoint, diagnostics) {
super(delegate);
this.shimAdapter = shimAdapter;
this.shimTagger = shimTagger;
this.entryPoint = null;
this.entryPoint = entryPoint;
this.constructionDiagnostics = diagnostics;
this.inputFiles = [...inputFiles, ...shimAdapter.extraInputFiles];
this.rootDirs = rootDirs;
if (this.resolveModuleNames === void 0) {
this.resolveModuleNames = this.createCachedResolveModuleNamesFunction();
}
}
get ignoreForEmit() {
return this.shimAdapter.ignoreForEmit;
}
get shimExtensionPrefixes() {
return this.shimAdapter.extensionPrefixes;
}
postProgramCreationCleanup() {
this.shimTagger.finalize();
}
static wrap(delegate, inputFiles, options, oldProgram) {
const topLevelShimGenerators = [];
const perFileShimGenerators = [];
const rootDirs = getRootDirs(delegate, options);
perFileShimGenerators.push(new TypeCheckShimGenerator());
let diagnostics = [];
const normalizedTsInputFiles = [];
for (const inputFile of inputFiles) {
if (!isNonDeclarationTsPath(inputFile)) {
continue;
}
normalizedTsInputFiles.push(resolve(inputFile));
}
let entryPoint = null;
if (options.flatModuleOutFile != null && options.flatModuleOutFile !== "") {
entryPoint = findFlatIndexEntryPoint(normalizedTsInputFiles);
if (entryPoint === null) {
diagnostics.push({
category: import_typescript122.default.DiagnosticCategory.Error,
code: ngErrorCode(ErrorCode.CONFIG_FLAT_MODULE_NO_INDEX),
file: void 0,
start: void 0,
length: void 0,
messageText: 'Angular compiler option "flatModuleOutFile" requires one and only one .ts file in the "files" field.'
});
} else {
const flatModuleId = options.flatModuleId || null;
const flatModuleOutFile = normalizeSeparators2(options.flatModuleOutFile);
const flatIndexGenerator = new FlatIndexGenerator(entryPoint, flatModuleOutFile, flatModuleId);
topLevelShimGenerators.push(flatIndexGenerator);
}
}
const shimAdapter = new ShimAdapter(delegate, normalizedTsInputFiles, topLevelShimGenerators, perFileShimGenerators, oldProgram);
const shimTagger = new ShimReferenceTagger(perFileShimGenerators.map((gen) => gen.extensionPrefix));
return new NgCompilerHost(delegate, inputFiles, rootDirs, shimAdapter, shimTagger, entryPoint, diagnostics);
}
isShim(sf) {
return isShim(sf);
}
isResource(sf) {
return false;
}
getSourceFile(fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile) {
const shimSf = this.shimAdapter.maybeGenerate(resolve(fileName));
if (shimSf !== null) {
return shimSf;
}
const sf = this.delegate.getSourceFile(fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile);
if (sf === void 0) {
return void 0;
}
this.shimTagger.tag(sf);
return sf;
}
fileExists(fileName) {
return this.delegate.fileExists(fileName) || this.shimAdapter.maybeGenerate(resolve(fileName)) != null;
}
get unifiedModulesHost() {
return this.fileNameToModuleName !== void 0 ? this : null;
}
createCachedResolveModuleNamesFunction() {
const moduleResolutionCache = import_typescript122.default.createModuleResolutionCache(this.getCurrentDirectory(), this.getCanonicalFileName.bind(this));
return (moduleNames, containingFile, reusedNames, redirectedReference, options) => {
return moduleNames.map((moduleName) => {
const module2 = import_typescript122.default.resolveModuleName(moduleName, containingFile, options, this, moduleResolutionCache, redirectedReference);
return module2.resolvedModule;
});
};
}
};
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/program.mjs
var NgtscProgram = class {
constructor(rootNames, options, delegateHost, oldProgram) {
this.options = options;
const perfRecorder = ActivePerfRecorder.zeroedToNow();
perfRecorder.phase(PerfPhase.Setup);
if (!options.disableTypeScriptVersionCheck) {
verifySupportedTypeScriptVersion();
}
if (options.compilationMode === "experimental-local") {
options.noEmitOnError = false;
}
const reuseProgram = oldProgram == null ? void 0 : oldProgram.compiler.getCurrentProgram();
this.host = NgCompilerHost.wrap(delegateHost, rootNames, options, reuseProgram != null ? reuseProgram : null);
if (reuseProgram !== void 0) {
retagAllTsFiles(reuseProgram);
}
this.tsProgram = perfRecorder.inPhase(PerfPhase.TypeScriptProgramCreate, () => import_typescript124.default.createProgram(this.host.inputFiles, options, this.host, reuseProgram));
perfRecorder.phase(PerfPhase.Unaccounted);
perfRecorder.memory(PerfCheckpoint.TypeScriptProgramCreate);
this.host.postProgramCreationCleanup();
const programDriver = new TsCreateProgramDriver(this.tsProgram, this.host, this.options, this.host.shimExtensionPrefixes);
this.incrementalStrategy = oldProgram !== void 0 ? oldProgram.incrementalStrategy.toNextBuildStrategy() : new TrackedIncrementalBuildStrategy();
const modifiedResourceFiles = /* @__PURE__ */ new Set();
if (this.host.getModifiedResourceFiles !== void 0) {
const strings = this.host.getModifiedResourceFiles();
if (strings !== void 0) {
for (const fileString of strings) {
modifiedResourceFiles.add(absoluteFrom(fileString));
}
}
}
let ticket;
if (oldProgram === void 0) {
ticket = freshCompilationTicket(
this.tsProgram,
options,
this.incrementalStrategy,
programDriver,
perfRecorder,
false,
false
);
} else {
ticket = incrementalFromCompilerTicket(oldProgram.compiler, this.tsProgram, this.incrementalStrategy, programDriver, modifiedResourceFiles, perfRecorder);
}
this.compiler = NgCompiler.fromTicket(ticket, this.host);
}
getTsProgram() {
return this.tsProgram;
}
getReuseTsProgram() {
return this.compiler.getCurrentProgram();
}
getTsOptionDiagnostics(cancellationToken) {
return this.compiler.perfRecorder.inPhase(PerfPhase.TypeScriptDiagnostics, () => this.tsProgram.getOptionsDiagnostics(cancellationToken));
}
getTsSyntacticDiagnostics(sourceFile, cancellationToken) {
return this.compiler.perfRecorder.inPhase(PerfPhase.TypeScriptDiagnostics, () => {
const ignoredFiles = this.compiler.ignoreForDiagnostics;
let res;
if (sourceFile !== void 0) {
if (ignoredFiles.has(sourceFile)) {
return [];
}
res = this.tsProgram.getSyntacticDiagnostics(sourceFile, cancellationToken);
} else {
const diagnostics = [];
for (const sf of this.tsProgram.getSourceFiles()) {
if (!ignoredFiles.has(sf)) {
diagnostics.push(...this.tsProgram.getSyntacticDiagnostics(sf, cancellationToken));
}
}
res = diagnostics;
}
return res;
});
}
getTsSemanticDiagnostics(sourceFile, cancellationToken) {
if (this.options.compilationMode === "experimental-local") {
return [];
}
return this.compiler.perfRecorder.inPhase(PerfPhase.TypeScriptDiagnostics, () => {
const ignoredFiles = this.compiler.ignoreForDiagnostics;
let res;
if (sourceFile !== void 0) {
if (ignoredFiles.has(sourceFile)) {
return [];
}
res = this.tsProgram.getSemanticDiagnostics(sourceFile, cancellationToken);
} else {
const diagnostics = [];
for (const sf of this.tsProgram.getSourceFiles()) {
if (!ignoredFiles.has(sf)) {
diagnostics.push(...this.tsProgram.getSemanticDiagnostics(sf, cancellationToken));
}
}
res = diagnostics;
}
return res;
});
}
getNgOptionDiagnostics(cancellationToken) {
return this.compiler.getOptionDiagnostics();
}
getNgStructuralDiagnostics(cancellationToken) {
return [];
}
getNgSemanticDiagnostics(fileName, cancellationToken) {
let sf = void 0;
if (fileName !== void 0) {
sf = this.tsProgram.getSourceFile(fileName);
if (sf === void 0) {
return [];
}
}
if (sf === void 0) {
return this.compiler.getDiagnostics();
} else {
return this.compiler.getDiagnosticsForFile(sf, OptimizeFor.WholeProgram);
}
}
loadNgStructureAsync() {
return this.compiler.analyzeAsync();
}
listLazyRoutes(entryRoute) {
return [];
}
emitXi18n() {
var _a2, _b2, _c2;
const ctx = new MessageBundle(new HtmlParser(), [], {}, (_a2 = this.options.i18nOutLocale) != null ? _a2 : null, this.options.i18nPreserveWhitespaceForLegacyExtraction);
this.compiler.xi18n(ctx);
i18nExtract((_b2 = this.options.i18nOutFormat) != null ? _b2 : null, (_c2 = this.options.i18nOutFile) != null ? _c2 : null, this.host, this.options, ctx, resolve);
}
emit(opts) {
var _a2;
if (opts !== void 0 && opts.emitFlags !== void 0 && opts.emitFlags & EmitFlags.I18nBundle) {
this.emitXi18n();
if (!(opts.emitFlags & EmitFlags.JS)) {
return {
diagnostics: [],
emitSkipped: true,
emittedFiles: []
};
}
}
const forceEmit = (_a2 = opts == null ? void 0 : opts.forceEmit) != null ? _a2 : false;
this.compiler.perfRecorder.memory(PerfCheckpoint.PreEmit);
const res = this.compiler.perfRecorder.inPhase(PerfPhase.TypeScriptEmit, () => {
var _a3;
const { transformers } = this.compiler.prepareEmit();
const ignoreFiles = this.compiler.ignoreForEmit;
const emitCallback = (_a3 = opts == null ? void 0 : opts.emitCallback) != null ? _a3 : defaultEmitCallback;
const writeFile = (fileName, data, writeByteOrderMark, onError, sourceFiles) => {
if (sourceFiles !== void 0) {
for (const writtenSf of sourceFiles) {
if (writtenSf.isDeclarationFile) {
continue;
}
this.compiler.incrementalCompilation.recordSuccessfulEmit(writtenSf);
}
}
this.host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles);
};
const customTransforms = opts && opts.customTransformers;
const beforeTransforms = transformers.before || [];
const afterDeclarationsTransforms = transformers.afterDeclarations;
if (customTransforms !== void 0 && customTransforms.beforeTs !== void 0) {
beforeTransforms.push(...customTransforms.beforeTs);
}
const emitResults = [];
for (const targetSourceFile of this.tsProgram.getSourceFiles()) {
if (targetSourceFile.isDeclarationFile || ignoreFiles.has(targetSourceFile)) {
continue;
}
if (!forceEmit && this.compiler.incrementalCompilation.safeToSkipEmit(targetSourceFile)) {
this.compiler.perfRecorder.eventCount(PerfEvent.EmitSkipSourceFile);
continue;
}
this.compiler.perfRecorder.eventCount(PerfEvent.EmitSourceFile);
emitResults.push(emitCallback({
targetSourceFile,
program: this.tsProgram,
host: this.host,
options: this.options,
emitOnlyDtsFiles: false,
writeFile,
customTransformers: {
before: beforeTransforms,
after: customTransforms && customTransforms.afterTs,
afterDeclarations: afterDeclarationsTransforms
}
}));
}
this.compiler.perfRecorder.memory(PerfCheckpoint.Emit);
return (opts && opts.mergeEmitResultsCallback || mergeEmitResults)(emitResults);
});
if (this.options.tracePerformance !== void 0) {
const perf = this.compiler.perfRecorder.finalize();
getFileSystem().writeFile(getFileSystem().resolve(this.options.tracePerformance), JSON.stringify(perf, null, 2));
}
return res;
}
getIndexedComponents() {
return this.compiler.getIndexedComponents();
}
getApiDocumentation(entryPoint, privateModules) {
return this.compiler.getApiDocumentation(entryPoint, privateModules);
}
getEmittedSourceFiles() {
throw new Error("Method not implemented.");
}
};
var defaultEmitCallback = ({ program, targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers }) => program.emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers);
function mergeEmitResults(emitResults) {
const diagnostics = [];
let emitSkipped = false;
const emittedFiles = [];
for (const er of emitResults) {
diagnostics.push(...er.diagnostics);
emitSkipped = emitSkipped || er.emitSkipped;
emittedFiles.push(...er.emittedFiles || []);
}
return { diagnostics, emitSkipped, emittedFiles };
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/transformers/program.mjs
function createProgram({ rootNames, options, host, oldProgram }) {
return new NgtscProgram(rootNames, options, host, oldProgram);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/perform_compile.mjs
var import_typescript126 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/transformers/util.mjs
var import_typescript125 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/private/tooling.mjs
var GLOBAL_DEFS_FOR_TERSER = {
ngDevMode: false,
ngI18nClosureMode: false
};
var GLOBAL_DEFS_FOR_TERSER_WITH_AOT = __spreadProps(__spreadValues({}, GLOBAL_DEFS_FOR_TERSER), {
ngJitMode: false
});
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/logging/src/logger.mjs
var LogLevel;
(function(LogLevel2) {
LogLevel2[LogLevel2["debug"] = 0] = "debug";
LogLevel2[LogLevel2["info"] = 1] = "info";
LogLevel2[LogLevel2["warn"] = 2] = "warn";
LogLevel2[LogLevel2["error"] = 3] = "error";
})(LogLevel || (LogLevel = {}));
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/src/ngtsc/logging/src/console_logger.mjs
var RESET = "\x1B[0m";
var RED = "\x1B[31m";
var YELLOW = "\x1B[33m";
var BLUE = "\x1B[36m";
var DEBUG = `${BLUE}Debug:${RESET}`;
var WARN = `${YELLOW}Warning:${RESET}`;
var ERROR = `${RED}Error:${RESET}`;
// bazel-out/darwin_arm64-fastbuild/bin/packages/compiler-cli/index.mjs
setFileSystem(new NodeJSFileSystem());
// bazel-out/darwin_arm64-fastbuild/bin/packages/core/schematics/ng-generate/standalone-migration/index.mjs
var import_fs2 = require("fs");
var import_path7 = require("path");
var import_typescript138 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/core/schematics/utils/change_tracker.mjs
var import_typescript127 = __toESM(require("typescript"), 1);
var ChangeTracker = class {
constructor(_printer, _importRemapper) {
__publicField(this, "_printer");
__publicField(this, "_importRemapper");
__publicField(this, "_changes", /* @__PURE__ */ new Map());
__publicField(this, "_importManager");
__publicField(this, "_quotesCache", /* @__PURE__ */ new WeakMap());
this._printer = _printer;
this._importRemapper = _importRemapper;
this._importManager = new ImportManager({
shouldUseSingleQuotes: (file) => this._getQuoteKind(file) === 0
});
}
insertText(sourceFile, index, text2) {
this._trackChange(sourceFile, { start: index, text: text2 });
}
replaceText(sourceFile, start, removeLength, text2) {
this._trackChange(sourceFile, { start, removeLength, text: text2 });
}
replaceNode(oldNode, newNode, emitHint = import_typescript127.default.EmitHint.Unspecified, sourceFileWhenPrinting) {
const sourceFile = oldNode.getSourceFile();
this.replaceText(sourceFile, oldNode.getStart(), oldNode.getWidth(), this._printer.printNode(emitHint, newNode, sourceFileWhenPrinting || sourceFile));
}
removeNode(node) {
this._trackChange(node.getSourceFile(), {
start: node.getStart(),
removeLength: node.getWidth(),
text: ""
});
}
addImport(sourceFile, symbolName, moduleName, alias) {
if (this._importRemapper) {
moduleName = this._importRemapper(moduleName, sourceFile.fileName);
}
moduleName = normalizePath(moduleName);
if (!this._changes.has(sourceFile)) {
this._changes.set(sourceFile, []);
}
return this._importManager.addImport({
requestedFile: sourceFile,
exportSymbolName: symbolName,
exportModuleSpecifier: moduleName,
unsafeAliasOverride: alias
});
}
removeImport(sourceFile, symbolName, moduleName) {
moduleName = normalizePath(moduleName);
if (!this._changes.has(sourceFile)) {
this._changes.set(sourceFile, []);
}
this._importManager.removeImport(sourceFile, symbolName, moduleName);
}
recordChanges() {
this._recordImports();
return this._changes;
}
clearChanges() {
this._changes.clear();
}
_trackChange(file, change) {
const changes = this._changes.get(file);
if (changes) {
const insertIndex = changes.findIndex((current) => current.start <= change.start);
if (insertIndex === -1) {
changes.push(change);
} else {
changes.splice(insertIndex, 0, change);
}
} else {
this._changes.set(file, [change]);
}
}
_getQuoteKind(sourceFile) {
if (this._quotesCache.has(sourceFile)) {
return this._quotesCache.get(sourceFile);
}
let kind = 0;
for (const statement of sourceFile.statements) {
if (import_typescript127.default.isImportDeclaration(statement) && import_typescript127.default.isStringLiteral(statement.moduleSpecifier)) {
kind = statement.moduleSpecifier.getText()[0] === '"' ? 1 : 0;
this._quotesCache.set(sourceFile, kind);
break;
}
}
return kind;
}
_recordImports() {
const { newImports, updatedImports, deletedImports } = this._importManager.finalize();
for (const [original, replacement] of updatedImports) {
this.replaceNode(original, replacement);
}
for (const node of deletedImports) {
this.removeNode(node);
}
for (const [sourceFile] of this._changes) {
const importsToAdd = newImports.get(sourceFile.fileName);
if (!importsToAdd) {
continue;
}
const importLines = [];
let lastImport = null;
for (const statement of sourceFile.statements) {
if (import_typescript127.default.isImportDeclaration(statement)) {
lastImport = statement;
}
}
for (const decl of importsToAdd) {
importLines.push(this._printer.printNode(import_typescript127.default.EmitHint.Unspecified, decl, sourceFile));
}
this.insertText(sourceFile, lastImport ? lastImport.getEnd() : 0, (lastImport ? "\n" : "") + importLines.join("\n"));
}
}
};
function normalizePath(path4) {
return path4.replace(/\\/g, "/");
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/core/schematics/utils/project_tsconfig_paths.mjs
var import_core19 = require("@angular-devkit/core");
function getProjectTsConfigPaths(tree) {
return __async(this, null, function* () {
const buildPaths = /* @__PURE__ */ new Set();
const testPaths = /* @__PURE__ */ new Set();
const workspace = yield getWorkspace(tree);
for (const [, project] of workspace.projects) {
for (const [name, target] of project.targets) {
if (name !== "build" && name !== "test") {
continue;
}
for (const [, options] of allTargetOptions(target)) {
const tsConfig = options["tsConfig"];
if (typeof tsConfig !== "string" || !tree.exists(tsConfig)) {
continue;
}
if (name === "build") {
buildPaths.add((0, import_core19.normalize)(tsConfig));
} else {
testPaths.add((0, import_core19.normalize)(tsConfig));
}
}
}
}
return {
buildPaths: [...buildPaths],
testPaths: [...testPaths]
};
});
}
function* allTargetOptions(target) {
if (target.options) {
yield [void 0, target.options];
}
if (!target.configurations) {
return;
}
for (const [name, options] of Object.entries(target.configurations)) {
if (options) {
yield [name, options];
}
}
}
function createHost(tree) {
return {
readFile(path4) {
return __async(this, null, function* () {
const data = tree.read(path4);
if (!data) {
throw new Error("File not found.");
}
return import_core19.virtualFs.fileBufferToString(data);
});
},
writeFile(path4, data) {
return __async(this, null, function* () {
return tree.overwrite(path4, data);
});
},
isDirectory(path4) {
return __async(this, null, function* () {
return !tree.exists(path4) && tree.getDir(path4).subfiles.length > 0;
});
},
isFile(path4) {
return __async(this, null, function* () {
return tree.exists(path4);
});
}
};
}
function getWorkspace(tree) {
return __async(this, null, function* () {
const host = createHost(tree);
const { workspace } = yield import_core19.workspaces.readWorkspace("/", host);
return workspace;
});
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/core/schematics/utils/typescript/compiler_host.mjs
var import_path4 = require("path");
var import_typescript129 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/core/schematics/utils/typescript/parse_tsconfig.mjs
var path3 = __toESM(require("path"), 1);
var import_typescript128 = __toESM(require("typescript"), 1);
function parseTsconfigFile(tsconfigPath, basePath) {
const { config } = import_typescript128.default.readConfigFile(tsconfigPath, import_typescript128.default.sys.readFile);
const parseConfigHost = {
useCaseSensitiveFileNames: import_typescript128.default.sys.useCaseSensitiveFileNames,
fileExists: import_typescript128.default.sys.fileExists,
readDirectory: import_typescript128.default.sys.readDirectory,
readFile: import_typescript128.default.sys.readFile
};
if (!path3.isAbsolute(basePath)) {
throw Error("Unexpected relative base path has been specified.");
}
return import_typescript128.default.parseJsonConfigFileContent(config, parseConfigHost, basePath, {});
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/core/schematics/utils/typescript/compiler_host.mjs
function createProgramOptions(tree, tsconfigPath, basePath, fakeFileRead, additionalFiles, optionOverrides) {
tsconfigPath = (0, import_path4.resolve)(basePath, tsconfigPath);
const parsed = parseTsconfigFile(tsconfigPath, (0, import_path4.dirname)(tsconfigPath));
const options = optionOverrides ? __spreadValues(__spreadValues({}, parsed.options), optionOverrides) : parsed.options;
const host = createMigrationCompilerHost(tree, options, basePath, fakeFileRead);
return { rootNames: parsed.fileNames.concat(additionalFiles || []), options, host };
}
function createMigrationCompilerHost(tree, options, basePath, fakeRead) {
const host = import_typescript129.default.createCompilerHost(options, true);
const defaultReadFile = host.readFile;
host.readFile = (fileName) => {
var _a2;
const treeRelativePath = (0, import_path4.relative)(basePath, fileName);
let result = fakeRead == null ? void 0 : fakeRead(treeRelativePath);
if (typeof result !== "string") {
result = treeRelativePath.startsWith("..") ? defaultReadFile.call(host, fileName) : (_a2 = tree.read(treeRelativePath)) == null ? void 0 : _a2.toString();
}
return typeof result === "string" ? result.replace(/^\uFEFF/, "") : void 0;
};
return host;
}
function canMigrateFile(basePath, sourceFile, program) {
if (sourceFile.fileName.endsWith(".ngtypecheck.ts") || sourceFile.isDeclarationFile || program.isSourceFileFromExternalLibrary(sourceFile)) {
return false;
}
return !(0, import_path4.relative)(basePath, sourceFile.fileName).startsWith("..");
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/core/schematics/ng-generate/standalone-migration/prune-modules.mjs
var import_typescript136 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/core/schematics/utils/typescript/decorators.mjs
var import_typescript131 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/core/schematics/utils/typescript/imports.mjs
var import_typescript130 = __toESM(require("typescript"), 1);
function getImportOfIdentifier(typeChecker, node) {
const symbol = typeChecker.getSymbolAtLocation(node);
if (!symbol || symbol.declarations === void 0 || !symbol.declarations.length) {
return null;
}
const decl = symbol.declarations[0];
if (!import_typescript130.default.isImportSpecifier(decl)) {
return null;
}
const importDecl = decl.parent.parent.parent;
if (!import_typescript130.default.isImportDeclaration(importDecl) || !import_typescript130.default.isStringLiteral(importDecl.moduleSpecifier)) {
return null;
}
return {
name: decl.propertyName ? decl.propertyName.text : decl.name.text,
importModule: importDecl.moduleSpecifier.text,
node: importDecl
};
}
function getImportSpecifier(sourceFile, moduleName, specifierName) {
var _a2;
return (_a2 = getImportSpecifiers(sourceFile, moduleName, specifierName)[0]) != null ? _a2 : null;
}
function getImportSpecifiers(sourceFile, moduleName, specifierOrSpecifiers) {
var _a2;
const matches = [];
for (const node of sourceFile.statements) {
if (!import_typescript130.default.isImportDeclaration(node) || !import_typescript130.default.isStringLiteral(node.moduleSpecifier)) {
continue;
}
const namedBindings = (_a2 = node.importClause) == null ? void 0 : _a2.namedBindings;
const isMatch = typeof moduleName === "string" ? node.moduleSpecifier.text === moduleName : moduleName.test(node.moduleSpecifier.text);
if (!isMatch || !namedBindings || !import_typescript130.default.isNamedImports(namedBindings)) {
continue;
}
if (typeof specifierOrSpecifiers === "string") {
const match = findImportSpecifier(namedBindings.elements, specifierOrSpecifiers);
if (match) {
matches.push(match);
}
} else {
for (const specifierName of specifierOrSpecifiers) {
const match = findImportSpecifier(namedBindings.elements, specifierName);
if (match) {
matches.push(match);
}
}
}
}
return matches;
}
function findImportSpecifier(nodes, specifierName) {
return nodes.find((element2) => {
const { name, propertyName } = element2;
return propertyName ? propertyName.text === specifierName : name.text === specifierName;
});
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/core/schematics/utils/typescript/decorators.mjs
function getCallDecoratorImport(typeChecker, decorator) {
if (!import_typescript131.default.isCallExpression(decorator.expression) || !import_typescript131.default.isIdentifier(decorator.expression.expression)) {
return null;
}
const identifier = decorator.expression.expression;
return getImportOfIdentifier(typeChecker, identifier);
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/core/schematics/utils/ng_decorators.mjs
function getAngularDecorators2(typeChecker, decorators) {
return decorators.map((node) => ({ node, importData: getCallDecoratorImport(typeChecker, node) })).filter(({ importData }) => importData && importData.importModule.startsWith("@angular/")).map(({ node, importData }) => ({
node,
name: importData.name,
moduleName: importData.importModule,
importNode: importData.node
}));
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/core/schematics/utils/typescript/nodes.mjs
var import_typescript132 = __toESM(require("typescript"), 1);
function closestNode(node, predicate) {
let current = node.parent;
while (current && !import_typescript132.default.isSourceFile(current)) {
if (predicate(current)) {
return current;
}
current = current.parent;
}
return null;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/core/schematics/ng-generate/standalone-migration/util.mjs
var import_path5 = require("path");
var import_typescript133 = __toESM(require("typescript"), 1);
var UniqueItemTracker = class {
constructor() {
__publicField(this, "_nodes", /* @__PURE__ */ new Map());
}
track(key, item) {
const set = this._nodes.get(key);
if (set) {
set.add(item);
} else {
this._nodes.set(key, /* @__PURE__ */ new Set([item]));
}
}
get(key) {
return this._nodes.get(key);
}
getEntries() {
return this._nodes.entries();
}
};
var ReferenceResolver = class {
constructor(_program, _host, _rootFileNames, _basePath, _excludedFiles) {
__publicField(this, "_program");
__publicField(this, "_host");
__publicField(this, "_rootFileNames");
__publicField(this, "_basePath");
__publicField(this, "_excludedFiles");
__publicField(this, "_languageService");
__publicField(this, "_tempOnlyFile", null);
this._program = _program;
this._host = _host;
this._rootFileNames = _rootFileNames;
this._basePath = _basePath;
this._excludedFiles = _excludedFiles;
}
findReferencesInProject(node) {
const languageService = this._getLanguageService();
const fileName = node.getSourceFile().fileName;
const start = node.getStart();
let referencedSymbols;
try {
referencedSymbols = languageService.findReferences(fileName, start) || [];
} catch (e) {
console.error("Failed reference lookup for node " + node.getText(), e.message);
referencedSymbols = [];
}
const results = /* @__PURE__ */ new Map();
for (const symbol of referencedSymbols) {
for (const ref of symbol.references) {
if (!ref.isDefinition || symbol.definition.kind === import_typescript133.default.ScriptElementKind.alias) {
if (!results.has(ref.fileName)) {
results.set(ref.fileName, []);
}
results.get(ref.fileName).push([ref.textSpan.start, ref.textSpan.start + ref.textSpan.length]);
}
}
}
return results;
}
findSameFileReferences(node, fileName) {
this._tempOnlyFile = fileName;
const nodeStart = node.getStart();
const results = [];
let highlights;
try {
highlights = this._getLanguageService().getDocumentHighlights(fileName, nodeStart, [
fileName
]);
} catch (e) {
console.error("Failed reference lookup for node " + node.getText(), e.message);
}
if (highlights) {
for (const file of highlights) {
if (file.fileName === fileName) {
for (const { textSpan: { start, length }, kind } of file.highlightSpans) {
if (kind !== import_typescript133.default.HighlightSpanKind.none) {
results.push([start, start + length]);
}
}
}
}
}
this._tempOnlyFile = null;
return results;
}
_readFile(path4) {
var _a2;
if (this._tempOnlyFile !== null && path4 !== this._tempOnlyFile || ((_a2 = this._excludedFiles) == null ? void 0 : _a2.test(path4))) {
return "";
}
return this._host.readFile(path4);
}
_getLanguageService() {
if (!this._languageService) {
const rootFileNames = this._rootFileNames.slice();
this._program.getTsProgram().getSourceFiles().forEach(({ fileName }) => {
var _a2;
if (!((_a2 = this._excludedFiles) == null ? void 0 : _a2.test(fileName)) && !rootFileNames.includes(fileName)) {
rootFileNames.push(fileName);
}
});
this._languageService = import_typescript133.default.createLanguageService({
getCompilationSettings: () => this._program.getTsProgram().getCompilerOptions(),
getScriptFileNames: () => rootFileNames,
getScriptVersion: () => "0",
getScriptSnapshot: (path4) => {
const content = this._readFile(path4);
return content ? import_typescript133.default.ScriptSnapshot.fromString(content) : void 0;
},
getCurrentDirectory: () => this._basePath,
getDefaultLibFileName: (options) => import_typescript133.default.getDefaultLibFilePath(options),
readFile: (path4) => this._readFile(path4),
fileExists: (path4) => this._host.fileExists(path4)
}, import_typescript133.default.createDocumentRegistry(), import_typescript133.default.LanguageServiceMode.PartialSemantic);
}
return this._languageService;
}
};
function getNodeLookup(sourceFile) {
const lookup = /* @__PURE__ */ new Map();
sourceFile.forEachChild(function walk(node) {
const nodesAtStart = lookup.get(node.getStart());
if (nodesAtStart) {
nodesAtStart.push(node);
} else {
lookup.set(node.getStart(), [node]);
}
node.forEachChild(walk);
});
return lookup;
}
function offsetsToNodes(lookup, offsets, results) {
var _a2;
for (const [start, end] of offsets) {
const match = (_a2 = lookup.get(start)) == null ? void 0 : _a2.find((node) => node.getEnd() === end);
if (match) {
results.add(match);
}
}
return results;
}
function findClassDeclaration(reference2, typeChecker) {
var _a2, _b2;
return ((_b2 = (_a2 = typeChecker.getTypeAtLocation(reference2).getSymbol()) == null ? void 0 : _a2.declarations) == null ? void 0 : _b2.find(import_typescript133.default.isClassDeclaration)) || null;
}
function findLiteralProperty(literal3, name) {
return literal3.properties.find((prop) => prop.name && import_typescript133.default.isIdentifier(prop.name) && prop.name.text === name);
}
function getRelativeImportPath(fromFile, toFile) {
let path4 = (0, import_path5.relative)((0, import_path5.dirname)(fromFile), toFile).replace(/\.ts$/, "");
if (!path4.startsWith(".")) {
path4 = "./" + path4;
}
return normalizePath(path4);
}
function knownInternalAliasRemapper(imports) {
return imports.map((current) => current.moduleSpecifier === "@angular/common" && current.symbolName === "NgForOf" ? __spreadProps(__spreadValues({}, current), { symbolName: "NgFor" }) : current);
}
function closestOrSelf(node, predicate) {
return predicate(node) ? node : closestNode(node, predicate);
}
function isClassReferenceInAngularModule(node, className, moduleName, typeChecker) {
var _a2;
const symbol = typeChecker.getTypeAtLocation(node).getSymbol();
const externalName = `@angular/${moduleName}`;
const internalName = `angular2/rc/packages/${moduleName}`;
return !!((_a2 = symbol == null ? void 0 : symbol.declarations) == null ? void 0 : _a2.some((decl) => {
const closestClass = closestOrSelf(decl, import_typescript133.default.isClassDeclaration);
const closestClassFileName = closestClass == null ? void 0 : closestClass.getSourceFile().fileName;
if (!closestClass || !closestClassFileName || !closestClass.name || !import_typescript133.default.isIdentifier(closestClass.name) || !closestClassFileName.includes(externalName) && !closestClassFileName.includes(internalName)) {
return false;
}
return typeof className === "string" ? closestClass.name.text === className : className.test(closestClass.name.text);
}));
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/core/schematics/ng-generate/standalone-migration/to-standalone.mjs
var import_typescript135 = __toESM(require("typescript"), 1);
// bazel-out/darwin_arm64-fastbuild/bin/packages/core/schematics/utils/typescript/symbol.mjs
var import_typescript134 = __toESM(require("typescript"), 1);
function isReferenceToImport(typeChecker, node, importSpecifier) {
var _a2, _b2;
if (import_typescript134.default.isIdentifier(node) && node.text !== importSpecifier.name.text) {
return false;
}
const nodeSymbol = typeChecker.getTypeAtLocation(node).getSymbol();
const importSymbol = typeChecker.getTypeAtLocation(importSpecifier).getSymbol();
return !!(((_a2 = nodeSymbol == null ? void 0 : nodeSymbol.declarations) == null ? void 0 : _a2[0]) && ((_b2 = importSymbol == null ? void 0 : importSymbol.declarations) == null ? void 0 : _b2[0])) && nodeSymbol.declarations[0] === importSymbol.declarations[0];
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/core/schematics/ng-generate/standalone-migration/to-standalone.mjs
function toStandalone(sourceFiles, program, printer, fileImportRemapper, componentImportRemapper) {
const templateTypeChecker = program.compiler.getTemplateTypeChecker();
const typeChecker = program.getTsProgram().getTypeChecker();
const modulesToMigrate = /* @__PURE__ */ new Set();
const testObjectsToMigrate = /* @__PURE__ */ new Set();
const declarations = /* @__PURE__ */ new Set();
const tracker = new ChangeTracker(printer, fileImportRemapper);
for (const sourceFile of sourceFiles) {
const modules = findNgModuleClassesToMigrate(sourceFile, typeChecker);
const testObjects = findTestObjectsToMigrate(sourceFile, typeChecker);
for (const module2 of modules) {
const allModuleDeclarations = extractDeclarationsFromModule(module2, templateTypeChecker);
const unbootstrappedDeclarations = filterNonBootstrappedDeclarations(allModuleDeclarations, module2, templateTypeChecker, typeChecker);
if (unbootstrappedDeclarations.length > 0) {
modulesToMigrate.add(module2);
unbootstrappedDeclarations.forEach((decl) => declarations.add(decl));
}
}
testObjects.forEach((obj) => testObjectsToMigrate.add(obj));
}
for (const declaration of declarations) {
convertNgModuleDeclarationToStandalone(declaration, declarations, tracker, templateTypeChecker, componentImportRemapper);
}
for (const node of modulesToMigrate) {
migrateNgModuleClass(node, declarations, tracker, typeChecker, templateTypeChecker);
}
migrateTestDeclarations(testObjectsToMigrate, declarations, tracker, templateTypeChecker, typeChecker);
return tracker.recordChanges();
}
function convertNgModuleDeclarationToStandalone(decl, allDeclarations, tracker, typeChecker, importRemapper) {
var _a2;
const directiveMeta = typeChecker.getDirectiveMetadata(decl);
if (directiveMeta && directiveMeta.decorator && !directiveMeta.isStandalone) {
let decorator = addStandaloneToDecorator(directiveMeta.decorator);
if (directiveMeta.isComponent) {
const importsToAdd = getComponentImportExpressions(decl, allDeclarations, tracker, typeChecker, importRemapper);
if (importsToAdd.length > 0) {
const hasTrailingComma = importsToAdd.length > 2 && !!((_a2 = extractMetadataLiteral(directiveMeta.decorator)) == null ? void 0 : _a2.properties.hasTrailingComma);
decorator = setPropertyOnAngularDecorator(decorator, "imports", import_typescript135.default.factory.createArrayLiteralExpression(
import_typescript135.default.factory.createNodeArray(importsToAdd, hasTrailingComma),
hasTrailingComma
));
}
}
tracker.replaceNode(directiveMeta.decorator, decorator);
} else {
const pipeMeta = typeChecker.getPipeMetadata(decl);
if (pipeMeta && pipeMeta.decorator && !pipeMeta.isStandalone) {
tracker.replaceNode(pipeMeta.decorator, addStandaloneToDecorator(pipeMeta.decorator));
}
}
}
function getComponentImportExpressions(decl, allDeclarations, tracker, typeChecker, importRemapper) {
const templateDependencies = findTemplateDependencies(decl, typeChecker);
const usedDependenciesInMigration = new Set(templateDependencies.filter((dep) => allDeclarations.has(dep.node)));
const seenImports = /* @__PURE__ */ new Set();
const resolvedDependencies = [];
for (const dep of templateDependencies) {
const importLocation = findImportLocation(dep, decl, usedDependenciesInMigration.has(dep) ? PotentialImportMode.ForceDirect : PotentialImportMode.Normal, typeChecker);
if (importLocation && !seenImports.has(importLocation.symbolName)) {
seenImports.add(importLocation.symbolName);
resolvedDependencies.push(importLocation);
}
}
return potentialImportsToExpressions(resolvedDependencies, decl, tracker, importRemapper);
}
function potentialImportsToExpressions(potentialImports, component, tracker, importRemapper) {
const processedDependencies = importRemapper ? importRemapper(potentialImports, component) : potentialImports;
return processedDependencies.map((importLocation) => {
if (importLocation.moduleSpecifier) {
return tracker.addImport(component.getSourceFile(), importLocation.symbolName, importLocation.moduleSpecifier);
}
const identifier = import_typescript135.default.factory.createIdentifier(importLocation.symbolName);
if (!importLocation.isForwardReference) {
return identifier;
}
const forwardRefExpression = tracker.addImport(component.getSourceFile(), "forwardRef", "@angular/core");
const arrowFunction = import_typescript135.default.factory.createArrowFunction(void 0, void 0, [], void 0, void 0, identifier);
return import_typescript135.default.factory.createCallExpression(forwardRefExpression, void 0, [arrowFunction]);
});
}
function migrateNgModuleClass(node, allDeclarations, tracker, typeChecker, templateTypeChecker) {
var _a2;
const decorator = (_a2 = templateTypeChecker.getNgModuleMetadata(node)) == null ? void 0 : _a2.decorator;
const metadata = decorator ? extractMetadataLiteral(decorator) : null;
if (metadata) {
moveDeclarationsToImports(metadata, allDeclarations, typeChecker, templateTypeChecker, tracker);
}
}
function moveDeclarationsToImports(literal3, allDeclarations, typeChecker, templateTypeChecker, tracker) {
const declarationsProp = findLiteralProperty(literal3, "declarations");
if (!declarationsProp) {
return;
}
const declarationsToPreserve = [];
const declarationsToCopy = [];
const properties = [];
const importsProp = findLiteralProperty(literal3, "imports");
const hasAnyArrayTrailingComma = literal3.properties.some((prop) => import_typescript135.default.isPropertyAssignment(prop) && import_typescript135.default.isArrayLiteralExpression(prop.initializer) && prop.initializer.elements.hasTrailingComma);
if (import_typescript135.default.isPropertyAssignment(declarationsProp)) {
if (import_typescript135.default.isArrayLiteralExpression(declarationsProp.initializer)) {
for (const el of declarationsProp.initializer.elements) {
if (import_typescript135.default.isIdentifier(el)) {
const correspondingClass = findClassDeclaration(el, typeChecker);
if (!correspondingClass || isStandaloneDeclaration(correspondingClass, allDeclarations, templateTypeChecker)) {
declarationsToCopy.push(el);
} else {
declarationsToPreserve.push(el);
}
} else {
declarationsToCopy.push(el);
}
}
} else {
declarationsToCopy.push(import_typescript135.default.factory.createSpreadElement(declarationsProp.initializer));
}
}
if (!importsProp && declarationsToCopy.length > 0) {
properties.push(import_typescript135.default.factory.createPropertyAssignment("imports", import_typescript135.default.factory.createArrayLiteralExpression(import_typescript135.default.factory.createNodeArray(declarationsToCopy, hasAnyArrayTrailingComma && declarationsToCopy.length > 2))));
}
for (const prop of literal3.properties) {
if (!isNamedPropertyAssignment(prop)) {
properties.push(prop);
continue;
}
if (prop === declarationsProp) {
if (declarationsToPreserve.length > 0) {
const hasTrailingComma = import_typescript135.default.isArrayLiteralExpression(prop.initializer) ? prop.initializer.elements.hasTrailingComma : hasAnyArrayTrailingComma;
properties.push(import_typescript135.default.factory.updatePropertyAssignment(prop, prop.name, import_typescript135.default.factory.createArrayLiteralExpression(import_typescript135.default.factory.createNodeArray(declarationsToPreserve, hasTrailingComma && declarationsToPreserve.length > 2))));
}
continue;
}
if (prop === importsProp && declarationsToCopy.length > 0) {
let initializer;
if (import_typescript135.default.isArrayLiteralExpression(prop.initializer)) {
initializer = import_typescript135.default.factory.updateArrayLiteralExpression(prop.initializer, import_typescript135.default.factory.createNodeArray([...prop.initializer.elements, ...declarationsToCopy], prop.initializer.elements.hasTrailingComma));
} else {
initializer = import_typescript135.default.factory.createArrayLiteralExpression(import_typescript135.default.factory.createNodeArray(
[import_typescript135.default.factory.createSpreadElement(prop.initializer), ...declarationsToCopy],
hasAnyArrayTrailingComma && declarationsToCopy.length > 1
));
}
properties.push(import_typescript135.default.factory.updatePropertyAssignment(prop, prop.name, initializer));
continue;
}
properties.push(prop);
}
tracker.replaceNode(literal3, import_typescript135.default.factory.updateObjectLiteralExpression(literal3, import_typescript135.default.factory.createNodeArray(properties, literal3.properties.hasTrailingComma)), import_typescript135.default.EmitHint.Expression);
}
function addStandaloneToDecorator(node) {
return setPropertyOnAngularDecorator(node, "standalone", import_typescript135.default.factory.createToken(import_typescript135.default.SyntaxKind.TrueKeyword));
}
function setPropertyOnAngularDecorator(node, name, initializer) {
if (!import_typescript135.default.isCallExpression(node.expression) || node.expression.arguments.length > 1) {
return node;
}
let literalProperties;
let hasTrailingComma = false;
if (node.expression.arguments.length === 0) {
literalProperties = [import_typescript135.default.factory.createPropertyAssignment(name, initializer)];
} else if (import_typescript135.default.isObjectLiteralExpression(node.expression.arguments[0])) {
const literal3 = node.expression.arguments[0];
const existingProperty = findLiteralProperty(literal3, name);
hasTrailingComma = literal3.properties.hasTrailingComma;
if (existingProperty && import_typescript135.default.isPropertyAssignment(existingProperty)) {
literalProperties = literal3.properties.slice();
literalProperties[literalProperties.indexOf(existingProperty)] = import_typescript135.default.factory.updatePropertyAssignment(existingProperty, existingProperty.name, initializer);
} else {
literalProperties = [
...literal3.properties,
import_typescript135.default.factory.createPropertyAssignment(name, initializer)
];
}
} else {
return node;
}
return import_typescript135.default.factory.createDecorator(import_typescript135.default.factory.createCallExpression(node.expression.expression, node.expression.typeArguments, [
import_typescript135.default.factory.createObjectLiteralExpression(import_typescript135.default.factory.createNodeArray(literalProperties, hasTrailingComma), literalProperties.length > 1)
]));
}
function isNamedPropertyAssignment(node) {
return import_typescript135.default.isPropertyAssignment(node) && node.name && import_typescript135.default.isIdentifier(node.name);
}
function findImportLocation(target, inComponent, importMode, typeChecker) {
const importLocations = typeChecker.getPotentialImportsFor(target, inComponent, importMode);
let firstSameFileImport = null;
let firstModuleImport = null;
for (const location of importLocations) {
if (location.kind === PotentialImportKind.Standalone) {
return location;
}
if (!location.moduleSpecifier && !firstSameFileImport) {
firstSameFileImport = location;
}
if (location.kind === PotentialImportKind.NgModule && !firstModuleImport && !location.symbolName.startsWith("\u0275")) {
firstModuleImport = location;
}
}
return firstSameFileImport || firstModuleImport || importLocations[0] || null;
}
function hasNgModuleMetadataElements(node) {
return import_typescript135.default.isPropertyAssignment(node) && (!import_typescript135.default.isArrayLiteralExpression(node.initializer) || node.initializer.elements.length > 0);
}
function findNgModuleClassesToMigrate(sourceFile, typeChecker) {
const modules = [];
if (getImportSpecifier(sourceFile, "@angular/core", "NgModule")) {
sourceFile.forEachChild(function walk(node) {
if (import_typescript135.default.isClassDeclaration(node)) {
const decorator = getAngularDecorators2(typeChecker, import_typescript135.default.getDecorators(node) || []).find((current) => current.name === "NgModule");
const metadata = decorator ? extractMetadataLiteral(decorator.node) : null;
if (metadata) {
const declarations = findLiteralProperty(metadata, "declarations");
if (declarations != null && hasNgModuleMetadataElements(declarations)) {
modules.push(node);
}
}
}
node.forEachChild(walk);
});
}
return modules;
}
function findTestObjectsToMigrate(sourceFile, typeChecker) {
const testObjects = [];
const testBedImport = getImportSpecifier(sourceFile, "@angular/core/testing", "TestBed");
const catalystImport = getImportSpecifier(sourceFile, /testing\/catalyst$/, "setupModule");
if (testBedImport || catalystImport) {
sourceFile.forEachChild(function walk(node) {
const isObjectLiteralCall = import_typescript135.default.isCallExpression(node) && node.arguments.length > 0 && import_typescript135.default.isObjectLiteralExpression(node.arguments[0]);
const config = isObjectLiteralCall ? node.arguments[0] : null;
const isTestBedCall = isObjectLiteralCall && testBedImport && import_typescript135.default.isPropertyAccessExpression(node.expression) && node.expression.name.text === "configureTestingModule" && isReferenceToImport(typeChecker, node.expression.expression, testBedImport);
const isCatalystCall = isObjectLiteralCall && catalystImport && import_typescript135.default.isIdentifier(node.expression) && isReferenceToImport(typeChecker, node.expression, catalystImport);
if ((isTestBedCall || isCatalystCall) && config) {
const declarations = findLiteralProperty(config, "declarations");
if (declarations && import_typescript135.default.isPropertyAssignment(declarations) && import_typescript135.default.isArrayLiteralExpression(declarations.initializer) && declarations.initializer.elements.length > 0) {
testObjects.push(config);
}
}
node.forEachChild(walk);
});
}
return testObjects;
}
function findTemplateDependencies(decl, typeChecker) {
const results = [];
const usedDirectives = typeChecker.getUsedDirectives(decl);
const usedPipes = typeChecker.getUsedPipes(decl);
if (usedDirectives !== null) {
for (const dir of usedDirectives) {
if (import_typescript135.default.isClassDeclaration(dir.ref.node)) {
results.push(dir.ref);
}
}
}
if (usedPipes !== null) {
const potentialPipes = typeChecker.getPotentialPipes(decl);
for (const pipe2 of potentialPipes) {
if (import_typescript135.default.isClassDeclaration(pipe2.ref.node) && usedPipes.some((current) => pipe2.name === current)) {
results.push(pipe2.ref);
}
}
}
return results;
}
function filterNonBootstrappedDeclarations(declarations, ngModule, templateTypeChecker, typeChecker) {
const metadata = templateTypeChecker.getNgModuleMetadata(ngModule);
const metaLiteral = metadata && metadata.decorator ? extractMetadataLiteral(metadata.decorator) : null;
const bootstrapProp = metaLiteral ? findLiteralProperty(metaLiteral, "bootstrap") : null;
if (!bootstrapProp) {
return declarations;
}
if (!import_typescript135.default.isPropertyAssignment(bootstrapProp) || !import_typescript135.default.isArrayLiteralExpression(bootstrapProp.initializer)) {
return [];
}
const bootstrappedClasses = /* @__PURE__ */ new Set();
for (const el of bootstrapProp.initializer.elements) {
const referencedClass = import_typescript135.default.isIdentifier(el) ? findClassDeclaration(el, typeChecker) : null;
if (referencedClass) {
bootstrappedClasses.add(referencedClass);
} else {
return [];
}
}
return declarations.filter((ref) => !bootstrappedClasses.has(ref));
}
function extractDeclarationsFromModule(ngModule, templateTypeChecker) {
const metadata = templateTypeChecker.getNgModuleMetadata(ngModule);
return metadata ? metadata.declarations.filter((decl) => import_typescript135.default.isClassDeclaration(decl.node)).map((decl) => decl.node) : [];
}
function migrateTestDeclarations(testObjects, declarationsOutsideOfTestFiles, tracker, templateTypeChecker, typeChecker) {
var _a2;
const { decorators, componentImports } = analyzeTestingModules(testObjects, typeChecker);
const allDeclarations = new Set(declarationsOutsideOfTestFiles);
for (const decorator of decorators) {
const closestClass = closestNode(decorator.node, import_typescript135.default.isClassDeclaration);
if (decorator.name === "Pipe" || decorator.name === "Directive") {
tracker.replaceNode(decorator.node, addStandaloneToDecorator(decorator.node));
if (closestClass) {
allDeclarations.add(closestClass);
}
} else if (decorator.name === "Component") {
const newDecorator = addStandaloneToDecorator(decorator.node);
const importsToAdd = componentImports.get(decorator.node);
if (closestClass) {
allDeclarations.add(closestClass);
}
if (importsToAdd && importsToAdd.size > 0) {
const hasTrailingComma = importsToAdd.size > 2 && !!((_a2 = extractMetadataLiteral(decorator.node)) == null ? void 0 : _a2.properties.hasTrailingComma);
const importsArray = import_typescript135.default.factory.createNodeArray(Array.from(importsToAdd), hasTrailingComma);
tracker.replaceNode(decorator.node, setPropertyOnAngularDecorator(newDecorator, "imports", import_typescript135.default.factory.createArrayLiteralExpression(importsArray)));
} else {
tracker.replaceNode(decorator.node, newDecorator);
}
}
}
for (const obj of testObjects) {
moveDeclarationsToImports(obj, allDeclarations, typeChecker, templateTypeChecker, tracker);
}
}
function analyzeTestingModules(testObjects, typeChecker) {
const seenDeclarations = /* @__PURE__ */ new Set();
const decorators = [];
const componentImports = /* @__PURE__ */ new Map();
for (const obj of testObjects) {
const declarations = extractDeclarationsFromTestObject(obj, typeChecker);
if (declarations.length === 0) {
continue;
}
const importsProp = findLiteralProperty(obj, "imports");
const importElements = importsProp && hasNgModuleMetadataElements(importsProp) && import_typescript135.default.isArrayLiteralExpression(importsProp.initializer) ? importsProp.initializer.elements.filter((el) => {
return !import_typescript135.default.isCallExpression(el) && !isClassReferenceInAngularModule(el, /^BrowserAnimationsModule|NoopAnimationsModule$/, "platform-browser/animations", typeChecker);
}) : null;
for (const decl of declarations) {
if (seenDeclarations.has(decl)) {
continue;
}
const [decorator] = getAngularDecorators2(typeChecker, import_typescript135.default.getDecorators(decl) || []);
if (decorator) {
seenDeclarations.add(decl);
decorators.push(decorator);
if (decorator.name === "Component" && importElements) {
let imports = componentImports.get(decorator.node);
if (!imports) {
imports = /* @__PURE__ */ new Set();
componentImports.set(decorator.node, imports);
}
importElements.forEach((imp) => imports.add(imp));
}
}
}
}
return { decorators, componentImports };
}
function extractDeclarationsFromTestObject(obj, typeChecker) {
const results = [];
const declarations = findLiteralProperty(obj, "declarations");
if (declarations && hasNgModuleMetadataElements(declarations) && import_typescript135.default.isArrayLiteralExpression(declarations.initializer)) {
for (const element2 of declarations.initializer.elements) {
const declaration = findClassDeclaration(element2, typeChecker);
if (declaration && declaration.getSourceFile().fileName === obj.getSourceFile().fileName) {
results.push(declaration);
}
}
}
return results;
}
function extractMetadataLiteral(decorator) {
return import_typescript135.default.isCallExpression(decorator.expression) && decorator.expression.arguments.length === 1 && import_typescript135.default.isObjectLiteralExpression(decorator.expression.arguments[0]) ? decorator.expression.arguments[0] : null;
}
function isStandaloneDeclaration(node, declarationsInMigration, templateTypeChecker) {
if (declarationsInMigration.has(node)) {
return true;
}
const metadata = templateTypeChecker.getDirectiveMetadata(node) || templateTypeChecker.getPipeMetadata(node);
return metadata != null && metadata.isStandalone;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/core/schematics/ng-generate/standalone-migration/prune-modules.mjs
function pruneNgModules(program, host, basePath, rootFileNames, sourceFiles, printer, importRemapper, referenceLookupExcludedFiles, componentImportRemapper) {
const filesToRemove = /* @__PURE__ */ new Set();
const tracker = new ChangeTracker(printer, importRemapper);
const tsProgram = program.getTsProgram();
const typeChecker = tsProgram.getTypeChecker();
const templateTypeChecker = program.compiler.getTemplateTypeChecker();
const referenceResolver = new ReferenceResolver(program, host, rootFileNames, basePath, referenceLookupExcludedFiles);
const removalLocations = {
arrays: new UniqueItemTracker(),
imports: new UniqueItemTracker(),
exports: new UniqueItemTracker(),
unknown: /* @__PURE__ */ new Set()
};
const classesToRemove = /* @__PURE__ */ new Set();
const barrelExports = new UniqueItemTracker();
const componentImportArrays = new UniqueItemTracker();
const nodesToRemove = /* @__PURE__ */ new Set();
sourceFiles.forEach(function walk(node) {
var _a2, _b2;
if (import_typescript136.default.isClassDeclaration(node) && canRemoveClass(node, typeChecker)) {
collectChangeLocations(node, removalLocations, componentImportArrays, templateTypeChecker, referenceResolver, program);
classesToRemove.add(node);
} else if (import_typescript136.default.isExportDeclaration(node) && !node.exportClause && node.moduleSpecifier && import_typescript136.default.isStringLiteralLike(node.moduleSpecifier) && node.moduleSpecifier.text.startsWith(".")) {
const exportedSourceFile = (_b2 = (_a2 = typeChecker.getSymbolAtLocation(node.moduleSpecifier)) == null ? void 0 : _a2.valueDeclaration) == null ? void 0 : _b2.getSourceFile();
if (exportedSourceFile) {
barrelExports.track(exportedSourceFile, node);
}
}
node.forEachChild(walk);
});
replaceInImportsArray(componentImportArrays, classesToRemove, tracker, typeChecker, templateTypeChecker, componentImportRemapper);
removeArrayReferences(removalLocations.arrays, tracker);
removeImportReferences(removalLocations.imports, tracker);
removeExportReferences(removalLocations.exports, tracker);
addRemovalTodos(removalLocations.unknown, tracker);
(function trackNodesToRemove(nodes) {
for (const node of nodes) {
const sourceFile = node.getSourceFile();
if (!filesToRemove.has(sourceFile) && canRemoveFile(sourceFile, nodes)) {
const barrelExportsForFile = barrelExports.get(sourceFile);
nodesToRemove.add(node);
filesToRemove.add(sourceFile);
barrelExportsForFile && trackNodesToRemove(barrelExportsForFile);
} else {
nodesToRemove.add(node);
}
}
})(classesToRemove);
for (const node of nodesToRemove) {
const sourceFile = node.getSourceFile();
if (!filesToRemove.has(sourceFile) && canRemoveFile(sourceFile, nodesToRemove)) {
filesToRemove.add(sourceFile);
} else {
tracker.removeNode(node);
}
}
return { pendingChanges: tracker.recordChanges(), filesToRemove };
}
function collectChangeLocations(ngModule, removalLocations, componentImportArrays, templateTypeChecker, referenceResolver, program) {
const refsByFile = referenceResolver.findReferencesInProject(ngModule.name);
const tsProgram = program.getTsProgram();
const nodes = /* @__PURE__ */ new Set();
for (const [fileName, refs] of refsByFile) {
const sourceFile = tsProgram.getSourceFile(fileName);
if (sourceFile) {
offsetsToNodes(getNodeLookup(sourceFile), refs, nodes);
}
}
for (const node of nodes) {
const closestArray = closestNode(node, import_typescript136.default.isArrayLiteralExpression);
if (closestArray) {
const closestAssignment = closestNode(closestArray, import_typescript136.default.isPropertyAssignment);
if (closestAssignment && isInImportsArray(closestAssignment, closestArray)) {
const closestDecorator = closestNode(closestAssignment, import_typescript136.default.isDecorator);
const closestClass = closestDecorator ? closestNode(closestDecorator, import_typescript136.default.isClassDeclaration) : null;
const directiveMeta = closestClass ? templateTypeChecker.getDirectiveMetadata(closestClass) : null;
if (directiveMeta && directiveMeta.isComponent && directiveMeta.isStandalone) {
componentImportArrays.track(closestArray, node);
continue;
}
}
removalLocations.arrays.track(closestArray, node);
continue;
}
const closestImport = closestNode(node, import_typescript136.default.isNamedImports);
if (closestImport) {
removalLocations.imports.track(closestImport, node);
continue;
}
const closestExport = closestNode(node, import_typescript136.default.isNamedExports);
if (closestExport) {
removalLocations.exports.track(closestExport, node);
continue;
}
removalLocations.unknown.add(node);
}
}
function replaceInImportsArray(componentImportArrays, classesToRemove, tracker, typeChecker, templateTypeChecker, importRemapper) {
for (const [array, toReplace] of componentImportArrays.getEntries()) {
const closestClass = closestNode(array, import_typescript136.default.isClassDeclaration);
if (!closestClass) {
continue;
}
const replacements = new UniqueItemTracker();
const usedImports = new Set(findTemplateDependencies(closestClass, templateTypeChecker).map((ref) => ref.node));
for (const node of toReplace) {
const moduleDecl = findClassDeclaration(node, typeChecker);
if (moduleDecl) {
const moduleMeta = templateTypeChecker.getNgModuleMetadata(moduleDecl);
if (moduleMeta) {
moduleMeta.exports.forEach((exp) => {
if (usedImports.has(exp.node)) {
replacements.track(node, exp);
}
});
} else {
classesToRemove.delete(moduleDecl);
}
}
}
replaceModulesInImportsArray(array, closestClass, replacements, tracker, templateTypeChecker, importRemapper);
}
}
function replaceModulesInImportsArray(array, componentClass, replacements, tracker, templateTypeChecker, importRemapper) {
const newElements = [];
for (const element2 of array.elements) {
const replacementRefs = replacements.get(element2);
if (!replacementRefs) {
newElements.push(element2);
continue;
}
const potentialImports = [];
for (const ref of replacementRefs) {
const importLocation = findImportLocation(ref, componentClass, PotentialImportMode.Normal, templateTypeChecker);
if (importLocation) {
potentialImports.push(importLocation);
}
}
newElements.push(...potentialImportsToExpressions(potentialImports, componentClass, tracker, importRemapper));
}
tracker.replaceNode(array, import_typescript136.default.factory.updateArrayLiteralExpression(array, newElements));
}
function removeArrayReferences(locations, tracker) {
for (const [array, toRemove] of locations.getEntries()) {
const newElements = filterRemovedElements(array.elements, toRemove);
tracker.replaceNode(array, import_typescript136.default.factory.updateArrayLiteralExpression(array, import_typescript136.default.factory.createNodeArray(newElements, array.elements.hasTrailingComma)));
}
}
function removeImportReferences(locations, tracker) {
for (const [namedImports, toRemove] of locations.getEntries()) {
const newElements = filterRemovedElements(namedImports.elements, toRemove);
if (newElements.length === 0) {
const importClause = closestNode(namedImports, import_typescript136.default.isImportClause);
if (importClause && importClause.name) {
tracker.replaceNode(importClause, import_typescript136.default.factory.updateImportClause(importClause, importClause.isTypeOnly, importClause.name, void 0));
} else {
const declaration = closestNode(namedImports, import_typescript136.default.isImportDeclaration);
if (declaration) {
tracker.removeNode(declaration);
}
}
} else {
tracker.replaceNode(namedImports, import_typescript136.default.factory.updateNamedImports(namedImports, newElements));
}
}
}
function removeExportReferences(locations, tracker) {
for (const [namedExports, toRemove] of locations.getEntries()) {
const newElements = filterRemovedElements(namedExports.elements, toRemove);
if (newElements.length === 0) {
const declaration = closestNode(namedExports, import_typescript136.default.isExportDeclaration);
if (declaration) {
tracker.removeNode(declaration);
}
} else {
tracker.replaceNode(namedExports, import_typescript136.default.factory.updateNamedExports(namedExports, newElements));
}
}
}
function canRemoveClass(node, typeChecker) {
var _a2;
const decorator = (_a2 = findNgModuleDecorator(node, typeChecker)) == null ? void 0 : _a2.node;
if (!decorator || !import_typescript136.default.isCallExpression(decorator.expression)) {
return false;
}
if (decorator.expression.arguments.length > 0 && !import_typescript136.default.isObjectLiteralExpression(decorator.expression.arguments[0])) {
return false;
}
if (node.members.length > 0 && node.members.some((member) => !isEmptyConstructor(member))) {
return false;
}
if (decorator.expression.arguments.length === 0) {
return true;
}
const literal3 = decorator.expression.arguments[0];
const imports = findLiteralProperty(literal3, "imports");
if (imports && isNonEmptyNgModuleProperty(imports)) {
for (const dep of imports.initializer.elements) {
if (!import_typescript136.default.isIdentifier(dep)) {
return false;
}
const depDeclaration = findClassDeclaration(dep, typeChecker);
const depNgModule = depDeclaration ? findNgModuleDecorator(depDeclaration, typeChecker) : null;
if (depDeclaration !== null && depNgModule !== null && !canRemoveClass(depDeclaration, typeChecker)) {
return false;
}
}
}
for (const prop of literal3.properties) {
if (isNonEmptyNgModuleProperty(prop) && (prop.name.text === "declarations" || prop.name.text === "providers" || prop.name.text === "bootstrap")) {
return false;
}
}
return true;
}
function isNonEmptyNgModuleProperty(node) {
return import_typescript136.default.isPropertyAssignment(node) && import_typescript136.default.isIdentifier(node.name) && import_typescript136.default.isArrayLiteralExpression(node.initializer) && node.initializer.elements.length > 0;
}
function canRemoveFile(sourceFile, nodesToBeRemoved) {
var _a2;
for (const node of sourceFile.statements) {
if (import_typescript136.default.isImportDeclaration(node) || nodesToBeRemoved.has(node)) {
continue;
}
if (import_typescript136.default.isExportDeclaration(node) || import_typescript136.default.canHaveModifiers(node) && ((_a2 = import_typescript136.default.getModifiers(node)) == null ? void 0 : _a2.some((m) => m.kind === import_typescript136.default.SyntaxKind.ExportKeyword))) {
return false;
}
}
return true;
}
function contains(parent, child) {
return parent === child || parent.getSourceFile().fileName === child.getSourceFile().fileName && child.getStart() >= parent.getStart() && child.getStart() <= parent.getEnd();
}
function filterRemovedElements(elements, toRemove) {
return elements.filter((el) => {
for (const node of toRemove) {
if (contains(el, node)) {
return false;
}
}
return true;
});
}
function isEmptyConstructor(node) {
return import_typescript136.default.isConstructorDeclaration(node) && node.parameters.length === 0 && (node.body == null || node.body.statements.length === 0);
}
function addRemovalTodos(nodes, tracker) {
for (const node of nodes) {
tracker.insertText(node.getSourceFile(), node.getFullStart(), ` /* TODO(standalone-migration): clean up removed NgModule reference manually. */ `);
}
}
function findNgModuleDecorator(node, typeChecker) {
const decorators = getAngularDecorators2(typeChecker, import_typescript136.default.getDecorators(node) || []);
return decorators.find((decorator) => decorator.name === "NgModule") || null;
}
function isInImportsArray(closestAssignment, closestArray) {
return closestAssignment.initializer === closestArray && (import_typescript136.default.isIdentifier(closestAssignment.name) || import_typescript136.default.isStringLiteralLike(closestAssignment.name)) && closestAssignment.name.text === "imports";
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/core/schematics/ng-generate/standalone-migration/standalone-bootstrap.mjs
var import_path6 = require("path");
var import_typescript137 = __toESM(require("typescript"), 1);
function toStandaloneBootstrap(program, host, basePath, rootFileNames, sourceFiles, printer, importRemapper, referenceLookupExcludedFiles, componentImportRemapper) {
const tracker = new ChangeTracker(printer, importRemapper);
const typeChecker = program.getTsProgram().getTypeChecker();
const templateTypeChecker = program.compiler.getTemplateTypeChecker();
const referenceResolver = new ReferenceResolver(program, host, rootFileNames, basePath, referenceLookupExcludedFiles);
const bootstrapCalls = [];
const testObjects = /* @__PURE__ */ new Set();
const allDeclarations = /* @__PURE__ */ new Set();
const additionalProviders = hasImport(program, rootFileNames, "protractor") ? /* @__PURE__ */ new Map([["provideProtractorTestingSupport", "@angular/platform-browser"]]) : null;
for (const sourceFile of sourceFiles) {
sourceFile.forEachChild(function walk(node) {
if (import_typescript137.default.isCallExpression(node) && import_typescript137.default.isPropertyAccessExpression(node.expression) && node.expression.name.text === "bootstrapModule" && isClassReferenceInAngularModule(node.expression, "PlatformRef", "core", typeChecker)) {
const call2 = analyzeBootstrapCall(node, typeChecker, templateTypeChecker);
if (call2) {
bootstrapCalls.push(call2);
}
}
node.forEachChild(walk);
});
findTestObjectsToMigrate(sourceFile, typeChecker).forEach((obj) => testObjects.add(obj));
}
for (const call2 of bootstrapCalls) {
call2.declarations.forEach((decl) => allDeclarations.add(decl));
migrateBootstrapCall(call2, tracker, additionalProviders, referenceResolver, typeChecker, printer);
}
for (const declaration of allDeclarations) {
convertNgModuleDeclarationToStandalone(declaration, allDeclarations, tracker, templateTypeChecker, componentImportRemapper);
}
migrateTestDeclarations(testObjects, allDeclarations, tracker, templateTypeChecker, typeChecker);
return tracker.recordChanges();
}
function analyzeBootstrapCall(call2, typeChecker, templateTypeChecker) {
if (call2.arguments.length === 0 || !import_typescript137.default.isIdentifier(call2.arguments[0])) {
return null;
}
const declaration = findClassDeclaration(call2.arguments[0], typeChecker);
if (!declaration) {
return null;
}
const decorator = getAngularDecorators2(typeChecker, import_typescript137.default.getDecorators(declaration) || []).find((decorator2) => decorator2.name === "NgModule");
if (!decorator || decorator.node.expression.arguments.length === 0 || !import_typescript137.default.isObjectLiteralExpression(decorator.node.expression.arguments[0])) {
return null;
}
const metadata = decorator.node.expression.arguments[0];
const bootstrapProp = findLiteralProperty(metadata, "bootstrap");
if (!bootstrapProp || !import_typescript137.default.isPropertyAssignment(bootstrapProp) || !import_typescript137.default.isArrayLiteralExpression(bootstrapProp.initializer) || bootstrapProp.initializer.elements.length === 0 || !import_typescript137.default.isIdentifier(bootstrapProp.initializer.elements[0])) {
return null;
}
const component = findClassDeclaration(bootstrapProp.initializer.elements[0], typeChecker);
if (component && component.name && import_typescript137.default.isIdentifier(component.name)) {
return {
module: declaration,
metadata,
component,
call: call2,
declarations: extractDeclarationsFromModule(declaration, templateTypeChecker)
};
}
return null;
}
function migrateBootstrapCall(analysis, tracker, additionalProviders, referenceResolver, typeChecker, printer) {
const sourceFile = analysis.call.getSourceFile();
const moduleSourceFile = analysis.metadata.getSourceFile();
const providers = findLiteralProperty(analysis.metadata, "providers");
const imports = findLiteralProperty(analysis.metadata, "imports");
const nodesToCopy = /* @__PURE__ */ new Set();
const providersInNewCall = [];
const moduleImportsInNewCall = [];
let nodeLookup = null;
tracker.insertText(moduleSourceFile, analysis.metadata.getStart(), "/* TODO(standalone-migration): clean up removed NgModule class manually. \n");
tracker.insertText(moduleSourceFile, analysis.metadata.getEnd(), " */");
if (providers && import_typescript137.default.isPropertyAssignment(providers)) {
nodeLookup = nodeLookup || getNodeLookup(moduleSourceFile);
if (import_typescript137.default.isArrayLiteralExpression(providers.initializer)) {
providersInNewCall.push(...providers.initializer.elements);
} else {
providersInNewCall.push(import_typescript137.default.factory.createSpreadElement(providers.initializer));
}
addNodesToCopy(sourceFile, providers, nodeLookup, tracker, nodesToCopy, referenceResolver);
}
if (imports && import_typescript137.default.isPropertyAssignment(imports)) {
nodeLookup = nodeLookup || getNodeLookup(moduleSourceFile);
migrateImportsForBootstrapCall(sourceFile, imports, nodeLookup, moduleImportsInNewCall, providersInNewCall, tracker, nodesToCopy, referenceResolver, typeChecker);
}
if (additionalProviders) {
additionalProviders.forEach((moduleSpecifier, name) => {
providersInNewCall.push(import_typescript137.default.factory.createCallExpression(tracker.addImport(sourceFile, name, moduleSpecifier), void 0, void 0));
});
}
if (nodesToCopy.size > 0) {
let text2 = "\n\n";
nodesToCopy.forEach((node) => {
const transformedNode = remapDynamicImports(sourceFile.fileName, node);
if (transformedNode === node) {
text2 += transformedNode.getText() + "\n";
} else {
text2 += printer.printNode(import_typescript137.default.EmitHint.Unspecified, transformedNode, node.getSourceFile());
}
});
text2 += "\n";
tracker.insertText(sourceFile, getLastImportEnd(sourceFile), text2);
}
replaceBootstrapCallExpression(analysis, providersInNewCall, moduleImportsInNewCall, tracker);
}
function replaceBootstrapCallExpression(analysis, providers, modules, tracker) {
const sourceFile = analysis.call.getSourceFile();
const componentPath = getRelativeImportPath(sourceFile.fileName, analysis.component.getSourceFile().fileName);
const args = [tracker.addImport(sourceFile, analysis.component.name.text, componentPath)];
const bootstrapExpression = tracker.addImport(sourceFile, "bootstrapApplication", "@angular/platform-browser");
if (providers.length > 0 || modules.length > 0) {
const combinedProviders = [];
if (modules.length > 0) {
const importProvidersExpression = tracker.addImport(sourceFile, "importProvidersFrom", "@angular/core");
combinedProviders.push(import_typescript137.default.factory.createCallExpression(importProvidersExpression, [], modules));
}
combinedProviders.push(...providers);
const providersArray = import_typescript137.default.factory.createNodeArray(combinedProviders, analysis.metadata.properties.hasTrailingComma && combinedProviders.length > 2);
const initializer = remapDynamicImports(sourceFile.fileName, import_typescript137.default.factory.createArrayLiteralExpression(providersArray, combinedProviders.length > 1));
args.push(import_typescript137.default.factory.createObjectLiteralExpression([import_typescript137.default.factory.createPropertyAssignment("providers", initializer)], true));
}
tracker.replaceNode(
analysis.call,
import_typescript137.default.factory.createCallExpression(bootstrapExpression, [], args),
void 0,
analysis.metadata.getSourceFile()
);
}
function migrateImportsForBootstrapCall(sourceFile, imports, nodeLookup, importsForNewCall, providersInNewCall, tracker, nodesToCopy, referenceResolver, typeChecker) {
if (!import_typescript137.default.isArrayLiteralExpression(imports.initializer)) {
importsForNewCall.push(imports.initializer);
return;
}
for (const element2 of imports.initializer.elements) {
if (import_typescript137.default.isCallExpression(element2) && import_typescript137.default.isPropertyAccessExpression(element2.expression) && element2.arguments.length > 0 && element2.expression.name.text === "forRoot" && isClassReferenceInAngularModule(element2.expression.expression, "RouterModule", "router", typeChecker)) {
const options = element2.arguments[1];
const features = options ? getRouterModuleForRootFeatures(sourceFile, options, tracker) : [];
if (features !== null) {
providersInNewCall.push(import_typescript137.default.factory.createCallExpression(tracker.addImport(sourceFile, "provideRouter", "@angular/router"), [], [element2.arguments[0], ...features]));
addNodesToCopy(sourceFile, element2.arguments[0], nodeLookup, tracker, nodesToCopy, referenceResolver);
if (options) {
addNodesToCopy(sourceFile, options, nodeLookup, tracker, nodesToCopy, referenceResolver);
}
continue;
}
}
if (import_typescript137.default.isIdentifier(element2)) {
const animationsModule = "platform-browser/animations";
const animationsImport = `@angular/${animationsModule}`;
if (isClassReferenceInAngularModule(element2, "BrowserAnimationsModule", animationsModule, typeChecker)) {
providersInNewCall.push(import_typescript137.default.factory.createCallExpression(tracker.addImport(sourceFile, "provideAnimations", animationsImport), [], []));
continue;
}
if (isClassReferenceInAngularModule(element2, "NoopAnimationsModule", animationsModule, typeChecker)) {
providersInNewCall.push(import_typescript137.default.factory.createCallExpression(tracker.addImport(sourceFile, "provideNoopAnimations", animationsImport), [], []));
continue;
}
const httpClientModule = "common/http";
const httpClientImport = `@angular/${httpClientModule}`;
if (isClassReferenceInAngularModule(element2, "HttpClientModule", httpClientModule, typeChecker)) {
const callArgs = [
import_typescript137.default.factory.createCallExpression(tracker.addImport(sourceFile, "withInterceptorsFromDi", httpClientImport), [], [])
];
providersInNewCall.push(import_typescript137.default.factory.createCallExpression(tracker.addImport(sourceFile, "provideHttpClient", httpClientImport), [], callArgs));
continue;
}
}
const target = import_typescript137.default.isCallExpression(element2) && import_typescript137.default.isPropertyAccessExpression(element2.expression) ? element2.expression.expression : element2;
const classDeclaration = findClassDeclaration(target, typeChecker);
const decorators = classDeclaration ? getAngularDecorators2(typeChecker, import_typescript137.default.getDecorators(classDeclaration) || []) : void 0;
if (!decorators || decorators.length === 0 || decorators.every(({ name }) => name !== "Directive" && name !== "Component" && name !== "Pipe")) {
importsForNewCall.push(element2);
addNodesToCopy(sourceFile, element2, nodeLookup, tracker, nodesToCopy, referenceResolver);
}
}
}
function getRouterModuleForRootFeatures(sourceFile, options, tracker) {
if (!import_typescript137.default.isObjectLiteralExpression(options)) {
return null;
}
const featureExpressions = [];
const configOptions = [];
const inMemoryScrollingOptions = [];
const features = new UniqueItemTracker();
for (const prop of options.properties) {
if (!import_typescript137.default.isPropertyAssignment(prop) || !import_typescript137.default.isIdentifier(prop.name) && !import_typescript137.default.isStringLiteralLike(prop.name)) {
return null;
}
switch (prop.name.text) {
case "preloadingStrategy":
features.track("withPreloading", prop.initializer);
break;
case "enableTracing":
if (prop.initializer.kind === import_typescript137.default.SyntaxKind.TrueKeyword) {
features.track("withDebugTracing", null);
}
break;
case "initialNavigation":
if (!import_typescript137.default.isStringLiteralLike(prop.initializer)) {
return null;
}
if (prop.initializer.text === "enabledBlocking" || prop.initializer.text === "enabled") {
features.track("withEnabledBlockingInitialNavigation", null);
} else if (prop.initializer.text === "disabled") {
features.track("withDisabledInitialNavigation", null);
}
break;
case "useHash":
if (prop.initializer.kind === import_typescript137.default.SyntaxKind.TrueKeyword) {
features.track("withHashLocation", null);
}
break;
case "errorHandler":
features.track("withNavigationErrorHandler", prop.initializer);
break;
case "anchorScrolling":
case "scrollPositionRestoration":
inMemoryScrollingOptions.push(prop);
break;
default:
configOptions.push(prop);
break;
}
}
if (inMemoryScrollingOptions.length > 0) {
features.track("withInMemoryScrolling", import_typescript137.default.factory.createObjectLiteralExpression(inMemoryScrollingOptions));
}
if (configOptions.length > 0) {
features.track("withRouterConfig", import_typescript137.default.factory.createObjectLiteralExpression(configOptions));
}
for (const [feature, featureArgs] of features.getEntries()) {
const callArgs = [];
featureArgs.forEach((arg) => {
if (arg !== null) {
callArgs.push(arg);
}
});
featureExpressions.push(import_typescript137.default.factory.createCallExpression(tracker.addImport(sourceFile, feature, "@angular/router"), [], callArgs));
}
return featureExpressions;
}
function addNodesToCopy(targetFile, rootNode, nodeLookup, tracker, nodesToCopy, referenceResolver) {
const refs = findAllSameFileReferences(rootNode, nodeLookup, referenceResolver);
for (const ref of refs) {
const importSpecifier = closestOrSelf(ref, import_typescript137.default.isImportSpecifier);
const importDeclaration = importSpecifier ? closestNode(importSpecifier, import_typescript137.default.isImportDeclaration) : null;
if (importDeclaration && importSpecifier && import_typescript137.default.isStringLiteralLike(importDeclaration.moduleSpecifier)) {
const moduleName = importDeclaration.moduleSpecifier.text.startsWith(".") ? remapRelativeImport(targetFile.fileName, importDeclaration.moduleSpecifier) : importDeclaration.moduleSpecifier.text;
const symbolName = importSpecifier.propertyName ? importSpecifier.propertyName.text : importSpecifier.name.text;
const alias = importSpecifier.propertyName ? importSpecifier.name.text : void 0;
tracker.addImport(targetFile, symbolName, moduleName, alias);
continue;
}
const variableDeclaration = closestOrSelf(ref, import_typescript137.default.isVariableDeclaration);
const variableStatement = variableDeclaration ? closestNode(variableDeclaration, import_typescript137.default.isVariableStatement) : null;
if (variableDeclaration && variableStatement && import_typescript137.default.isIdentifier(variableDeclaration.name)) {
if (isExported(variableStatement)) {
tracker.addImport(targetFile, variableDeclaration.name.text, getRelativeImportPath(targetFile.fileName, ref.getSourceFile().fileName));
} else {
nodesToCopy.add(variableStatement);
}
continue;
}
const closestExportable = closestOrSelf(ref, isExportableDeclaration);
if (closestExportable) {
if (isExported(closestExportable) && closestExportable.name) {
tracker.addImport(targetFile, closestExportable.name.text, getRelativeImportPath(targetFile.fileName, ref.getSourceFile().fileName));
} else {
nodesToCopy.add(closestExportable);
}
}
}
}
function findAllSameFileReferences(rootNode, nodeLookup, referenceResolver) {
const results = /* @__PURE__ */ new Set();
const traversedTopLevelNodes = /* @__PURE__ */ new Set();
const excludeStart = rootNode.getStart();
const excludeEnd = rootNode.getEnd();
(function walk(node) {
if (!isReferenceIdentifier(node)) {
node.forEachChild(walk);
return;
}
const refs = referencesToNodeWithinSameFile(node, nodeLookup, excludeStart, excludeEnd, referenceResolver);
if (refs === null) {
return;
}
for (const ref of refs) {
if (results.has(ref)) {
continue;
}
results.add(ref);
const closestTopLevel = closestNode(ref, isTopLevelStatement);
if (!closestTopLevel || traversedTopLevelNodes.has(closestTopLevel)) {
continue;
}
if (!import_typescript137.default.isImportDeclaration(closestTopLevel) && isOutsideRange(excludeStart, excludeEnd, closestTopLevel.getStart(), closestTopLevel.getEnd())) {
traversedTopLevelNodes.add(closestTopLevel);
walk(closestTopLevel);
}
}
})(rootNode);
return results;
}
function referencesToNodeWithinSameFile(node, nodeLookup, excludeStart, excludeEnd, referenceResolver) {
const offsets = referenceResolver.findSameFileReferences(node, node.getSourceFile().fileName).filter(([start, end]) => isOutsideRange(excludeStart, excludeEnd, start, end));
if (offsets.length > 0) {
const nodes = offsetsToNodes(nodeLookup, offsets, /* @__PURE__ */ new Set());
if (nodes.size > 0) {
return nodes;
}
}
return null;
}
function remapDynamicImports(targetFileName, rootNode) {
let hasChanged = false;
const transformer = (context) => {
return (sourceFile) => import_typescript137.default.visitNode(sourceFile, function walk(node) {
if (import_typescript137.default.isCallExpression(node) && node.expression.kind === import_typescript137.default.SyntaxKind.ImportKeyword && node.arguments.length > 0 && import_typescript137.default.isStringLiteralLike(node.arguments[0]) && node.arguments[0].text.startsWith(".")) {
hasChanged = true;
return context.factory.updateCallExpression(node, node.expression, node.typeArguments, [
context.factory.createStringLiteral(remapRelativeImport(targetFileName, node.arguments[0])),
...node.arguments.slice(1)
]);
}
return import_typescript137.default.visitEachChild(node, walk, context);
});
};
const result = import_typescript137.default.transform(rootNode, [transformer]).transformed[0];
return hasChanged ? result : rootNode;
}
function isTopLevelStatement(node) {
return node.parent != null && import_typescript137.default.isSourceFile(node.parent);
}
function isReferenceIdentifier(node) {
return import_typescript137.default.isIdentifier(node) && (!import_typescript137.default.isPropertyAssignment(node.parent) && !import_typescript137.default.isParameter(node.parent) || node.parent.name !== node);
}
function isOutsideRange(excludeStart, excludeEnd, start, end) {
return start < excludeStart && end < excludeStart || start > excludeEnd;
}
function remapRelativeImport(targetFileName, specifier) {
return getRelativeImportPath(targetFileName, (0, import_path6.join)((0, import_path6.dirname)(specifier.getSourceFile().fileName), specifier.text));
}
function isExported(node) {
return import_typescript137.default.canHaveModifiers(node) && node.modifiers ? node.modifiers.some((modifier) => modifier.kind === import_typescript137.default.SyntaxKind.ExportKeyword) : false;
}
function isExportableDeclaration(node) {
return import_typescript137.default.isEnumDeclaration(node) || import_typescript137.default.isClassDeclaration(node) || import_typescript137.default.isFunctionDeclaration(node) || import_typescript137.default.isInterfaceDeclaration(node) || import_typescript137.default.isTypeAliasDeclaration(node);
}
function getLastImportEnd(sourceFile) {
let index = 0;
for (const statement of sourceFile.statements) {
if (import_typescript137.default.isImportDeclaration(statement)) {
index = Math.max(index, statement.getEnd());
} else {
break;
}
}
return index;
}
function hasImport(program, rootFileNames, moduleName) {
const tsProgram = program.getTsProgram();
const deepImportStart = moduleName + "/";
for (const fileName of rootFileNames) {
const sourceFile = tsProgram.getSourceFile(fileName);
if (!sourceFile) {
continue;
}
for (const statement of sourceFile.statements) {
if (import_typescript137.default.isImportDeclaration(statement) && import_typescript137.default.isStringLiteralLike(statement.moduleSpecifier) && (statement.moduleSpecifier.text === moduleName || statement.moduleSpecifier.text.startsWith(deepImportStart))) {
return true;
}
}
}
return false;
}
// bazel-out/darwin_arm64-fastbuild/bin/packages/core/schematics/ng-generate/standalone-migration/index.mjs
var MigrationMode;
(function(MigrationMode2) {
MigrationMode2["toStandalone"] = "convert-to-standalone";
MigrationMode2["pruneModules"] = "prune-ng-modules";
MigrationMode2["standaloneBootstrap"] = "standalone-bootstrap";
})(MigrationMode || (MigrationMode = {}));
function standalone_migration_default(options) {
return (tree, context) => __async(this, null, function* () {
const { buildPaths, testPaths } = yield getProjectTsConfigPaths(tree);
const basePath = process.cwd();
const allPaths = [...buildPaths, ...testPaths];
const pathToMigrate = normalizePath((0, import_path7.join)(basePath, options.path));
let migratedFiles = 0;
if (!allPaths.length) {
throw new import_schematics.SchematicsException("Could not find any tsconfig file. Cannot run the standalone migration.");
}
for (const tsconfigPath of allPaths) {
migratedFiles += standaloneMigration(tree, tsconfigPath, basePath, pathToMigrate, options);
}
if (migratedFiles === 0) {
throw new import_schematics.SchematicsException(`Could not find any files to migrate under the path ${pathToMigrate}. Cannot run the standalone migration.`);
}
context.logger.info("\u{1F389} Automated migration step has finished! \u{1F389}");
context.logger.info("IMPORTANT! Please verify manually that your application builds and behaves as expected.");
context.logger.info(`See https://angular.dev/reference/migrations/standalone for more information.`);
});
}
function standaloneMigration(tree, tsconfigPath, basePath, pathToMigrate, schematicOptions, oldProgram) {
if (schematicOptions.path.startsWith("..")) {
throw new import_schematics.SchematicsException("Cannot run standalone migration outside of the current project.");
}
const { host, options, rootNames } = createProgramOptions(tree, tsconfigPath, basePath, void 0, void 0, {
_enableTemplateTypeChecker: true,
compileNonExportedClasses: true,
skipLibCheck: true,
skipDefaultLibCheck: true
});
const referenceLookupExcludedFiles = /node_modules|\.ngtypecheck\.ts/;
const program = createProgram({ rootNames, host, options, oldProgram });
const printer = import_typescript138.default.createPrinter();
if ((0, import_fs2.existsSync)(pathToMigrate) && !(0, import_fs2.statSync)(pathToMigrate).isDirectory()) {
throw new import_schematics.SchematicsException(`Migration path ${pathToMigrate} has to be a directory. Cannot run the standalone migration.`);
}
const sourceFiles = program.getTsProgram().getSourceFiles().filter((sourceFile) => sourceFile.fileName.startsWith(pathToMigrate) && canMigrateFile(basePath, sourceFile, program.getTsProgram()));
if (sourceFiles.length === 0) {
return 0;
}
let pendingChanges;
let filesToRemove = null;
if (schematicOptions.mode === MigrationMode.pruneModules) {
const result = pruneNgModules(program, host, basePath, rootNames, sourceFiles, printer, void 0, referenceLookupExcludedFiles, knownInternalAliasRemapper);
pendingChanges = result.pendingChanges;
filesToRemove = result.filesToRemove;
} else if (schematicOptions.mode === MigrationMode.standaloneBootstrap) {
pendingChanges = toStandaloneBootstrap(program, host, basePath, rootNames, sourceFiles, printer, void 0, referenceLookupExcludedFiles, knownInternalAliasRemapper);
} else {
pendingChanges = toStandalone(sourceFiles, program, printer, void 0, knownInternalAliasRemapper);
}
for (const [file, changes] of pendingChanges.entries()) {
if (filesToRemove == null ? void 0 : filesToRemove.has(file)) {
continue;
}
const update = tree.beginUpdate((0, import_path7.relative)(basePath, file.fileName));
changes.forEach((change) => {
if (change.removeLength != null) {
update.remove(change.start, change.removeLength);
}
update.insertRight(change.start, change.text);
});
tree.commitUpdate(update);
}
if (filesToRemove) {
for (const file of filesToRemove) {
tree.delete((0, import_path7.relative)(basePath, file.fileName));
}
}
if (schematicOptions.mode === MigrationMode.standaloneBootstrap) {
return standaloneMigration(tree, tsconfigPath, basePath, pathToMigrate, __spreadProps(__spreadValues({}, schematicOptions), { mode: MigrationMode.pruneModules }), program) + sourceFiles.length;
}
return sourceFiles.length;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {});
/*!
* @license
* Copyright Google LLC 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.dev/license
*/
/**
*
* @license
* Copyright Google LLC 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.dev/license
*/
/**
* @license
* Copyright Google LLC 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.dev/license
*/