1 |
|
2 | import {createRequire as __cjsCompatRequire} from 'module';
|
3 | const require = __cjsCompatRequire(import.meta.url);
|
4 | const __ESM_IMPORT_META_URL__ = import.meta.url;
|
5 |
|
6 | var __defProp = Object.defineProperty;
|
7 | var __defProps = Object.defineProperties;
|
8 | var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
|
9 | var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
10 | var __hasOwnProp = Object.prototype.hasOwnProperty;
|
11 | var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
12 | var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
13 | var __spreadValues = (a, b) => {
|
14 | for (var prop in b || (b = {}))
|
15 | if (__hasOwnProp.call(b, prop))
|
16 | __defNormalProp(a, prop, b[prop]);
|
17 | if (__getOwnPropSymbols)
|
18 | for (var prop of __getOwnPropSymbols(b)) {
|
19 | if (__propIsEnum.call(b, prop))
|
20 | __defNormalProp(a, prop, b[prop]);
|
21 | }
|
22 | return a;
|
23 | };
|
24 | var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
|
25 | var __require = ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
26 | get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
27 | }) : x)(function(x) {
|
28 | if (typeof require !== "undefined")
|
29 | return require.apply(this, arguments);
|
30 | throw new Error('Dynamic require of "' + x + '" is not supported');
|
31 | });
|
32 |
|
33 |
|
34 | import { dirname as dirname6, join as join6 } from "path";
|
35 | import { fileURLToPath as fileURLToPath2 } from "url";
|
36 |
|
37 |
|
38 | import {
|
39 | EOL
|
40 | } from "os";
|
41 | import ts from "typescript";
|
42 |
|
43 |
|
44 | var InvalidFileSystem = class {
|
45 | exists(path7) {
|
46 | throw makeError();
|
47 | }
|
48 | readFile(path7) {
|
49 | throw makeError();
|
50 | }
|
51 | readFileBuffer(path7) {
|
52 | throw makeError();
|
53 | }
|
54 | writeFile(path7, data, exclusive) {
|
55 | throw makeError();
|
56 | }
|
57 | removeFile(path7) {
|
58 | throw makeError();
|
59 | }
|
60 | symlink(target, path7) {
|
61 | throw makeError();
|
62 | }
|
63 | readdir(path7) {
|
64 | throw makeError();
|
65 | }
|
66 | lstat(path7) {
|
67 | throw makeError();
|
68 | }
|
69 | stat(path7) {
|
70 | throw makeError();
|
71 | }
|
72 | pwd() {
|
73 | throw makeError();
|
74 | }
|
75 | chdir(path7) {
|
76 | throw makeError();
|
77 | }
|
78 | extname(path7) {
|
79 | throw makeError();
|
80 | }
|
81 | copyFile(from, to) {
|
82 | throw makeError();
|
83 | }
|
84 | moveFile(from, to) {
|
85 | throw makeError();
|
86 | }
|
87 | ensureDir(path7) {
|
88 | throw makeError();
|
89 | }
|
90 | removeDeep(path7) {
|
91 | throw makeError();
|
92 | }
|
93 | isCaseSensitive() {
|
94 | throw makeError();
|
95 | }
|
96 | resolve(...paths) {
|
97 | throw makeError();
|
98 | }
|
99 | dirname(file) {
|
100 | throw makeError();
|
101 | }
|
102 | join(basePath, ...paths) {
|
103 | throw makeError();
|
104 | }
|
105 | isRoot(path7) {
|
106 | throw makeError();
|
107 | }
|
108 | isRooted(path7) {
|
109 | throw makeError();
|
110 | }
|
111 | relative(from, to) {
|
112 | throw makeError();
|
113 | }
|
114 | basename(filePath, extension) {
|
115 | throw makeError();
|
116 | }
|
117 | realpath(filePath) {
|
118 | throw makeError();
|
119 | }
|
120 | getDefaultLibLocation() {
|
121 | throw makeError();
|
122 | }
|
123 | normalize(path7) {
|
124 | throw makeError();
|
125 | }
|
126 | };
|
127 | function makeError() {
|
128 | return new Error("FileSystem has not been configured. Please call `setFileSystem()` before calling this method.");
|
129 | }
|
130 |
|
131 |
|
132 | var TS_DTS_JS_EXTENSION = /(?:\.d)?\.ts$|\.js$/;
|
133 | function stripExtension(path7) {
|
134 | return path7.replace(TS_DTS_JS_EXTENSION, "");
|
135 | }
|
136 |
|
137 |
|
138 | var fs = new InvalidFileSystem();
|
139 | function getFileSystem() {
|
140 | return fs;
|
141 | }
|
142 | function setFileSystem(fileSystem) {
|
143 | fs = fileSystem;
|
144 | }
|
145 | function absoluteFrom(path7) {
|
146 | if (!fs.isRooted(path7)) {
|
147 | throw new Error(`Internal Error: absoluteFrom(${path7}): path is not absolute`);
|
148 | }
|
149 | return fs.resolve(path7);
|
150 | }
|
151 | var ABSOLUTE_PATH = Symbol("AbsolutePath");
|
152 | function absoluteFromSourceFile(sf) {
|
153 | const sfWithPatch = sf;
|
154 | if (sfWithPatch[ABSOLUTE_PATH] === void 0) {
|
155 | sfWithPatch[ABSOLUTE_PATH] = fs.resolve(sfWithPatch.fileName);
|
156 | }
|
157 | return sfWithPatch[ABSOLUTE_PATH];
|
158 | }
|
159 | function dirname(file) {
|
160 | return fs.dirname(file);
|
161 | }
|
162 | function resolve(basePath, ...paths) {
|
163 | return fs.resolve(basePath, ...paths);
|
164 | }
|
165 | function isRooted(path7) {
|
166 | return fs.isRooted(path7);
|
167 | }
|
168 | function relative(from, to) {
|
169 | return fs.relative(from, to);
|
170 | }
|
171 | function isLocalRelativePath(relativePath) {
|
172 | return !isRooted(relativePath) && !relativePath.startsWith("..");
|
173 | }
|
174 | function toRelativeImport(relativePath) {
|
175 | return isLocalRelativePath(relativePath) ? `./${relativePath}` : relativePath;
|
176 | }
|
177 |
|
178 |
|
179 | var NgtscCompilerHost = class {
|
180 | constructor(fs5, options = {}) {
|
181 | this.fs = fs5;
|
182 | this.options = options;
|
183 | }
|
184 | getSourceFile(fileName, languageVersion) {
|
185 | const text = this.readFile(fileName);
|
186 | return text !== void 0 ? ts.createSourceFile(fileName, text, languageVersion, true) : void 0;
|
187 | }
|
188 | getDefaultLibFileName(options) {
|
189 | return this.fs.join(this.getDefaultLibLocation(), ts.getDefaultLibFileName(options));
|
190 | }
|
191 | getDefaultLibLocation() {
|
192 | return this.fs.getDefaultLibLocation();
|
193 | }
|
194 | writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles) {
|
195 | const path7 = absoluteFrom(fileName);
|
196 | this.fs.ensureDir(this.fs.dirname(path7));
|
197 | this.fs.writeFile(path7, data);
|
198 | }
|
199 | getCurrentDirectory() {
|
200 | return this.fs.pwd();
|
201 | }
|
202 | getCanonicalFileName(fileName) {
|
203 | return this.useCaseSensitiveFileNames() ? fileName : fileName.toLowerCase();
|
204 | }
|
205 | useCaseSensitiveFileNames() {
|
206 | return this.fs.isCaseSensitive();
|
207 | }
|
208 | getNewLine() {
|
209 | switch (this.options.newLine) {
|
210 | case ts.NewLineKind.CarriageReturnLineFeed:
|
211 | return "\r\n";
|
212 | case ts.NewLineKind.LineFeed:
|
213 | return "\n";
|
214 | default:
|
215 | return EOL;
|
216 | }
|
217 | }
|
218 | fileExists(fileName) {
|
219 | const absPath = this.fs.resolve(fileName);
|
220 | return this.fs.exists(absPath) && this.fs.stat(absPath).isFile();
|
221 | }
|
222 | readFile(fileName) {
|
223 | const absPath = this.fs.resolve(fileName);
|
224 | if (!this.fileExists(absPath)) {
|
225 | return void 0;
|
226 | }
|
227 | return this.fs.readFile(absPath);
|
228 | }
|
229 | };
|
230 |
|
231 |
|
232 | var LogicalProjectPath = {
|
233 | relativePathBetween: function(from, to) {
|
234 | const relativePath = relative(dirname(resolve(from)), resolve(to));
|
235 | return toRelativeImport(relativePath);
|
236 | }
|
237 | };
|
238 | var LogicalFileSystem = class {
|
239 | constructor(rootDirs, compilerHost) {
|
240 | this.compilerHost = compilerHost;
|
241 | this.cache = new Map();
|
242 | this.rootDirs = rootDirs.concat([]).sort((a, b) => b.length - a.length);
|
243 | this.canonicalRootDirs = this.rootDirs.map((dir) => this.compilerHost.getCanonicalFileName(dir));
|
244 | }
|
245 | logicalPathOfSf(sf) {
|
246 | return this.logicalPathOfFile(absoluteFrom(sf.fileName));
|
247 | }
|
248 | logicalPathOfFile(physicalFile) {
|
249 | const canonicalFilePath = this.compilerHost.getCanonicalFileName(physicalFile);
|
250 | if (!this.cache.has(canonicalFilePath)) {
|
251 | let logicalFile = null;
|
252 | for (let i = 0; i < this.rootDirs.length; i++) {
|
253 | const rootDir = this.rootDirs[i];
|
254 | const canonicalRootDir = this.canonicalRootDirs[i];
|
255 | if (isWithinBasePath(canonicalRootDir, canonicalFilePath)) {
|
256 | logicalFile = this.createLogicalProjectPath(physicalFile, rootDir);
|
257 | if (logicalFile.indexOf("/node_modules/") !== -1) {
|
258 | logicalFile = null;
|
259 | } else {
|
260 | break;
|
261 | }
|
262 | }
|
263 | }
|
264 | this.cache.set(canonicalFilePath, logicalFile);
|
265 | }
|
266 | return this.cache.get(canonicalFilePath);
|
267 | }
|
268 | createLogicalProjectPath(file, rootDir) {
|
269 | const logicalPath = stripExtension(file.substr(rootDir.length));
|
270 | return logicalPath.startsWith("/") ? logicalPath : "/" + logicalPath;
|
271 | }
|
272 | };
|
273 | function isWithinBasePath(base, path7) {
|
274 | return isLocalRelativePath(relative(base, path7));
|
275 | }
|
276 |
|
277 |
|
278 | import {
|
279 | copyFileSync,
|
280 | existsSync,
|
281 | lstatSync,
|
282 | mkdirSync,
|
283 | readFileSync,
|
284 | readdirSync,
|
285 | realpathSync,
|
286 | renameSync,
|
287 | rmdirSync,
|
288 | statSync,
|
289 | symlinkSync,
|
290 | unlinkSync,
|
291 | writeFileSync
|
292 | } from "fs";
|
293 | import module from "module";
|
294 | import {
|
295 | basename,
|
296 | dirname as dirname2,
|
297 | extname,
|
298 | isAbsolute,
|
299 | join,
|
300 | relative as relative2,
|
301 | resolve as resolve2
|
302 | } from "path";
|
303 | import { fileURLToPath } from "url";
|
304 | var NodeJSPathManipulation = class {
|
305 | pwd() {
|
306 | return this.normalize(process.cwd());
|
307 | }
|
308 | chdir(dir) {
|
309 | process.chdir(dir);
|
310 | }
|
311 | resolve(...paths) {
|
312 | return this.normalize(resolve2(...paths));
|
313 | }
|
314 | dirname(file) {
|
315 | return this.normalize(dirname2(file));
|
316 | }
|
317 | join(basePath, ...paths) {
|
318 | return this.normalize(join(basePath, ...paths));
|
319 | }
|
320 | isRoot(path7) {
|
321 | return this.dirname(path7) === this.normalize(path7);
|
322 | }
|
323 | isRooted(path7) {
|
324 | return isAbsolute(path7);
|
325 | }
|
326 | relative(from, to) {
|
327 | return this.normalize(relative2(from, to));
|
328 | }
|
329 | basename(filePath, extension) {
|
330 | return basename(filePath, extension);
|
331 | }
|
332 | extname(path7) {
|
333 | return extname(path7);
|
334 | }
|
335 | normalize(path7) {
|
336 | return path7.replace(/\\/g, "/");
|
337 | }
|
338 | };
|
339 | var isCommonJS = typeof __filename !== "undefined";
|
340 | var currentFileUrl = isCommonJS ? null : __ESM_IMPORT_META_URL__;
|
341 | var currentFileName = isCommonJS ? __filename : fileURLToPath(currentFileUrl);
|
342 | var NodeJSReadonlyFileSystem = class extends NodeJSPathManipulation {
|
343 | constructor() {
|
344 | super(...arguments);
|
345 | this._caseSensitive = void 0;
|
346 | }
|
347 | isCaseSensitive() {
|
348 | if (this._caseSensitive === void 0) {
|
349 | this._caseSensitive = !existsSync(this.normalize(toggleCase(currentFileName)));
|
350 | }
|
351 | return this._caseSensitive;
|
352 | }
|
353 | exists(path7) {
|
354 | return existsSync(path7);
|
355 | }
|
356 | readFile(path7) {
|
357 | return readFileSync(path7, "utf8");
|
358 | }
|
359 | readFileBuffer(path7) {
|
360 | return readFileSync(path7);
|
361 | }
|
362 | readdir(path7) {
|
363 | return readdirSync(path7);
|
364 | }
|
365 | lstat(path7) {
|
366 | return lstatSync(path7);
|
367 | }
|
368 | stat(path7) {
|
369 | return statSync(path7);
|
370 | }
|
371 | realpath(path7) {
|
372 | return this.resolve(realpathSync(path7));
|
373 | }
|
374 | getDefaultLibLocation() {
|
375 | const requireFn = isCommonJS ? __require : module.createRequire(currentFileUrl);
|
376 | return this.resolve(requireFn.resolve("typescript"), "..");
|
377 | }
|
378 | };
|
379 | var NodeJSFileSystem = class extends NodeJSReadonlyFileSystem {
|
380 | writeFile(path7, data, exclusive = false) {
|
381 | writeFileSync(path7, data, exclusive ? { flag: "wx" } : void 0);
|
382 | }
|
383 | removeFile(path7) {
|
384 | unlinkSync(path7);
|
385 | }
|
386 | symlink(target, path7) {
|
387 | symlinkSync(target, path7);
|
388 | }
|
389 | copyFile(from, to) {
|
390 | copyFileSync(from, to);
|
391 | }
|
392 | moveFile(from, to) {
|
393 | renameSync(from, to);
|
394 | }
|
395 | ensureDir(path7) {
|
396 | const parents = [];
|
397 | while (!this.isRoot(path7) && !this.exists(path7)) {
|
398 | parents.push(path7);
|
399 | path7 = this.dirname(path7);
|
400 | }
|
401 | while (parents.length) {
|
402 | this.safeMkdir(parents.pop());
|
403 | }
|
404 | }
|
405 | removeDeep(path7) {
|
406 | rmdirSync(path7, { recursive: true });
|
407 | }
|
408 | safeMkdir(path7) {
|
409 | try {
|
410 | mkdirSync(path7);
|
411 | } catch (err) {
|
412 | if (!this.exists(path7) || !this.stat(path7).isDirectory()) {
|
413 | throw err;
|
414 | }
|
415 | }
|
416 | }
|
417 | };
|
418 | function toggleCase(str) {
|
419 | return str.replace(/\w/g, (ch) => ch.toUpperCase() === ch ? ch.toLowerCase() : ch.toUpperCase());
|
420 | }
|
421 |
|
422 |
|
423 | import ts9 from "typescript";
|
424 |
|
425 |
|
426 | import ts3 from "typescript";
|
427 |
|
428 |
|
429 | import ts2 from "typescript";
|
430 | var D_TS = /\.d\.ts$/i;
|
431 | function isSymbolWithValueDeclaration(symbol) {
|
432 | return symbol != null && symbol.valueDeclaration !== void 0 && symbol.declarations !== void 0;
|
433 | }
|
434 | function isDtsPath(filePath) {
|
435 | return D_TS.test(filePath);
|
436 | }
|
437 | function isFromDtsFile(node) {
|
438 | let sf = node.getSourceFile();
|
439 | if (sf === void 0) {
|
440 | sf = ts2.getOriginalNode(node).getSourceFile();
|
441 | }
|
442 | return sf !== void 0 && sf.isDeclarationFile;
|
443 | }
|
444 | function nodeNameForError(node) {
|
445 | if (node.name !== void 0 && ts2.isIdentifier(node.name)) {
|
446 | return node.name.text;
|
447 | } else {
|
448 | const kind = ts2.SyntaxKind[node.kind];
|
449 | const { line, character } = ts2.getLineAndCharacterOfPosition(node.getSourceFile(), node.getStart());
|
450 | return `${kind}@${line}:${character}`;
|
451 | }
|
452 | }
|
453 | function getSourceFile(node) {
|
454 | const directSf = node.getSourceFile();
|
455 | return directSf !== void 0 ? directSf : ts2.getOriginalNode(node).getSourceFile();
|
456 | }
|
457 | function getSourceFileOrNull(program, fileName) {
|
458 | return program.getSourceFile(fileName) || null;
|
459 | }
|
460 | function identifierOfNode(decl) {
|
461 | if (decl.name !== void 0 && ts2.isIdentifier(decl.name)) {
|
462 | return decl.name;
|
463 | } else {
|
464 | return null;
|
465 | }
|
466 | }
|
467 | function isDeclaration(node) {
|
468 | return isValueDeclaration(node) || isTypeDeclaration(node);
|
469 | }
|
470 | function isValueDeclaration(node) {
|
471 | return ts2.isClassDeclaration(node) || ts2.isFunctionDeclaration(node) || ts2.isVariableDeclaration(node);
|
472 | }
|
473 | function isTypeDeclaration(node) {
|
474 | return ts2.isEnumDeclaration(node) || ts2.isTypeAliasDeclaration(node) || ts2.isInterfaceDeclaration(node);
|
475 | }
|
476 | function isNamedDeclaration(node) {
|
477 | const namedNode = node;
|
478 | return namedNode.name !== void 0 && ts2.isIdentifier(namedNode.name);
|
479 | }
|
480 | function nodeDebugInfo(node) {
|
481 | const sf = getSourceFile(node);
|
482 | const { line, character } = ts2.getLineAndCharacterOfPosition(sf, node.pos);
|
483 | return `[${sf.fileName}: ${ts2.SyntaxKind[node.kind]} @ ${line}:${character}]`;
|
484 | }
|
485 | function resolveModuleName(moduleName, containingFile, compilerOptions, compilerHost, moduleResolutionCache) {
|
486 | if (compilerHost.resolveModuleNames) {
|
487 | return compilerHost.resolveModuleNames([moduleName], containingFile, void 0, void 0, compilerOptions)[0];
|
488 | } else {
|
489 | return ts2.resolveModuleName(moduleName, containingFile, compilerOptions, compilerHost, moduleResolutionCache !== null ? moduleResolutionCache : void 0).resolvedModule;
|
490 | }
|
491 | }
|
492 | function isAssignment(node) {
|
493 | return ts2.isBinaryExpression(node) && node.operatorToken.kind === ts2.SyntaxKind.EqualsToken;
|
494 | }
|
495 |
|
496 |
|
497 | function findNamespaceOfIdentifier(id) {
|
498 | return id.parent && ts3.isPropertyAccessExpression(id.parent) && id.parent.name === id && ts3.isIdentifier(id.parent.expression) ? id.parent.expression : null;
|
499 | }
|
500 | function findRequireCallReference(id, checker) {
|
501 | var _a, _b;
|
502 | const symbol = checker.getSymbolAtLocation(id) || null;
|
503 | const declaration = (_b = symbol == null ? void 0 : symbol.valueDeclaration) != null ? _b : (_a = symbol == null ? void 0 : symbol.declarations) == null ? void 0 : _a[0];
|
504 | const initializer = declaration && ts3.isVariableDeclaration(declaration) && declaration.initializer || null;
|
505 | return initializer && isRequireCall(initializer) ? initializer : null;
|
506 | }
|
507 | function isWildcardReexportStatement(stmt) {
|
508 | if (!ts3.isExpressionStatement(stmt) || !ts3.isCallExpression(stmt.expression)) {
|
509 | return false;
|
510 | }
|
511 | let fnName = null;
|
512 | if (ts3.isIdentifier(stmt.expression.expression)) {
|
513 | fnName = stmt.expression.expression.text;
|
514 | } else if (ts3.isPropertyAccessExpression(stmt.expression.expression) && ts3.isIdentifier(stmt.expression.expression.name)) {
|
515 | fnName = stmt.expression.expression.name.text;
|
516 | }
|
517 | if (fnName !== "__export" && fnName !== "__exportStar") {
|
518 | return false;
|
519 | }
|
520 | return stmt.expression.arguments.length > 0;
|
521 | }
|
522 | function isDefinePropertyReexportStatement(stmt) {
|
523 | if (!ts3.isExpressionStatement(stmt) || !ts3.isCallExpression(stmt.expression)) {
|
524 | return false;
|
525 | }
|
526 | if (!ts3.isPropertyAccessExpression(stmt.expression.expression) || !ts3.isIdentifier(stmt.expression.expression.expression) || stmt.expression.expression.expression.text !== "Object" || !ts3.isIdentifier(stmt.expression.expression.name) || stmt.expression.expression.name.text !== "defineProperty") {
|
527 | return false;
|
528 | }
|
529 | const args = stmt.expression.arguments;
|
530 | if (args.length !== 3) {
|
531 | return false;
|
532 | }
|
533 | const exportsObject = args[0];
|
534 | if (!ts3.isIdentifier(exportsObject) || exportsObject.text !== "exports") {
|
535 | return false;
|
536 | }
|
537 | const propertyKey = args[1];
|
538 | if (!ts3.isStringLiteral(propertyKey)) {
|
539 | return false;
|
540 | }
|
541 | const propertyDescriptor = args[2];
|
542 | if (!ts3.isObjectLiteralExpression(propertyDescriptor)) {
|
543 | return false;
|
544 | }
|
545 | return propertyDescriptor.properties.some((prop) => prop.name !== void 0 && ts3.isIdentifier(prop.name) && prop.name.text === "get");
|
546 | }
|
547 | function extractGetterFnExpression(statement) {
|
548 | const args = statement.expression.arguments;
|
549 | const getterFn = args[2].properties.find((prop) => prop.name !== void 0 && ts3.isIdentifier(prop.name) && prop.name.text === "get");
|
550 | if (getterFn === void 0 || !ts3.isPropertyAssignment(getterFn) || !ts3.isFunctionExpression(getterFn.initializer)) {
|
551 | return null;
|
552 | }
|
553 | const returnStatement = getterFn.initializer.body.statements[0];
|
554 | if (!ts3.isReturnStatement(returnStatement) || returnStatement.expression === void 0) {
|
555 | return null;
|
556 | }
|
557 | return returnStatement.expression;
|
558 | }
|
559 | function isRequireCall(node) {
|
560 | return ts3.isCallExpression(node) && ts3.isIdentifier(node.expression) && node.expression.text === "require" && node.arguments.length === 1 && ts3.isStringLiteral(node.arguments[0]);
|
561 | }
|
562 | function isExternalImport(path7) {
|
563 | return !/^\.\.?(\/|$)/.test(path7);
|
564 | }
|
565 | function isExportsDeclaration(expr) {
|
566 | return expr.parent && isExportsAssignment(expr.parent);
|
567 | }
|
568 | function isExportsAssignment(expr) {
|
569 | return isAssignment(expr) && ts3.isPropertyAccessExpression(expr.left) && ts3.isIdentifier(expr.left.expression) && expr.left.expression.text === "exports" && ts3.isIdentifier(expr.left.name);
|
570 | }
|
571 | function isExportsStatement(stmt) {
|
572 | return ts3.isExpressionStatement(stmt) && isExportsAssignment(stmt.expression);
|
573 | }
|
574 | function skipAliases(node) {
|
575 | while (isAssignment(node)) {
|
576 | node = node.right;
|
577 | }
|
578 | return node;
|
579 | }
|
580 |
|
581 |
|
582 | import ts8 from "typescript";
|
583 |
|
584 |
|
585 | import ts4 from "typescript";
|
586 | var Decorator = {
|
587 | nodeForError: (decorator) => {
|
588 | if (decorator.node !== null) {
|
589 | return decorator.node;
|
590 | } else {
|
591 | return decorator.synthesizedFor;
|
592 | }
|
593 | }
|
594 | };
|
595 | function isDecoratorIdentifier(exp) {
|
596 | return ts4.isIdentifier(exp) || ts4.isPropertyAccessExpression(exp) && ts4.isIdentifier(exp.expression) && ts4.isIdentifier(exp.name);
|
597 | }
|
598 | var ClassMemberKind;
|
599 | (function(ClassMemberKind2) {
|
600 | ClassMemberKind2[ClassMemberKind2["Constructor"] = 0] = "Constructor";
|
601 | ClassMemberKind2[ClassMemberKind2["Getter"] = 1] = "Getter";
|
602 | ClassMemberKind2[ClassMemberKind2["Setter"] = 2] = "Setter";
|
603 | ClassMemberKind2[ClassMemberKind2["Property"] = 3] = "Property";
|
604 | ClassMemberKind2[ClassMemberKind2["Method"] = 4] = "Method";
|
605 | })(ClassMemberKind || (ClassMemberKind = {}));
|
606 | var KnownDeclaration;
|
607 | (function(KnownDeclaration2) {
|
608 | KnownDeclaration2[KnownDeclaration2["JsGlobalObject"] = 0] = "JsGlobalObject";
|
609 | KnownDeclaration2[KnownDeclaration2["TsHelperAssign"] = 1] = "TsHelperAssign";
|
610 | KnownDeclaration2[KnownDeclaration2["TsHelperSpread"] = 2] = "TsHelperSpread";
|
611 | KnownDeclaration2[KnownDeclaration2["TsHelperSpreadArrays"] = 3] = "TsHelperSpreadArrays";
|
612 | KnownDeclaration2[KnownDeclaration2["TsHelperSpreadArray"] = 4] = "TsHelperSpreadArray";
|
613 | KnownDeclaration2[KnownDeclaration2["TsHelperRead"] = 5] = "TsHelperRead";
|
614 | })(KnownDeclaration || (KnownDeclaration = {}));
|
615 | function isConcreteDeclaration(decl) {
|
616 | return decl.kind === 0;
|
617 | }
|
618 |
|
619 |
|
620 | import ts5 from "typescript";
|
621 | function typeToValue(typeNode, checker) {
|
622 | if (typeNode === null) {
|
623 | return missingType();
|
624 | }
|
625 | if (!ts5.isTypeReferenceNode(typeNode)) {
|
626 | return unsupportedType(typeNode);
|
627 | }
|
628 | const symbols = resolveTypeSymbols(typeNode, checker);
|
629 | if (symbols === null) {
|
630 | return unknownReference(typeNode);
|
631 | }
|
632 | const { local, decl } = symbols;
|
633 | if (decl.valueDeclaration === void 0 || decl.flags & ts5.SymbolFlags.ConstEnum) {
|
634 | let typeOnlyDecl = null;
|
635 | if (decl.declarations !== void 0 && decl.declarations.length > 0) {
|
636 | typeOnlyDecl = decl.declarations[0];
|
637 | }
|
638 | return noValueDeclaration(typeNode, typeOnlyDecl);
|
639 | }
|
640 | const firstDecl = local.declarations && local.declarations[0];
|
641 | if (firstDecl !== void 0) {
|
642 | if (ts5.isImportClause(firstDecl) && firstDecl.name !== void 0) {
|
643 | if (firstDecl.isTypeOnly) {
|
644 | return typeOnlyImport(typeNode, firstDecl);
|
645 | }
|
646 | return {
|
647 | kind: 0,
|
648 | expression: firstDecl.name,
|
649 | defaultImportStatement: firstDecl.parent
|
650 | };
|
651 | } else if (ts5.isImportSpecifier(firstDecl)) {
|
652 | if (firstDecl.parent.parent.isTypeOnly) {
|
653 | return typeOnlyImport(typeNode, firstDecl.parent.parent);
|
654 | }
|
655 | const importedName = (firstDecl.propertyName || firstDecl.name).text;
|
656 | const [_localName, ...nestedPath] = symbols.symbolNames;
|
657 | const moduleName = extractModuleName(firstDecl.parent.parent.parent);
|
658 | return {
|
659 | kind: 1,
|
660 | valueDeclaration: decl.valueDeclaration,
|
661 | moduleName,
|
662 | importedName,
|
663 | nestedPath
|
664 | };
|
665 | } else if (ts5.isNamespaceImport(firstDecl)) {
|
666 | if (firstDecl.parent.isTypeOnly) {
|
667 | return typeOnlyImport(typeNode, firstDecl.parent);
|
668 | }
|
669 | if (symbols.symbolNames.length === 1) {
|
670 | return namespaceImport(typeNode, firstDecl.parent);
|
671 | }
|
672 | const [_ns, importedName, ...nestedPath] = symbols.symbolNames;
|
673 | const moduleName = extractModuleName(firstDecl.parent.parent);
|
674 | return {
|
675 | kind: 1,
|
676 | valueDeclaration: decl.valueDeclaration,
|
677 | moduleName,
|
678 | importedName,
|
679 | nestedPath
|
680 | };
|
681 | }
|
682 | }
|
683 | const expression = typeNodeToValueExpr(typeNode);
|
684 | if (expression !== null) {
|
685 | return {
|
686 | kind: 0,
|
687 | expression,
|
688 | defaultImportStatement: null
|
689 | };
|
690 | } else {
|
691 | return unsupportedType(typeNode);
|
692 | }
|
693 | }
|
694 | function unsupportedType(typeNode) {
|
695 | return {
|
696 | kind: 2,
|
697 | reason: { kind: 5, typeNode }
|
698 | };
|
699 | }
|
700 | function noValueDeclaration(typeNode, decl) {
|
701 | return {
|
702 | kind: 2,
|
703 | reason: { kind: 1, typeNode, decl }
|
704 | };
|
705 | }
|
706 | function typeOnlyImport(typeNode, importClause) {
|
707 | return {
|
708 | kind: 2,
|
709 | reason: { kind: 2, typeNode, importClause }
|
710 | };
|
711 | }
|
712 | function unknownReference(typeNode) {
|
713 | return {
|
714 | kind: 2,
|
715 | reason: { kind: 3, typeNode }
|
716 | };
|
717 | }
|
718 | function namespaceImport(typeNode, importClause) {
|
719 | return {
|
720 | kind: 2,
|
721 | reason: { kind: 4, typeNode, importClause }
|
722 | };
|
723 | }
|
724 | function missingType() {
|
725 | return {
|
726 | kind: 2,
|
727 | reason: { kind: 0 }
|
728 | };
|
729 | }
|
730 | function typeNodeToValueExpr(node) {
|
731 | if (ts5.isTypeReferenceNode(node)) {
|
732 | return entityNameToValue(node.typeName);
|
733 | } else {
|
734 | return null;
|
735 | }
|
736 | }
|
737 | function resolveTypeSymbols(typeRef, checker) {
|
738 | const typeName = typeRef.typeName;
|
739 | const typeRefSymbol = checker.getSymbolAtLocation(typeName);
|
740 | if (typeRefSymbol === void 0) {
|
741 | return null;
|
742 | }
|
743 | let local = typeRefSymbol;
|
744 | let leftMost = typeName;
|
745 | const symbolNames = [];
|
746 | while (ts5.isQualifiedName(leftMost)) {
|
747 | symbolNames.unshift(leftMost.right.text);
|
748 | leftMost = leftMost.left;
|
749 | }
|
750 | symbolNames.unshift(leftMost.text);
|
751 | if (leftMost !== typeName) {
|
752 | const localTmp = checker.getSymbolAtLocation(leftMost);
|
753 | if (localTmp !== void 0) {
|
754 | local = localTmp;
|
755 | }
|
756 | }
|
757 | let decl = typeRefSymbol;
|
758 | if (typeRefSymbol.flags & ts5.SymbolFlags.Alias) {
|
759 | decl = checker.getAliasedSymbol(typeRefSymbol);
|
760 | }
|
761 | return { local, decl, symbolNames };
|
762 | }
|
763 | function entityNameToValue(node) {
|
764 | if (ts5.isQualifiedName(node)) {
|
765 | const left = entityNameToValue(node.left);
|
766 | return left !== null ? ts5.createPropertyAccess(left, node.right) : null;
|
767 | } else if (ts5.isIdentifier(node)) {
|
768 | return ts5.getMutableClone(node);
|
769 | } else {
|
770 | return null;
|
771 | }
|
772 | }
|
773 | function extractModuleName(node) {
|
774 | if (!ts5.isStringLiteral(node.moduleSpecifier)) {
|
775 | throw new Error("not a module specifier");
|
776 | }
|
777 | return node.moduleSpecifier.text;
|
778 | }
|
779 |
|
780 |
|
781 | import ts7 from "typescript";
|
782 |
|
783 |
|
784 | import ts6 from "typescript";
|
785 | function isNamedClassDeclaration(node) {
|
786 | return ts6.isClassDeclaration(node) && isIdentifier(node.name);
|
787 | }
|
788 | function isNamedFunctionDeclaration(node) {
|
789 | return ts6.isFunctionDeclaration(node) && isIdentifier(node.name);
|
790 | }
|
791 | function isNamedVariableDeclaration(node) {
|
792 | return ts6.isVariableDeclaration(node) && isIdentifier(node.name);
|
793 | }
|
794 | function isIdentifier(node) {
|
795 | return node !== void 0 && ts6.isIdentifier(node);
|
796 | }
|
797 |
|
798 |
|
799 | var TypeScriptReflectionHost = class {
|
800 | constructor(checker) {
|
801 | this.checker = checker;
|
802 | }
|
803 | getDecoratorsOfDeclaration(declaration) {
|
804 | if (declaration.decorators === void 0 || declaration.decorators.length === 0) {
|
805 | return null;
|
806 | }
|
807 | return declaration.decorators.map((decorator) => this._reflectDecorator(decorator)).filter((dec) => dec !== null);
|
808 | }
|
809 | getMembersOfClass(clazz) {
|
810 | const tsClazz = castDeclarationToClassOrDie(clazz);
|
811 | return tsClazz.members.map((member) => this._reflectMember(member)).filter((member) => member !== null);
|
812 | }
|
813 | getConstructorParameters(clazz) {
|
814 | const tsClazz = castDeclarationToClassOrDie(clazz);
|
815 | const isDeclaration2 = tsClazz.getSourceFile().isDeclarationFile;
|
816 | const ctor = tsClazz.members.find((member) => ts7.isConstructorDeclaration(member) && (isDeclaration2 || member.body !== void 0));
|
817 | if (ctor === void 0) {
|
818 | return null;
|
819 | }
|
820 | return ctor.parameters.map((node) => {
|
821 | const name = parameterName(node.name);
|
822 | const decorators = this.getDecoratorsOfDeclaration(node);
|
823 | let originalTypeNode = node.type || null;
|
824 | let typeNode = originalTypeNode;
|
825 | if (typeNode && ts7.isUnionTypeNode(typeNode)) {
|
826 | let childTypeNodes = typeNode.types.filter((childTypeNode) => !(ts7.isLiteralTypeNode(childTypeNode) && childTypeNode.literal.kind === ts7.SyntaxKind.NullKeyword));
|
827 | if (childTypeNodes.length === 1) {
|
828 | typeNode = childTypeNodes[0];
|
829 | }
|
830 | }
|
831 | const typeValueReference = typeToValue(typeNode, this.checker);
|
832 | return {
|
833 | name,
|
834 | nameNode: node.name,
|
835 | typeValueReference,
|
836 | typeNode: originalTypeNode,
|
837 | decorators
|
838 | };
|
839 | });
|
840 | }
|
841 | getImportOfIdentifier(id) {
|
842 | const directImport = this.getDirectImportOfIdentifier(id);
|
843 | if (directImport !== null) {
|
844 | return directImport;
|
845 | } else if (ts7.isQualifiedName(id.parent) && id.parent.right === id) {
|
846 | return this.getImportOfNamespacedIdentifier(id, getQualifiedNameRoot(id.parent));
|
847 | } else if (ts7.isPropertyAccessExpression(id.parent) && id.parent.name === id) {
|
848 | return this.getImportOfNamespacedIdentifier(id, getFarLeftIdentifier(id.parent));
|
849 | } else {
|
850 | return null;
|
851 | }
|
852 | }
|
853 | getExportsOfModule(node) {
|
854 | if (!ts7.isSourceFile(node)) {
|
855 | throw new Error(`getExportsOfModule() called on non-SourceFile in TS code`);
|
856 | }
|
857 | const symbol = this.checker.getSymbolAtLocation(node);
|
858 | if (symbol === void 0) {
|
859 | return null;
|
860 | }
|
861 | const map = new Map();
|
862 | this.checker.getExportsOfModule(symbol).forEach((exportSymbol) => {
|
863 | const decl = this.getDeclarationOfSymbol(exportSymbol, null);
|
864 | if (decl !== null) {
|
865 | map.set(exportSymbol.name, decl);
|
866 | }
|
867 | });
|
868 | return map;
|
869 | }
|
870 | isClass(node) {
|
871 | return isNamedClassDeclaration(node);
|
872 | }
|
873 | hasBaseClass(clazz) {
|
874 | return this.getBaseClassExpression(clazz) !== null;
|
875 | }
|
876 | getBaseClassExpression(clazz) {
|
877 | if (!(ts7.isClassDeclaration(clazz) || ts7.isClassExpression(clazz)) || clazz.heritageClauses === void 0) {
|
878 | return null;
|
879 | }
|
880 | const extendsClause = clazz.heritageClauses.find((clause) => clause.token === ts7.SyntaxKind.ExtendsKeyword);
|
881 | if (extendsClause === void 0) {
|
882 | return null;
|
883 | }
|
884 | const extendsType = extendsClause.types[0];
|
885 | if (extendsType === void 0) {
|
886 | return null;
|
887 | }
|
888 | return extendsType.expression;
|
889 | }
|
890 | getDeclarationOfIdentifier(id) {
|
891 | let symbol = this.checker.getSymbolAtLocation(id);
|
892 | if (symbol === void 0) {
|
893 | return null;
|
894 | }
|
895 | return this.getDeclarationOfSymbol(symbol, id);
|
896 | }
|
897 | getDefinitionOfFunction(node) {
|
898 | if (!ts7.isFunctionDeclaration(node) && !ts7.isMethodDeclaration(node) && !ts7.isFunctionExpression(node)) {
|
899 | return null;
|
900 | }
|
901 | return {
|
902 | node,
|
903 | body: node.body !== void 0 ? Array.from(node.body.statements) : null,
|
904 | parameters: node.parameters.map((param) => {
|
905 | const name = parameterName(param.name);
|
906 | const initializer = param.initializer || null;
|
907 | return { name, node: param, initializer };
|
908 | })
|
909 | };
|
910 | }
|
911 | getGenericArityOfClass(clazz) {
|
912 | if (!ts7.isClassDeclaration(clazz)) {
|
913 | return null;
|
914 | }
|
915 | return clazz.typeParameters !== void 0 ? clazz.typeParameters.length : 0;
|
916 | }
|
917 | getVariableValue(declaration) {
|
918 | return declaration.initializer || null;
|
919 | }
|
920 | getDtsDeclaration(_) {
|
921 | return null;
|
922 | }
|
923 | getInternalNameOfClass(clazz) {
|
924 | return clazz.name;
|
925 | }
|
926 | getAdjacentNameOfClass(clazz) {
|
927 | return clazz.name;
|
928 | }
|
929 | isStaticallyExported(decl) {
|
930 | let topLevel = decl;
|
931 | if (ts7.isVariableDeclaration(decl) && ts7.isVariableDeclarationList(decl.parent)) {
|
932 | topLevel = decl.parent.parent;
|
933 | }
|
934 | if (topLevel.modifiers !== void 0 && topLevel.modifiers.some((modifier) => modifier.kind === ts7.SyntaxKind.ExportKeyword)) {
|
935 | return true;
|
936 | }
|
937 | if (topLevel.parent === void 0 || !ts7.isSourceFile(topLevel.parent)) {
|
938 | return false;
|
939 | }
|
940 | const localExports = this.getLocalExportedDeclarationsOfSourceFile(decl.getSourceFile());
|
941 | return localExports.has(decl);
|
942 | }
|
943 | getDirectImportOfIdentifier(id) {
|
944 | const symbol = this.checker.getSymbolAtLocation(id);
|
945 | if (symbol === void 0 || symbol.declarations === void 0 || symbol.declarations.length !== 1) {
|
946 | return null;
|
947 | }
|
948 | const decl = symbol.declarations[0];
|
949 | const importDecl = getContainingImportDeclaration(decl);
|
950 | if (importDecl === null) {
|
951 | return null;
|
952 | }
|
953 | if (!ts7.isStringLiteral(importDecl.moduleSpecifier)) {
|
954 | return null;
|
955 | }
|
956 | return { from: importDecl.moduleSpecifier.text, name: getExportedName(decl, id) };
|
957 | }
|
958 | getImportOfNamespacedIdentifier(id, namespaceIdentifier) {
|
959 | if (namespaceIdentifier === null) {
|
960 | return null;
|
961 | }
|
962 | const namespaceSymbol = this.checker.getSymbolAtLocation(namespaceIdentifier);
|
963 | if (!namespaceSymbol || namespaceSymbol.declarations === void 0) {
|
964 | return null;
|
965 | }
|
966 | const declaration = namespaceSymbol.declarations.length === 1 ? namespaceSymbol.declarations[0] : null;
|
967 | if (!declaration) {
|
968 | return null;
|
969 | }
|
970 | const namespaceDeclaration = ts7.isNamespaceImport(declaration) ? declaration : null;
|
971 | if (!namespaceDeclaration) {
|
972 | return null;
|
973 | }
|
974 | const importDeclaration = namespaceDeclaration.parent.parent;
|
975 | if (!ts7.isStringLiteral(importDeclaration.moduleSpecifier)) {
|
976 | return null;
|
977 | }
|
978 | return {
|
979 | from: importDeclaration.moduleSpecifier.text,
|
980 | name: id.text
|
981 | };
|
982 | }
|
983 | getDeclarationOfSymbol(symbol, originalId) {
|
984 | let valueDeclaration = void 0;
|
985 | if (symbol.valueDeclaration !== void 0) {
|
986 | valueDeclaration = symbol.valueDeclaration;
|
987 | } else if (symbol.declarations !== void 0 && symbol.declarations.length > 0) {
|
988 | valueDeclaration = symbol.declarations[0];
|
989 | }
|
990 | if (valueDeclaration !== void 0 && ts7.isShorthandPropertyAssignment(valueDeclaration)) {
|
991 | const shorthandSymbol = this.checker.getShorthandAssignmentValueSymbol(valueDeclaration);
|
992 | if (shorthandSymbol === void 0) {
|
993 | return null;
|
994 | }
|
995 | return this.getDeclarationOfSymbol(shorthandSymbol, originalId);
|
996 | } else if (valueDeclaration !== void 0 && ts7.isExportSpecifier(valueDeclaration)) {
|
997 | const targetSymbol = this.checker.getExportSpecifierLocalTargetSymbol(valueDeclaration);
|
998 | if (targetSymbol === void 0) {
|
999 | return null;
|
1000 | }
|
1001 | return this.getDeclarationOfSymbol(targetSymbol, originalId);
|
1002 | }
|
1003 | const importInfo = originalId && this.getImportOfIdentifier(originalId);
|
1004 | const viaModule = importInfo !== null && importInfo.from !== null && !importInfo.from.startsWith(".") ? importInfo.from : null;
|
1005 | while (symbol.flags & ts7.SymbolFlags.Alias) {
|
1006 | symbol = this.checker.getAliasedSymbol(symbol);
|
1007 | }
|
1008 | if (symbol.valueDeclaration !== void 0) {
|
1009 | return {
|
1010 | node: symbol.valueDeclaration,
|
1011 | known: null,
|
1012 | viaModule,
|
1013 | identity: null,
|
1014 | kind: 0
|
1015 | };
|
1016 | } else if (symbol.declarations !== void 0 && symbol.declarations.length > 0) {
|
1017 | return {
|
1018 | node: symbol.declarations[0],
|
1019 | known: null,
|
1020 | viaModule,
|
1021 | identity: null,
|
1022 | kind: 0
|
1023 | };
|
1024 | } else {
|
1025 | return null;
|
1026 | }
|
1027 | }
|
1028 | _reflectDecorator(node) {
|
1029 | let decoratorExpr = node.expression;
|
1030 | let args = null;
|
1031 | if (ts7.isCallExpression(decoratorExpr)) {
|
1032 | args = Array.from(decoratorExpr.arguments);
|
1033 | decoratorExpr = decoratorExpr.expression;
|
1034 | }
|
1035 | if (!isDecoratorIdentifier(decoratorExpr)) {
|
1036 | return null;
|
1037 | }
|
1038 | const decoratorIdentifier = ts7.isIdentifier(decoratorExpr) ? decoratorExpr : decoratorExpr.name;
|
1039 | const importDecl = this.getImportOfIdentifier(decoratorIdentifier);
|
1040 | return {
|
1041 | name: decoratorIdentifier.text,
|
1042 | identifier: decoratorExpr,
|
1043 | import: importDecl,
|
1044 | node,
|
1045 | args
|
1046 | };
|
1047 | }
|
1048 | _reflectMember(node) {
|
1049 | let kind = null;
|
1050 | let value = null;
|
1051 | let name = null;
|
1052 | let nameNode = null;
|
1053 | if (ts7.isPropertyDeclaration(node)) {
|
1054 | kind = ClassMemberKind.Property;
|
1055 | value = node.initializer || null;
|
1056 | } else if (ts7.isGetAccessorDeclaration(node)) {
|
1057 | kind = ClassMemberKind.Getter;
|
1058 | } else if (ts7.isSetAccessorDeclaration(node)) {
|
1059 | kind = ClassMemberKind.Setter;
|
1060 | } else if (ts7.isMethodDeclaration(node)) {
|
1061 | kind = ClassMemberKind.Method;
|
1062 | } else if (ts7.isConstructorDeclaration(node)) {
|
1063 | kind = ClassMemberKind.Constructor;
|
1064 | } else {
|
1065 | return null;
|
1066 | }
|
1067 | if (ts7.isConstructorDeclaration(node)) {
|
1068 | name = "constructor";
|
1069 | } else if (ts7.isIdentifier(node.name)) {
|
1070 | name = node.name.text;
|
1071 | nameNode = node.name;
|
1072 | } else if (ts7.isStringLiteral(node.name)) {
|
1073 | name = node.name.text;
|
1074 | nameNode = node.name;
|
1075 | } else {
|
1076 | return null;
|
1077 | }
|
1078 | const decorators = this.getDecoratorsOfDeclaration(node);
|
1079 | const isStatic = node.modifiers !== void 0 && node.modifiers.some((mod) => mod.kind === ts7.SyntaxKind.StaticKeyword);
|
1080 | return {
|
1081 | node,
|
1082 | implementation: node,
|
1083 | kind,
|
1084 | type: node.type || null,
|
1085 | name,
|
1086 | nameNode,
|
1087 | decorators,
|
1088 | value,
|
1089 | isStatic
|
1090 | };
|
1091 | }
|
1092 | getLocalExportedDeclarationsOfSourceFile(file) {
|
1093 | const cacheSf = file;
|
1094 | if (cacheSf[LocalExportedDeclarations] !== void 0) {
|
1095 | return cacheSf[LocalExportedDeclarations];
|
1096 | }
|
1097 | const exportSet = new Set();
|
1098 | cacheSf[LocalExportedDeclarations] = exportSet;
|
1099 | const sfSymbol = this.checker.getSymbolAtLocation(cacheSf);
|
1100 | if (sfSymbol === void 0 || sfSymbol.exports === void 0) {
|
1101 | return exportSet;
|
1102 | }
|
1103 | const iter = sfSymbol.exports.values();
|
1104 | let item = iter.next();
|
1105 | while (item.done !== true) {
|
1106 | let exportedSymbol = item.value;
|
1107 | if (exportedSymbol.flags & ts7.SymbolFlags.Alias) {
|
1108 | exportedSymbol = this.checker.getAliasedSymbol(exportedSymbol);
|
1109 | }
|
1110 | if (exportedSymbol.valueDeclaration !== void 0 && exportedSymbol.valueDeclaration.getSourceFile() === file) {
|
1111 | exportSet.add(exportedSymbol.valueDeclaration);
|
1112 | }
|
1113 | item = iter.next();
|
1114 | }
|
1115 | return exportSet;
|
1116 | }
|
1117 | };
|
1118 | function reflectTypeEntityToDeclaration(type, checker) {
|
1119 | let realSymbol = checker.getSymbolAtLocation(type);
|
1120 | if (realSymbol === void 0) {
|
1121 | throw new Error(`Cannot resolve type entity ${type.getText()} to symbol`);
|
1122 | }
|
1123 | while (realSymbol.flags & ts7.SymbolFlags.Alias) {
|
1124 | realSymbol = checker.getAliasedSymbol(realSymbol);
|
1125 | }
|
1126 | let node = null;
|
1127 | if (realSymbol.valueDeclaration !== void 0) {
|
1128 | node = realSymbol.valueDeclaration;
|
1129 | } else if (realSymbol.declarations !== void 0 && realSymbol.declarations.length === 1) {
|
1130 | node = realSymbol.declarations[0];
|
1131 | } else {
|
1132 | throw new Error(`Cannot resolve type entity symbol to declaration`);
|
1133 | }
|
1134 | if (ts7.isQualifiedName(type)) {
|
1135 | if (!ts7.isIdentifier(type.left)) {
|
1136 | throw new Error(`Cannot handle qualified name with non-identifier lhs`);
|
1137 | }
|
1138 | const symbol = checker.getSymbolAtLocation(type.left);
|
1139 | if (symbol === void 0 || symbol.declarations === void 0 || symbol.declarations.length !== 1) {
|
1140 | throw new Error(`Cannot resolve qualified type entity lhs to symbol`);
|
1141 | }
|
1142 | const decl = symbol.declarations[0];
|
1143 | if (ts7.isNamespaceImport(decl)) {
|
1144 | const clause = decl.parent;
|
1145 | const importDecl = clause.parent;
|
1146 | if (!ts7.isStringLiteral(importDecl.moduleSpecifier)) {
|
1147 | throw new Error(`Module specifier is not a string`);
|
1148 | }
|
1149 | return { node, from: importDecl.moduleSpecifier.text };
|
1150 | } else if (ts7.isModuleDeclaration(decl)) {
|
1151 | return { node, from: null };
|
1152 | } else {
|
1153 | throw new Error(`Unknown import type?`);
|
1154 | }
|
1155 | } else {
|
1156 | return { node, from: null };
|
1157 | }
|
1158 | }
|
1159 | function filterToMembersWithDecorator(members, name, module7) {
|
1160 | return members.filter((member) => !member.isStatic).map((member) => {
|
1161 | if (member.decorators === null) {
|
1162 | return null;
|
1163 | }
|
1164 | const decorators = member.decorators.filter((dec) => {
|
1165 | if (dec.import !== null) {
|
1166 | return dec.import.name === name && (module7 === void 0 || dec.import.from === module7);
|
1167 | } else {
|
1168 | return dec.name === name && module7 === void 0;
|
1169 | }
|
1170 | });
|
1171 | if (decorators.length === 0) {
|
1172 | return null;
|
1173 | }
|
1174 | return { member, decorators };
|
1175 | }).filter((value) => value !== null);
|
1176 | }
|
1177 | function reflectObjectLiteral(node) {
|
1178 | const map = new Map();
|
1179 | node.properties.forEach((prop) => {
|
1180 | if (ts7.isPropertyAssignment(prop)) {
|
1181 | const name = propertyNameToString(prop.name);
|
1182 | if (name === null) {
|
1183 | return;
|
1184 | }
|
1185 | map.set(name, prop.initializer);
|
1186 | } else if (ts7.isShorthandPropertyAssignment(prop)) {
|
1187 | map.set(prop.name.text, prop.name);
|
1188 | } else {
|
1189 | return;
|
1190 | }
|
1191 | });
|
1192 | return map;
|
1193 | }
|
1194 | function castDeclarationToClassOrDie(declaration) {
|
1195 | if (!ts7.isClassDeclaration(declaration)) {
|
1196 | throw new Error(`Reflecting on a ${ts7.SyntaxKind[declaration.kind]} instead of a ClassDeclaration.`);
|
1197 | }
|
1198 | return declaration;
|
1199 | }
|
1200 | function parameterName(name) {
|
1201 | if (ts7.isIdentifier(name)) {
|
1202 | return name.text;
|
1203 | } else {
|
1204 | return null;
|
1205 | }
|
1206 | }
|
1207 | function propertyNameToString(node) {
|
1208 | if (ts7.isIdentifier(node) || ts7.isStringLiteral(node) || ts7.isNumericLiteral(node)) {
|
1209 | return node.text;
|
1210 | } else {
|
1211 | return null;
|
1212 | }
|
1213 | }
|
1214 | function getQualifiedNameRoot(qualifiedName) {
|
1215 | while (ts7.isQualifiedName(qualifiedName.left)) {
|
1216 | qualifiedName = qualifiedName.left;
|
1217 | }
|
1218 | return ts7.isIdentifier(qualifiedName.left) ? qualifiedName.left : null;
|
1219 | }
|
1220 | function getFarLeftIdentifier(propertyAccess) {
|
1221 | while (ts7.isPropertyAccessExpression(propertyAccess.expression)) {
|
1222 | propertyAccess = propertyAccess.expression;
|
1223 | }
|
1224 | return ts7.isIdentifier(propertyAccess.expression) ? propertyAccess.expression : null;
|
1225 | }
|
1226 | function getContainingImportDeclaration(node) {
|
1227 | return ts7.isImportSpecifier(node) ? node.parent.parent.parent : ts7.isNamespaceImport(node) ? node.parent.parent : null;
|
1228 | }
|
1229 | function getExportedName(decl, originalId) {
|
1230 | return ts7.isImportSpecifier(decl) ? (decl.propertyName !== void 0 ? decl.propertyName : decl.name).text : originalId.text;
|
1231 | }
|
1232 | var LocalExportedDeclarations = Symbol("LocalExportedDeclarations");
|
1233 |
|
1234 |
|
1235 | function isDefined(value) {
|
1236 | return value !== void 0 && value !== null;
|
1237 | }
|
1238 | function getNameText(name) {
|
1239 | return ts8.isIdentifier(name) || ts8.isLiteralExpression(name) ? name.text : name.getText();
|
1240 | }
|
1241 | function hasNameIdentifier(declaration) {
|
1242 | const namedDeclaration = declaration;
|
1243 | return namedDeclaration.name !== void 0 && ts8.isIdentifier(namedDeclaration.name);
|
1244 | }
|
1245 | function isRelativePath(path7) {
|
1246 | return isRooted(path7) || /^\.\.?(\/|\\|$)/.test(path7);
|
1247 | }
|
1248 | var FactoryMap = class {
|
1249 | constructor(factory, entries) {
|
1250 | this.factory = factory;
|
1251 | this.internalMap = new Map(entries);
|
1252 | }
|
1253 | get(key) {
|
1254 | if (!this.internalMap.has(key)) {
|
1255 | this.internalMap.set(key, this.factory(key));
|
1256 | }
|
1257 | return this.internalMap.get(key);
|
1258 | }
|
1259 | set(key, value) {
|
1260 | this.internalMap.set(key, value);
|
1261 | }
|
1262 | };
|
1263 | function resolveFileWithPostfixes(fs5, path7, postFixes) {
|
1264 | for (const postFix of postFixes) {
|
1265 | const testPath = absoluteFrom(path7 + postFix);
|
1266 | if (fs5.exists(testPath) && fs5.stat(testPath).isFile()) {
|
1267 | return testPath;
|
1268 | }
|
1269 | }
|
1270 | return null;
|
1271 | }
|
1272 | function getTsHelperFnFromDeclaration(decl) {
|
1273 | if (!ts8.isFunctionDeclaration(decl) && !ts8.isVariableDeclaration(decl)) {
|
1274 | return null;
|
1275 | }
|
1276 | if (decl.name === void 0 || !ts8.isIdentifier(decl.name)) {
|
1277 | return null;
|
1278 | }
|
1279 | return getTsHelperFnFromIdentifier(decl.name);
|
1280 | }
|
1281 | function getTsHelperFnFromIdentifier(id) {
|
1282 | switch (stripDollarSuffix(id.text)) {
|
1283 | case "__assign":
|
1284 | return KnownDeclaration.TsHelperAssign;
|
1285 | case "__spread":
|
1286 | return KnownDeclaration.TsHelperSpread;
|
1287 | case "__spreadArrays":
|
1288 | return KnownDeclaration.TsHelperSpreadArrays;
|
1289 | case "__spreadArray":
|
1290 | return KnownDeclaration.TsHelperSpreadArray;
|
1291 | case "__read":
|
1292 | return KnownDeclaration.TsHelperRead;
|
1293 | default:
|
1294 | return null;
|
1295 | }
|
1296 | }
|
1297 | function stripDollarSuffix(value) {
|
1298 | return value.replace(/\$\d+$/, "");
|
1299 | }
|
1300 | function stripExtension2(fileName) {
|
1301 | return fileName.replace(/\..+$/, "");
|
1302 | }
|
1303 |
|
1304 |
|
1305 | var ModuleResolver = class {
|
1306 | constructor(fs5, pathMappings, relativeExtensions = ["", ".js", "/index.js"]) {
|
1307 | this.fs = fs5;
|
1308 | this.relativeExtensions = relativeExtensions;
|
1309 | this.pathMappings = pathMappings ? this.processPathMappings(pathMappings) : [];
|
1310 | }
|
1311 | resolveModuleImport(moduleName, fromPath) {
|
1312 | if (isRelativePath(moduleName)) {
|
1313 | return this.resolveAsRelativePath(moduleName, fromPath);
|
1314 | } else {
|
1315 | return this.pathMappings.length && this.resolveByPathMappings(moduleName, fromPath) || this.resolveAsEntryPoint(moduleName, fromPath);
|
1316 | }
|
1317 | }
|
1318 | processPathMappings(pathMappings) {
|
1319 | const baseUrl = this.fs.resolve(pathMappings.baseUrl);
|
1320 | return Object.keys(pathMappings.paths).map((pathPattern) => {
|
1321 | const matcher = splitOnStar(pathPattern);
|
1322 | const templates = pathMappings.paths[pathPattern].map(splitOnStar);
|
1323 | return { matcher, templates, baseUrl };
|
1324 | });
|
1325 | }
|
1326 | resolveAsRelativePath(moduleName, fromPath) {
|
1327 | const resolvedPath = resolveFileWithPostfixes(this.fs, this.fs.resolve(this.fs.dirname(fromPath), moduleName), this.relativeExtensions);
|
1328 | return resolvedPath && new ResolvedRelativeModule(resolvedPath);
|
1329 | }
|
1330 | resolveByPathMappings(moduleName, fromPath) {
|
1331 | const mappedPaths = this.findMappedPaths(moduleName);
|
1332 | if (mappedPaths.length > 0) {
|
1333 | const packagePath = this.findPackagePath(fromPath);
|
1334 | if (packagePath !== null) {
|
1335 | for (const mappedPath of mappedPaths) {
|
1336 | if (this.isEntryPoint(mappedPath)) {
|
1337 | return new ResolvedExternalModule(mappedPath);
|
1338 | }
|
1339 | const nonEntryPointImport = this.resolveAsRelativePath(mappedPath, fromPath);
|
1340 | if (nonEntryPointImport !== null) {
|
1341 | return isRelativeImport(packagePath, mappedPath) ? nonEntryPointImport : new ResolvedDeepImport(mappedPath);
|
1342 | }
|
1343 | }
|
1344 | }
|
1345 | }
|
1346 | return null;
|
1347 | }
|
1348 | resolveAsEntryPoint(moduleName, fromPath) {
|
1349 | let folder = fromPath;
|
1350 | while (!this.fs.isRoot(folder)) {
|
1351 | folder = this.fs.dirname(folder);
|
1352 | if (folder.endsWith("node_modules")) {
|
1353 | folder = this.fs.dirname(folder);
|
1354 | }
|
1355 | const modulePath = this.fs.resolve(folder, "node_modules", moduleName);
|
1356 | if (this.isEntryPoint(modulePath)) {
|
1357 | return new ResolvedExternalModule(modulePath);
|
1358 | } else if (this.resolveAsRelativePath(modulePath, fromPath)) {
|
1359 | return new ResolvedDeepImport(modulePath);
|
1360 | }
|
1361 | }
|
1362 | return null;
|
1363 | }
|
1364 | isEntryPoint(modulePath) {
|
1365 | return this.fs.exists(this.fs.join(modulePath, "package.json"));
|
1366 | }
|
1367 | findMappedPaths(moduleName) {
|
1368 | const matches = this.pathMappings.map((mapping) => this.matchMapping(moduleName, mapping));
|
1369 | let bestMapping;
|
1370 | let bestMatch;
|
1371 | for (let index = 0; index < this.pathMappings.length; index++) {
|
1372 | const mapping = this.pathMappings[index];
|
1373 | const match = matches[index];
|
1374 | if (match !== null) {
|
1375 | if (!mapping.matcher.hasWildcard) {
|
1376 | bestMatch = match;
|
1377 | bestMapping = mapping;
|
1378 | break;
|
1379 | }
|
1380 | if (!bestMapping || mapping.matcher.prefix > bestMapping.matcher.prefix) {
|
1381 | bestMatch = match;
|
1382 | bestMapping = mapping;
|
1383 | }
|
1384 | }
|
1385 | }
|
1386 | return bestMapping !== void 0 && bestMatch !== void 0 ? this.computeMappedTemplates(bestMapping, bestMatch) : [];
|
1387 | }
|
1388 | matchMapping(path7, mapping) {
|
1389 | const { prefix, postfix, hasWildcard } = mapping.matcher;
|
1390 | if (hasWildcard) {
|
1391 | return path7.startsWith(prefix) && path7.endsWith(postfix) ? path7.substring(prefix.length, path7.length - postfix.length) : null;
|
1392 | } else {
|
1393 | return path7 === prefix ? "" : null;
|
1394 | }
|
1395 | }
|
1396 | computeMappedTemplates(mapping, match) {
|
1397 | return mapping.templates.map((template) => this.fs.resolve(mapping.baseUrl, template.prefix + match + template.postfix));
|
1398 | }
|
1399 | findPackagePath(path7) {
|
1400 | let folder = path7;
|
1401 | while (!this.fs.isRoot(folder)) {
|
1402 | folder = this.fs.dirname(folder);
|
1403 | if (this.fs.exists(this.fs.join(folder, "package.json"))) {
|
1404 | return folder;
|
1405 | }
|
1406 | }
|
1407 | return null;
|
1408 | }
|
1409 | };
|
1410 | var ResolvedExternalModule = class {
|
1411 | constructor(entryPointPath) {
|
1412 | this.entryPointPath = entryPointPath;
|
1413 | }
|
1414 | };
|
1415 | var ResolvedRelativeModule = class {
|
1416 | constructor(modulePath) {
|
1417 | this.modulePath = modulePath;
|
1418 | }
|
1419 | };
|
1420 | var ResolvedDeepImport = class {
|
1421 | constructor(importPath) {
|
1422 | this.importPath = importPath;
|
1423 | }
|
1424 | };
|
1425 | function splitOnStar(str) {
|
1426 | const [prefix, postfix] = str.split("*", 2);
|
1427 | return { prefix, postfix: postfix || "", hasWildcard: postfix !== void 0 };
|
1428 | }
|
1429 | function isRelativeImport(from, to) {
|
1430 | return to.startsWith(from) && !to.includes("node_modules");
|
1431 | }
|
1432 |
|
1433 |
|
1434 | function createDependencyInfo() {
|
1435 | return { dependencies: new Set(), missing: new Set(), deepImports: new Set() };
|
1436 | }
|
1437 | var DependencyHostBase = class {
|
1438 | constructor(fs5, moduleResolver) {
|
1439 | this.fs = fs5;
|
1440 | this.moduleResolver = moduleResolver;
|
1441 | }
|
1442 | collectDependencies(entryPointPath, { dependencies, missing, deepImports }) {
|
1443 | const resolvedFile = resolveFileWithPostfixes(this.fs, entryPointPath, this.moduleResolver.relativeExtensions);
|
1444 | if (resolvedFile !== null) {
|
1445 | const alreadySeen = new Set();
|
1446 | this.recursivelyCollectDependencies(resolvedFile, dependencies, missing, deepImports, alreadySeen);
|
1447 | }
|
1448 | }
|
1449 | collectDependenciesInFiles(files, { dependencies, missing, deepImports }) {
|
1450 | const alreadySeen = new Set();
|
1451 | for (const file of files) {
|
1452 | this.processFile(file, dependencies, missing, deepImports, alreadySeen);
|
1453 | }
|
1454 | }
|
1455 | recursivelyCollectDependencies(file, dependencies, missing, deepImports, alreadySeen) {
|
1456 | const fromContents = this.fs.readFile(file);
|
1457 | if (this.canSkipFile(fromContents)) {
|
1458 | return;
|
1459 | }
|
1460 | const imports = this.extractImports(file, fromContents);
|
1461 | for (const importPath of imports) {
|
1462 | const resolved = this.processImport(importPath, file, dependencies, missing, deepImports, alreadySeen);
|
1463 | if (!resolved) {
|
1464 | missing.add(importPath);
|
1465 | }
|
1466 | }
|
1467 | }
|
1468 | processImport(importPath, file, dependencies, missing, deepImports, alreadySeen) {
|
1469 | const resolvedModule = this.moduleResolver.resolveModuleImport(importPath, file);
|
1470 | if (resolvedModule === null) {
|
1471 | return false;
|
1472 | }
|
1473 | if (resolvedModule instanceof ResolvedRelativeModule) {
|
1474 | this.processFile(resolvedModule.modulePath, dependencies, missing, deepImports, alreadySeen);
|
1475 | } else if (resolvedModule instanceof ResolvedDeepImport) {
|
1476 | deepImports.add(resolvedModule.importPath);
|
1477 | } else {
|
1478 | dependencies.add(resolvedModule.entryPointPath);
|
1479 | }
|
1480 | return true;
|
1481 | }
|
1482 | processFile(file, dependencies, missing, deepImports, alreadySeen) {
|
1483 | if (!alreadySeen.has(file)) {
|
1484 | alreadySeen.add(file);
|
1485 | this.recursivelyCollectDependencies(file, dependencies, missing, deepImports, alreadySeen);
|
1486 | }
|
1487 | }
|
1488 | };
|
1489 |
|
1490 |
|
1491 | var CommonJsDependencyHost = class extends DependencyHostBase {
|
1492 | canSkipFile(fileContents) {
|
1493 | return !hasRequireCalls(fileContents);
|
1494 | }
|
1495 | extractImports(file, fileContents) {
|
1496 | const sf = ts9.createSourceFile(file, fileContents, ts9.ScriptTarget.ES2015, false, ts9.ScriptKind.JS);
|
1497 | const requireCalls = [];
|
1498 | for (const stmt of sf.statements) {
|
1499 | if (ts9.isVariableStatement(stmt)) {
|
1500 | const declarations = stmt.declarationList.declarations;
|
1501 | for (const declaration of declarations) {
|
1502 | if (declaration.initializer !== void 0 && isRequireCall(declaration.initializer)) {
|
1503 | requireCalls.push(declaration.initializer);
|
1504 | }
|
1505 | }
|
1506 | } else if (ts9.isExpressionStatement(stmt)) {
|
1507 | if (isRequireCall(stmt.expression)) {
|
1508 | requireCalls.push(stmt.expression);
|
1509 | } else if (isWildcardReexportStatement(stmt)) {
|
1510 | const firstExportArg = stmt.expression.arguments[0];
|
1511 | if (isRequireCall(firstExportArg)) {
|
1512 | requireCalls.push(firstExportArg);
|
1513 | }
|
1514 | } else if (ts9.isBinaryExpression(stmt.expression) && stmt.expression.operatorToken.kind === ts9.SyntaxKind.EqualsToken) {
|
1515 | if (isRequireCall(stmt.expression.right)) {
|
1516 | requireCalls.push(stmt.expression.right);
|
1517 | } else if (ts9.isObjectLiteralExpression(stmt.expression.right)) {
|
1518 | stmt.expression.right.properties.forEach((prop) => {
|
1519 | if (ts9.isPropertyAssignment(prop) && isRequireCall(prop.initializer)) {
|
1520 | requireCalls.push(prop.initializer);
|
1521 | }
|
1522 | });
|
1523 | }
|
1524 | }
|
1525 | }
|
1526 | }
|
1527 | return new Set(requireCalls.map((call) => call.arguments[0].text));
|
1528 | }
|
1529 | };
|
1530 | function hasRequireCalls(source) {
|
1531 | return /require\(['"]/.test(source);
|
1532 | }
|
1533 |
|
1534 |
|
1535 | import { DepGraph } from "dependency-graph";
|
1536 | import module2 from "module";
|
1537 |
|
1538 |
|
1539 | import ts14 from "typescript";
|
1540 |
|
1541 |
|
1542 | import ts13 from "typescript";
|
1543 |
|
1544 |
|
1545 | import ts11 from "typescript";
|
1546 |
|
1547 |
|
1548 | function isWithinPackage(packagePath, filePath) {
|
1549 | const relativePath = relative(packagePath, filePath);
|
1550 | return isLocalRelativePath(relativePath) && !relativePath.startsWith("node_modules/");
|
1551 | }
|
1552 | var NoopDependencyTracker = class {
|
1553 | addDependency() {
|
1554 | }
|
1555 | addResourceDependency() {
|
1556 | }
|
1557 | recordDependencyAnalysisFailure() {
|
1558 | }
|
1559 | };
|
1560 | var NOOP_DEPENDENCY_TRACKER = new NoopDependencyTracker();
|
1561 |
|
1562 |
|
1563 | import ts10 from "typescript";
|
1564 | function stripParentheses(node) {
|
1565 | return ts10.isParenthesizedExpression(node) ? node.expression : node;
|
1566 | }
|
1567 |
|
1568 |
|
1569 | var DECORATORS = "decorators";
|
1570 | var PROP_DECORATORS = "propDecorators";
|
1571 | var CONSTRUCTOR = "__constructor";
|
1572 | var CONSTRUCTOR_PARAMS = "ctorParameters";
|
1573 | var Esm2015ReflectionHost = class extends TypeScriptReflectionHost {
|
1574 | constructor(logger, isCore, src, dts = null) {
|
1575 | super(src.program.getTypeChecker());
|
1576 | this.logger = logger;
|
1577 | this.isCore = isCore;
|
1578 | this.src = src;
|
1579 | this.dts = dts;
|
1580 | this.publicDtsDeclarationMap = null;
|
1581 | this.privateDtsDeclarationMap = null;
|
1582 | this.preprocessedSourceFiles = new Set();
|
1583 | this.aliasedClassDeclarations = new Map();
|
1584 | this.decoratorCache = new Map();
|
1585 | }
|
1586 | getClassSymbol(declaration) {
|
1587 | const symbol = this.getClassSymbolFromOuterDeclaration(declaration);
|
1588 | if (symbol !== void 0) {
|
1589 | return symbol;
|
1590 | }
|
1591 | const innerDeclaration = this.getInnerDeclarationFromAliasOrInner(declaration);
|
1592 | return this.getClassSymbolFromInnerDeclaration(innerDeclaration);
|
1593 | }
|
1594 | getDecoratorsOfDeclaration(declaration) {
|
1595 | const symbol = this.getClassSymbol(declaration);
|
1596 | if (!symbol) {
|
1597 | return null;
|
1598 | }
|
1599 | return this.getDecoratorsOfSymbol(symbol);
|
1600 | }
|
1601 | getMembersOfClass(clazz) {
|
1602 | const classSymbol = this.getClassSymbol(clazz);
|
1603 | if (!classSymbol) {
|
1604 | throw new Error(`Attempted to get members of a non-class: "${clazz.getText()}"`);
|
1605 | }
|
1606 | return this.getMembersOfSymbol(classSymbol);
|
1607 | }
|
1608 | getConstructorParameters(clazz) {
|
1609 | const classSymbol = this.getClassSymbol(clazz);
|
1610 | if (!classSymbol) {
|
1611 | throw new Error(`Attempted to get constructor parameters of a non-class: "${clazz.getText()}"`);
|
1612 | }
|
1613 | const parameterNodes = this.getConstructorParameterDeclarations(classSymbol);
|
1614 | if (parameterNodes) {
|
1615 | return this.getConstructorParamInfo(classSymbol, parameterNodes);
|
1616 | }
|
1617 | return null;
|
1618 | }
|
1619 | getBaseClassExpression(clazz) {
|
1620 | const superBaseClassIdentifier = super.getBaseClassExpression(clazz);
|
1621 | if (superBaseClassIdentifier) {
|
1622 | return superBaseClassIdentifier;
|
1623 | }
|
1624 | const classSymbol = this.getClassSymbol(clazz);
|
1625 | if ((classSymbol == null ? void 0 : classSymbol.implementation.valueDeclaration) === void 0 || !isNamedDeclaration2(classSymbol.implementation.valueDeclaration)) {
|
1626 | return null;
|
1627 | }
|
1628 | return super.getBaseClassExpression(classSymbol.implementation.valueDeclaration);
|
1629 | }
|
1630 | getInternalNameOfClass(clazz) {
|
1631 | const classSymbol = this.getClassSymbol(clazz);
|
1632 | if (classSymbol === void 0) {
|
1633 | throw new Error(`getInternalNameOfClass() called on a non-class: expected ${clazz.name.text} to be a class declaration.`);
|
1634 | }
|
1635 | return this.getNameFromClassSymbolDeclaration(classSymbol, classSymbol.implementation.valueDeclaration);
|
1636 | }
|
1637 | getAdjacentNameOfClass(clazz) {
|
1638 | const classSymbol = this.getClassSymbol(clazz);
|
1639 | if (classSymbol === void 0) {
|
1640 | throw new Error(`getAdjacentNameOfClass() called on a non-class: expected ${clazz.name.text} to be a class declaration.`);
|
1641 | }
|
1642 | return this.getAdjacentNameOfClassSymbol(classSymbol);
|
1643 | }
|
1644 | getNameFromClassSymbolDeclaration(classSymbol, declaration) {
|
1645 | if (declaration === void 0) {
|
1646 | throw new Error(`getInternalNameOfClass() called on a class with an undefined internal declaration. External class name: ${classSymbol.name}; internal class name: ${classSymbol.implementation.name}.`);
|
1647 | }
|
1648 | if (!isNamedDeclaration2(declaration)) {
|
1649 | throw new Error(`getInternalNameOfClass() called on a class with an anonymous inner declaration: expected a name on:
|
1650 | ${declaration.getText()}`);
|
1651 | }
|
1652 | return declaration.name;
|
1653 | }
|
1654 | isClass(node) {
|
1655 | return super.isClass(node) || this.getClassSymbol(node) !== void 0;
|
1656 | }
|
1657 | getDeclarationOfIdentifier(id) {
|
1658 | const superDeclaration = super.getDeclarationOfIdentifier(id);
|
1659 | if (superDeclaration === null) {
|
1660 | return superDeclaration;
|
1661 | }
|
1662 | if (superDeclaration.known !== null || isConcreteDeclaration(superDeclaration) && superDeclaration.identity !== null) {
|
1663 | return superDeclaration;
|
1664 | }
|
1665 | let declarationNode = superDeclaration.node;
|
1666 | if (isNamedVariableDeclaration(superDeclaration.node) && !isTopLevel(superDeclaration.node)) {
|
1667 | const variableValue = this.getVariableValue(superDeclaration.node);
|
1668 | if (variableValue !== null && ts11.isClassExpression(variableValue)) {
|
1669 | declarationNode = getContainingStatement(variableValue);
|
1670 | }
|
1671 | }
|
1672 | const outerNode = getOuterNodeFromInnerDeclaration(declarationNode);
|
1673 | const declaration = outerNode !== null && isNamedVariableDeclaration(outerNode) ? this.getDeclarationOfIdentifier(outerNode.name) : superDeclaration;
|
1674 | if (declaration === null || declaration.known !== null || isConcreteDeclaration(declaration) && declaration.identity !== null) {
|
1675 | return declaration;
|
1676 | }
|
1677 | const aliasedIdentifier = this.resolveAliasedClassIdentifier(declaration.node);
|
1678 | if (aliasedIdentifier !== null) {
|
1679 | return this.getDeclarationOfIdentifier(aliasedIdentifier);
|
1680 | }
|
1681 | if (isConcreteDeclaration(declaration) && ts11.isVariableDeclaration(declaration.node)) {
|
1682 | const enumMembers = this.resolveEnumMembers(declaration.node);
|
1683 | if (enumMembers !== null) {
|
1684 | declaration.identity = { kind: 0, enumMembers };
|
1685 | }
|
1686 | }
|
1687 | return declaration;
|
1688 | }
|
1689 | getDecoratorsOfSymbol(symbol) {
|
1690 | const { classDecorators } = this.acquireDecoratorInfo(symbol);
|
1691 | if (classDecorators === null) {
|
1692 | return null;
|
1693 | }
|
1694 | return Array.from(classDecorators);
|
1695 | }
|
1696 | getVariableValue(declaration) {
|
1697 | const value = super.getVariableValue(declaration);
|
1698 | if (value) {
|
1699 | return value;
|
1700 | }
|
1701 | const block = declaration.parent.parent.parent;
|
1702 | const symbol = this.checker.getSymbolAtLocation(declaration.name);
|
1703 | if (symbol && (ts11.isBlock(block) || ts11.isSourceFile(block))) {
|
1704 | const decorateCall = this.findDecoratedVariableValue(block, symbol);
|
1705 | const target = decorateCall && decorateCall.arguments[1];
|
1706 | if (target && ts11.isIdentifier(target)) {
|
1707 | const targetSymbol = this.checker.getSymbolAtLocation(target);
|
1708 | const targetDeclaration = targetSymbol && targetSymbol.valueDeclaration;
|
1709 | if (targetDeclaration) {
|
1710 | if (ts11.isClassDeclaration(targetDeclaration) || ts11.isFunctionDeclaration(targetDeclaration)) {
|
1711 | return targetDeclaration.name || null;
|
1712 | } else if (ts11.isVariableDeclaration(targetDeclaration)) {
|
1713 | let targetValue = targetDeclaration.initializer;
|
1714 | while (targetValue && isAssignment2(targetValue)) {
|
1715 | targetValue = targetValue.right;
|
1716 | }
|
1717 | if (targetValue) {
|
1718 | return targetValue;
|
1719 | }
|
1720 | }
|
1721 | }
|
1722 | }
|
1723 | }
|
1724 | return null;
|
1725 | }
|
1726 | findClassSymbols(sourceFile) {
|
1727 | const classes = new Map();
|
1728 | this.getModuleStatements(sourceFile).forEach((statement) => this.addClassSymbolsFromStatement(classes, statement));
|
1729 | return Array.from(classes.values());
|
1730 | }
|
1731 | getGenericArityOfClass(clazz) {
|
1732 | const dtsDeclaration = this.getDtsDeclaration(clazz);
|
1733 | if (dtsDeclaration && ts11.isClassDeclaration(dtsDeclaration)) {
|
1734 | return dtsDeclaration.typeParameters ? dtsDeclaration.typeParameters.length : 0;
|
1735 | }
|
1736 | return null;
|
1737 | }
|
1738 | getDtsDeclaration(declaration) {
|
1739 | if (this.dts === null) {
|
1740 | return null;
|
1741 | }
|
1742 | if (!isNamedDeclaration2(declaration)) {
|
1743 | throw new Error(`Cannot get the dts file for a declaration that has no name: ${declaration.getText()} in ${declaration.getSourceFile().fileName}`);
|
1744 | }
|
1745 | const decl = this.getDeclarationOfIdentifier(declaration.name);
|
1746 | if (decl === null) {
|
1747 | throw new Error(`Cannot get the dts file for a node that cannot be associated with a declaration ${declaration.getText()} in ${declaration.getSourceFile().fileName}`);
|
1748 | }
|
1749 | if (this.publicDtsDeclarationMap === null) {
|
1750 | this.publicDtsDeclarationMap = this.computePublicDtsDeclarationMap(this.src, this.dts);
|
1751 | }
|
1752 | if (this.publicDtsDeclarationMap.has(decl.node)) {
|
1753 | return this.publicDtsDeclarationMap.get(decl.node);
|
1754 | }
|
1755 | if (this.privateDtsDeclarationMap === null) {
|
1756 | this.privateDtsDeclarationMap = this.computePrivateDtsDeclarationMap(this.src, this.dts);
|
1757 | }
|
1758 | if (this.privateDtsDeclarationMap.has(decl.node)) {
|
1759 | return this.privateDtsDeclarationMap.get(decl.node);
|
1760 | }
|
1761 | return null;
|
1762 | }
|
1763 | getEndOfClass(classSymbol) {
|
1764 | const implementation = classSymbol.implementation;
|
1765 | let last = implementation.valueDeclaration;
|
1766 | const implementationStatement = getContainingStatement(last);
|
1767 | if (implementationStatement === null)
|
1768 | return last;
|
1769 | const container = implementationStatement.parent;
|
1770 | if (ts11.isBlock(container)) {
|
1771 | const returnStatementIndex = container.statements.findIndex(ts11.isReturnStatement);
|
1772 | if (returnStatementIndex === -1) {
|
1773 | throw new Error(`Compiled class wrapper IIFE does not have a return statement: ${classSymbol.name} in ${classSymbol.declaration.valueDeclaration.getSourceFile().fileName}`);
|
1774 | }
|
1775 | last = container.statements[returnStatementIndex - 1];
|
1776 | } else if (ts11.isSourceFile(container)) {
|
1777 | if (implementation.exports !== void 0) {
|
1778 | implementation.exports.forEach((exportSymbol) => {
|
1779 | if (exportSymbol.valueDeclaration === void 0) {
|
1780 | return;
|
1781 | }
|
1782 | const exportStatement = getContainingStatement(exportSymbol.valueDeclaration);
|
1783 | if (exportStatement !== null && last.getEnd() < exportStatement.getEnd()) {
|
1784 | last = exportStatement;
|
1785 | }
|
1786 | });
|
1787 | }
|
1788 | const helpers = this.getHelperCallsForClass(classSymbol, ["__decorate", "__extends", "__param", "__metadata"]);
|
1789 | helpers.forEach((helper) => {
|
1790 | const helperStatement = getContainingStatement(helper);
|
1791 | if (helperStatement !== null && last.getEnd() < helperStatement.getEnd()) {
|
1792 | last = helperStatement;
|
1793 | }
|
1794 | });
|
1795 | }
|
1796 | return last;
|
1797 | }
|
1798 | detectKnownDeclaration(decl) {
|
1799 | if (decl.known === null && this.isJavaScriptObjectDeclaration(decl)) {
|
1800 | decl.known = KnownDeclaration.JsGlobalObject;
|
1801 | }
|
1802 | return decl;
|
1803 | }
|
1804 | addClassSymbolsFromStatement(classes, statement) {
|
1805 | if (ts11.isVariableStatement(statement)) {
|
1806 | statement.declarationList.declarations.forEach((declaration) => {
|
1807 | const classSymbol = this.getClassSymbol(declaration);
|
1808 | if (classSymbol) {
|
1809 | classes.set(classSymbol.implementation, classSymbol);
|
1810 | }
|
1811 | });
|
1812 | } else if (ts11.isClassDeclaration(statement)) {
|
1813 | const classSymbol = this.getClassSymbol(statement);
|
1814 | if (classSymbol) {
|
1815 | classes.set(classSymbol.implementation, classSymbol);
|
1816 | }
|
1817 | }
|
1818 | }
|
1819 | getInnerDeclarationFromAliasOrInner(declaration) {
|
1820 | if (declaration.parent !== void 0 && isNamedVariableDeclaration(declaration.parent)) {
|
1821 | const variableValue = this.getVariableValue(declaration.parent);
|
1822 | if (variableValue !== null) {
|
1823 | declaration = variableValue;
|
1824 | }
|
1825 | }
|
1826 | return declaration;
|
1827 | }
|
1828 | getClassSymbolFromOuterDeclaration(declaration) {
|
1829 | if (isNamedClassDeclaration(declaration) && isTopLevel(declaration)) {
|
1830 | return this.createClassSymbol(declaration.name, null);
|
1831 | }
|
1832 | if (!isInitializedVariableClassDeclaration(declaration)) {
|
1833 | return void 0;
|
1834 | }
|
1835 | const innerDeclaration = getInnerClassDeclaration(skipClassAliases(declaration));
|
1836 | if (innerDeclaration === null) {
|
1837 | return void 0;
|
1838 | }
|
1839 | return this.createClassSymbol(declaration.name, innerDeclaration);
|
1840 | }
|
1841 | getClassSymbolFromInnerDeclaration(declaration) {
|
1842 | let outerDeclaration = void 0;
|
1843 | if (ts11.isClassExpression(declaration) && hasNameIdentifier(declaration)) {
|
1844 | outerDeclaration = getFarLeftHandSideOfAssignment(declaration);
|
1845 | if (outerDeclaration !== void 0 && !isTopLevel(outerDeclaration)) {
|
1846 | outerDeclaration = getContainingVariableDeclaration(outerDeclaration);
|
1847 | }
|
1848 | } else if (isNamedClassDeclaration(declaration)) {
|
1849 | if (isTopLevel(declaration)) {
|
1850 | outerDeclaration = declaration;
|
1851 | } else {
|
1852 | outerDeclaration = getContainingVariableDeclaration(declaration);
|
1853 | }
|
1854 | }
|
1855 | if (outerDeclaration === void 0 || !hasNameIdentifier(outerDeclaration)) {
|
1856 | return void 0;
|
1857 | }
|
1858 | return this.createClassSymbol(outerDeclaration.name, declaration);
|
1859 | }
|
1860 | createClassSymbol(outerDeclaration, innerDeclaration) {
|
1861 | const declarationSymbol = this.checker.getSymbolAtLocation(outerDeclaration);
|
1862 | if (declarationSymbol === void 0) {
|
1863 | return void 0;
|
1864 | }
|
1865 | let implementationSymbol = declarationSymbol;
|
1866 | if (innerDeclaration !== null && isNamedDeclaration2(innerDeclaration)) {
|
1867 | implementationSymbol = this.checker.getSymbolAtLocation(innerDeclaration.name);
|
1868 | }
|
1869 | if (!isSymbolWithValueDeclaration(implementationSymbol)) {
|
1870 | return void 0;
|
1871 | }
|
1872 | const classSymbol = {
|
1873 | name: declarationSymbol.name,
|
1874 | declaration: declarationSymbol,
|
1875 | implementation: implementationSymbol,
|
1876 | adjacent: this.getAdjacentSymbol(declarationSymbol, implementationSymbol)
|
1877 | };
|
1878 | return classSymbol;
|
1879 | }
|
1880 | getAdjacentSymbol(declarationSymbol, implementationSymbol) {
|
1881 | if (declarationSymbol === implementationSymbol) {
|
1882 | return void 0;
|
1883 | }
|
1884 | const innerDeclaration = implementationSymbol.valueDeclaration;
|
1885 | if (!ts11.isClassExpression(innerDeclaration) && !ts11.isFunctionExpression(innerDeclaration)) {
|
1886 | return void 0;
|
1887 | }
|
1888 | const adjacentDeclaration = getFarLeftHandSideOfAssignment(innerDeclaration);
|
1889 | if (adjacentDeclaration === void 0 || !isNamedVariableDeclaration(adjacentDeclaration)) {
|
1890 | return void 0;
|
1891 | }
|
1892 | const adjacentSymbol = this.checker.getSymbolAtLocation(adjacentDeclaration.name);
|
1893 | if (adjacentSymbol === declarationSymbol || adjacentSymbol === implementationSymbol || !isSymbolWithValueDeclaration(adjacentSymbol)) {
|
1894 | return void 0;
|
1895 | }
|
1896 | return adjacentSymbol;
|
1897 | }
|
1898 | getDeclarationOfSymbol(symbol, originalId) {
|
1899 | const declaration = super.getDeclarationOfSymbol(symbol, originalId);
|
1900 | if (declaration === null) {
|
1901 | return null;
|
1902 | }
|
1903 | return this.detectKnownDeclaration(declaration);
|
1904 | }
|
1905 | resolveAliasedClassIdentifier(declaration) {
|
1906 | this.ensurePreprocessed(declaration.getSourceFile());
|
1907 | return this.aliasedClassDeclarations.has(declaration) ? this.aliasedClassDeclarations.get(declaration) : null;
|
1908 | }
|
1909 | ensurePreprocessed(sourceFile) {
|
1910 | if (!this.preprocessedSourceFiles.has(sourceFile)) {
|
1911 | this.preprocessedSourceFiles.add(sourceFile);
|
1912 | for (const statement of this.getModuleStatements(sourceFile)) {
|
1913 | this.preprocessStatement(statement);
|
1914 | }
|
1915 | }
|
1916 | }
|
1917 | preprocessStatement(statement) {
|
1918 | if (!ts11.isVariableStatement(statement)) {
|
1919 | return;
|
1920 | }
|
1921 | const declarations = statement.declarationList.declarations;
|
1922 | if (declarations.length !== 1) {
|
1923 | return;
|
1924 | }
|
1925 | const declaration = declarations[0];
|
1926 | const initializer = declaration.initializer;
|
1927 | if (!ts11.isIdentifier(declaration.name) || !initializer || !isAssignment2(initializer) || !ts11.isIdentifier(initializer.left) || !this.isClass(declaration)) {
|
1928 | return;
|
1929 | }
|
1930 | const aliasedIdentifier = initializer.left;
|
1931 | const aliasedDeclaration = this.getDeclarationOfIdentifier(aliasedIdentifier);
|
1932 | if (aliasedDeclaration === null) {
|
1933 | throw new Error(`Unable to locate declaration of ${aliasedIdentifier.text} in "${statement.getText()}"`);
|
1934 | }
|
1935 | this.aliasedClassDeclarations.set(aliasedDeclaration.node, declaration.name);
|
1936 | }
|
1937 | getModuleStatements(sourceFile) {
|
1938 | return Array.from(sourceFile.statements);
|
1939 | }
|
1940 | findDecoratedVariableValue(node, symbol) {
|
1941 | if (!node) {
|
1942 | return null;
|
1943 | }
|
1944 | if (ts11.isBinaryExpression(node) && node.operatorToken.kind === ts11.SyntaxKind.EqualsToken) {
|
1945 | const left = node.left;
|
1946 | const right = node.right;
|
1947 | if (ts11.isIdentifier(left) && this.checker.getSymbolAtLocation(left) === symbol) {
|
1948 | return ts11.isCallExpression(right) && getCalleeName(right) === "__decorate" ? right : null;
|
1949 | }
|
1950 | return this.findDecoratedVariableValue(right, symbol);
|
1951 | }
|
1952 | return node.forEachChild((node2) => this.findDecoratedVariableValue(node2, symbol)) || null;
|
1953 | }
|
1954 | getStaticProperty(symbol, propertyName) {
|
1955 | var _a, _b, _c, _d;
|
1956 | return ((_a = symbol.implementation.exports) == null ? void 0 : _a.get(propertyName)) || ((_c = (_b = symbol.adjacent) == null ? void 0 : _b.exports) == null ? void 0 : _c.get(propertyName)) || ((_d = symbol.declaration.exports) == null ? void 0 : _d.get(propertyName));
|
1957 | }
|
1958 | acquireDecoratorInfo(classSymbol) {
|
1959 | const decl = classSymbol.declaration.valueDeclaration;
|
1960 | if (this.decoratorCache.has(decl)) {
|
1961 | return this.decoratorCache.get(decl);
|
1962 | }
|
1963 | const staticProps = this.computeDecoratorInfoFromStaticProperties(classSymbol);
|
1964 | const helperCalls = this.computeDecoratorInfoFromHelperCalls(classSymbol);
|
1965 | const decoratorInfo = {
|
1966 | classDecorators: staticProps.classDecorators || helperCalls.classDecorators,
|
1967 | memberDecorators: staticProps.memberDecorators || helperCalls.memberDecorators,
|
1968 | constructorParamInfo: staticProps.constructorParamInfo || helperCalls.constructorParamInfo
|
1969 | };
|
1970 | this.decoratorCache.set(decl, decoratorInfo);
|
1971 | return decoratorInfo;
|
1972 | }
|
1973 | computeDecoratorInfoFromStaticProperties(classSymbol) {
|
1974 | let classDecorators = null;
|
1975 | let memberDecorators = null;
|
1976 | let constructorParamInfo = null;
|
1977 | const decoratorsProperty = this.getStaticProperty(classSymbol, DECORATORS);
|
1978 | if (decoratorsProperty !== void 0) {
|
1979 | classDecorators = this.getClassDecoratorsFromStaticProperty(decoratorsProperty);
|
1980 | }
|
1981 | const propDecoratorsProperty = this.getStaticProperty(classSymbol, PROP_DECORATORS);
|
1982 | if (propDecoratorsProperty !== void 0) {
|
1983 | memberDecorators = this.getMemberDecoratorsFromStaticProperty(propDecoratorsProperty);
|
1984 | }
|
1985 | const constructorParamsProperty = this.getStaticProperty(classSymbol, CONSTRUCTOR_PARAMS);
|
1986 | if (constructorParamsProperty !== void 0) {
|
1987 | constructorParamInfo = this.getParamInfoFromStaticProperty(constructorParamsProperty);
|
1988 | }
|
1989 | return { classDecorators, memberDecorators, constructorParamInfo };
|
1990 | }
|
1991 | getClassDecoratorsFromStaticProperty(decoratorsSymbol) {
|
1992 | const decoratorsIdentifier = decoratorsSymbol.valueDeclaration;
|
1993 | if (decoratorsIdentifier && decoratorsIdentifier.parent) {
|
1994 | if (ts11.isBinaryExpression(decoratorsIdentifier.parent) && decoratorsIdentifier.parent.operatorToken.kind === ts11.SyntaxKind.EqualsToken) {
|
1995 | const decoratorsArray = decoratorsIdentifier.parent.right;
|
1996 | return this.reflectDecorators(decoratorsArray).filter((decorator) => this.isFromCore(decorator));
|
1997 | }
|
1998 | }
|
1999 | return null;
|
2000 | }
|
2001 | getMembersOfSymbol(symbol) {
|
2002 | const members = [];
|
2003 | const { memberDecorators } = this.acquireDecoratorInfo(symbol);
|
2004 | const decoratorsMap = new Map(memberDecorators);
|
2005 | if (symbol.implementation.members) {
|
2006 | symbol.implementation.members.forEach((value, key) => {
|
2007 | const decorators = decoratorsMap.get(key);
|
2008 | const reflectedMembers = this.reflectMembers(value, decorators);
|
2009 | if (reflectedMembers) {
|
2010 | decoratorsMap.delete(key);
|
2011 | members.push(...reflectedMembers);
|
2012 | }
|
2013 | });
|
2014 | }
|
2015 | if (symbol.implementation.exports) {
|
2016 | symbol.implementation.exports.forEach((value, key) => {
|
2017 | const decorators = decoratorsMap.get(key);
|
2018 | const reflectedMembers = this.reflectMembers(value, decorators, true);
|
2019 | if (reflectedMembers) {
|
2020 | decoratorsMap.delete(key);
|
2021 | members.push(...reflectedMembers);
|
2022 | }
|
2023 | });
|
2024 | }
|
2025 | if (ts11.isVariableDeclaration(symbol.declaration.valueDeclaration)) {
|
2026 | if (symbol.declaration.exports) {
|
2027 | symbol.declaration.exports.forEach((value, key) => {
|
2028 | const decorators = decoratorsMap.get(key);
|
2029 | const reflectedMembers = this.reflectMembers(value, decorators, true);
|
2030 | if (reflectedMembers) {
|
2031 | decoratorsMap.delete(key);
|
2032 | members.push(...reflectedMembers);
|
2033 | }
|
2034 | });
|
2035 | }
|
2036 | }
|
2037 | if (symbol.adjacent !== void 0) {
|
2038 | if (ts11.isVariableDeclaration(symbol.adjacent.valueDeclaration)) {
|
2039 | if (symbol.adjacent.exports !== void 0) {
|
2040 | symbol.adjacent.exports.forEach((value, key) => {
|
2041 | const decorators = decoratorsMap.get(key);
|
2042 | const reflectedMembers = this.reflectMembers(value, decorators, true);
|
2043 | if (reflectedMembers) {
|
2044 | decoratorsMap.delete(key);
|
2045 | members.push(...reflectedMembers);
|
2046 | }
|
2047 | });
|
2048 | }
|
2049 | }
|
2050 | }
|
2051 | decoratorsMap.forEach((value, key) => {
|
2052 | members.push({
|
2053 | implementation: null,
|
2054 | decorators: value,
|
2055 | isStatic: false,
|
2056 | kind: ClassMemberKind.Property,
|
2057 | name: key,
|
2058 | nameNode: null,
|
2059 | node: null,
|
2060 | type: null,
|
2061 | value: null
|
2062 | });
|
2063 | });
|
2064 | return members;
|
2065 | }
|
2066 | getMemberDecoratorsFromStaticProperty(decoratorsProperty) {
|
2067 | const memberDecorators = new Map();
|
2068 | const propDecoratorsMap = getPropertyValueFromSymbol(decoratorsProperty);
|
2069 | if (propDecoratorsMap && ts11.isObjectLiteralExpression(propDecoratorsMap)) {
|
2070 | const propertiesMap = reflectObjectLiteral(propDecoratorsMap);
|
2071 | propertiesMap.forEach((value, name) => {
|
2072 | const decorators = this.reflectDecorators(value).filter((decorator) => this.isFromCore(decorator));
|
2073 | if (decorators.length) {
|
2074 | memberDecorators.set(name, decorators);
|
2075 | }
|
2076 | });
|
2077 | }
|
2078 | return memberDecorators;
|
2079 | }
|
2080 | computeDecoratorInfoFromHelperCalls(classSymbol) {
|
2081 | let classDecorators = null;
|
2082 | const memberDecorators = new Map();
|
2083 | const constructorParamInfo = [];
|
2084 | const getConstructorParamInfo = (index) => {
|
2085 | let param = constructorParamInfo[index];
|
2086 | if (param === void 0) {
|
2087 | param = constructorParamInfo[index] = { decorators: null, typeExpression: null };
|
2088 | }
|
2089 | return param;
|
2090 | };
|
2091 | const helperCalls = this.getHelperCallsForClass(classSymbol, ["__decorate"]);
|
2092 | const outerDeclaration = classSymbol.declaration.valueDeclaration;
|
2093 | const innerDeclaration = classSymbol.implementation.valueDeclaration;
|
2094 | const adjacentDeclaration = this.getAdjacentNameOfClassSymbol(classSymbol).parent;
|
2095 | const matchesClass = (identifier) => {
|
2096 | const decl = this.getDeclarationOfIdentifier(identifier);
|
2097 | return decl !== null && (decl.node === adjacentDeclaration || decl.node === outerDeclaration || decl.node === innerDeclaration);
|
2098 | };
|
2099 | for (const helperCall of helperCalls) {
|
2100 | if (isClassDecorateCall(helperCall, matchesClass)) {
|
2101 | const helperArgs = helperCall.arguments[0];
|
2102 | for (const element of helperArgs.elements) {
|
2103 | const entry = this.reflectDecorateHelperEntry(element);
|
2104 | if (entry === null) {
|
2105 | continue;
|
2106 | }
|
2107 | if (entry.type === "decorator") {
|
2108 | if (this.isFromCore(entry.decorator)) {
|
2109 | (classDecorators || (classDecorators = [])).push(entry.decorator);
|
2110 | }
|
2111 | } else if (entry.type === "param:decorators") {
|
2112 | const param = getConstructorParamInfo(entry.index);
|
2113 | (param.decorators || (param.decorators = [])).push(entry.decorator);
|
2114 | } else if (entry.type === "params") {
|
2115 | entry.types.forEach((type, index) => getConstructorParamInfo(index).typeExpression = type);
|
2116 | }
|
2117 | }
|
2118 | } else if (isMemberDecorateCall(helperCall, matchesClass)) {
|
2119 | const helperArgs = helperCall.arguments[0];
|
2120 | const memberName = helperCall.arguments[2].text;
|
2121 | for (const element of helperArgs.elements) {
|
2122 | const entry = this.reflectDecorateHelperEntry(element);
|
2123 | if (entry === null) {
|
2124 | continue;
|
2125 | }
|
2126 | if (entry.type === "decorator") {
|
2127 | if (this.isFromCore(entry.decorator)) {
|
2128 | const decorators = memberDecorators.has(memberName) ? memberDecorators.get(memberName) : [];
|
2129 | decorators.push(entry.decorator);
|
2130 | memberDecorators.set(memberName, decorators);
|
2131 | }
|
2132 | } else {
|
2133 | }
|
2134 | }
|
2135 | }
|
2136 | }
|
2137 | return { classDecorators, memberDecorators, constructorParamInfo };
|
2138 | }
|
2139 | reflectDecorateHelperEntry(expression) {
|
2140 | if (!ts11.isCallExpression(expression)) {
|
2141 | return null;
|
2142 | }
|
2143 | const call = expression;
|
2144 | const helperName = getCalleeName(call);
|
2145 | if (helperName === "__metadata") {
|
2146 | const key = call.arguments[0];
|
2147 | if (key === void 0 || !ts11.isStringLiteral(key) || key.text !== "design:paramtypes") {
|
2148 | return null;
|
2149 | }
|
2150 | const value = call.arguments[1];
|
2151 | if (value === void 0 || !ts11.isArrayLiteralExpression(value)) {
|
2152 | return null;
|
2153 | }
|
2154 | return {
|
2155 | type: "params",
|
2156 | types: Array.from(value.elements)
|
2157 | };
|
2158 | }
|
2159 | if (helperName === "__param") {
|
2160 | const indexArg = call.arguments[0];
|
2161 | const index = indexArg && ts11.isNumericLiteral(indexArg) ? parseInt(indexArg.text, 10) : NaN;
|
2162 | if (isNaN(index)) {
|
2163 | return null;
|
2164 | }
|
2165 | const decoratorCall = call.arguments[1];
|
2166 | if (decoratorCall === void 0 || !ts11.isCallExpression(decoratorCall)) {
|
2167 | return null;
|
2168 | }
|
2169 | const decorator2 = this.reflectDecoratorCall(decoratorCall);
|
2170 | if (decorator2 === null) {
|
2171 | return null;
|
2172 | }
|
2173 | return {
|
2174 | type: "param:decorators",
|
2175 | index,
|
2176 | decorator: decorator2
|
2177 | };
|
2178 | }
|
2179 | const decorator = this.reflectDecoratorCall(call);
|
2180 | if (decorator === null) {
|
2181 | return null;
|
2182 | }
|
2183 | return {
|
2184 | type: "decorator",
|
2185 | decorator
|
2186 | };
|
2187 | }
|
2188 | reflectDecoratorCall(call) {
|
2189 | const decoratorExpression = call.expression;
|
2190 | if (!isDecoratorIdentifier(decoratorExpression)) {
|
2191 | return null;
|
2192 | }
|
2193 | const decoratorIdentifier = ts11.isIdentifier(decoratorExpression) ? decoratorExpression : decoratorExpression.name;
|
2194 | return {
|
2195 | name: decoratorIdentifier.text,
|
2196 | identifier: decoratorExpression,
|
2197 | import: this.getImportOfIdentifier(decoratorIdentifier),
|
2198 | node: call,
|
2199 | args: Array.from(call.arguments)
|
2200 | };
|
2201 | }
|
2202 | getHelperCall(statement, helperNames) {
|
2203 | if ((ts11.isExpressionStatement(statement) || ts11.isReturnStatement(statement)) && statement.expression) {
|
2204 | let expression = statement.expression;
|
2205 | while (isAssignment2(expression)) {
|
2206 | expression = expression.right;
|
2207 | }
|
2208 | if (ts11.isCallExpression(expression)) {
|
2209 | const calleeName = getCalleeName(expression);
|
2210 | if (calleeName !== null && helperNames.includes(calleeName)) {
|
2211 | return expression;
|
2212 | }
|
2213 | }
|
2214 | }
|
2215 | return null;
|
2216 | }
|
2217 | reflectDecorators(decoratorsArray) {
|
2218 | const decorators = [];
|
2219 | if (ts11.isArrayLiteralExpression(decoratorsArray)) {
|
2220 | decoratorsArray.elements.forEach((node) => {
|
2221 | if (ts11.isObjectLiteralExpression(node)) {
|
2222 | const decorator = reflectObjectLiteral(node);
|
2223 | if (decorator.has("type")) {
|
2224 | let decoratorType = decorator.get("type");
|
2225 | if (isDecoratorIdentifier(decoratorType)) {
|
2226 | const decoratorIdentifier = ts11.isIdentifier(decoratorType) ? decoratorType : decoratorType.name;
|
2227 | decorators.push({
|
2228 | name: decoratorIdentifier.text,
|
2229 | identifier: decoratorType,
|
2230 | import: this.getImportOfIdentifier(decoratorIdentifier),
|
2231 | node,
|
2232 | args: getDecoratorArgs(node)
|
2233 | });
|
2234 | }
|
2235 | }
|
2236 | }
|
2237 | });
|
2238 | }
|
2239 | return decorators;
|
2240 | }
|
2241 | reflectMembers(symbol, decorators, isStatic) {
|
2242 | if (symbol.flags & ts11.SymbolFlags.Accessor) {
|
2243 | const members = [];
|
2244 | const setter = symbol.declarations && symbol.declarations.find(ts11.isSetAccessor);
|
2245 | const getter = symbol.declarations && symbol.declarations.find(ts11.isGetAccessor);
|
2246 | const setterMember = setter && this.reflectMember(setter, ClassMemberKind.Setter, decorators, isStatic);
|
2247 | if (setterMember) {
|
2248 | members.push(setterMember);
|
2249 | decorators = void 0;
|
2250 | }
|
2251 | const getterMember = getter && this.reflectMember(getter, ClassMemberKind.Getter, decorators, isStatic);
|
2252 | if (getterMember) {
|
2253 | members.push(getterMember);
|
2254 | }
|
2255 | return members;
|
2256 | }
|
2257 | let kind = null;
|
2258 | if (symbol.flags & ts11.SymbolFlags.Method) {
|
2259 | kind = ClassMemberKind.Method;
|
2260 | } else if (symbol.flags & ts11.SymbolFlags.Property) {
|
2261 | kind = ClassMemberKind.Property;
|
2262 | }
|
2263 | const node = symbol.valueDeclaration || symbol.declarations && symbol.declarations[0];
|
2264 | if (!node) {
|
2265 | return null;
|
2266 | }
|
2267 | const member = this.reflectMember(node, kind, decorators, isStatic);
|
2268 | if (!member) {
|
2269 | return null;
|
2270 | }
|
2271 | return [member];
|
2272 | }
|
2273 | reflectMember(node, kind, decorators, isStatic) {
|
2274 | let value = null;
|
2275 | let name = null;
|
2276 | let nameNode = null;
|
2277 | if (!isClassMemberType(node)) {
|
2278 | return null;
|
2279 | }
|
2280 | if (isStatic && isPropertyAccess(node)) {
|
2281 | name = node.name.text;
|
2282 | value = kind === ClassMemberKind.Property ? node.parent.right : null;
|
2283 | } else if (isThisAssignment(node)) {
|
2284 | kind = ClassMemberKind.Property;
|
2285 | name = node.left.name.text;
|
2286 | value = node.right;
|
2287 | isStatic = false;
|
2288 | } else if (ts11.isConstructorDeclaration(node)) {
|
2289 | kind = ClassMemberKind.Constructor;
|
2290 | name = "constructor";
|
2291 | isStatic = false;
|
2292 | }
|
2293 | if (kind === null) {
|
2294 | this.logger.warn(`Unknown member type: "${node.getText()}`);
|
2295 | return null;
|
2296 | }
|
2297 | if (!name) {
|
2298 | if (isNamedDeclaration2(node)) {
|
2299 | name = node.name.text;
|
2300 | nameNode = node.name;
|
2301 | } else {
|
2302 | return null;
|
2303 | }
|
2304 | }
|
2305 | if (isStatic === void 0) {
|
2306 | isStatic = node.modifiers !== void 0 && node.modifiers.some((mod) => mod.kind === ts11.SyntaxKind.StaticKeyword);
|
2307 | }
|
2308 | const type = node.type || null;
|
2309 | return {
|
2310 | node,
|
2311 | implementation: node,
|
2312 | kind,
|
2313 | type,
|
2314 | name,
|
2315 | nameNode,
|
2316 | value,
|
2317 | isStatic,
|
2318 | decorators: decorators || []
|
2319 | };
|
2320 | }
|
2321 | getConstructorParameterDeclarations(classSymbol) {
|
2322 | const members = classSymbol.implementation.members;
|
2323 | if (members && members.has(CONSTRUCTOR)) {
|
2324 | const constructorSymbol = members.get(CONSTRUCTOR);
|
2325 | const constructor = constructorSymbol.declarations && constructorSymbol.declarations[0];
|
2326 | if (!constructor) {
|
2327 | return [];
|
2328 | }
|
2329 | if (constructor.parameters.length > 0) {
|
2330 | return Array.from(constructor.parameters);
|
2331 | }
|
2332 | if (isSynthesizedConstructor(constructor)) {
|
2333 | return null;
|
2334 | }
|
2335 | return [];
|
2336 | }
|
2337 | return null;
|
2338 | }
|
2339 | getConstructorParamInfo(classSymbol, parameterNodes) {
|
2340 | const { constructorParamInfo } = this.acquireDecoratorInfo(classSymbol);
|
2341 | return parameterNodes.map((node, index) => {
|
2342 | const { decorators, typeExpression } = constructorParamInfo[index] ? constructorParamInfo[index] : { decorators: null, typeExpression: null };
|
2343 | const nameNode = node.name;
|
2344 | const typeValueReference = this.typeToValue(typeExpression);
|
2345 | return {
|
2346 | name: getNameText(nameNode),
|
2347 | nameNode,
|
2348 | typeValueReference,
|
2349 | typeNode: null,
|
2350 | decorators
|
2351 | };
|
2352 | });
|
2353 | }
|
2354 | typeToValue(typeExpression) {
|
2355 | if (typeExpression === null) {
|
2356 | return {
|
2357 | kind: 2,
|
2358 | reason: { kind: 0 }
|
2359 | };
|
2360 | }
|
2361 | const imp = this.getImportOfExpression(typeExpression);
|
2362 | const decl = this.getDeclarationOfExpression(typeExpression);
|
2363 | if (imp === null || decl === null) {
|
2364 | return {
|
2365 | kind: 0,
|
2366 | expression: typeExpression,
|
2367 | defaultImportStatement: null
|
2368 | };
|
2369 | }
|
2370 | return {
|
2371 | kind: 1,
|
2372 | valueDeclaration: decl.node,
|
2373 | moduleName: imp.from,
|
2374 | importedName: imp.name,
|
2375 | nestedPath: null
|
2376 | };
|
2377 | }
|
2378 | getImportOfExpression(expression) {
|
2379 | if (ts11.isIdentifier(expression)) {
|
2380 | return this.getImportOfIdentifier(expression);
|
2381 | } else if (ts11.isPropertyAccessExpression(expression) && ts11.isIdentifier(expression.name)) {
|
2382 | return this.getImportOfIdentifier(expression.name);
|
2383 | } else {
|
2384 | return null;
|
2385 | }
|
2386 | }
|
2387 | getParamInfoFromStaticProperty(paramDecoratorsProperty) {
|
2388 | const paramDecorators = getPropertyValueFromSymbol(paramDecoratorsProperty);
|
2389 | if (paramDecorators) {
|
2390 | const container = ts11.isArrowFunction(paramDecorators) ? paramDecorators.body : paramDecorators;
|
2391 | if (ts11.isArrayLiteralExpression(container)) {
|
2392 | const elements = container.elements;
|
2393 | return elements.map((element) => ts11.isObjectLiteralExpression(element) ? reflectObjectLiteral(element) : null).map((paramInfo) => {
|
2394 | const typeExpression = paramInfo && paramInfo.has("type") ? paramInfo.get("type") : null;
|
2395 | const decoratorInfo = paramInfo && paramInfo.has("decorators") ? paramInfo.get("decorators") : null;
|
2396 | const decorators = decoratorInfo && this.reflectDecorators(decoratorInfo).filter((decorator) => this.isFromCore(decorator));
|
2397 | return { typeExpression, decorators };
|
2398 | });
|
2399 | } else if (paramDecorators !== void 0) {
|
2400 | this.logger.warn("Invalid constructor parameter decorator in " + paramDecorators.getSourceFile().fileName + ":\n", paramDecorators.getText());
|
2401 | }
|
2402 | }
|
2403 | return null;
|
2404 | }
|
2405 | getHelperCallsForClass(classSymbol, helperNames) {
|
2406 | return this.getStatementsForClass(classSymbol).map((statement) => this.getHelperCall(statement, helperNames)).filter(isDefined);
|
2407 | }
|
2408 | getStatementsForClass(classSymbol) {
|
2409 | const classNode = classSymbol.implementation.valueDeclaration;
|
2410 | if (isTopLevel(classNode)) {
|
2411 | return this.getModuleStatements(classNode.getSourceFile());
|
2412 | }
|
2413 | const statement = getContainingStatement(classNode);
|
2414 | if (ts11.isBlock(statement.parent)) {
|
2415 | return Array.from(statement.parent.statements);
|
2416 | }
|
2417 | throw new Error(`Unable to find adjacent statements for ${classSymbol.name}`);
|
2418 | }
|
2419 | isFromCore(decorator) {
|
2420 | if (this.isCore) {
|
2421 | return !decorator.import || /^\./.test(decorator.import.from);
|
2422 | } else {
|
2423 | return !!decorator.import && decorator.import.from === "@angular/core";
|
2424 | }
|
2425 | }
|
2426 | computePublicDtsDeclarationMap(src, dts) {
|
2427 | const declarationMap = new Map();
|
2428 | const dtsDeclarationMap = new Map();
|
2429 | const rootDts = getRootFileOrFail(dts);
|
2430 | this.collectDtsExportedDeclarations(dtsDeclarationMap, rootDts, dts.program.getTypeChecker());
|
2431 | const rootSrc = getRootFileOrFail(src);
|
2432 | this.collectSrcExportedDeclarations(declarationMap, dtsDeclarationMap, rootSrc);
|
2433 | return declarationMap;
|
2434 | }
|
2435 | computePrivateDtsDeclarationMap(src, dts) {
|
2436 | const declarationMap = new Map();
|
2437 | const dtsDeclarationMap = new Map();
|
2438 | const typeChecker = dts.program.getTypeChecker();
|
2439 | const dtsFiles = getNonRootPackageFiles(dts);
|
2440 | for (const dtsFile of dtsFiles) {
|
2441 | this.collectDtsExportedDeclarations(dtsDeclarationMap, dtsFile, typeChecker);
|
2442 | }
|
2443 | const srcFiles = getNonRootPackageFiles(src);
|
2444 | for (const srcFile of srcFiles) {
|
2445 | this.collectSrcExportedDeclarations(declarationMap, dtsDeclarationMap, srcFile);
|
2446 | }
|
2447 | return declarationMap;
|
2448 | }
|
2449 | collectDtsExportedDeclarations(dtsDeclarationMap, srcFile, checker) {
|
2450 | const srcModule = srcFile && checker.getSymbolAtLocation(srcFile);
|
2451 | const moduleExports = srcModule && checker.getExportsOfModule(srcModule);
|
2452 | if (moduleExports) {
|
2453 | moduleExports.forEach((exportedSymbol) => {
|
2454 | const name = exportedSymbol.name;
|
2455 | if (exportedSymbol.flags & ts11.SymbolFlags.Alias) {
|
2456 | exportedSymbol = checker.getAliasedSymbol(exportedSymbol);
|
2457 | }
|
2458 | const declaration = exportedSymbol.valueDeclaration;
|
2459 | if (declaration && !dtsDeclarationMap.has(name)) {
|
2460 | dtsDeclarationMap.set(name, declaration);
|
2461 | }
|
2462 | });
|
2463 | }
|
2464 | }
|
2465 | collectSrcExportedDeclarations(declarationMap, dtsDeclarationMap, srcFile) {
|
2466 | const fileExports = this.getExportsOfModule(srcFile);
|
2467 | if (fileExports !== null) {
|
2468 | for (const [exportName, { node: declarationNode }] of fileExports) {
|
2469 | if (dtsDeclarationMap.has(exportName)) {
|
2470 | declarationMap.set(declarationNode, dtsDeclarationMap.get(exportName));
|
2471 | }
|
2472 | }
|
2473 | }
|
2474 | }
|
2475 | getDeclarationOfExpression(expression) {
|
2476 | if (ts11.isIdentifier(expression)) {
|
2477 | return this.getDeclarationOfIdentifier(expression);
|
2478 | }
|
2479 | if (!ts11.isPropertyAccessExpression(expression) || !ts11.isIdentifier(expression.expression)) {
|
2480 | return null;
|
2481 | }
|
2482 | const namespaceDecl = this.getDeclarationOfIdentifier(expression.expression);
|
2483 | if (!namespaceDecl || !ts11.isSourceFile(namespaceDecl.node)) {
|
2484 | return null;
|
2485 | }
|
2486 | const namespaceExports = this.getExportsOfModule(namespaceDecl.node);
|
2487 | if (namespaceExports === null) {
|
2488 | return null;
|
2489 | }
|
2490 | if (!namespaceExports.has(expression.name.text)) {
|
2491 | return null;
|
2492 | }
|
2493 | const exportDecl = namespaceExports.get(expression.name.text);
|
2494 | return __spreadProps(__spreadValues({}, exportDecl), { viaModule: namespaceDecl.viaModule });
|
2495 | }
|
2496 | isJavaScriptObjectDeclaration(decl) {
|
2497 | const node = decl.node;
|
2498 | if (!ts11.isVariableDeclaration(node) || !ts11.isIdentifier(node.name) || node.name.text !== "Object" || node.type === void 0) {
|
2499 | return false;
|
2500 | }
|
2501 | const typeNode = node.type;
|
2502 | if (!ts11.isTypeReferenceNode(typeNode) || !ts11.isIdentifier(typeNode.typeName) || typeNode.typeName.text !== "ObjectConstructor") {
|
2503 | return false;
|
2504 | }
|
2505 | return this.src.program.isSourceFileDefaultLibrary(node.getSourceFile());
|
2506 | }
|
2507 | resolveEnumMembers(declaration) {
|
2508 | if (declaration.initializer !== void 0)
|
2509 | return null;
|
2510 | const variableStmt = declaration.parent.parent;
|
2511 | if (!ts11.isVariableStatement(variableStmt))
|
2512 | return null;
|
2513 | const block = variableStmt.parent;
|
2514 | if (!ts11.isBlock(block) && !ts11.isSourceFile(block))
|
2515 | return null;
|
2516 | const declarationIndex = block.statements.findIndex((statement) => statement === variableStmt);
|
2517 | if (declarationIndex === -1 || declarationIndex === block.statements.length - 1)
|
2518 | return null;
|
2519 | const subsequentStmt = block.statements[declarationIndex + 1];
|
2520 | if (!ts11.isExpressionStatement(subsequentStmt))
|
2521 | return null;
|
2522 | const iife = stripParentheses(subsequentStmt.expression);
|
2523 | if (!ts11.isCallExpression(iife) || !isEnumDeclarationIife(iife))
|
2524 | return null;
|
2525 | const fn = stripParentheses(iife.expression);
|
2526 | if (!ts11.isFunctionExpression(fn))
|
2527 | return null;
|
2528 | return this.reflectEnumMembers(fn);
|
2529 | }
|
2530 | reflectEnumMembers(fn) {
|
2531 | if (fn.parameters.length !== 1)
|
2532 | return null;
|
2533 | const enumName = fn.parameters[0].name;
|
2534 | if (!ts11.isIdentifier(enumName))
|
2535 | return null;
|
2536 | const enumMembers = [];
|
2537 | for (const statement of fn.body.statements) {
|
2538 | const enumMember = this.reflectEnumMember(enumName, statement);
|
2539 | if (enumMember === null) {
|
2540 | return null;
|
2541 | }
|
2542 | enumMembers.push(enumMember);
|
2543 | }
|
2544 | return enumMembers;
|
2545 | }
|
2546 | reflectEnumMember(enumName, statement) {
|
2547 | if (!ts11.isExpressionStatement(statement))
|
2548 | return null;
|
2549 | const expression = statement.expression;
|
2550 | if (!isEnumAssignment(enumName, expression)) {
|
2551 | return null;
|
2552 | }
|
2553 | const assignment = reflectEnumAssignment(expression);
|
2554 | if (assignment != null) {
|
2555 | return assignment;
|
2556 | }
|
2557 | const innerExpression = expression.left.argumentExpression;
|
2558 | if (!isEnumAssignment(enumName, innerExpression)) {
|
2559 | return null;
|
2560 | }
|
2561 | return reflectEnumAssignment(innerExpression);
|
2562 | }
|
2563 | getAdjacentNameOfClassSymbol(classSymbol) {
|
2564 | if (classSymbol.adjacent !== void 0) {
|
2565 | return this.getNameFromClassSymbolDeclaration(classSymbol, classSymbol.adjacent.valueDeclaration);
|
2566 | } else {
|
2567 | return this.getNameFromClassSymbolDeclaration(classSymbol, classSymbol.implementation.valueDeclaration);
|
2568 | }
|
2569 | }
|
2570 | };
|
2571 | function isEnumDeclarationIife(iife) {
|
2572 | if (iife.arguments.length !== 1)
|
2573 | return false;
|
2574 | const arg = iife.arguments[0];
|
2575 | if (!ts11.isBinaryExpression(arg) || arg.operatorToken.kind !== ts11.SyntaxKind.BarBarToken || !ts11.isParenthesizedExpression(arg.right)) {
|
2576 | return false;
|
2577 | }
|
2578 | const right = arg.right.expression;
|
2579 | if (!ts11.isBinaryExpression(right) || right.operatorToken.kind !== ts11.SyntaxKind.EqualsToken) {
|
2580 | return false;
|
2581 | }
|
2582 | if (!ts11.isObjectLiteralExpression(right.right) || right.right.properties.length !== 0) {
|
2583 | return false;
|
2584 | }
|
2585 | return true;
|
2586 | }
|
2587 | function isEnumAssignment(enumName, expression) {
|
2588 | if (!ts11.isBinaryExpression(expression) || expression.operatorToken.kind !== ts11.SyntaxKind.EqualsToken || !ts11.isElementAccessExpression(expression.left)) {
|
2589 | return false;
|
2590 | }
|
2591 | const enumIdentifier = expression.left.expression;
|
2592 | return ts11.isIdentifier(enumIdentifier) && enumIdentifier.text === enumName.text;
|
2593 | }
|
2594 | function reflectEnumAssignment(expression) {
|
2595 | const memberName = expression.left.argumentExpression;
|
2596 | if (!ts11.isPropertyName(memberName))
|
2597 | return null;
|
2598 | return { name: memberName, initializer: expression.right };
|
2599 | }
|
2600 | function isAssignmentStatement(statement) {
|
2601 | return ts11.isExpressionStatement(statement) && isAssignment2(statement.expression) && ts11.isIdentifier(statement.expression.left);
|
2602 | }
|
2603 | function getIifeBody(expression) {
|
2604 | const call = stripParentheses(expression);
|
2605 | if (!ts11.isCallExpression(call)) {
|
2606 | return void 0;
|
2607 | }
|
2608 | const fn = stripParentheses(call.expression);
|
2609 | if (!ts11.isFunctionExpression(fn) && !ts11.isArrowFunction(fn)) {
|
2610 | return void 0;
|
2611 | }
|
2612 | return fn.body;
|
2613 | }
|
2614 | function isAssignment2(node) {
|
2615 | return ts11.isBinaryExpression(node) && node.operatorToken.kind === ts11.SyntaxKind.EqualsToken;
|
2616 | }
|
2617 | function isClassDecorateCall(call, matches) {
|
2618 | const helperArgs = call.arguments[0];
|
2619 | if (helperArgs === void 0 || !ts11.isArrayLiteralExpression(helperArgs)) {
|
2620 | return false;
|
2621 | }
|
2622 | const target = call.arguments[1];
|
2623 | return target !== void 0 && ts11.isIdentifier(target) && matches(target);
|
2624 | }
|
2625 | function isMemberDecorateCall(call, matches) {
|
2626 | const helperArgs = call.arguments[0];
|
2627 | if (helperArgs === void 0 || !ts11.isArrayLiteralExpression(helperArgs)) {
|
2628 | return false;
|
2629 | }
|
2630 | const target = call.arguments[1];
|
2631 | if (target === void 0 || !ts11.isPropertyAccessExpression(target) || !ts11.isIdentifier(target.expression) || !matches(target.expression) || target.name.text !== "prototype") {
|
2632 | return false;
|
2633 | }
|
2634 | const memberName = call.arguments[2];
|
2635 | return memberName !== void 0 && ts11.isStringLiteral(memberName);
|
2636 | }
|
2637 | function getPropertyValueFromSymbol(propSymbol) {
|
2638 | const propIdentifier = propSymbol.valueDeclaration;
|
2639 | const parent = propIdentifier && propIdentifier.parent;
|
2640 | return parent && ts11.isBinaryExpression(parent) ? parent.right : void 0;
|
2641 | }
|
2642 | function getCalleeName(call) {
|
2643 | if (ts11.isIdentifier(call.expression)) {
|
2644 | return stripDollarSuffix(call.expression.text);
|
2645 | }
|
2646 | if (ts11.isPropertyAccessExpression(call.expression)) {
|
2647 | return stripDollarSuffix(call.expression.name.text);
|
2648 | }
|
2649 | return null;
|
2650 | }
|
2651 | function isInitializedVariableClassDeclaration(node) {
|
2652 | return isNamedVariableDeclaration(node) && node.initializer !== void 0;
|
2653 | }
|
2654 | function skipClassAliases(node) {
|
2655 | let expression = node.initializer;
|
2656 | while (isAssignment2(expression)) {
|
2657 | expression = expression.right;
|
2658 | }
|
2659 | return expression;
|
2660 | }
|
2661 | function getInnerClassDeclaration(expression) {
|
2662 | if (ts11.isClassExpression(expression) && hasNameIdentifier(expression)) {
|
2663 | return expression;
|
2664 | }
|
2665 | const iifeBody = getIifeBody(expression);
|
2666 | if (iifeBody === void 0) {
|
2667 | return null;
|
2668 | }
|
2669 | if (!ts11.isBlock(iifeBody)) {
|
2670 | return ts11.isClassExpression(iifeBody) && isNamedDeclaration2(iifeBody) ? iifeBody : null;
|
2671 | } else {
|
2672 | for (const statement of iifeBody.statements) {
|
2673 | if (isNamedClassDeclaration(statement) || isNamedFunctionDeclaration(statement)) {
|
2674 | return statement;
|
2675 | }
|
2676 | if (ts11.isVariableStatement(statement)) {
|
2677 | for (const declaration of statement.declarationList.declarations) {
|
2678 | if (isInitializedVariableClassDeclaration(declaration)) {
|
2679 | const expression2 = skipClassAliases(declaration);
|
2680 | if (ts11.isClassExpression(expression2) && hasNameIdentifier(expression2)) {
|
2681 | return expression2;
|
2682 | }
|
2683 | }
|
2684 | }
|
2685 | }
|
2686 | }
|
2687 | }
|
2688 | return null;
|
2689 | }
|
2690 | function getDecoratorArgs(node) {
|
2691 | const argsProperty = node.properties.filter(ts11.isPropertyAssignment).find((property2) => getNameText(property2.name) === "args");
|
2692 | const argsExpression = argsProperty && argsProperty.initializer;
|
2693 | return argsExpression && ts11.isArrayLiteralExpression(argsExpression) ? Array.from(argsExpression.elements) : [];
|
2694 | }
|
2695 | function isPropertyAccess(node) {
|
2696 | return !!node.parent && ts11.isBinaryExpression(node.parent) && ts11.isPropertyAccessExpression(node);
|
2697 | }
|
2698 | function isThisAssignment(node) {
|
2699 | return ts11.isBinaryExpression(node) && ts11.isPropertyAccessExpression(node.left) && node.left.expression.kind === ts11.SyntaxKind.ThisKeyword;
|
2700 | }
|
2701 | function isNamedDeclaration2(node) {
|
2702 | const anyNode = node;
|
2703 | return !!anyNode.name && ts11.isIdentifier(anyNode.name);
|
2704 | }
|
2705 | function isClassMemberType(node) {
|
2706 | return (ts11.isClassElement(node) || isPropertyAccess(node) || ts11.isBinaryExpression(node)) && !ts11.isIndexSignatureDeclaration(node);
|
2707 | }
|
2708 | function getFarLeftHandSideOfAssignment(declaration) {
|
2709 | let node = declaration.parent;
|
2710 | if (isAssignment2(node) && ts11.isIdentifier(node.left)) {
|
2711 | node = node.parent;
|
2712 | }
|
2713 | return ts11.isVariableDeclaration(node) ? node : void 0;
|
2714 | }
|
2715 | function getContainingVariableDeclaration(node) {
|
2716 | node = node.parent;
|
2717 | while (node !== void 0) {
|
2718 | if (isNamedVariableDeclaration(node)) {
|
2719 | return node;
|
2720 | }
|
2721 | node = node.parent;
|
2722 | }
|
2723 | return void 0;
|
2724 | }
|
2725 | function isSynthesizedConstructor(constructor) {
|
2726 | if (!constructor.body)
|
2727 | return false;
|
2728 | const firstStatement = constructor.body.statements[0];
|
2729 | if (!firstStatement || !ts11.isExpressionStatement(firstStatement))
|
2730 | return false;
|
2731 | return isSynthesizedSuperCall(firstStatement.expression);
|
2732 | }
|
2733 | function isSynthesizedSuperCall(expression) {
|
2734 | if (!ts11.isCallExpression(expression))
|
2735 | return false;
|
2736 | if (expression.expression.kind !== ts11.SyntaxKind.SuperKeyword)
|
2737 | return false;
|
2738 | if (expression.arguments.length !== 1)
|
2739 | return false;
|
2740 | const argument = expression.arguments[0];
|
2741 | return ts11.isSpreadElement(argument) && ts11.isIdentifier(argument.expression) && argument.expression.text === "arguments";
|
2742 | }
|
2743 | function getContainingStatement(node) {
|
2744 | while (node.parent) {
|
2745 | if (ts11.isBlock(node.parent) || ts11.isSourceFile(node.parent)) {
|
2746 | break;
|
2747 | }
|
2748 | node = node.parent;
|
2749 | }
|
2750 | return node;
|
2751 | }
|
2752 | function getRootFileOrFail(bundle) {
|
2753 | const rootFile = bundle.program.getSourceFile(bundle.path);
|
2754 | if (rootFile === void 0) {
|
2755 | throw new Error(`The given rootPath ${rootFile} is not a file of the program.`);
|
2756 | }
|
2757 | return rootFile;
|
2758 | }
|
2759 | function getNonRootPackageFiles(bundle) {
|
2760 | const rootFile = bundle.program.getSourceFile(bundle.path);
|
2761 | return bundle.program.getSourceFiles().filter((f) => f !== rootFile && isWithinPackage(bundle.package, absoluteFromSourceFile(f)));
|
2762 | }
|
2763 | function isTopLevel(node) {
|
2764 | while (node = node.parent) {
|
2765 | if (ts11.isBlock(node)) {
|
2766 | return false;
|
2767 | }
|
2768 | }
|
2769 | return true;
|
2770 | }
|
2771 | function getOuterNodeFromInnerDeclaration(node) {
|
2772 | if (!ts11.isFunctionDeclaration(node) && !ts11.isClassDeclaration(node) && !ts11.isVariableStatement(node)) {
|
2773 | return null;
|
2774 | }
|
2775 | let outerNode = node.parent;
|
2776 | if (!outerNode || !ts11.isBlock(outerNode))
|
2777 | return null;
|
2778 | outerNode = outerNode.parent;
|
2779 | if (!outerNode || !ts11.isFunctionExpression(outerNode) && !ts11.isArrowFunction(outerNode)) {
|
2780 | return null;
|
2781 | }
|
2782 | outerNode = outerNode.parent;
|
2783 | if (outerNode && ts11.isParenthesizedExpression(outerNode))
|
2784 | outerNode = outerNode.parent;
|
2785 | if (!outerNode || !ts11.isCallExpression(outerNode))
|
2786 | return null;
|
2787 | outerNode = outerNode.parent;
|
2788 | if (outerNode && ts11.isParenthesizedExpression(outerNode))
|
2789 | outerNode = outerNode.parent;
|
2790 | while (isAssignment2(outerNode.parent)) {
|
2791 | outerNode = outerNode.parent;
|
2792 | }
|
2793 | return outerNode;
|
2794 | }
|
2795 |
|
2796 |
|
2797 | import ts12 from "typescript";
|
2798 | var Esm5ReflectionHost = class extends Esm2015ReflectionHost {
|
2799 | getBaseClassExpression(clazz) {
|
2800 | const superBaseClassExpression = super.getBaseClassExpression(clazz);
|
2801 | if (superBaseClassExpression !== null) {
|
2802 | return superBaseClassExpression;
|
2803 | }
|
2804 | const iife = getIifeFn(this.getClassSymbol(clazz));
|
2805 | if (iife === null)
|
2806 | return null;
|
2807 | if (iife.parameters.length !== 1 || !isSuperIdentifier(iife.parameters[0].name)) {
|
2808 | return null;
|
2809 | }
|
2810 | if (!ts12.isCallExpression(iife.parent)) {
|
2811 | return null;
|
2812 | }
|
2813 | return iife.parent.arguments[0];
|
2814 | }
|
2815 | getDeclarationOfIdentifier(id) {
|
2816 | const declaration = super.getDeclarationOfIdentifier(id);
|
2817 | if (declaration === null) {
|
2818 | const nonEmittedNorImportedTsHelperDeclaration = getTsHelperFnFromIdentifier(id);
|
2819 | if (nonEmittedNorImportedTsHelperDeclaration !== null) {
|
2820 | return {
|
2821 | kind: 1,
|
2822 | node: id,
|
2823 | known: nonEmittedNorImportedTsHelperDeclaration,
|
2824 | viaModule: null
|
2825 | };
|
2826 | }
|
2827 | }
|
2828 | if (declaration === null || declaration.node === null || declaration.known !== null) {
|
2829 | return declaration;
|
2830 | }
|
2831 | if (!ts12.isVariableDeclaration(declaration.node) || declaration.node.initializer !== void 0 || !ts12.isBlock(declaration.node.parent.parent.parent)) {
|
2832 | return declaration;
|
2833 | }
|
2834 | const block = declaration.node.parent.parent.parent;
|
2835 | const aliasSymbol = this.checker.getSymbolAtLocation(declaration.node.name);
|
2836 | for (let i = 0; i < block.statements.length; i++) {
|
2837 | const statement = block.statements[i];
|
2838 | if (isAssignmentStatement(statement) && ts12.isIdentifier(statement.expression.left) && ts12.isIdentifier(statement.expression.right) && this.checker.getSymbolAtLocation(statement.expression.left) === aliasSymbol) {
|
2839 | return this.getDeclarationOfIdentifier(statement.expression.right);
|
2840 | }
|
2841 | }
|
2842 | return declaration;
|
2843 | }
|
2844 | getDefinitionOfFunction(node) {
|
2845 | const definition = super.getDefinitionOfFunction(node);
|
2846 | if (definition === null) {
|
2847 | return null;
|
2848 | }
|
2849 | if (definition.body !== null) {
|
2850 | let lookingForInitializers = true;
|
2851 | const statements = definition.body.filter((s) => {
|
2852 | lookingForInitializers = lookingForInitializers && captureParamInitializer(s, definition.parameters);
|
2853 | return !lookingForInitializers;
|
2854 | });
|
2855 | definition.body = statements;
|
2856 | }
|
2857 | return definition;
|
2858 | }
|
2859 | detectKnownDeclaration(decl) {
|
2860 | decl = super.detectKnownDeclaration(decl);
|
2861 | if (decl.known === null && decl.node !== null) {
|
2862 | decl.known = getTsHelperFnFromDeclaration(decl.node);
|
2863 | }
|
2864 | return decl;
|
2865 | }
|
2866 | getClassSymbolFromInnerDeclaration(declaration) {
|
2867 | const classSymbol = super.getClassSymbolFromInnerDeclaration(declaration);
|
2868 | if (classSymbol !== void 0) {
|
2869 | return classSymbol;
|
2870 | }
|
2871 | if (!isNamedFunctionDeclaration(declaration)) {
|
2872 | return void 0;
|
2873 | }
|
2874 | const outerNode = getOuterNodeFromInnerDeclaration(declaration);
|
2875 | if (outerNode === null || !hasNameIdentifier(outerNode)) {
|
2876 | return void 0;
|
2877 | }
|
2878 | return this.createClassSymbol(outerNode.name, declaration);
|
2879 | }
|
2880 | getConstructorParameterDeclarations(classSymbol) {
|
2881 | const constructor = classSymbol.implementation.valueDeclaration;
|
2882 | if (!ts12.isFunctionDeclaration(constructor))
|
2883 | return null;
|
2884 | if (constructor.parameters.length > 0) {
|
2885 | return Array.from(constructor.parameters);
|
2886 | }
|
2887 | if (this.isSynthesizedConstructor(constructor)) {
|
2888 | return null;
|
2889 | }
|
2890 | return [];
|
2891 | }
|
2892 | getParamInfoFromStaticProperty(paramDecoratorsProperty) {
|
2893 | const paramDecorators = getPropertyValueFromSymbol(paramDecoratorsProperty);
|
2894 | const returnStatement = getReturnStatement(paramDecorators);
|
2895 | const expression = returnStatement ? returnStatement.expression : paramDecorators;
|
2896 | if (expression && ts12.isArrayLiteralExpression(expression)) {
|
2897 | const elements = expression.elements;
|
2898 | return elements.map(reflectArrayElement).map((paramInfo) => {
|
2899 | const typeExpression = paramInfo && paramInfo.has("type") ? paramInfo.get("type") : null;
|
2900 | const decoratorInfo = paramInfo && paramInfo.has("decorators") ? paramInfo.get("decorators") : null;
|
2901 | const decorators = decoratorInfo && this.reflectDecorators(decoratorInfo);
|
2902 | return { typeExpression, decorators };
|
2903 | });
|
2904 | } else if (paramDecorators !== void 0) {
|
2905 | this.logger.warn("Invalid constructor parameter decorator in " + paramDecorators.getSourceFile().fileName + ":\n", paramDecorators.getText());
|
2906 | }
|
2907 | return null;
|
2908 | }
|
2909 | reflectMembers(symbol, decorators, isStatic) {
|
2910 | const node = symbol.valueDeclaration || symbol.declarations && symbol.declarations[0];
|
2911 | const propertyDefinition = node && getPropertyDefinition(node);
|
2912 | if (propertyDefinition) {
|
2913 | const members2 = [];
|
2914 | if (propertyDefinition.setter) {
|
2915 | members2.push({
|
2916 | node,
|
2917 | implementation: propertyDefinition.setter,
|
2918 | kind: ClassMemberKind.Setter,
|
2919 | type: null,
|
2920 | name: symbol.name,
|
2921 | nameNode: null,
|
2922 | value: null,
|
2923 | isStatic: isStatic || false,
|
2924 | decorators: decorators || []
|
2925 | });
|
2926 | decorators = void 0;
|
2927 | }
|
2928 | if (propertyDefinition.getter) {
|
2929 | members2.push({
|
2930 | node,
|
2931 | implementation: propertyDefinition.getter,
|
2932 | kind: ClassMemberKind.Getter,
|
2933 | type: null,
|
2934 | name: symbol.name,
|
2935 | nameNode: null,
|
2936 | value: null,
|
2937 | isStatic: isStatic || false,
|
2938 | decorators: decorators || []
|
2939 | });
|
2940 | }
|
2941 | return members2;
|
2942 | }
|
2943 | const members = super.reflectMembers(symbol, decorators, isStatic);
|
2944 | members && members.forEach((member) => {
|
2945 | if (member && member.kind === ClassMemberKind.Method && member.isStatic && member.node && ts12.isPropertyAccessExpression(member.node) && member.node.parent && ts12.isBinaryExpression(member.node.parent) && ts12.isFunctionExpression(member.node.parent.right)) {
|
2946 | member.implementation = member.node.parent.right;
|
2947 | }
|
2948 | });
|
2949 | return members;
|
2950 | }
|
2951 | getStatementsForClass(classSymbol) {
|
2952 | const classDeclarationParent = classSymbol.implementation.valueDeclaration.parent;
|
2953 | return ts12.isBlock(classDeclarationParent) ? Array.from(classDeclarationParent.statements) : [];
|
2954 | }
|
2955 | isSynthesizedConstructor(constructor) {
|
2956 | if (!constructor.body)
|
2957 | return false;
|
2958 | const firstStatement = constructor.body.statements[0];
|
2959 | if (!firstStatement)
|
2960 | return false;
|
2961 | return this.isSynthesizedSuperThisAssignment(firstStatement) || this.isSynthesizedSuperReturnStatement(firstStatement);
|
2962 | }
|
2963 | isSynthesizedSuperThisAssignment(statement) {
|
2964 | if (!ts12.isVariableStatement(statement))
|
2965 | return false;
|
2966 | const variableDeclarations = statement.declarationList.declarations;
|
2967 | if (variableDeclarations.length !== 1)
|
2968 | return false;
|
2969 | const variableDeclaration = variableDeclarations[0];
|
2970 | if (!ts12.isIdentifier(variableDeclaration.name) || !variableDeclaration.name.text.startsWith("_this"))
|
2971 | return false;
|
2972 | const initializer = variableDeclaration.initializer;
|
2973 | if (!initializer)
|
2974 | return false;
|
2975 | return this.isSynthesizedDefaultSuperCall(initializer);
|
2976 | }
|
2977 | isSynthesizedSuperReturnStatement(statement) {
|
2978 | if (!ts12.isReturnStatement(statement))
|
2979 | return false;
|
2980 | const expression = statement.expression;
|
2981 | if (!expression)
|
2982 | return false;
|
2983 | return this.isSynthesizedDefaultSuperCall(expression);
|
2984 | }
|
2985 | isSynthesizedDefaultSuperCall(expression) {
|
2986 | if (!isBinaryExpr(expression, ts12.SyntaxKind.BarBarToken))
|
2987 | return false;
|
2988 | if (expression.right.kind !== ts12.SyntaxKind.ThisKeyword)
|
2989 | return false;
|
2990 | const left = expression.left;
|
2991 | if (isBinaryExpr(left, ts12.SyntaxKind.AmpersandAmpersandToken)) {
|
2992 | return isSuperNotNull(left.left) && this.isSuperApplyCall(left.right);
|
2993 | } else {
|
2994 | return this.isSuperApplyCall(left);
|
2995 | }
|
2996 | }
|
2997 | isSuperApplyCall(expression) {
|
2998 | if (!ts12.isCallExpression(expression) || expression.arguments.length !== 2)
|
2999 | return false;
|
3000 | const targetFn = expression.expression;
|
3001 | if (!ts12.isPropertyAccessExpression(targetFn))
|
3002 | return false;
|
3003 | if (!isSuperIdentifier(targetFn.expression))
|
3004 | return false;
|
3005 | if (targetFn.name.text !== "apply")
|
3006 | return false;
|
3007 | const thisArgument = expression.arguments[0];
|
3008 | if (thisArgument.kind !== ts12.SyntaxKind.ThisKeyword)
|
3009 | return false;
|
3010 | const argumentsExpr = expression.arguments[1];
|
3011 | if (isArgumentsIdentifier(argumentsExpr)) {
|
3012 | return true;
|
3013 | }
|
3014 | return this.isSpreadArgumentsExpression(argumentsExpr);
|
3015 | }
|
3016 | isSpreadArgumentsExpression(expression) {
|
3017 | const call = this.extractKnownHelperCall(expression);
|
3018 | if (call === null) {
|
3019 | return false;
|
3020 | }
|
3021 | if (call.helper === KnownDeclaration.TsHelperSpread) {
|
3022 | return call.args.length === 1 && isArgumentsIdentifier(call.args[0]);
|
3023 | } else if (call.helper === KnownDeclaration.TsHelperSpreadArray) {
|
3024 | if (call.args.length !== 2 && call.args.length !== 3) {
|
3025 | return false;
|
3026 | }
|
3027 | const firstArg = call.args[0];
|
3028 | if (!ts12.isArrayLiteralExpression(firstArg) || firstArg.elements.length !== 0) {
|
3029 | return false;
|
3030 | }
|
3031 | const secondArg = this.extractKnownHelperCall(call.args[1]);
|
3032 | if (secondArg === null || secondArg.helper !== KnownDeclaration.TsHelperRead) {
|
3033 | return false;
|
3034 | }
|
3035 | return secondArg.args.length === 1 && isArgumentsIdentifier(secondArg.args[0]);
|
3036 | } else {
|
3037 | return false;
|
3038 | }
|
3039 | }
|
3040 | extractKnownHelperCall(expression) {
|
3041 | if (!ts12.isCallExpression(expression)) {
|
3042 | return null;
|
3043 | }
|
3044 | const receiverExpr = expression.expression;
|
3045 | let receiver = null;
|
3046 | if (ts12.isIdentifier(receiverExpr)) {
|
3047 | receiver = this.getDeclarationOfIdentifier(receiverExpr);
|
3048 | } else if (ts12.isPropertyAccessExpression(receiverExpr) && ts12.isIdentifier(receiverExpr.name)) {
|
3049 | receiver = this.getDeclarationOfIdentifier(receiverExpr.name);
|
3050 | }
|
3051 | if (receiver === null || receiver.known === null) {
|
3052 | return null;
|
3053 | }
|
3054 | return {
|
3055 | helper: receiver.known,
|
3056 | args: expression.arguments
|
3057 | };
|
3058 | }
|
3059 | };
|
3060 | function getPropertyDefinition(node) {
|
3061 | if (!ts12.isCallExpression(node))
|
3062 | return null;
|
3063 | const fn = node.expression;
|
3064 | if (!ts12.isPropertyAccessExpression(fn) || !ts12.isIdentifier(fn.expression) || fn.expression.text !== "Object" || fn.name.text !== "defineProperty")
|
3065 | return null;
|
3066 | const descriptor = node.arguments[2];
|
3067 | if (!descriptor || !ts12.isObjectLiteralExpression(descriptor))
|
3068 | return null;
|
3069 | return {
|
3070 | setter: readPropertyFunctionExpression(descriptor, "set"),
|
3071 | getter: readPropertyFunctionExpression(descriptor, "get")
|
3072 | };
|
3073 | }
|
3074 | function readPropertyFunctionExpression(object, name) {
|
3075 | const property2 = object.properties.find((p2) => ts12.isPropertyAssignment(p2) && ts12.isIdentifier(p2.name) && p2.name.text === name);
|
3076 | return property2 && ts12.isFunctionExpression(property2.initializer) && property2.initializer || null;
|
3077 | }
|
3078 | function getReturnStatement(declaration) {
|
3079 | return declaration && ts12.isFunctionExpression(declaration) ? declaration.body.statements.find(ts12.isReturnStatement) : void 0;
|
3080 | }
|
3081 | function reflectArrayElement(element) {
|
3082 | return ts12.isObjectLiteralExpression(element) ? reflectObjectLiteral(element) : null;
|
3083 | }
|
3084 | function isArgumentsIdentifier(expression) {
|
3085 | return ts12.isIdentifier(expression) && expression.text === "arguments";
|
3086 | }
|
3087 | function isSuperNotNull(expression) {
|
3088 | return isBinaryExpr(expression, ts12.SyntaxKind.ExclamationEqualsEqualsToken) && isSuperIdentifier(expression.left);
|
3089 | }
|
3090 | function isBinaryExpr(expression, operator) {
|
3091 | return ts12.isBinaryExpression(expression) && expression.operatorToken.kind === operator;
|
3092 | }
|
3093 | function isSuperIdentifier(node) {
|
3094 | return ts12.isIdentifier(node) && node.text.startsWith("_super");
|
3095 | }
|
3096 | function captureParamInitializer(statement, parameters) {
|
3097 | if (ts12.isIfStatement(statement) && isUndefinedComparison(statement.expression) && ts12.isBlock(statement.thenStatement) && statement.thenStatement.statements.length === 1) {
|
3098 | const ifStatementComparison = statement.expression;
|
3099 | const thenStatement = statement.thenStatement.statements[0];
|
3100 | if (isAssignmentStatement(thenStatement)) {
|
3101 | const comparisonName = ifStatementComparison.left.text;
|
3102 | const assignmentName = thenStatement.expression.left.text;
|
3103 | if (comparisonName === assignmentName) {
|
3104 | const parameter = parameters.find((p2) => p2.name === comparisonName);
|
3105 | if (parameter) {
|
3106 | parameter.initializer = thenStatement.expression.right;
|
3107 | return true;
|
3108 | }
|
3109 | }
|
3110 | }
|
3111 | }
|
3112 | return false;
|
3113 | }
|
3114 | function isUndefinedComparison(expression) {
|
3115 | return ts12.isBinaryExpression(expression) && expression.operatorToken.kind === ts12.SyntaxKind.EqualsEqualsEqualsToken && ts12.isVoidExpression(expression.right) && ts12.isIdentifier(expression.left);
|
3116 | }
|
3117 | function getIifeFn(classSymbol) {
|
3118 | if (classSymbol === void 0) {
|
3119 | return null;
|
3120 | }
|
3121 | const innerDeclaration = classSymbol.implementation.valueDeclaration;
|
3122 | const iifeBody = innerDeclaration.parent;
|
3123 | if (!ts12.isBlock(iifeBody)) {
|
3124 | return null;
|
3125 | }
|
3126 | const iifeWrapper = iifeBody.parent;
|
3127 | return iifeWrapper && ts12.isFunctionExpression(iifeWrapper) ? iifeWrapper : null;
|
3128 | }
|
3129 |
|
3130 |
|
3131 | var UmdReflectionHost = class extends Esm5ReflectionHost {
|
3132 | constructor(logger, isCore, src, dts = null) {
|
3133 | super(logger, isCore, src, dts);
|
3134 | this.umdModules = new FactoryMap((sf) => this.computeUmdModule(sf));
|
3135 | this.umdExports = new FactoryMap((sf) => this.computeExportsOfUmdModule(sf));
|
3136 | this.umdImportPaths = new FactoryMap((param) => this.computeImportPath(param));
|
3137 | this.program = src.program;
|
3138 | this.compilerHost = src.host;
|
3139 | }
|
3140 | getImportOfIdentifier(id) {
|
3141 | const nsIdentifier = findNamespaceOfIdentifier(id);
|
3142 | const importParameter = nsIdentifier && this.findUmdImportParameter(nsIdentifier);
|
3143 | const from = importParameter && this.getUmdImportPath(importParameter);
|
3144 | return from !== null ? { from, name: id.text } : null;
|
3145 | }
|
3146 | getDeclarationOfIdentifier(id) {
|
3147 | const declaration = this.getExportsDeclaration(id) || this.getUmdModuleDeclaration(id) || this.getUmdDeclaration(id);
|
3148 | if (declaration !== null) {
|
3149 | return declaration;
|
3150 | }
|
3151 | const superDeclaration = super.getDeclarationOfIdentifier(id);
|
3152 | if (superDeclaration === null) {
|
3153 | return null;
|
3154 | }
|
3155 | const outerNode = getOuterNodeFromInnerDeclaration(superDeclaration.node);
|
3156 | if (outerNode === null) {
|
3157 | return superDeclaration;
|
3158 | }
|
3159 | if (!isExportsAssignment(outerNode)) {
|
3160 | return superDeclaration;
|
3161 | }
|
3162 | return {
|
3163 | kind: 1,
|
3164 | node: outerNode.left,
|
3165 | implementation: outerNode.right,
|
3166 | known: null,
|
3167 | viaModule: null
|
3168 | };
|
3169 | }
|
3170 | getExportsOfModule(module7) {
|
3171 | return super.getExportsOfModule(module7) || this.umdExports.get(module7.getSourceFile());
|
3172 | }
|
3173 | getUmdModule(sourceFile) {
|
3174 | if (sourceFile.isDeclarationFile) {
|
3175 | return null;
|
3176 | }
|
3177 | return this.umdModules.get(sourceFile);
|
3178 | }
|
3179 | getUmdImportPath(importParameter) {
|
3180 | return this.umdImportPaths.get(importParameter);
|
3181 | }
|
3182 | getModuleStatements(sourceFile) {
|
3183 | const umdModule = this.getUmdModule(sourceFile);
|
3184 | return umdModule !== null ? Array.from(umdModule.factoryFn.body.statements) : [];
|
3185 | }
|
3186 | getClassSymbolFromOuterDeclaration(declaration) {
|
3187 | const superSymbol = super.getClassSymbolFromOuterDeclaration(declaration);
|
3188 | if (superSymbol) {
|
3189 | return superSymbol;
|
3190 | }
|
3191 | if (!isExportsDeclaration(declaration)) {
|
3192 | return void 0;
|
3193 | }
|
3194 | let initializer = skipAliases(declaration.parent.right);
|
3195 | if (ts13.isIdentifier(initializer)) {
|
3196 | const implementation = this.getDeclarationOfIdentifier(initializer);
|
3197 | if (implementation !== null) {
|
3198 | const implementationSymbol = this.getClassSymbol(implementation.node);
|
3199 | if (implementationSymbol !== null) {
|
3200 | return implementationSymbol;
|
3201 | }
|
3202 | }
|
3203 | }
|
3204 | const innerDeclaration = getInnerClassDeclaration(initializer);
|
3205 | if (innerDeclaration !== null) {
|
3206 | return this.createClassSymbol(declaration.name, innerDeclaration);
|
3207 | }
|
3208 | return void 0;
|
3209 | }
|
3210 | getClassSymbolFromInnerDeclaration(declaration) {
|
3211 | const superClassSymbol = super.getClassSymbolFromInnerDeclaration(declaration);
|
3212 | if (superClassSymbol !== void 0) {
|
3213 | return superClassSymbol;
|
3214 | }
|
3215 | if (!isNamedFunctionDeclaration(declaration)) {
|
3216 | return void 0;
|
3217 | }
|
3218 | const outerNode = getOuterNodeFromInnerDeclaration(declaration);
|
3219 | if (outerNode === null || !isExportsAssignment(outerNode)) {
|
3220 | return void 0;
|
3221 | }
|
3222 | return this.createClassSymbol(outerNode.left.name, declaration);
|
3223 | }
|
3224 | addClassSymbolsFromStatement(classes, statement) {
|
3225 | super.addClassSymbolsFromStatement(classes, statement);
|
3226 | if (isExportsStatement(statement)) {
|
3227 | const classSymbol = this.getClassSymbol(statement.expression.left);
|
3228 | if (classSymbol) {
|
3229 | classes.set(classSymbol.implementation, classSymbol);
|
3230 | }
|
3231 | }
|
3232 | }
|
3233 | preprocessStatement(statement) {
|
3234 | super.preprocessStatement(statement);
|
3235 | if (!isExportsStatement(statement)) {
|
3236 | return;
|
3237 | }
|
3238 | const declaration = statement.expression.left;
|
3239 | const initializer = statement.expression.right;
|
3240 | if (!isAssignment2(initializer) || !ts13.isIdentifier(initializer.left) || !this.isClass(declaration)) {
|
3241 | return;
|
3242 | }
|
3243 | const aliasedIdentifier = initializer.left;
|
3244 | const aliasedDeclaration = this.getDeclarationOfIdentifier(aliasedIdentifier);
|
3245 | if (aliasedDeclaration === null || aliasedDeclaration.node === null) {
|
3246 | throw new Error(`Unable to locate declaration of ${aliasedIdentifier.text} in "${statement.getText()}"`);
|
3247 | }
|
3248 | this.aliasedClassDeclarations.set(aliasedDeclaration.node, declaration.name);
|
3249 | }
|
3250 | computeUmdModule(sourceFile) {
|
3251 | if (sourceFile.statements.length !== 1) {
|
3252 | throw new Error(`Expected UMD module file (${sourceFile.fileName}) to contain exactly one statement, but found ${sourceFile.statements.length}.`);
|
3253 | }
|
3254 | return parseStatementForUmdModule(sourceFile.statements[0]);
|
3255 | }
|
3256 | computeExportsOfUmdModule(sourceFile) {
|
3257 | const moduleMap = new Map();
|
3258 | for (const statement of this.getModuleStatements(sourceFile)) {
|
3259 | if (isExportsStatement(statement)) {
|
3260 | const exportDeclaration = this.extractBasicUmdExportDeclaration(statement);
|
3261 | if (!moduleMap.has(exportDeclaration.name)) {
|
3262 | moduleMap.set(exportDeclaration.name, exportDeclaration.declaration);
|
3263 | }
|
3264 | } else if (isWildcardReexportStatement(statement)) {
|
3265 | const reexports = this.extractUmdWildcardReexports(statement, sourceFile);
|
3266 | for (const reexport of reexports) {
|
3267 | moduleMap.set(reexport.name, reexport.declaration);
|
3268 | }
|
3269 | } else if (isDefinePropertyReexportStatement(statement)) {
|
3270 | const exportDeclaration = this.extractUmdDefinePropertyExportDeclaration(statement);
|
3271 | if (exportDeclaration !== null) {
|
3272 | moduleMap.set(exportDeclaration.name, exportDeclaration.declaration);
|
3273 | }
|
3274 | }
|
3275 | }
|
3276 | return moduleMap;
|
3277 | }
|
3278 | computeImportPath(param) {
|
3279 | const umdModule = this.getUmdModule(param.getSourceFile());
|
3280 | if (umdModule === null) {
|
3281 | return null;
|
3282 | }
|
3283 | const imports = getImportsOfUmdModule(umdModule);
|
3284 | if (imports === null) {
|
3285 | return null;
|
3286 | }
|
3287 | let importPath = null;
|
3288 | for (const i of imports) {
|
3289 | this.umdImportPaths.set(i.parameter, i.path);
|
3290 | if (i.parameter === param) {
|
3291 | importPath = i.path;
|
3292 | }
|
3293 | }
|
3294 | return importPath;
|
3295 | }
|
3296 | extractBasicUmdExportDeclaration(statement) {
|
3297 | var _a;
|
3298 | const name = statement.expression.left.name.text;
|
3299 | const exportExpression = skipAliases(statement.expression.right);
|
3300 | const declaration = (_a = this.getDeclarationOfExpression(exportExpression)) != null ? _a : {
|
3301 | kind: 1,
|
3302 | node: statement.expression.left,
|
3303 | implementation: statement.expression.right,
|
3304 | known: null,
|
3305 | viaModule: null
|
3306 | };
|
3307 | return { name, declaration };
|
3308 | }
|
3309 | extractUmdWildcardReexports(statement, containingFile) {
|
3310 | const reexportArg = statement.expression.arguments[0];
|
3311 | const requireCall = isRequireCall(reexportArg) ? reexportArg : ts13.isIdentifier(reexportArg) ? findRequireCallReference(reexportArg, this.checker) : null;
|
3312 | let importPath = null;
|
3313 | if (requireCall !== null) {
|
3314 | importPath = requireCall.arguments[0].text;
|
3315 | } else if (ts13.isIdentifier(reexportArg)) {
|
3316 | const importParameter = this.findUmdImportParameter(reexportArg);
|
3317 | importPath = importParameter && this.getUmdImportPath(importParameter);
|
3318 | }
|
3319 | if (importPath === null) {
|
3320 | return [];
|
3321 | }
|
3322 | const importedFile = this.resolveModuleName(importPath, containingFile);
|
3323 | if (importedFile === void 0) {
|
3324 | return [];
|
3325 | }
|
3326 | const importedExports = this.getExportsOfModule(importedFile);
|
3327 | if (importedExports === null) {
|
3328 | return [];
|
3329 | }
|
3330 | const viaModule = stripExtension2(importedFile.fileName);
|
3331 | const reexports = [];
|
3332 | importedExports.forEach((decl, name) => reexports.push({ name, declaration: __spreadProps(__spreadValues({}, decl), { viaModule }) }));
|
3333 | return reexports;
|
3334 | }
|
3335 | extractUmdDefinePropertyExportDeclaration(statement) {
|
3336 | const args = statement.expression.arguments;
|
3337 | const name = args[1].text;
|
3338 | const getterFnExpression = extractGetterFnExpression(statement);
|
3339 | if (getterFnExpression === null) {
|
3340 | return null;
|
3341 | }
|
3342 | const declaration = this.getDeclarationOfExpression(getterFnExpression);
|
3343 | if (declaration !== null) {
|
3344 | return { name, declaration };
|
3345 | }
|
3346 | return {
|
3347 | name,
|
3348 | declaration: {
|
3349 | kind: 1,
|
3350 | node: args[1],
|
3351 | implementation: getterFnExpression,
|
3352 | known: null,
|
3353 | viaModule: null
|
3354 | }
|
3355 | };
|
3356 | }
|
3357 | findUmdImportParameter(id) {
|
3358 | const symbol = id && this.checker.getSymbolAtLocation(id) || null;
|
3359 | const declaration = symbol && symbol.valueDeclaration;
|
3360 | return declaration && ts13.isParameter(declaration) ? declaration : null;
|
3361 | }
|
3362 | getUmdDeclaration(id) {
|
3363 | const nsIdentifier = findNamespaceOfIdentifier(id);
|
3364 | if (nsIdentifier === null) {
|
3365 | return null;
|
3366 | }
|
3367 | if (nsIdentifier.parent.parent && isExportsAssignment(nsIdentifier.parent.parent)) {
|
3368 | const initializer = nsIdentifier.parent.parent.right;
|
3369 | if (ts13.isIdentifier(initializer)) {
|
3370 | return this.getDeclarationOfIdentifier(initializer);
|
3371 | }
|
3372 | return this.detectKnownDeclaration({
|
3373 | kind: 1,
|
3374 | node: nsIdentifier.parent.parent.left,
|
3375 | implementation: skipAliases(nsIdentifier.parent.parent.right),
|
3376 | viaModule: null,
|
3377 | known: null
|
3378 | });
|
3379 | }
|
3380 | const moduleDeclaration = this.getUmdModuleDeclaration(nsIdentifier);
|
3381 | if (moduleDeclaration === null || moduleDeclaration.node === null || !ts13.isSourceFile(moduleDeclaration.node)) {
|
3382 | return null;
|
3383 | }
|
3384 | const moduleExports = this.getExportsOfModule(moduleDeclaration.node);
|
3385 | if (moduleExports === null) {
|
3386 | return null;
|
3387 | }
|
3388 | const declaration = moduleExports.get(id.text);
|
3389 | if (!moduleExports.has(id.text)) {
|
3390 | return null;
|
3391 | }
|
3392 | const viaModule = declaration.viaModule === null ? moduleDeclaration.viaModule : declaration.viaModule;
|
3393 | return __spreadProps(__spreadValues({}, declaration), { viaModule, known: getTsHelperFnFromIdentifier(id) });
|
3394 | }
|
3395 | getExportsDeclaration(id) {
|
3396 | if (!isExportsIdentifier(id)) {
|
3397 | return null;
|
3398 | }
|
3399 | const exportsSymbol = this.checker.getSymbolsInScope(id, ts13.SymbolFlags.Variable).find((symbol) => symbol.name === "exports");
|
3400 | const node = (exportsSymbol == null ? void 0 : exportsSymbol.valueDeclaration) !== void 0 && !ts13.isFunctionExpression(exportsSymbol.valueDeclaration.parent) ? exportsSymbol.valueDeclaration : id.getSourceFile();
|
3401 | return {
|
3402 | kind: 0,
|
3403 | node,
|
3404 | viaModule: null,
|
3405 | known: null,
|
3406 | identity: null
|
3407 | };
|
3408 | }
|
3409 | getUmdModuleDeclaration(id) {
|
3410 | const importPath = this.getImportPathFromParameter(id) || this.getImportPathFromRequireCall(id);
|
3411 | if (importPath === null) {
|
3412 | return null;
|
3413 | }
|
3414 | const module7 = this.resolveModuleName(importPath, id.getSourceFile());
|
3415 | if (module7 === void 0) {
|
3416 | return null;
|
3417 | }
|
3418 | const viaModule = isExternalImport(importPath) ? importPath : null;
|
3419 | return { kind: 0, node: module7, viaModule, known: null, identity: null };
|
3420 | }
|
3421 | getImportPathFromParameter(id) {
|
3422 | const importParameter = this.findUmdImportParameter(id);
|
3423 | if (importParameter === null) {
|
3424 | return null;
|
3425 | }
|
3426 | return this.getUmdImportPath(importParameter);
|
3427 | }
|
3428 | getImportPathFromRequireCall(id) {
|
3429 | const requireCall = findRequireCallReference(id, this.checker);
|
3430 | if (requireCall === null) {
|
3431 | return null;
|
3432 | }
|
3433 | return requireCall.arguments[0].text;
|
3434 | }
|
3435 | getDeclarationOfExpression(expression) {
|
3436 | const inner = getInnerClassDeclaration(expression);
|
3437 | if (inner !== null) {
|
3438 | const outer = getOuterNodeFromInnerDeclaration(inner);
|
3439 | if (outer !== null && isExportsAssignment(outer)) {
|
3440 | return {
|
3441 | kind: 1,
|
3442 | node: outer.left,
|
3443 | implementation: inner,
|
3444 | known: null,
|
3445 | viaModule: null
|
3446 | };
|
3447 | }
|
3448 | }
|
3449 | return super.getDeclarationOfExpression(expression);
|
3450 | }
|
3451 | resolveModuleName(moduleName, containingFile) {
|
3452 | if (this.compilerHost.resolveModuleNames) {
|
3453 | const moduleInfo = this.compilerHost.resolveModuleNames([moduleName], containingFile.fileName, void 0, void 0, this.program.getCompilerOptions())[0];
|
3454 | return moduleInfo && this.program.getSourceFile(absoluteFrom(moduleInfo.resolvedFileName));
|
3455 | } else {
|
3456 | const moduleInfo = ts13.resolveModuleName(moduleName, containingFile.fileName, this.program.getCompilerOptions(), this.compilerHost);
|
3457 | return moduleInfo.resolvedModule && this.program.getSourceFile(absoluteFrom(moduleInfo.resolvedModule.resolvedFileName));
|
3458 | }
|
3459 | }
|
3460 | };
|
3461 | function parseStatementForUmdModule(statement) {
|
3462 | const wrapper = getUmdWrapper(statement);
|
3463 | if (wrapper === null)
|
3464 | return null;
|
3465 | const factoryFnParamIndex = wrapper.fn.parameters.findIndex((parameter) => ts13.isIdentifier(parameter.name) && parameter.name.text === "factory");
|
3466 | if (factoryFnParamIndex === -1)
|
3467 | return null;
|
3468 | const factoryFn = stripParentheses(wrapper.call.arguments[factoryFnParamIndex]);
|
3469 | if (!factoryFn || !ts13.isFunctionExpression(factoryFn))
|
3470 | return null;
|
3471 | let factoryCalls = null;
|
3472 | return {
|
3473 | wrapperFn: wrapper.fn,
|
3474 | factoryFn,
|
3475 | get factoryCalls() {
|
3476 | if (factoryCalls === null) {
|
3477 | factoryCalls = parseUmdWrapperFunction(this.wrapperFn);
|
3478 | }
|
3479 | return factoryCalls;
|
3480 | }
|
3481 | };
|
3482 | }
|
3483 | function getUmdWrapper(statement) {
|
3484 | if (!ts13.isExpressionStatement(statement))
|
3485 | return null;
|
3486 | if (ts13.isParenthesizedExpression(statement.expression) && ts13.isCallExpression(statement.expression.expression) && ts13.isFunctionExpression(statement.expression.expression.expression)) {
|
3487 | const call = statement.expression.expression;
|
3488 | const fn = statement.expression.expression.expression;
|
3489 | return { call, fn };
|
3490 | }
|
3491 | if (ts13.isCallExpression(statement.expression) && ts13.isParenthesizedExpression(statement.expression.expression) && ts13.isFunctionExpression(statement.expression.expression.expression)) {
|
3492 | const call = statement.expression;
|
3493 | const fn = statement.expression.expression.expression;
|
3494 | return { call, fn };
|
3495 | }
|
3496 | return null;
|
3497 | }
|
3498 | function parseUmdWrapperFunction(wrapperFn) {
|
3499 | const stmt = wrapperFn.body.statements[0];
|
3500 | let conditionalFactoryCalls;
|
3501 | if (ts13.isExpressionStatement(stmt) && ts13.isConditionalExpression(stmt.expression)) {
|
3502 | conditionalFactoryCalls = extractFactoryCallsFromConditionalExpression(stmt.expression);
|
3503 | } else if (ts13.isIfStatement(stmt)) {
|
3504 | conditionalFactoryCalls = extractFactoryCallsFromIfStatement(stmt);
|
3505 | } else {
|
3506 | throw new Error("UMD wrapper body is not in a supported format (expected a conditional expression or if statement):\n" + wrapperFn.body.getText());
|
3507 | }
|
3508 | const amdDefine = getAmdDefineCall(conditionalFactoryCalls);
|
3509 | const commonJs = getCommonJsFactoryCall(conditionalFactoryCalls);
|
3510 | const commonJs2 = getCommonJs2FactoryCall(conditionalFactoryCalls);
|
3511 | const global = getGlobalFactoryCall(conditionalFactoryCalls);
|
3512 | const cjsCallForImports = commonJs2 || commonJs;
|
3513 | if (cjsCallForImports === null) {
|
3514 | throw new Error("Unable to find a CommonJS or CommonJS2 factory call inside the UMD wrapper function:\n" + stmt.getText());
|
3515 | }
|
3516 | return { amdDefine, commonJs, commonJs2, global, cjsCallForImports };
|
3517 | }
|
3518 | function extractFactoryCallsFromConditionalExpression(node) {
|
3519 | const factoryCalls = [];
|
3520 | let currentNode = node;
|
3521 | while (ts13.isConditionalExpression(currentNode)) {
|
3522 | if (!ts13.isBinaryExpression(currentNode.condition)) {
|
3523 | throw new Error("Condition inside UMD wrapper is not a binary expression:\n" + currentNode.condition.getText());
|
3524 | }
|
3525 | factoryCalls.push({
|
3526 | condition: currentNode.condition,
|
3527 | factoryCall: getFunctionCallFromExpression(currentNode.whenTrue)
|
3528 | });
|
3529 | currentNode = currentNode.whenFalse;
|
3530 | }
|
3531 | factoryCalls.push({
|
3532 | condition: null,
|
3533 | factoryCall: getFunctionCallFromExpression(currentNode)
|
3534 | });
|
3535 | return factoryCalls;
|
3536 | }
|
3537 | function extractFactoryCallsFromIfStatement(node) {
|
3538 | const factoryCalls = [];
|
3539 | let currentNode = node;
|
3540 | while (currentNode && ts13.isIfStatement(currentNode)) {
|
3541 | if (!ts13.isBinaryExpression(currentNode.expression)) {
|
3542 | throw new Error("Condition inside UMD wrapper is not a binary expression:\n" + currentNode.expression.getText());
|
3543 | }
|
3544 | if (!ts13.isExpressionStatement(currentNode.thenStatement)) {
|
3545 | throw new Error("Then-statement inside UMD wrapper is not an expression statement:\n" + currentNode.thenStatement.getText());
|
3546 | }
|
3547 | factoryCalls.push({
|
3548 | condition: currentNode.expression,
|
3549 | factoryCall: getFunctionCallFromExpression(currentNode.thenStatement.expression)
|
3550 | });
|
3551 | currentNode = currentNode.elseStatement;
|
3552 | }
|
3553 | if (currentNode) {
|
3554 | if (!ts13.isExpressionStatement(currentNode)) {
|
3555 | throw new Error("Else-statement inside UMD wrapper is not an expression statement:\n" + currentNode.getText());
|
3556 | }
|
3557 | factoryCalls.push({
|
3558 | condition: null,
|
3559 | factoryCall: getFunctionCallFromExpression(currentNode.expression)
|
3560 | });
|
3561 | }
|
3562 | return factoryCalls;
|
3563 | }
|
3564 | function getFunctionCallFromExpression(node) {
|
3565 | if (ts13.isParenthesizedExpression(node)) {
|
3566 | return getFunctionCallFromExpression(node.expression);
|
3567 | }
|
3568 | if (ts13.isBinaryExpression(node) && [ts13.SyntaxKind.CommaToken, ts13.SyntaxKind.EqualsToken].includes(node.operatorToken.kind)) {
|
3569 | return getFunctionCallFromExpression(node.right);
|
3570 | }
|
3571 | if (!ts13.isCallExpression(node)) {
|
3572 | throw new Error("Expression inside UMD wrapper is not a call expression:\n" + node.getText());
|
3573 | }
|
3574 | return node;
|
3575 | }
|
3576 | function getAmdDefineCall(calls) {
|
3577 | var _a;
|
3578 | const amdConditionalCall = calls.find((call) => {
|
3579 | var _a2;
|
3580 | return ((_a2 = call.condition) == null ? void 0 : _a2.operatorToken.kind) === ts13.SyntaxKind.AmpersandAmpersandToken && oneOfBinaryConditions(call.condition, (exp) => isTypeOf(exp, "define")) && ts13.isIdentifier(call.factoryCall.expression) && call.factoryCall.expression.text === "define";
|
3581 | });
|
3582 | return (_a = amdConditionalCall == null ? void 0 : amdConditionalCall.factoryCall) != null ? _a : null;
|
3583 | }
|
3584 | function getCommonJsFactoryCall(calls) {
|
3585 | var _a;
|
3586 | const cjsConditionalCall = calls.find((call) => {
|
3587 | var _a2;
|
3588 | return ((_a2 = call.condition) == null ? void 0 : _a2.operatorToken.kind) === ts13.SyntaxKind.EqualsEqualsEqualsToken && isTypeOf(call.condition, "exports") && ts13.isIdentifier(call.factoryCall.expression) && call.factoryCall.expression.text === "factory";
|
3589 | });
|
3590 | return (_a = cjsConditionalCall == null ? void 0 : cjsConditionalCall.factoryCall) != null ? _a : null;
|
3591 | }
|
3592 | function getCommonJs2FactoryCall(calls) {
|
3593 | var _a;
|
3594 | const cjs2ConditionalCall = calls.find((call) => {
|
3595 | var _a2;
|
3596 | return ((_a2 = call.condition) == null ? void 0 : _a2.operatorToken.kind) === ts13.SyntaxKind.AmpersandAmpersandToken && oneOfBinaryConditions(call.condition, (exp) => isTypeOf(exp, "exports", "module")) && ts13.isIdentifier(call.factoryCall.expression) && call.factoryCall.expression.text === "factory";
|
3597 | });
|
3598 | return (_a = cjs2ConditionalCall == null ? void 0 : cjs2ConditionalCall.factoryCall) != null ? _a : null;
|
3599 | }
|
3600 | function getGlobalFactoryCall(calls) {
|
3601 | var _a;
|
3602 | const globalConditionalCall = calls.find((call) => call.condition === null);
|
3603 | return (_a = globalConditionalCall == null ? void 0 : globalConditionalCall.factoryCall) != null ? _a : null;
|
3604 | }
|
3605 | function oneOfBinaryConditions(node, test) {
|
3606 | return test(node.left) || test(node.right);
|
3607 | }
|
3608 | function isTypeOf(node, ...types) {
|
3609 | return ts13.isBinaryExpression(node) && ts13.isTypeOfExpression(node.left) && ts13.isIdentifier(node.left.expression) && types.includes(node.left.expression.text);
|
3610 | }
|
3611 | function getImportsOfUmdModule(umdModule) {
|
3612 | const imports = [];
|
3613 | const cjsFactoryCall = umdModule.factoryCalls.cjsCallForImports;
|
3614 | const depStartIndex = cjsFactoryCall.arguments.findIndex((arg) => isRequireCall(arg));
|
3615 | if (depStartIndex !== -1) {
|
3616 | for (let i = depStartIndex; i < umdModule.factoryFn.parameters.length; i++) {
|
3617 | imports.push({
|
3618 | parameter: umdModule.factoryFn.parameters[i],
|
3619 | path: getRequiredModulePath(cjsFactoryCall, i)
|
3620 | });
|
3621 | }
|
3622 | }
|
3623 | return imports;
|
3624 | }
|
3625 | function getRequiredModulePath(cjsFactoryCall, paramIndex) {
|
3626 | const requireCall = cjsFactoryCall.arguments[paramIndex];
|
3627 | if (requireCall !== void 0 && !isRequireCall(requireCall)) {
|
3628 | throw new Error(`Argument at index ${paramIndex} of UMD factory call is not a \`require\` call with a single string argument:
|
3629 | ` + cjsFactoryCall.getText());
|
3630 | }
|
3631 | return requireCall.arguments[0].text;
|
3632 | }
|
3633 | function isExportsIdentifier(node) {
|
3634 | return ts13.isIdentifier(node) && node.text === "exports";
|
3635 | }
|
3636 |
|
3637 |
|
3638 | var SUPPORTED_FORMAT_PROPERTIES = ["fesm2015", "fesm5", "es2015", "esm2015", "esm5", "main", "module", "browser"];
|
3639 | var NO_ENTRY_POINT = "no-entry-point";
|
3640 | var IGNORED_ENTRY_POINT = "ignored-entry-point";
|
3641 | var INCOMPATIBLE_ENTRY_POINT = "incompatible-entry-point";
|
3642 | function getEntryPointInfo(fs5, config, logger, packagePath, entryPointPath) {
|
3643 | const packagePackageJsonPath = fs5.resolve(packagePath, "package.json");
|
3644 | const entryPointPackageJsonPath = fs5.resolve(entryPointPath, "package.json");
|
3645 | const loadedPackagePackageJson = loadPackageJson(fs5, packagePackageJsonPath);
|
3646 | const loadedEntryPointPackageJson = packagePackageJsonPath === entryPointPackageJsonPath ? loadedPackagePackageJson : loadPackageJson(fs5, entryPointPackageJsonPath);
|
3647 | const { packageName, packageVersion } = getPackageNameAndVersion(fs5, packagePath, loadedPackagePackageJson, loadedEntryPointPackageJson);
|
3648 | const repositoryUrl = getRepositoryUrl(loadedPackagePackageJson);
|
3649 | const packageConfig = config.getPackageConfig(packageName, packagePath, packageVersion);
|
3650 | const entryPointConfig = packageConfig.entryPoints.get(entryPointPath);
|
3651 | let entryPointPackageJson;
|
3652 | if (entryPointConfig === void 0) {
|
3653 | if (!fs5.exists(entryPointPackageJsonPath)) {
|
3654 | return NO_ENTRY_POINT;
|
3655 | } else if (loadedEntryPointPackageJson === null) {
|
3656 | logger.warn(`Failed to read entry point info from invalid 'package.json' file: ${entryPointPackageJsonPath}`);
|
3657 | return INCOMPATIBLE_ENTRY_POINT;
|
3658 | } else {
|
3659 | entryPointPackageJson = loadedEntryPointPackageJson;
|
3660 | }
|
3661 | } else if (entryPointConfig.ignore === true) {
|
3662 | return IGNORED_ENTRY_POINT;
|
3663 | } else {
|
3664 | entryPointPackageJson = mergeConfigAndPackageJson(fs5, loadedEntryPointPackageJson, entryPointConfig, packagePath, entryPointPath);
|
3665 | }
|
3666 | const typings = entryPointPackageJson.typings || entryPointPackageJson.types || guessTypingsFromPackageJson(fs5, entryPointPath, entryPointPackageJson);
|
3667 | if (typeof typings !== "string") {
|
3668 | return INCOMPATIBLE_ENTRY_POINT;
|
3669 | }
|
3670 | const metadataPath = fs5.resolve(entryPointPath, typings.replace(/\.d\.ts$/, "") + ".metadata.json");
|
3671 | const compiledByAngular = entryPointConfig !== void 0 || fs5.exists(metadataPath);
|
3672 | const entryPointInfo = {
|
3673 | name: entryPointPackageJson.name,
|
3674 | path: entryPointPath,
|
3675 | packageName,
|
3676 | packagePath,
|
3677 | repositoryUrl,
|
3678 | packageJson: entryPointPackageJson,
|
3679 | typings: fs5.resolve(entryPointPath, typings),
|
3680 | compiledByAngular,
|
3681 | ignoreMissingDependencies: entryPointConfig !== void 0 ? !!entryPointConfig.ignoreMissingDependencies : false,
|
3682 | generateDeepReexports: entryPointConfig !== void 0 ? !!entryPointConfig.generateDeepReexports : false
|
3683 | };
|
3684 | return entryPointInfo;
|
3685 | }
|
3686 | function isEntryPoint(result) {
|
3687 | return result !== NO_ENTRY_POINT && result !== INCOMPATIBLE_ENTRY_POINT && result !== IGNORED_ENTRY_POINT;
|
3688 | }
|
3689 | function getEntryPointFormat(fs5, entryPoint, property2) {
|
3690 | switch (property2) {
|
3691 | case "fesm2015":
|
3692 | return "esm2015";
|
3693 | case "fesm5":
|
3694 | return "esm5";
|
3695 | case "es2015":
|
3696 | return "esm2015";
|
3697 | case "esm2015":
|
3698 | return "esm2015";
|
3699 | case "esm5":
|
3700 | return "esm5";
|
3701 | case "browser":
|
3702 | const browserFile = entryPoint.packageJson["browser"];
|
3703 | if (typeof browserFile !== "string") {
|
3704 | return void 0;
|
3705 | }
|
3706 | return sniffModuleFormat(fs5, fs5.join(entryPoint.path, browserFile));
|
3707 | case "main":
|
3708 | const mainFile = entryPoint.packageJson["main"];
|
3709 | if (mainFile === void 0) {
|
3710 | return void 0;
|
3711 | }
|
3712 | return sniffModuleFormat(fs5, fs5.join(entryPoint.path, mainFile));
|
3713 | case "module":
|
3714 | const moduleFilePath = entryPoint.packageJson["module"];
|
3715 | if (typeof moduleFilePath === "string" && moduleFilePath.includes("esm2015")) {
|
3716 | return `esm2015`;
|
3717 | }
|
3718 | return "esm5";
|
3719 | default:
|
3720 | return void 0;
|
3721 | }
|
3722 | }
|
3723 | function loadPackageJson(fs5, packageJsonPath) {
|
3724 | try {
|
3725 | return JSON.parse(fs5.readFile(packageJsonPath));
|
3726 | } catch {
|
3727 | return null;
|
3728 | }
|
3729 | }
|
3730 | function sniffModuleFormat(fs5, sourceFilePath) {
|
3731 | const resolvedPath = resolveFileWithPostfixes(fs5, sourceFilePath, ["", ".js", "/index.js"]);
|
3732 | if (resolvedPath === null) {
|
3733 | return void 0;
|
3734 | }
|
3735 | const sourceFile = ts14.createSourceFile(sourceFilePath, fs5.readFile(resolvedPath), ts14.ScriptTarget.ES5);
|
3736 | if (sourceFile.statements.length === 0) {
|
3737 | return void 0;
|
3738 | }
|
3739 | if (ts14.isExternalModule(sourceFile)) {
|
3740 | return "esm5";
|
3741 | } else if (parseStatementForUmdModule(sourceFile.statements[0]) !== null) {
|
3742 | return "umd";
|
3743 | } else {
|
3744 | return "commonjs";
|
3745 | }
|
3746 | }
|
3747 | function mergeConfigAndPackageJson(fs5, entryPointPackageJson, entryPointConfig, packagePath, entryPointPath) {
|
3748 | if (entryPointPackageJson !== null) {
|
3749 | return __spreadValues(__spreadValues({}, entryPointPackageJson), entryPointConfig.override);
|
3750 | } else {
|
3751 | const name = `${fs5.basename(packagePath)}/${fs5.relative(packagePath, entryPointPath)}`;
|
3752 | return __spreadValues({ name }, entryPointConfig.override);
|
3753 | }
|
3754 | }
|
3755 | function guessTypingsFromPackageJson(fs5, entryPointPath, entryPointPackageJson) {
|
3756 | for (const prop of SUPPORTED_FORMAT_PROPERTIES) {
|
3757 | const field = entryPointPackageJson[prop];
|
3758 | if (typeof field !== "string") {
|
3759 | continue;
|
3760 | }
|
3761 | const relativeTypingsPath = field.replace(/\.js$/, ".d.ts");
|
3762 | const typingsPath = fs5.resolve(entryPointPath, relativeTypingsPath);
|
3763 | if (fs5.exists(typingsPath)) {
|
3764 | return typingsPath;
|
3765 | }
|
3766 | }
|
3767 | return null;
|
3768 | }
|
3769 | function getPackageNameAndVersion(fs5, packagePath, packagePackageJson, entryPointPackageJson) {
|
3770 | var _a;
|
3771 | let packageName;
|
3772 | if (packagePackageJson !== null) {
|
3773 | packageName = packagePackageJson.name;
|
3774 | } else if (entryPointPackageJson !== null) {
|
3775 | packageName = /^(?:@[^/]+\/)?[^/]*/.exec(entryPointPackageJson.name)[0];
|
3776 | } else {
|
3777 | const lastSegment = fs5.basename(packagePath);
|
3778 | const secondLastSegment = fs5.basename(fs5.dirname(packagePath));
|
3779 | packageName = secondLastSegment.startsWith("@") ? `${secondLastSegment}/${lastSegment}` : lastSegment;
|
3780 | }
|
3781 | return {
|
3782 | packageName,
|
3783 | packageVersion: (_a = packagePackageJson == null ? void 0 : packagePackageJson.version) != null ? _a : null
|
3784 | };
|
3785 | }
|
3786 | function getRepositoryUrl(packageJson) {
|
3787 | if ((packageJson == null ? void 0 : packageJson.repository) === void 0) {
|
3788 | return "";
|
3789 | }
|
3790 | if (typeof packageJson.repository === "string") {
|
3791 | return packageJson.repository;
|
3792 | }
|
3793 | return packageJson.repository.url;
|
3794 | }
|
3795 |
|
3796 |
|
3797 | var builtinNodeJsModules = new Set(module2.builtinModules);
|
3798 | var DependencyResolver = class {
|
3799 | constructor(fs5, logger, config, hosts, typingsHost) {
|
3800 | this.fs = fs5;
|
3801 | this.logger = logger;
|
3802 | this.config = config;
|
3803 | this.hosts = hosts;
|
3804 | this.typingsHost = typingsHost;
|
3805 | }
|
3806 | sortEntryPointsByDependency(entryPoints, target) {
|
3807 | const { invalidEntryPoints, ignoredDependencies, graph } = this.computeDependencyGraph(entryPoints);
|
3808 | let sortedEntryPointNodes;
|
3809 | if (target) {
|
3810 | if (target.compiledByAngular && graph.hasNode(target.path)) {
|
3811 | sortedEntryPointNodes = graph.dependenciesOf(target.path);
|
3812 | sortedEntryPointNodes.push(target.path);
|
3813 | } else {
|
3814 | sortedEntryPointNodes = [];
|
3815 | }
|
3816 | } else {
|
3817 | sortedEntryPointNodes = graph.overallOrder();
|
3818 | }
|
3819 | return {
|
3820 | entryPoints: sortedEntryPointNodes.map((path7) => graph.getNodeData(path7)),
|
3821 | graph,
|
3822 | invalidEntryPoints,
|
3823 | ignoredDependencies
|
3824 | };
|
3825 | }
|
3826 | getEntryPointWithDependencies(entryPoint) {
|
3827 | const dependencies = createDependencyInfo();
|
3828 | if (entryPoint.compiledByAngular) {
|
3829 | const formatInfo = this.getEntryPointFormatInfo(entryPoint);
|
3830 | const host = this.hosts[formatInfo.format];
|
3831 | if (!host) {
|
3832 | throw new Error(`Could not find a suitable format for computing dependencies of entry-point: '${entryPoint.path}'.`);
|
3833 | }
|
3834 | host.collectDependencies(formatInfo.path, dependencies);
|
3835 | this.typingsHost.collectDependencies(entryPoint.typings, dependencies);
|
3836 | }
|
3837 | return { entryPoint, depInfo: dependencies };
|
3838 | }
|
3839 | computeDependencyGraph(entryPoints) {
|
3840 | const invalidEntryPoints = [];
|
3841 | const ignoredDependencies = [];
|
3842 | const graph = new DepGraph();
|
3843 | const angularEntryPoints = entryPoints.filter((e) => e.entryPoint.compiledByAngular);
|
3844 | angularEntryPoints.forEach((e) => graph.addNode(e.entryPoint.path, e.entryPoint));
|
3845 | angularEntryPoints.forEach(({ entryPoint, depInfo: { dependencies, missing, deepImports } }) => {
|
3846 | const missingDependencies = Array.from(missing).filter((dep) => !builtinNodeJsModules.has(dep));
|
3847 | if (missingDependencies.length > 0 && !entryPoint.ignoreMissingDependencies) {
|
3848 | removeNodes(entryPoint, missingDependencies);
|
3849 | } else {
|
3850 | dependencies.forEach((dependencyPath) => {
|
3851 | if (!graph.hasNode(entryPoint.path)) {
|
3852 | } else if (graph.hasNode(dependencyPath)) {
|
3853 | graph.addDependency(entryPoint.path, dependencyPath);
|
3854 | } else if (invalidEntryPoints.some((i) => i.entryPoint.path === dependencyPath)) {
|
3855 | removeNodes(entryPoint, [dependencyPath]);
|
3856 | } else {
|
3857 | ignoredDependencies.push({ entryPoint, dependencyPath });
|
3858 | }
|
3859 | });
|
3860 | }
|
3861 | if (deepImports.size > 0) {
|
3862 | const notableDeepImports = this.filterIgnorableDeepImports(entryPoint, deepImports);
|
3863 | if (notableDeepImports.length > 0) {
|
3864 | const imports = notableDeepImports.map((i) => `'${i}'`).join(", ");
|
3865 | this.logger.warn(`Entry point '${entryPoint.name}' contains deep imports into ${imports}. This is probably not a problem, but may cause the compilation of entry points to be out of order.`);
|
3866 | }
|
3867 | }
|
3868 | });
|
3869 | return { invalidEntryPoints, ignoredDependencies, graph };
|
3870 | function removeNodes(entryPoint, missingDependencies) {
|
3871 | const nodesToRemove = [entryPoint.path, ...graph.dependantsOf(entryPoint.path)];
|
3872 | nodesToRemove.forEach((node) => {
|
3873 | invalidEntryPoints.push({ entryPoint: graph.getNodeData(node), missingDependencies });
|
3874 | graph.removeNode(node);
|
3875 | });
|
3876 | }
|
3877 | }
|
3878 | getEntryPointFormatInfo(entryPoint) {
|
3879 | for (const property2 of SUPPORTED_FORMAT_PROPERTIES) {
|
3880 | const formatPath = entryPoint.packageJson[property2];
|
3881 | if (formatPath === void 0)
|
3882 | continue;
|
3883 | const format = getEntryPointFormat(this.fs, entryPoint, property2);
|
3884 | if (format === void 0)
|
3885 | continue;
|
3886 | return { format, path: this.fs.resolve(entryPoint.path, formatPath) };
|
3887 | }
|
3888 | throw new Error(`There is no appropriate source code format in '${entryPoint.path}' entry-point.`);
|
3889 | }
|
3890 | filterIgnorableDeepImports(entryPoint, deepImports) {
|
3891 | const version = entryPoint.packageJson.version || null;
|
3892 | const packageConfig = this.config.getPackageConfig(entryPoint.packageName, entryPoint.packagePath, version);
|
3893 | const matchers = packageConfig.ignorableDeepImportMatchers;
|
3894 | return Array.from(deepImports).filter((deepImport) => !matchers.some((matcher) => matcher.test(deepImport)));
|
3895 | }
|
3896 | };
|
3897 |
|
3898 |
|
3899 | import ts15 from "typescript";
|
3900 | var EsmDependencyHost = class extends DependencyHostBase {
|
3901 | constructor(fs5, moduleResolver, scanImportExpressions = true) {
|
3902 | super(fs5, moduleResolver);
|
3903 | this.scanImportExpressions = scanImportExpressions;
|
3904 | this.scanner = ts15.createScanner(ts15.ScriptTarget.Latest, true);
|
3905 | }
|
3906 | canSkipFile(fileContents) {
|
3907 | return !hasImportOrReexportStatements(fileContents);
|
3908 | }
|
3909 | extractImports(file, fileContents) {
|
3910 | const imports = new Set();
|
3911 | const templateStack = [];
|
3912 | let lastToken = ts15.SyntaxKind.Unknown;
|
3913 | let currentToken = ts15.SyntaxKind.Unknown;
|
3914 | const stopAtIndex = findLastPossibleImportOrReexport(fileContents);
|
3915 | this.scanner.setText(fileContents);
|
3916 | while ((currentToken = this.scanner.scan()) !== ts15.SyntaxKind.EndOfFileToken) {
|
3917 | if (this.scanner.getTokenPos() > stopAtIndex) {
|
3918 | break;
|
3919 | }
|
3920 | switch (currentToken) {
|
3921 | case ts15.SyntaxKind.TemplateHead:
|
3922 | templateStack.push(currentToken);
|
3923 | break;
|
3924 | case ts15.SyntaxKind.OpenBraceToken:
|
3925 | if (templateStack.length > 0) {
|
3926 | templateStack.push(currentToken);
|
3927 | }
|
3928 | break;
|
3929 | case ts15.SyntaxKind.CloseBraceToken:
|
3930 | if (templateStack.length > 0) {
|
3931 | const templateToken = templateStack[templateStack.length - 1];
|
3932 | if (templateToken === ts15.SyntaxKind.TemplateHead) {
|
3933 | currentToken = this.scanner.reScanTemplateToken(false);
|
3934 | if (currentToken === ts15.SyntaxKind.TemplateTail) {
|
3935 | templateStack.pop();
|
3936 | }
|
3937 | } else {
|
3938 | templateStack.pop();
|
3939 | }
|
3940 | }
|
3941 | break;
|
3942 | case ts15.SyntaxKind.SlashToken:
|
3943 | case ts15.SyntaxKind.SlashEqualsToken:
|
3944 | if (canPrecedeARegex(lastToken)) {
|
3945 | currentToken = this.scanner.reScanSlashToken();
|
3946 | }
|
3947 | break;
|
3948 | case ts15.SyntaxKind.ImportKeyword:
|
3949 | const importPath = this.extractImportPath();
|
3950 | if (importPath !== null) {
|
3951 | imports.add(importPath);
|
3952 | }
|
3953 | break;
|
3954 | case ts15.SyntaxKind.ExportKeyword:
|
3955 | const reexportPath = this.extractReexportPath();
|
3956 | if (reexportPath !== null) {
|
3957 | imports.add(reexportPath);
|
3958 | }
|
3959 | break;
|
3960 | }
|
3961 | lastToken = currentToken;
|
3962 | }
|
3963 | this.scanner.setText("");
|
3964 | return imports;
|
3965 | }
|
3966 | extractImportPath() {
|
3967 | let sideEffectImportPath = this.tryStringLiteral();
|
3968 | if (sideEffectImportPath !== null) {
|
3969 | return sideEffectImportPath;
|
3970 | }
|
3971 | let kind = this.scanner.getToken();
|
3972 | if (kind === ts15.SyntaxKind.OpenParenToken) {
|
3973 | return this.scanImportExpressions ? this.tryStringLiteral() : null;
|
3974 | }
|
3975 | if (kind === ts15.SyntaxKind.Identifier) {
|
3976 | kind = this.scanner.scan();
|
3977 | if (kind === ts15.SyntaxKind.CommaToken) {
|
3978 | kind = this.scanner.scan();
|
3979 | }
|
3980 | }
|
3981 | if (kind === ts15.SyntaxKind.AsteriskToken) {
|
3982 | kind = this.skipNamespacedClause();
|
3983 | if (kind === null) {
|
3984 | return null;
|
3985 | }
|
3986 | } else if (kind === ts15.SyntaxKind.OpenBraceToken) {
|
3987 | kind = this.skipNamedClause();
|
3988 | }
|
3989 | if (kind !== ts15.SyntaxKind.FromKeyword) {
|
3990 | return null;
|
3991 | }
|
3992 | return this.tryStringLiteral();
|
3993 | }
|
3994 | extractReexportPath() {
|
3995 | let token = this.scanner.scan();
|
3996 | if (token === ts15.SyntaxKind.AsteriskToken) {
|
3997 | token = this.skipNamespacedClause();
|
3998 | if (token === null) {
|
3999 | return null;
|
4000 | }
|
4001 | } else if (token === ts15.SyntaxKind.OpenBraceToken) {
|
4002 | token = this.skipNamedClause();
|
4003 | }
|
4004 | if (token !== ts15.SyntaxKind.FromKeyword) {
|
4005 | return null;
|
4006 | }
|
4007 | return this.tryStringLiteral();
|
4008 | }
|
4009 | skipNamespacedClause() {
|
4010 | let token = this.scanner.scan();
|
4011 | if (token === ts15.SyntaxKind.AsKeyword) {
|
4012 | token = this.scanner.scan();
|
4013 | if (token !== ts15.SyntaxKind.Identifier) {
|
4014 | return null;
|
4015 | }
|
4016 | token = this.scanner.scan();
|
4017 | }
|
4018 | return token;
|
4019 | }
|
4020 | skipNamedClause() {
|
4021 | let braceCount = 1;
|
4022 | let token = this.scanner.scan();
|
4023 | while (braceCount > 0 && token !== ts15.SyntaxKind.EndOfFileToken) {
|
4024 | if (token === ts15.SyntaxKind.OpenBraceToken) {
|
4025 | braceCount++;
|
4026 | } else if (token === ts15.SyntaxKind.CloseBraceToken) {
|
4027 | braceCount--;
|
4028 | }
|
4029 | token = this.scanner.scan();
|
4030 | }
|
4031 | return token;
|
4032 | }
|
4033 | tryStringLiteral() {
|
4034 | return this.scanner.scan() === ts15.SyntaxKind.StringLiteral ? this.scanner.getTokenValue() : null;
|
4035 | }
|
4036 | };
|
4037 | function hasImportOrReexportStatements(source) {
|
4038 | return /(?:import|export)[\s\S]+?(["'])(?:\\\1|.)+?\1/.test(source);
|
4039 | }
|
4040 | function findLastPossibleImportOrReexport(source) {
|
4041 | return Math.max(source.lastIndexOf("import"), source.lastIndexOf(" from "));
|
4042 | }
|
4043 | function canPrecedeARegex(kind) {
|
4044 | switch (kind) {
|
4045 | case ts15.SyntaxKind.Identifier:
|
4046 | case ts15.SyntaxKind.StringLiteral:
|
4047 | case ts15.SyntaxKind.NumericLiteral:
|
4048 | case ts15.SyntaxKind.BigIntLiteral:
|
4049 | case ts15.SyntaxKind.RegularExpressionLiteral:
|
4050 | case ts15.SyntaxKind.ThisKeyword:
|
4051 | case ts15.SyntaxKind.PlusPlusToken:
|
4052 | case ts15.SyntaxKind.MinusMinusToken:
|
4053 | case ts15.SyntaxKind.CloseParenToken:
|
4054 | case ts15.SyntaxKind.CloseBracketToken:
|
4055 | case ts15.SyntaxKind.CloseBraceToken:
|
4056 | case ts15.SyntaxKind.TrueKeyword:
|
4057 | case ts15.SyntaxKind.FalseKeyword:
|
4058 | return false;
|
4059 | default:
|
4060 | return true;
|
4061 | }
|
4062 | }
|
4063 |
|
4064 |
|
4065 | var DtsDependencyHost = class extends EsmDependencyHost {
|
4066 | constructor(fs5, pathMappings) {
|
4067 | super(fs5, new ModuleResolver(fs5, pathMappings, ["", ".d.ts", "/index.d.ts", ".js", "/index.js"]), false);
|
4068 | }
|
4069 | processImport(importPath, file, dependencies, missing, deepImports, alreadySeen) {
|
4070 | return super.processImport(importPath, file, dependencies, missing, deepImports, alreadySeen) || super.processImport(`@types/${importPath}`, file, dependencies, missing, deepImports, alreadySeen);
|
4071 | }
|
4072 | };
|
4073 |
|
4074 |
|
4075 | import ts16 from "typescript";
|
4076 | var UmdDependencyHost = class extends DependencyHostBase {
|
4077 | canSkipFile(fileContents) {
|
4078 | return !hasRequireCalls(fileContents);
|
4079 | }
|
4080 | extractImports(file, fileContents) {
|
4081 | const sf = ts16.createSourceFile(file, fileContents, ts16.ScriptTarget.ES2015, true, ts16.ScriptKind.JS);
|
4082 | if (sf.statements.length !== 1) {
|
4083 | return new Set();
|
4084 | }
|
4085 | const umdModule = parseStatementForUmdModule(sf.statements[0]);
|
4086 | const umdImports = umdModule && getImportsOfUmdModule(umdModule);
|
4087 | if (umdImports === null) {
|
4088 | return new Set();
|
4089 | }
|
4090 | return new Set(umdImports.map((i) => i.path));
|
4091 | }
|
4092 | };
|
4093 |
|
4094 |
|
4095 | function getBasePaths(logger, sourceDirectory, pathMappings) {
|
4096 | const fs5 = getFileSystem();
|
4097 | const basePaths = [sourceDirectory];
|
4098 | if (pathMappings) {
|
4099 | const baseUrl = fs5.resolve(pathMappings.baseUrl);
|
4100 | if (fs5.isRoot(baseUrl)) {
|
4101 | logger.warn(`The provided pathMappings baseUrl is the root path ${baseUrl}.
|
4102 | This is likely to mess up how ngcc finds entry-points and is probably not correct.
|
4103 | Please check your path mappings configuration such as in the tsconfig.json file.`);
|
4104 | }
|
4105 | for (const paths of Object.values(pathMappings.paths)) {
|
4106 | for (const path7 of paths) {
|
4107 | let foundMatch = false;
|
4108 | const { prefix, hasWildcard } = extractPathPrefix(path7);
|
4109 | let basePath = fs5.resolve(baseUrl, prefix);
|
4110 | if (fs5.exists(basePath) && fs5.stat(basePath).isFile()) {
|
4111 | basePath = fs5.dirname(basePath);
|
4112 | }
|
4113 | if (fs5.exists(basePath)) {
|
4114 | basePaths.push(basePath);
|
4115 | foundMatch = true;
|
4116 | }
|
4117 | if (hasWildcard) {
|
4118 | const wildcardContainer = fs5.dirname(basePath);
|
4119 | const wildcardPrefix = fs5.basename(basePath);
|
4120 | if (isExistingDirectory(fs5, wildcardContainer)) {
|
4121 | const candidates = fs5.readdir(wildcardContainer);
|
4122 | for (const candidate of candidates) {
|
4123 | if (candidate.startsWith(wildcardPrefix)) {
|
4124 | const candidatePath = fs5.resolve(wildcardContainer, candidate);
|
4125 | if (isExistingDirectory(fs5, candidatePath)) {
|
4126 | foundMatch = true;
|
4127 | basePaths.push(candidatePath);
|
4128 | }
|
4129 | }
|
4130 | }
|
4131 | }
|
4132 | }
|
4133 | if (!foundMatch) {
|
4134 | logger.debug(`The basePath "${basePath}" computed from baseUrl "${baseUrl}" and path mapping "${path7}" does not exist in the file-system.
|
4135 | It will not be scanned for entry-points.`);
|
4136 | }
|
4137 | }
|
4138 | }
|
4139 | }
|
4140 | const dedupedBasePaths = dedupePaths(fs5, basePaths);
|
4141 | if (fs5.basename(sourceDirectory) === "node_modules" && !dedupedBasePaths.includes(sourceDirectory)) {
|
4142 | dedupedBasePaths.unshift(sourceDirectory);
|
4143 | }
|
4144 | return dedupedBasePaths;
|
4145 | }
|
4146 | function isExistingDirectory(fs5, path7) {
|
4147 | return fs5.exists(path7) && fs5.stat(path7).isDirectory();
|
4148 | }
|
4149 | function extractPathPrefix(path7) {
|
4150 | const [prefix, rest] = path7.split("*", 2);
|
4151 | return { prefix, hasWildcard: rest !== void 0 };
|
4152 | }
|
4153 | function trackDuration(task, log) {
|
4154 | const startTime = Date.now();
|
4155 | const result = task();
|
4156 | const duration = Math.round((Date.now() - startTime) / 100) / 10;
|
4157 | log(duration);
|
4158 | return result;
|
4159 | }
|
4160 | function dedupePaths(fs5, paths) {
|
4161 | const root = { children: new Map() };
|
4162 | for (const path7 of paths) {
|
4163 | addPath(fs5, root, path7);
|
4164 | }
|
4165 | return flattenTree(root);
|
4166 | }
|
4167 | function addPath(fs5, root, path7) {
|
4168 | let node = root;
|
4169 | if (!fs5.isRoot(path7)) {
|
4170 | const segments = path7.split("/");
|
4171 | for (let index = 0; index < segments.length; index++) {
|
4172 | if (isLeaf(node)) {
|
4173 | return;
|
4174 | }
|
4175 | const next = segments[index];
|
4176 | if (!node.children.has(next)) {
|
4177 | node.children.set(next, { children: new Map() });
|
4178 | }
|
4179 | node = node.children.get(next);
|
4180 | }
|
4181 | }
|
4182 | convertToLeaf(node, path7);
|
4183 | }
|
4184 | function flattenTree(root) {
|
4185 | const paths = [];
|
4186 | const nodes = [root];
|
4187 | for (let index = 0; index < nodes.length; index++) {
|
4188 | const node = nodes[index];
|
4189 | if (isLeaf(node)) {
|
4190 | paths.push(node.path);
|
4191 | } else {
|
4192 | node.children.forEach((value) => nodes.push(value));
|
4193 | }
|
4194 | }
|
4195 | return paths;
|
4196 | }
|
4197 | function isLeaf(node) {
|
4198 | return node.path !== void 0;
|
4199 | }
|
4200 | function convertToLeaf(node, path7) {
|
4201 | node.path = path7;
|
4202 | }
|
4203 |
|
4204 |
|
4205 | var DirectoryWalkerEntryPointFinder = class {
|
4206 | constructor(logger, resolver, entryPointCollector, entryPointManifest, sourceDirectory, pathMappings) {
|
4207 | this.logger = logger;
|
4208 | this.resolver = resolver;
|
4209 | this.entryPointCollector = entryPointCollector;
|
4210 | this.entryPointManifest = entryPointManifest;
|
4211 | this.sourceDirectory = sourceDirectory;
|
4212 | this.pathMappings = pathMappings;
|
4213 | this.basePaths = getBasePaths(this.logger, this.sourceDirectory, this.pathMappings);
|
4214 | }
|
4215 | findEntryPoints() {
|
4216 | const unsortedEntryPoints = [];
|
4217 | for (const basePath of this.basePaths) {
|
4218 | const entryPoints = this.entryPointManifest.readEntryPointsUsingManifest(basePath) || this.walkBasePathForPackages(basePath);
|
4219 | entryPoints.forEach((e) => unsortedEntryPoints.push(e));
|
4220 | }
|
4221 | return this.resolver.sortEntryPointsByDependency(unsortedEntryPoints);
|
4222 | }
|
4223 | walkBasePathForPackages(basePath) {
|
4224 | this.logger.debug(`No manifest found for ${basePath} so walking the directories for entry-points.`);
|
4225 | const entryPoints = trackDuration(() => this.entryPointCollector.walkDirectoryForPackages(basePath), (duration) => this.logger.debug(`Walking ${basePath} for entry-points took ${duration}s.`));
|
4226 | this.entryPointManifest.writeEntryPointManifest(basePath, entryPoints);
|
4227 | return entryPoints;
|
4228 | }
|
4229 | };
|
4230 |
|
4231 |
|
4232 | var NGCC_BACKUP_EXTENSION = ".__ivy_ngcc_bak";
|
4233 | var InPlaceFileWriter = class {
|
4234 | constructor(fs5, logger, errorOnFailedEntryPoint) {
|
4235 | this.fs = fs5;
|
4236 | this.logger = logger;
|
4237 | this.errorOnFailedEntryPoint = errorOnFailedEntryPoint;
|
4238 | }
|
4239 | writeBundle(_bundle, transformedFiles, _formatProperties) {
|
4240 | transformedFiles.forEach((file) => this.writeFileAndBackup(file));
|
4241 | }
|
4242 | revertBundle(_entryPoint, transformedFilePaths, _formatProperties) {
|
4243 | for (const filePath of transformedFilePaths) {
|
4244 | this.revertFileAndBackup(filePath);
|
4245 | }
|
4246 | }
|
4247 | writeFileAndBackup(file) {
|
4248 | this.fs.ensureDir(dirname(file.path));
|
4249 | const backPath = absoluteFrom(`${file.path}${NGCC_BACKUP_EXTENSION}`);
|
4250 | if (this.fs.exists(backPath)) {
|
4251 | if (this.errorOnFailedEntryPoint) {
|
4252 | throw new Error(`Tried to overwrite ${backPath} with an ngcc back up file, which is disallowed.`);
|
4253 | } else {
|
4254 | this.logger.error(`Tried to write ${backPath} with an ngcc back up file but it already exists so not writing, nor backing up, ${file.path}.
|
4255 | This error may be caused by one of the following:
|
4256 | * two or more entry-points overlap and ngcc has been asked to process some files more than once.
|
4257 | In this case, you should check other entry-points in this package
|
4258 | and set up a config to ignore any that you are not using.
|
4259 | * a previous run of ngcc was killed in the middle of processing, in a way that cannot be recovered.
|
4260 | In this case, you should try cleaning the node_modules directory and any dist directories that contain local libraries. Then try again.`);
|
4261 | }
|
4262 | } else {
|
4263 | if (this.fs.exists(file.path)) {
|
4264 | this.fs.moveFile(file.path, backPath);
|
4265 | }
|
4266 | this.fs.writeFile(file.path, file.contents);
|
4267 | }
|
4268 | }
|
4269 | revertFileAndBackup(filePath) {
|
4270 | if (this.fs.exists(filePath)) {
|
4271 | this.fs.removeFile(filePath);
|
4272 | const backPath = absoluteFrom(`${filePath}${NGCC_BACKUP_EXTENSION}`);
|
4273 | if (this.fs.exists(backPath)) {
|
4274 | this.fs.moveFile(backPath, filePath);
|
4275 | }
|
4276 | }
|
4277 | }
|
4278 | };
|
4279 |
|
4280 |
|
4281 | var NGCC_DIRECTORY = "__ivy_ngcc__";
|
4282 | var NGCC_PROPERTY_EXTENSION = "_ivy_ngcc";
|
4283 | var NewEntryPointFileWriter = class extends InPlaceFileWriter {
|
4284 | constructor(fs5, logger, errorOnFailedEntryPoint, pkgJsonUpdater) {
|
4285 | super(fs5, logger, errorOnFailedEntryPoint);
|
4286 | this.pkgJsonUpdater = pkgJsonUpdater;
|
4287 | }
|
4288 | writeBundle(bundle, transformedFiles, formatProperties) {
|
4289 | const entryPoint = bundle.entryPoint;
|
4290 | const ngccFolder = this.fs.join(entryPoint.packagePath, NGCC_DIRECTORY);
|
4291 | this.copyBundle(bundle, entryPoint.packagePath, ngccFolder, transformedFiles);
|
4292 | transformedFiles.forEach((file) => this.writeFile(file, entryPoint.packagePath, ngccFolder));
|
4293 | this.updatePackageJson(entryPoint, formatProperties, ngccFolder);
|
4294 | }
|
4295 | revertBundle(entryPoint, transformedFilePaths, formatProperties) {
|
4296 | for (const filePath of transformedFilePaths) {
|
4297 | this.revertFile(filePath, entryPoint.packagePath);
|
4298 | }
|
4299 | this.revertPackageJson(entryPoint, formatProperties);
|
4300 | }
|
4301 | copyBundle(bundle, packagePath, ngccFolder, transformedFiles) {
|
4302 | const doNotCopy = new Set(transformedFiles.map((f) => f.path));
|
4303 | bundle.src.program.getSourceFiles().forEach((sourceFile) => {
|
4304 | const originalPath = absoluteFromSourceFile(sourceFile);
|
4305 | if (doNotCopy.has(originalPath)) {
|
4306 | return;
|
4307 | }
|
4308 | const relativePath = this.fs.relative(packagePath, originalPath);
|
4309 | const isInsidePackage = isLocalRelativePath(relativePath);
|
4310 | if (!sourceFile.isDeclarationFile && isInsidePackage) {
|
4311 | const newPath = this.fs.resolve(ngccFolder, relativePath);
|
4312 | this.fs.ensureDir(this.fs.dirname(newPath));
|
4313 | this.fs.copyFile(originalPath, newPath);
|
4314 | this.copyAndUpdateSourceMap(originalPath, newPath);
|
4315 | }
|
4316 | });
|
4317 | }
|
4318 | copyAndUpdateSourceMap(originalSrcPath, newSrcPath) {
|
4319 | var _a;
|
4320 | const sourceMapPath = originalSrcPath + ".map";
|
4321 | if (this.fs.exists(sourceMapPath)) {
|
4322 | try {
|
4323 | const sourceMap = JSON.parse(this.fs.readFile(sourceMapPath));
|
4324 | const newSourceMapPath = newSrcPath + ".map";
|
4325 | const relativePath = this.fs.relative(this.fs.dirname(newSourceMapPath), this.fs.dirname(sourceMapPath));
|
4326 | sourceMap.sourceRoot = this.fs.join(relativePath, sourceMap.sourceRoot || ".");
|
4327 | this.fs.ensureDir(this.fs.dirname(newSourceMapPath));
|
4328 | this.fs.writeFile(newSourceMapPath, JSON.stringify(sourceMap));
|
4329 | } catch (e) {
|
4330 | this.logger.warn(`Failed to process source-map at ${sourceMapPath}`);
|
4331 | this.logger.warn((_a = e.message) != null ? _a : e);
|
4332 | }
|
4333 | }
|
4334 | }
|
4335 | writeFile(file, packagePath, ngccFolder) {
|
4336 | if (isDtsPath(file.path.replace(/\.map$/, ""))) {
|
4337 | super.writeFileAndBackup(file);
|
4338 | } else {
|
4339 | const relativePath = this.fs.relative(packagePath, file.path);
|
4340 | const newFilePath = this.fs.resolve(ngccFolder, relativePath);
|
4341 | this.fs.ensureDir(this.fs.dirname(newFilePath));
|
4342 | this.fs.writeFile(newFilePath, file.contents);
|
4343 | }
|
4344 | }
|
4345 | revertFile(filePath, packagePath) {
|
4346 | if (isDtsPath(filePath.replace(/\.map$/, ""))) {
|
4347 | super.revertFileAndBackup(filePath);
|
4348 | } else if (this.fs.exists(filePath)) {
|
4349 | const relativePath = this.fs.relative(packagePath, filePath);
|
4350 | const newFilePath = this.fs.resolve(packagePath, NGCC_DIRECTORY, relativePath);
|
4351 | this.fs.removeFile(newFilePath);
|
4352 | }
|
4353 | }
|
4354 | updatePackageJson(entryPoint, formatProperties, ngccFolder) {
|
4355 | if (formatProperties.length === 0) {
|
4356 | return;
|
4357 | }
|
4358 | const packageJson = entryPoint.packageJson;
|
4359 | const packageJsonPath = this.fs.join(entryPoint.path, "package.json");
|
4360 | const oldFormatProp = formatProperties[0];
|
4361 | const oldFormatPath = packageJson[oldFormatProp];
|
4362 | const oldAbsFormatPath = this.fs.resolve(entryPoint.path, oldFormatPath);
|
4363 | const newAbsFormatPath = this.fs.resolve(ngccFolder, this.fs.relative(entryPoint.packagePath, oldAbsFormatPath));
|
4364 | const newFormatPath = this.fs.relative(entryPoint.path, newAbsFormatPath);
|
4365 | const update = this.pkgJsonUpdater.createUpdate();
|
4366 | for (const formatProperty of formatProperties) {
|
4367 | if (packageJson[formatProperty] !== oldFormatPath) {
|
4368 | throw new Error(`Unable to update '${packageJsonPath}': Format properties (${formatProperties.join(", ")}) map to more than one format-path.`);
|
4369 | }
|
4370 | update.addChange([`${formatProperty}${NGCC_PROPERTY_EXTENSION}`], newFormatPath, { before: formatProperty });
|
4371 | }
|
4372 | update.writeChanges(packageJsonPath, packageJson);
|
4373 | }
|
4374 | revertPackageJson(entryPoint, formatProperties) {
|
4375 | if (formatProperties.length === 0) {
|
4376 | return;
|
4377 | }
|
4378 | const packageJson = entryPoint.packageJson;
|
4379 | const packageJsonPath = this.fs.join(entryPoint.path, "package.json");
|
4380 | const update = this.pkgJsonUpdater.createUpdate();
|
4381 | for (const formatProperty of formatProperties) {
|
4382 | update.addChange([`${formatProperty}${NGCC_PROPERTY_EXTENSION}`], void 0);
|
4383 | }
|
4384 | update.writeChanges(packageJsonPath, packageJson);
|
4385 | }
|
4386 | };
|
4387 |
|
4388 |
|
4389 | var EntryPointCollector = class {
|
4390 | constructor(fs5, config, logger, resolver) {
|
4391 | this.fs = fs5;
|
4392 | this.config = config;
|
4393 | this.logger = logger;
|
4394 | this.resolver = resolver;
|
4395 | }
|
4396 | walkDirectoryForPackages(sourceDirectory) {
|
4397 | const primaryEntryPoint = getEntryPointInfo(this.fs, this.config, this.logger, sourceDirectory, sourceDirectory);
|
4398 | if (primaryEntryPoint === INCOMPATIBLE_ENTRY_POINT) {
|
4399 | return [];
|
4400 | }
|
4401 | const entryPoints = [];
|
4402 | if (primaryEntryPoint !== NO_ENTRY_POINT) {
|
4403 | if (primaryEntryPoint !== IGNORED_ENTRY_POINT) {
|
4404 | entryPoints.push(this.resolver.getEntryPointWithDependencies(primaryEntryPoint));
|
4405 | }
|
4406 | this.collectSecondaryEntryPoints(entryPoints, sourceDirectory, sourceDirectory, this.fs.readdir(sourceDirectory));
|
4407 | if (entryPoints.some((e) => e.entryPoint.compiledByAngular)) {
|
4408 | const nestedNodeModulesPath = this.fs.join(sourceDirectory, "node_modules");
|
4409 | if (this.fs.exists(nestedNodeModulesPath)) {
|
4410 | entryPoints.push(...this.walkDirectoryForPackages(nestedNodeModulesPath));
|
4411 | }
|
4412 | }
|
4413 | return entryPoints;
|
4414 | }
|
4415 | for (const path7 of this.fs.readdir(sourceDirectory)) {
|
4416 | if (isIgnorablePath(path7)) {
|
4417 | continue;
|
4418 | }
|
4419 | const absolutePath = this.fs.resolve(sourceDirectory, path7);
|
4420 | const stat = this.fs.lstat(absolutePath);
|
4421 | if (stat.isSymbolicLink() || !stat.isDirectory()) {
|
4422 | continue;
|
4423 | }
|
4424 | entryPoints.push(...this.walkDirectoryForPackages(this.fs.join(sourceDirectory, path7)));
|
4425 | }
|
4426 | return entryPoints;
|
4427 | }
|
4428 | collectSecondaryEntryPoints(entryPoints, packagePath, directory, paths) {
|
4429 | for (const path7 of paths) {
|
4430 | if (isIgnorablePath(path7)) {
|
4431 | continue;
|
4432 | }
|
4433 | const absolutePath = this.fs.resolve(directory, path7);
|
4434 | const stat = this.fs.lstat(absolutePath);
|
4435 | if (stat.isSymbolicLink()) {
|
4436 | continue;
|
4437 | }
|
4438 | const isDirectory = stat.isDirectory();
|
4439 | if (!path7.endsWith(".js") && !isDirectory) {
|
4440 | continue;
|
4441 | }
|
4442 | const possibleEntryPointPath = isDirectory ? absolutePath : stripJsExtension(absolutePath);
|
4443 | const subEntryPoint = getEntryPointInfo(this.fs, this.config, this.logger, packagePath, possibleEntryPointPath);
|
4444 | if (isEntryPoint(subEntryPoint)) {
|
4445 | entryPoints.push(this.resolver.getEntryPointWithDependencies(subEntryPoint));
|
4446 | }
|
4447 | if (!isDirectory) {
|
4448 | continue;
|
4449 | }
|
4450 | const canContainEntryPoints = subEntryPoint === NO_ENTRY_POINT || subEntryPoint === INCOMPATIBLE_ENTRY_POINT;
|
4451 | const childPaths = this.fs.readdir(absolutePath);
|
4452 | if (canContainEntryPoints && childPaths.some((childPath) => childPath.endsWith(".js") && this.fs.stat(this.fs.resolve(absolutePath, childPath)).isFile())) {
|
4453 | continue;
|
4454 | }
|
4455 | this.collectSecondaryEntryPoints(entryPoints, packagePath, absolutePath, childPaths);
|
4456 | }
|
4457 | }
|
4458 | };
|
4459 | function stripJsExtension(filePath) {
|
4460 | return filePath.replace(/\.js$/, "");
|
4461 | }
|
4462 | function isIgnorablePath(path7) {
|
4463 | return path7.startsWith(".") || path7 === "node_modules" || path7 === NGCC_DIRECTORY;
|
4464 | }
|
4465 |
|
4466 |
|
4467 | function getPathMappingsFromTsConfig(fs5, tsConfig, projectPath) {
|
4468 | if (tsConfig !== null && tsConfig.options.baseUrl !== void 0 && tsConfig.options.paths !== void 0) {
|
4469 | return {
|
4470 | baseUrl: fs5.resolve(projectPath, tsConfig.options.baseUrl),
|
4471 | paths: tsConfig.options.paths
|
4472 | };
|
4473 | }
|
4474 | }
|
4475 |
|
4476 |
|
4477 | var TracingEntryPointFinder = class {
|
4478 | constructor(fs5, config, logger, resolver, basePath, pathMappings) {
|
4479 | this.fs = fs5;
|
4480 | this.config = config;
|
4481 | this.logger = logger;
|
4482 | this.resolver = resolver;
|
4483 | this.basePath = basePath;
|
4484 | this.pathMappings = pathMappings;
|
4485 | this.basePaths = null;
|
4486 | }
|
4487 | findEntryPoints() {
|
4488 | const unsortedEntryPoints = new Map();
|
4489 | const unprocessedPaths = this.getInitialEntryPointPaths();
|
4490 | while (unprocessedPaths.length > 0) {
|
4491 | const path7 = unprocessedPaths.shift();
|
4492 | const entryPointWithDeps = this.getEntryPointWithDeps(path7);
|
4493 | if (entryPointWithDeps === null) {
|
4494 | continue;
|
4495 | }
|
4496 | unsortedEntryPoints.set(entryPointWithDeps.entryPoint.path, entryPointWithDeps);
|
4497 | entryPointWithDeps.depInfo.dependencies.forEach((dep) => {
|
4498 | if (!unsortedEntryPoints.has(dep)) {
|
4499 | unprocessedPaths.push(dep);
|
4500 | }
|
4501 | });
|
4502 | }
|
4503 | return this.resolver.sortEntryPointsByDependency(Array.from(unsortedEntryPoints.values()));
|
4504 | }
|
4505 | getBasePaths() {
|
4506 | if (this.basePaths === null) {
|
4507 | this.basePaths = getBasePaths(this.logger, this.basePath, this.pathMappings);
|
4508 | }
|
4509 | return this.basePaths;
|
4510 | }
|
4511 | };
|
4512 |
|
4513 |
|
4514 | var ProgramBasedEntryPointFinder = class extends TracingEntryPointFinder {
|
4515 | constructor(fs5, config, logger, resolver, entryPointCollector, entryPointManifest, basePath, tsConfig, projectPath) {
|
4516 | super(fs5, config, logger, resolver, basePath, getPathMappingsFromTsConfig(fs5, tsConfig, projectPath));
|
4517 | this.entryPointCollector = entryPointCollector;
|
4518 | this.entryPointManifest = entryPointManifest;
|
4519 | this.tsConfig = tsConfig;
|
4520 | this.entryPointsWithDependencies = null;
|
4521 | }
|
4522 | getInitialEntryPointPaths() {
|
4523 | const moduleResolver = new ModuleResolver(this.fs, this.pathMappings, ["", ".ts", "/index.ts"]);
|
4524 | const host = new EsmDependencyHost(this.fs, moduleResolver);
|
4525 | const dependencies = createDependencyInfo();
|
4526 | const rootFiles = this.tsConfig.rootNames.map((rootName) => this.fs.resolve(rootName));
|
4527 | this.logger.debug(`Using the program from ${this.tsConfig.project} to seed the entry-point finding.`);
|
4528 | this.logger.debug(`Collecting dependencies from the following files:` + rootFiles.map((file) => `
|
4529 | - ${file}`));
|
4530 | host.collectDependenciesInFiles(rootFiles, dependencies);
|
4531 | return Array.from(dependencies.dependencies);
|
4532 | }
|
4533 | getEntryPointWithDeps(entryPointPath) {
|
4534 | const entryPoints = this.findOrLoadEntryPoints();
|
4535 | if (!entryPoints.has(entryPointPath)) {
|
4536 | return null;
|
4537 | }
|
4538 | const entryPointWithDeps = entryPoints.get(entryPointPath);
|
4539 | if (!entryPointWithDeps.entryPoint.compiledByAngular) {
|
4540 | return null;
|
4541 | }
|
4542 | return entryPointWithDeps;
|
4543 | }
|
4544 | findOrLoadEntryPoints() {
|
4545 | if (this.entryPointsWithDependencies === null) {
|
4546 | const entryPointsWithDependencies = this.entryPointsWithDependencies = new Map();
|
4547 | for (const basePath of this.getBasePaths()) {
|
4548 | const entryPoints = this.entryPointManifest.readEntryPointsUsingManifest(basePath) || this.walkBasePathForPackages(basePath);
|
4549 | for (const e of entryPoints) {
|
4550 | entryPointsWithDependencies.set(e.entryPoint.path, e);
|
4551 | }
|
4552 | }
|
4553 | }
|
4554 | return this.entryPointsWithDependencies;
|
4555 | }
|
4556 | walkBasePathForPackages(basePath) {
|
4557 | this.logger.debug(`No manifest found for ${basePath} so walking the directories for entry-points.`);
|
4558 | const entryPoints = trackDuration(() => this.entryPointCollector.walkDirectoryForPackages(basePath), (duration) => this.logger.debug(`Walking ${basePath} for entry-points took ${duration}s.`));
|
4559 | this.entryPointManifest.writeEntryPointManifest(basePath, entryPoints);
|
4560 | return entryPoints;
|
4561 | }
|
4562 | };
|
4563 |
|
4564 |
|
4565 | var NGCC_VERSION = "13.0.3";
|
4566 | function needsCleaning(packageJson) {
|
4567 | return Object.values(packageJson.__processed_by_ivy_ngcc__ || {}).some((value) => value !== NGCC_VERSION);
|
4568 | }
|
4569 | function cleanPackageJson(packageJson) {
|
4570 | if (packageJson.__processed_by_ivy_ngcc__ !== void 0) {
|
4571 | delete packageJson.__processed_by_ivy_ngcc__;
|
4572 | for (const prop of Object.keys(packageJson)) {
|
4573 | if (prop.endsWith(NGCC_PROPERTY_EXTENSION)) {
|
4574 | delete packageJson[prop];
|
4575 | }
|
4576 | }
|
4577 | const scripts = packageJson.scripts;
|
4578 | if (scripts !== void 0 && scripts.prepublishOnly) {
|
4579 | delete scripts.prepublishOnly;
|
4580 | if (scripts.prepublishOnly__ivy_ngcc_bak !== void 0) {
|
4581 | scripts.prepublishOnly = scripts.prepublishOnly__ivy_ngcc_bak;
|
4582 | delete scripts.prepublishOnly__ivy_ngcc_bak;
|
4583 | }
|
4584 | }
|
4585 | return true;
|
4586 | }
|
4587 | return false;
|
4588 | }
|
4589 | function hasBeenProcessed(packageJson, format) {
|
4590 | return packageJson.__processed_by_ivy_ngcc__ !== void 0 && packageJson.__processed_by_ivy_ngcc__[format] === NGCC_VERSION;
|
4591 | }
|
4592 | function markAsProcessed(pkgJsonUpdater, packageJson, packageJsonPath, formatProperties) {
|
4593 | const update = pkgJsonUpdater.createUpdate();
|
4594 | for (const prop of formatProperties) {
|
4595 | update.addChange(["__processed_by_ivy_ngcc__", prop], NGCC_VERSION, "alphabetic");
|
4596 | }
|
4597 | const oldPrepublishOnly = packageJson.scripts && packageJson.scripts.prepublishOnly;
|
4598 | const newPrepublishOnly = `node --eval "console.error('ERROR: Trying to publish a package that has been compiled by NGCC. This is not allowed.\\nPlease delete and rebuild the package, without compiling with NGCC, before attempting to publish.\\nNote that NGCC may have been run by importing this package into another project that is being built with Ivy enabled.\\n')" && exit 1`;
|
4599 | if (oldPrepublishOnly && oldPrepublishOnly !== newPrepublishOnly) {
|
4600 | update.addChange(["scripts", "prepublishOnly__ivy_ngcc_bak"], oldPrepublishOnly);
|
4601 | }
|
4602 | update.addChange(["scripts", "prepublishOnly"], newPrepublishOnly);
|
4603 | update.writeChanges(packageJsonPath, packageJson);
|
4604 | }
|
4605 |
|
4606 |
|
4607 | var TargetedEntryPointFinder = class extends TracingEntryPointFinder {
|
4608 | constructor(fs5, config, logger, resolver, basePath, pathMappings, targetPath) {
|
4609 | super(fs5, config, logger, resolver, basePath, pathMappings);
|
4610 | this.targetPath = targetPath;
|
4611 | }
|
4612 | findEntryPoints() {
|
4613 | const entryPoints = super.findEntryPoints();
|
4614 | const invalidTarget = entryPoints.invalidEntryPoints.find((i) => i.entryPoint.path === this.targetPath);
|
4615 | if (invalidTarget !== void 0) {
|
4616 | throw new Error(`The target entry-point "${invalidTarget.entryPoint.name}" has missing dependencies:
|
4617 | ` + invalidTarget.missingDependencies.map((dep) => ` - ${dep}
|
4618 | `).join(""));
|
4619 | }
|
4620 | return entryPoints;
|
4621 | }
|
4622 | targetNeedsProcessingOrCleaning(propertiesToConsider, compileAllFormats) {
|
4623 | const entryPointWithDeps = this.getEntryPointWithDeps(this.targetPath);
|
4624 | if (entryPointWithDeps === null) {
|
4625 | return false;
|
4626 | }
|
4627 | for (const property2 of propertiesToConsider) {
|
4628 | if (entryPointWithDeps.entryPoint.packageJson[property2]) {
|
4629 | if (!hasBeenProcessed(entryPointWithDeps.entryPoint.packageJson, property2)) {
|
4630 | return true;
|
4631 | }
|
4632 | if (!compileAllFormats) {
|
4633 | return false;
|
4634 | }
|
4635 | }
|
4636 | }
|
4637 | return false;
|
4638 | }
|
4639 | getInitialEntryPointPaths() {
|
4640 | return [this.targetPath];
|
4641 | }
|
4642 | getEntryPointWithDeps(entryPointPath) {
|
4643 | const packagePath = this.computePackagePath(entryPointPath);
|
4644 | const entryPoint = getEntryPointInfo(this.fs, this.config, this.logger, packagePath, entryPointPath);
|
4645 | if (!isEntryPoint(entryPoint) || !entryPoint.compiledByAngular) {
|
4646 | return null;
|
4647 | }
|
4648 | return this.resolver.getEntryPointWithDependencies(entryPoint);
|
4649 | }
|
4650 | computePackagePath(entryPointPath) {
|
4651 | if (this.isPathContainedBy(this.basePath, entryPointPath)) {
|
4652 | const packagePath = this.computePackagePathFromContainingPath(entryPointPath, this.basePath);
|
4653 | if (packagePath !== null) {
|
4654 | return packagePath;
|
4655 | }
|
4656 | }
|
4657 | for (const basePath of this.getBasePaths()) {
|
4658 | if (this.isPathContainedBy(basePath, entryPointPath)) {
|
4659 | const packagePath = this.computePackagePathFromContainingPath(entryPointPath, basePath);
|
4660 | if (packagePath !== null) {
|
4661 | return packagePath;
|
4662 | }
|
4663 | break;
|
4664 | }
|
4665 | }
|
4666 | return this.computePackagePathFromNearestNodeModules(entryPointPath);
|
4667 | }
|
4668 | isPathContainedBy(base, test) {
|
4669 | return test === base || test.startsWith(base) && !this.fs.relative(base, test).startsWith("..");
|
4670 | }
|
4671 | computePackagePathFromContainingPath(entryPointPath, containingPath) {
|
4672 | let packagePath = containingPath;
|
4673 | const segments = this.splitPath(this.fs.relative(containingPath, entryPointPath));
|
4674 | let nodeModulesIndex = segments.lastIndexOf("node_modules");
|
4675 | if (nodeModulesIndex === -1) {
|
4676 | if (this.fs.exists(this.fs.join(packagePath, "package.json"))) {
|
4677 | return packagePath;
|
4678 | }
|
4679 | }
|
4680 | while (nodeModulesIndex >= 0) {
|
4681 | packagePath = this.fs.join(packagePath, segments.shift());
|
4682 | nodeModulesIndex--;
|
4683 | }
|
4684 | for (const segment of segments) {
|
4685 | packagePath = this.fs.join(packagePath, segment);
|
4686 | if (this.fs.exists(this.fs.join(packagePath, "package.json"))) {
|
4687 | return packagePath;
|
4688 | }
|
4689 | }
|
4690 | return null;
|
4691 | }
|
4692 | computePackagePathFromNearestNodeModules(entryPointPath) {
|
4693 | let packagePath = entryPointPath;
|
4694 | let scopedPackagePath = packagePath;
|
4695 | let containerPath = this.fs.dirname(packagePath);
|
4696 | while (!this.fs.isRoot(containerPath) && !containerPath.endsWith("node_modules")) {
|
4697 | scopedPackagePath = packagePath;
|
4698 | packagePath = containerPath;
|
4699 | containerPath = this.fs.dirname(containerPath);
|
4700 | }
|
4701 | if (this.fs.exists(this.fs.join(packagePath, "package.json"))) {
|
4702 | return packagePath;
|
4703 | } else if (this.fs.basename(packagePath).startsWith("@") && this.fs.exists(this.fs.join(scopedPackagePath, "package.json"))) {
|
4704 | return scopedPackagePath;
|
4705 | } else {
|
4706 | return entryPointPath;
|
4707 | }
|
4708 | }
|
4709 | splitPath(path7) {
|
4710 | const segments = [];
|
4711 | let container = this.fs.dirname(path7);
|
4712 | while (path7 !== container) {
|
4713 | segments.unshift(this.fs.basename(path7));
|
4714 | path7 = container;
|
4715 | container = this.fs.dirname(container);
|
4716 | }
|
4717 | return segments;
|
4718 | }
|
4719 | };
|
4720 |
|
4721 |
|
4722 | var DtsProcessing;
|
4723 | (function(DtsProcessing2) {
|
4724 | DtsProcessing2[DtsProcessing2["Yes"] = 0] = "Yes";
|
4725 | DtsProcessing2[DtsProcessing2["No"] = 1] = "No";
|
4726 | DtsProcessing2[DtsProcessing2["Only"] = 2] = "Only";
|
4727 | })(DtsProcessing || (DtsProcessing = {}));
|
4728 | var TaskDependencies = Map;
|
4729 |
|
4730 |
|
4731 | var stringifyTask = (task) => `{entryPoint: ${task.entryPoint.name}, formatProperty: ${task.formatProperty}, processDts: ${DtsProcessing[task.processDts]}}`;
|
4732 | function computeTaskDependencies(tasks, graph) {
|
4733 | const dependencies = new TaskDependencies();
|
4734 | const candidateDependencies = new Map();
|
4735 | tasks.forEach((task) => {
|
4736 | const entryPointPath = task.entryPoint.path;
|
4737 | const deps = graph.dependenciesOf(entryPointPath);
|
4738 | const taskDependencies = deps.filter((dep) => candidateDependencies.has(dep)).map((dep) => candidateDependencies.get(dep));
|
4739 | if (taskDependencies.length > 0) {
|
4740 | for (const dependency of taskDependencies) {
|
4741 | const taskDependents = getDependentsSet(dependencies, dependency);
|
4742 | taskDependents.add(task);
|
4743 | }
|
4744 | }
|
4745 | if (task.processDts !== DtsProcessing.No) {
|
4746 | if (candidateDependencies.has(entryPointPath)) {
|
4747 | const otherTask = candidateDependencies.get(entryPointPath);
|
4748 | throw new Error(`Invariant violated: Multiple tasks are assigned generating typings for '${entryPointPath}':
|
4749 | - ${stringifyTask(otherTask)}
|
4750 | - ${stringifyTask(task)}`);
|
4751 | }
|
4752 | candidateDependencies.set(entryPointPath, task);
|
4753 | } else {
|
4754 | if (candidateDependencies.has(entryPointPath)) {
|
4755 | const typingsTask = candidateDependencies.get(entryPointPath);
|
4756 | const typingsTaskDependents = getDependentsSet(dependencies, typingsTask);
|
4757 | typingsTaskDependents.add(task);
|
4758 | }
|
4759 | }
|
4760 | });
|
4761 | return dependencies;
|
4762 | }
|
4763 | function getDependentsSet(map, task) {
|
4764 | if (!map.has(task)) {
|
4765 | map.set(task, new Set());
|
4766 | }
|
4767 | return map.get(task);
|
4768 | }
|
4769 | function getBlockedTasks(dependencies) {
|
4770 | const blockedTasks = new Map();
|
4771 | for (const [dependency, dependents] of dependencies) {
|
4772 | for (const dependent of dependents) {
|
4773 | const dependentSet = getDependentsSet(blockedTasks, dependent);
|
4774 | dependentSet.add(dependency);
|
4775 | }
|
4776 | }
|
4777 | return blockedTasks;
|
4778 | }
|
4779 | function sortTasksByPriority(tasks, dependencies) {
|
4780 | const priorityPerTask = new Map();
|
4781 | const computePriority = (task, idx) => [dependencies.has(task) ? dependencies.get(task).size : 0, idx];
|
4782 | tasks.forEach((task, i) => priorityPerTask.set(task, computePriority(task, i)));
|
4783 | return tasks.slice().sort((task1, task2) => {
|
4784 | const [p1, idx1] = priorityPerTask.get(task1);
|
4785 | const [p2, idx2] = priorityPerTask.get(task2);
|
4786 | return p2 - p1 || idx1 - idx2;
|
4787 | });
|
4788 | }
|
4789 |
|
4790 |
|
4791 | var BaseTaskQueue = class {
|
4792 | constructor(logger, tasks, dependencies) {
|
4793 | this.logger = logger;
|
4794 | this.tasks = tasks;
|
4795 | this.dependencies = dependencies;
|
4796 | this.inProgressTasks = new Set();
|
4797 | this.tasksToSkip = new Map();
|
4798 | }
|
4799 | get allTasksCompleted() {
|
4800 | return this.tasks.length === 0 && this.inProgressTasks.size === 0;
|
4801 | }
|
4802 | getNextTask() {
|
4803 | let nextTask = this.computeNextTask();
|
4804 | while (nextTask !== null) {
|
4805 | if (!this.tasksToSkip.has(nextTask)) {
|
4806 | break;
|
4807 | }
|
4808 | this.markAsCompleted(nextTask);
|
4809 | const failedTask = this.tasksToSkip.get(nextTask);
|
4810 | this.logger.warn(`Skipping processing of ${nextTask.entryPoint.name} because its dependency ${failedTask.entryPoint.name} failed to compile.`);
|
4811 | nextTask = this.computeNextTask();
|
4812 | }
|
4813 | return nextTask;
|
4814 | }
|
4815 | markAsCompleted(task) {
|
4816 | if (!this.inProgressTasks.has(task)) {
|
4817 | throw new Error(`Trying to mark task that was not in progress as completed: ${stringifyTask(task)}`);
|
4818 | }
|
4819 | this.inProgressTasks.delete(task);
|
4820 | }
|
4821 | markAsFailed(task) {
|
4822 | if (this.dependencies.has(task)) {
|
4823 | for (const dependentTask of this.dependencies.get(task)) {
|
4824 | this.skipDependentTasks(dependentTask, task);
|
4825 | }
|
4826 | }
|
4827 | }
|
4828 | markAsUnprocessed(task) {
|
4829 | if (!this.inProgressTasks.has(task)) {
|
4830 | throw new Error(`Trying to mark task that was not in progress as unprocessed: ${stringifyTask(task)}`);
|
4831 | }
|
4832 | this.inProgressTasks.delete(task);
|
4833 | this.tasks.unshift(task);
|
4834 | }
|
4835 | toString() {
|
4836 | const inProgTasks = Array.from(this.inProgressTasks);
|
4837 | return `${this.constructor.name}
|
4838 | All tasks completed: ${this.allTasksCompleted}
|
4839 | Unprocessed tasks (${this.tasks.length}): ${this.stringifyTasks(this.tasks, " ")}
|
4840 | In-progress tasks (${inProgTasks.length}): ${this.stringifyTasks(inProgTasks, " ")}`;
|
4841 | }
|
4842 | skipDependentTasks(task, failedTask) {
|
4843 | this.tasksToSkip.set(task, failedTask);
|
4844 | if (this.dependencies.has(task)) {
|
4845 | for (const dependentTask of this.dependencies.get(task)) {
|
4846 | this.skipDependentTasks(dependentTask, failedTask);
|
4847 | }
|
4848 | }
|
4849 | }
|
4850 | stringifyTasks(tasks, indentation) {
|
4851 | return tasks.map((task) => `
|
4852 | ${indentation}- ${stringifyTask(task)}`).join("");
|
4853 | }
|
4854 | };
|
4855 |
|
4856 |
|
4857 | var ParallelTaskQueue = class extends BaseTaskQueue {
|
4858 | constructor(logger, tasks, dependencies) {
|
4859 | super(logger, sortTasksByPriority(tasks, dependencies), dependencies);
|
4860 | this.blockedTasks = getBlockedTasks(dependencies);
|
4861 | }
|
4862 | computeNextTask() {
|
4863 | const nextTaskIdx = this.tasks.findIndex((task) => !this.blockedTasks.has(task));
|
4864 | if (nextTaskIdx === -1)
|
4865 | return null;
|
4866 | const nextTask = this.tasks[nextTaskIdx];
|
4867 | this.tasks.splice(nextTaskIdx, 1);
|
4868 | this.inProgressTasks.add(nextTask);
|
4869 | return nextTask;
|
4870 | }
|
4871 | markAsCompleted(task) {
|
4872 | super.markAsCompleted(task);
|
4873 | if (!this.dependencies.has(task)) {
|
4874 | return;
|
4875 | }
|
4876 | for (const dependentTask of this.dependencies.get(task)) {
|
4877 | if (this.blockedTasks.has(dependentTask)) {
|
4878 | const blockingTasks = this.blockedTasks.get(dependentTask);
|
4879 | blockingTasks.delete(task);
|
4880 | if (blockingTasks.size === 0) {
|
4881 | this.blockedTasks.delete(dependentTask);
|
4882 | }
|
4883 | }
|
4884 | }
|
4885 | }
|
4886 | toString() {
|
4887 | return `${super.toString()}
|
4888 | Blocked tasks (${this.blockedTasks.size}): ${this.stringifyBlockedTasks(" ")}`;
|
4889 | }
|
4890 | stringifyBlockedTasks(indentation) {
|
4891 | return Array.from(this.blockedTasks).map(([task, blockingTasks]) => `
|
4892 | ${indentation}- ${stringifyTask(task)} (${blockingTasks.size}): ` + this.stringifyTasks(Array.from(blockingTasks), `${indentation} `)).join("");
|
4893 | }
|
4894 | };
|
4895 |
|
4896 |
|
4897 | var SerialTaskQueue = class extends BaseTaskQueue {
|
4898 | computeNextTask() {
|
4899 | const nextTask = this.tasks.shift() || null;
|
4900 | if (nextTask) {
|
4901 | if (this.inProgressTasks.size > 0) {
|
4902 | const inProgressTask = this.inProgressTasks.values().next().value;
|
4903 | throw new Error("Trying to get next task, while there is already a task in progress: " + stringifyTask(inProgressTask));
|
4904 | }
|
4905 | this.inProgressTasks.add(nextTask);
|
4906 | }
|
4907 | return nextTask;
|
4908 | }
|
4909 | };
|
4910 |
|
4911 |
|
4912 | function isLocalDirectory(fs5, path7) {
|
4913 | if (fs5.exists(path7)) {
|
4914 | const stat = fs5.lstat(path7);
|
4915 | return stat.isDirectory();
|
4916 | } else {
|
4917 | return false;
|
4918 | }
|
4919 | }
|
4920 |
|
4921 |
|
4922 | var PackageJsonCleaner = class {
|
4923 | constructor(fs5) {
|
4924 | this.fs = fs5;
|
4925 | }
|
4926 | canClean(_path, basename6) {
|
4927 | return basename6 === "package.json";
|
4928 | }
|
4929 | clean(path7, _basename) {
|
4930 | const packageJson = JSON.parse(this.fs.readFile(path7));
|
4931 | if (cleanPackageJson(packageJson)) {
|
4932 | this.fs.writeFile(path7, `${JSON.stringify(packageJson, null, 2)}
|
4933 | `);
|
4934 | }
|
4935 | }
|
4936 | };
|
4937 | var NgccDirectoryCleaner = class {
|
4938 | constructor(fs5) {
|
4939 | this.fs = fs5;
|
4940 | }
|
4941 | canClean(path7, basename6) {
|
4942 | return basename6 === NGCC_DIRECTORY && isLocalDirectory(this.fs, path7);
|
4943 | }
|
4944 | clean(path7, _basename) {
|
4945 | this.fs.removeDeep(path7);
|
4946 | }
|
4947 | };
|
4948 | var BackupFileCleaner = class {
|
4949 | constructor(fs5) {
|
4950 | this.fs = fs5;
|
4951 | }
|
4952 | canClean(path7, basename6) {
|
4953 | return this.fs.extname(basename6) === NGCC_BACKUP_EXTENSION && this.fs.exists(absoluteFrom(path7.replace(NGCC_BACKUP_EXTENSION, "")));
|
4954 | }
|
4955 | clean(path7, _basename) {
|
4956 | this.fs.moveFile(path7, absoluteFrom(path7.replace(NGCC_BACKUP_EXTENSION, "")));
|
4957 | }
|
4958 | };
|
4959 |
|
4960 |
|
4961 | var PackageCleaner = class {
|
4962 | constructor(fs5, cleaners) {
|
4963 | this.fs = fs5;
|
4964 | this.cleaners = cleaners;
|
4965 | }
|
4966 | clean(directory) {
|
4967 | const basenames = this.fs.readdir(directory);
|
4968 | for (const basename6 of basenames) {
|
4969 | if (basename6 === "node_modules") {
|
4970 | continue;
|
4971 | }
|
4972 | const path7 = this.fs.resolve(directory, basename6);
|
4973 | for (const cleaner of this.cleaners) {
|
4974 | if (cleaner.canClean(path7, basename6)) {
|
4975 | cleaner.clean(path7, basename6);
|
4976 | break;
|
4977 | }
|
4978 | }
|
4979 | if (isLocalDirectory(this.fs, path7)) {
|
4980 | this.clean(path7);
|
4981 | }
|
4982 | }
|
4983 | }
|
4984 | };
|
4985 | function cleanOutdatedPackages(fileSystem, entryPoints) {
|
4986 | const packagesToClean = new Set();
|
4987 | for (const entryPoint of entryPoints) {
|
4988 | if (needsCleaning(entryPoint.packageJson)) {
|
4989 | packagesToClean.add(entryPoint.packagePath);
|
4990 | }
|
4991 | }
|
4992 | const cleaner = new PackageCleaner(fileSystem, [
|
4993 | new PackageJsonCleaner(fileSystem),
|
4994 | new NgccDirectoryCleaner(fileSystem),
|
4995 | new BackupFileCleaner(fileSystem)
|
4996 | ]);
|
4997 | for (const packagePath of packagesToClean) {
|
4998 | cleaner.clean(packagePath);
|
4999 | }
|
5000 | return packagesToClean.size > 0;
|
5001 | }
|
5002 |
|
5003 |
|
5004 | function getAnalyzeEntryPointsFn(logger, finder, fileSystem, supportedPropertiesToConsider, typingsOnly, compileAllFormats, propertiesToConsider, inParallel) {
|
5005 | return () => {
|
5006 | logger.debug("Analyzing entry-points...");
|
5007 | const startTime = Date.now();
|
5008 | let entryPointInfo = finder.findEntryPoints();
|
5009 | const cleaned = cleanOutdatedPackages(fileSystem, entryPointInfo.entryPoints);
|
5010 | if (cleaned) {
|
5011 | entryPointInfo = finder.findEntryPoints();
|
5012 | }
|
5013 | const { entryPoints, invalidEntryPoints, graph } = entryPointInfo;
|
5014 | logInvalidEntryPoints(logger, invalidEntryPoints);
|
5015 | const unprocessableEntryPointPaths = [];
|
5016 | const tasks = [];
|
5017 | for (const entryPoint of entryPoints) {
|
5018 | const packageJson = entryPoint.packageJson;
|
5019 | const { propertiesToProcess, equivalentPropertiesMap } = getPropertiesToProcess(packageJson, supportedPropertiesToConsider, compileAllFormats, typingsOnly);
|
5020 | if (propertiesToProcess.length === 0) {
|
5021 | unprocessableEntryPointPaths.push(entryPoint.path);
|
5022 | continue;
|
5023 | }
|
5024 | const hasProcessedTypings = hasBeenProcessed(packageJson, "typings");
|
5025 | if (hasProcessedTypings && typingsOnly) {
|
5026 | logger.debug(`Skipping ${entryPoint.name} : typings have already been processed.`);
|
5027 | continue;
|
5028 | }
|
5029 | let processDts = hasProcessedTypings ? DtsProcessing.No : typingsOnly ? DtsProcessing.Only : DtsProcessing.Yes;
|
5030 | for (const formatProperty of propertiesToProcess) {
|
5031 | if (hasBeenProcessed(entryPoint.packageJson, formatProperty)) {
|
5032 | logger.debug(`Skipping ${entryPoint.name} : ${formatProperty} (already compiled).`);
|
5033 | continue;
|
5034 | }
|
5035 | const formatPropertiesToMarkAsProcessed = equivalentPropertiesMap.get(formatProperty);
|
5036 | tasks.push({ entryPoint, formatProperty, formatPropertiesToMarkAsProcessed, processDts });
|
5037 | processDts = DtsProcessing.No;
|
5038 | }
|
5039 | }
|
5040 | if (unprocessableEntryPointPaths.length > 0) {
|
5041 | throw new Error(`Unable to process any formats for the following entry-points (tried ${propertiesToConsider.join(", ")}): ` + unprocessableEntryPointPaths.map((path7) => `
|
5042 | - ${path7}`).join(""));
|
5043 | }
|
5044 | const duration = Math.round((Date.now() - startTime) / 100) / 10;
|
5045 | logger.debug(`Analyzed ${entryPoints.length} entry-points in ${duration}s. (Total tasks: ${tasks.length})`);
|
5046 | return getTaskQueue(logger, inParallel, tasks, graph);
|
5047 | };
|
5048 | }
|
5049 | function logInvalidEntryPoints(logger, invalidEntryPoints) {
|
5050 | invalidEntryPoints.forEach((invalidEntryPoint) => {
|
5051 | logger.debug(`Invalid entry-point ${invalidEntryPoint.entryPoint.path}.`, `It is missing required dependencies:
|
5052 | ` + invalidEntryPoint.missingDependencies.map((dep) => ` - ${dep}`).join("\n"));
|
5053 | });
|
5054 | }
|
5055 | function getPropertiesToProcess(packageJson, propertiesToConsider, compileAllFormats, typingsOnly) {
|
5056 | const formatPathsToConsider = new Set();
|
5057 | const propertiesToProcess = [];
|
5058 | for (const prop of propertiesToConsider) {
|
5059 | const formatPath = packageJson[prop];
|
5060 | if (typeof formatPath !== "string")
|
5061 | continue;
|
5062 | if (formatPathsToConsider.has(formatPath))
|
5063 | continue;
|
5064 | formatPathsToConsider.add(formatPath);
|
5065 | propertiesToProcess.push(prop);
|
5066 | if (!compileAllFormats)
|
5067 | break;
|
5068 | }
|
5069 | const formatPathToProperties = {};
|
5070 | for (const prop of SUPPORTED_FORMAT_PROPERTIES) {
|
5071 | const formatPath = packageJson[prop];
|
5072 | if (typeof formatPath !== "string")
|
5073 | continue;
|
5074 | if (!formatPathsToConsider.has(formatPath))
|
5075 | continue;
|
5076 | const list = formatPathToProperties[formatPath] || (formatPathToProperties[formatPath] = []);
|
5077 | list.push(prop);
|
5078 | }
|
5079 | const equivalentPropertiesMap = new Map();
|
5080 | for (const prop of propertiesToConsider) {
|
5081 | const formatPath = packageJson[prop];
|
5082 | const equivalentProperties = typingsOnly ? [] : formatPathToProperties[formatPath];
|
5083 | equivalentPropertiesMap.set(prop, equivalentProperties);
|
5084 | }
|
5085 | return { propertiesToProcess, equivalentPropertiesMap };
|
5086 | }
|
5087 | function getTaskQueue(logger, inParallel, tasks, graph) {
|
5088 | const dependencies = computeTaskDependencies(tasks, graph);
|
5089 | return inParallel ? new ParallelTaskQueue(logger, tasks, dependencies) : new SerialTaskQueue(logger, tasks, dependencies);
|
5090 | }
|
5091 |
|
5092 |
|
5093 | import cluster2 from "cluster";
|
5094 | import module3 from "module";
|
5095 |
|
5096 |
|
5097 | import cluster from "cluster";
|
5098 | var Deferred = class {
|
5099 | constructor() {
|
5100 | this.promise = new Promise((resolve5, reject) => {
|
5101 | this.resolve = resolve5;
|
5102 | this.reject = reject;
|
5103 | });
|
5104 | }
|
5105 | };
|
5106 | var sendMessageToWorker = (workerId, msg) => {
|
5107 | if (!cluster.isMaster) {
|
5108 | throw new Error("Unable to send message to worker process: Sender is not the master process.");
|
5109 | }
|
5110 | const worker = cluster.workers[workerId];
|
5111 | if (worker === void 0 || worker.isDead() || !worker.isConnected()) {
|
5112 | throw new Error("Unable to send message to worker process: Recipient does not exist or has disconnected.");
|
5113 | }
|
5114 | return new Promise((resolve5, reject) => {
|
5115 | worker.send(msg, (err) => err === null ? resolve5() : reject(err));
|
5116 | });
|
5117 | };
|
5118 |
|
5119 |
|
5120 | var ClusterMaster = class {
|
5121 | constructor(maxWorkerCount, fileSystem, logger, fileWriter, pkgJsonUpdater, analyzeEntryPoints, createTaskCompletedCallback) {
|
5122 | this.maxWorkerCount = maxWorkerCount;
|
5123 | this.fileSystem = fileSystem;
|
5124 | this.logger = logger;
|
5125 | this.fileWriter = fileWriter;
|
5126 | this.pkgJsonUpdater = pkgJsonUpdater;
|
5127 | this.finishedDeferred = new Deferred();
|
5128 | this.processingStartTime = -1;
|
5129 | this.taskAssignments = new Map();
|
5130 | this.remainingRespawnAttempts = 3;
|
5131 | if (!cluster2.isMaster) {
|
5132 | throw new Error("Tried to instantiate `ClusterMaster` on a worker process.");
|
5133 | }
|
5134 | cluster2.setupMaster({ exec: getClusterWorkerScriptPath(fileSystem) });
|
5135 | this.taskQueue = analyzeEntryPoints();
|
5136 | this.onTaskCompleted = createTaskCompletedCallback(this.taskQueue);
|
5137 | }
|
5138 | run() {
|
5139 | if (this.taskQueue.allTasksCompleted) {
|
5140 | return Promise.resolve();
|
5141 | }
|
5142 | this.logger.info('Processing legacy "View Engine" libraries:');
|
5143 | cluster2.on("message", this.wrapEventHandler((worker, msg) => this.onWorkerMessage(worker.id, msg)));
|
5144 | cluster2.on("exit", this.wrapEventHandler((worker, code, signal) => this.onWorkerExit(worker, code, signal)));
|
5145 | cluster2.fork();
|
5146 | return this.finishedDeferred.promise.then(() => this.stopWorkers(), (err) => {
|
5147 | this.stopWorkers();
|
5148 | return Promise.reject(err);
|
5149 | });
|
5150 | }
|
5151 | maybeDistributeWork() {
|
5152 | let isWorkerAvailable = false;
|
5153 | if (this.taskQueue.allTasksCompleted) {
|
5154 | const duration = Math.round((Date.now() - this.processingStartTime) / 100) / 10;
|
5155 | this.logger.debug(`Processed tasks in ${duration}s.`);
|
5156 | this.logger.info("Encourage the library authors to publish an Ivy distribution.");
|
5157 | return this.finishedDeferred.resolve();
|
5158 | }
|
5159 | for (const [workerId, assignedTask] of Array.from(this.taskAssignments)) {
|
5160 | if (assignedTask !== null) {
|
5161 | continue;
|
5162 | } else {
|
5163 | isWorkerAvailable = true;
|
5164 | }
|
5165 | const task = this.taskQueue.getNextTask();
|
5166 | if (task === null) {
|
5167 | break;
|
5168 | }
|
5169 | this.taskAssignments.set(workerId, { task });
|
5170 | sendMessageToWorker(workerId, { type: "process-task", task });
|
5171 | isWorkerAvailable = false;
|
5172 | }
|
5173 | if (!isWorkerAvailable) {
|
5174 | const spawnedWorkerCount = Object.keys(cluster2.workers).length;
|
5175 | if (spawnedWorkerCount < this.maxWorkerCount) {
|
5176 | this.logger.debug("Spawning another worker process as there is more work to be done.");
|
5177 | cluster2.fork();
|
5178 | } else {
|
5179 | this.logger.debug(`All ${spawnedWorkerCount} workers are currently busy and cannot take on more work.`);
|
5180 | }
|
5181 | } else {
|
5182 | const busyWorkers = Array.from(this.taskAssignments).filter(([_workerId, task]) => task !== null).map(([workerId]) => workerId);
|
5183 | const totalWorkerCount = this.taskAssignments.size;
|
5184 | const idleWorkerCount = totalWorkerCount - busyWorkers.length;
|
5185 | this.logger.debug(`No assignments for ${idleWorkerCount} idle (out of ${totalWorkerCount} total) workers. Busy workers: ${busyWorkers.join(", ")}`);
|
5186 | if (busyWorkers.length === 0) {
|
5187 | throw new Error(`There are still unprocessed tasks in the queue and no tasks are currently in progress, yet the queue did not return any available tasks: ${this.taskQueue}`);
|
5188 | }
|
5189 | }
|
5190 | }
|
5191 | onWorkerExit(worker, code, signal) {
|
5192 | if (worker.exitedAfterDisconnect)
|
5193 | return;
|
5194 | const assignment = this.taskAssignments.get(worker.id);
|
5195 | this.taskAssignments.delete(worker.id);
|
5196 | this.logger.warn(`Worker #${worker.id} exited unexpectedly (code: ${code} | signal: ${signal}).
|
5197 | Current task: ${assignment == null ? "-" : stringifyTask(assignment.task)}
|
5198 | Current phase: ${assignment == null ? "-" : assignment.files == null ? "compiling" : "writing files"}`);
|
5199 | if (assignment == null) {
|
5200 | this.logger.debug(`Spawning another worker process to replace #${worker.id}...`);
|
5201 | cluster2.fork();
|
5202 | } else {
|
5203 | const { task, files } = assignment;
|
5204 | if (files != null) {
|
5205 | this.logger.debug(`Reverting ${files.length} transformed files...`);
|
5206 | this.fileWriter.revertBundle(task.entryPoint, files, task.formatPropertiesToMarkAsProcessed);
|
5207 | }
|
5208 | this.taskQueue.markAsUnprocessed(task);
|
5209 | const spawnedWorkerCount = Object.keys(cluster2.workers).length;
|
5210 | if (spawnedWorkerCount > 0) {
|
5211 | this.logger.debug(`Not spawning another worker process to replace #${worker.id}. Continuing with ${spawnedWorkerCount} workers...`);
|
5212 | this.maybeDistributeWork();
|
5213 | } else if (this.remainingRespawnAttempts > 0) {
|
5214 | this.logger.debug(`Spawning another worker process to replace #${worker.id}...`);
|
5215 | this.remainingRespawnAttempts--;
|
5216 | cluster2.fork();
|
5217 | } else {
|
5218 | throw new Error("All worker processes crashed and attempts to re-spawn them failed. Please check your system and ensure there is enough memory available.");
|
5219 | }
|
5220 | }
|
5221 | }
|
5222 | onWorkerMessage(workerId, msg) {
|
5223 | if (msg.type === "ready") {
|
5224 | this.onWorkerReady(workerId);
|
5225 | return;
|
5226 | }
|
5227 | if (!this.taskAssignments.has(workerId)) {
|
5228 | const knownWorkers = Array.from(this.taskAssignments.keys());
|
5229 | throw new Error(`Received message from unknown worker #${workerId} (known workers: ${knownWorkers.join(", ")}): ${JSON.stringify(msg)}`);
|
5230 | }
|
5231 | switch (msg.type) {
|
5232 | case "error":
|
5233 | throw new Error(`Error on worker #${workerId}: ${msg.error}`);
|
5234 | case "task-completed":
|
5235 | return this.onWorkerTaskCompleted(workerId, msg);
|
5236 | case "transformed-files":
|
5237 | return this.onWorkerTransformedFiles(workerId, msg);
|
5238 | case "update-package-json":
|
5239 | return this.onWorkerUpdatePackageJson(workerId, msg);
|
5240 | default:
|
5241 | throw new Error(`Invalid message received from worker #${workerId}: ${JSON.stringify(msg)}`);
|
5242 | }
|
5243 | }
|
5244 | onWorkerReady(workerId) {
|
5245 | if (this.taskAssignments.has(workerId)) {
|
5246 | throw new Error(`Invariant violated: Worker #${workerId} came online more than once.`);
|
5247 | }
|
5248 | if (this.processingStartTime === -1) {
|
5249 | this.logger.debug("Processing tasks...");
|
5250 | this.processingStartTime = Date.now();
|
5251 | }
|
5252 | this.taskAssignments.set(workerId, null);
|
5253 | this.maybeDistributeWork();
|
5254 | }
|
5255 | onWorkerTaskCompleted(workerId, msg) {
|
5256 | const assignment = this.taskAssignments.get(workerId) || null;
|
5257 | if (assignment === null) {
|
5258 | throw new Error(`Expected worker #${workerId} to have a task assigned, while handling message: ` + JSON.stringify(msg));
|
5259 | }
|
5260 | this.onTaskCompleted(assignment.task, msg.outcome, msg.message);
|
5261 | this.taskQueue.markAsCompleted(assignment.task);
|
5262 | this.taskAssignments.set(workerId, null);
|
5263 | this.maybeDistributeWork();
|
5264 | }
|
5265 | onWorkerTransformedFiles(workerId, msg) {
|
5266 | const assignment = this.taskAssignments.get(workerId) || null;
|
5267 | if (assignment === null) {
|
5268 | throw new Error(`Expected worker #${workerId} to have a task assigned, while handling message: ` + JSON.stringify(msg));
|
5269 | }
|
5270 | const oldFiles = assignment.files;
|
5271 | const newFiles = msg.files;
|
5272 | if (oldFiles !== void 0) {
|
5273 | throw new Error(`Worker #${workerId} reported transformed files more than once.
|
5274 | Old files (${oldFiles.length}): [${oldFiles.join(", ")}]
|
5275 | New files (${newFiles.length}): [${newFiles.join(", ")}]
|
5276 | `);
|
5277 | }
|
5278 | assignment.files = newFiles;
|
5279 | }
|
5280 | onWorkerUpdatePackageJson(workerId, msg) {
|
5281 | const assignment = this.taskAssignments.get(workerId) || null;
|
5282 | if (assignment === null) {
|
5283 | throw new Error(`Expected worker #${workerId} to have a task assigned, while handling message: ` + JSON.stringify(msg));
|
5284 | }
|
5285 | const entryPoint = assignment.task.entryPoint;
|
5286 | const expectedPackageJsonPath = this.fileSystem.resolve(entryPoint.path, "package.json");
|
5287 | if (expectedPackageJsonPath !== msg.packageJsonPath) {
|
5288 | throw new Error(`Received '${msg.type}' message from worker #${workerId} for '${msg.packageJsonPath}', but was expecting '${expectedPackageJsonPath}' (based on task assignment).`);
|
5289 | }
|
5290 | this.pkgJsonUpdater.writeChanges(msg.changes, msg.packageJsonPath, entryPoint.packageJson);
|
5291 | }
|
5292 | stopWorkers() {
|
5293 | const workers = Object.values(cluster2.workers);
|
5294 | this.logger.debug(`Stopping ${workers.length} workers...`);
|
5295 | cluster2.removeAllListeners();
|
5296 | workers.forEach((worker) => worker.kill());
|
5297 | }
|
5298 | wrapEventHandler(fn) {
|
5299 | return async (...args) => {
|
5300 | try {
|
5301 | await fn(...args);
|
5302 | } catch (err) {
|
5303 | this.finishedDeferred.reject(err);
|
5304 | }
|
5305 | };
|
5306 | }
|
5307 | };
|
5308 | function getClusterWorkerScriptPath(fileSystem) {
|
5309 | const requireFn = typeof __require !== "undefined" ? __require : module3.createRequire(__ESM_IMPORT_META_URL__);
|
5310 | const workerScriptPath = requireFn.resolve("@angular/compiler-cli/ngcc/src/execution/cluster/ngcc_cluster_worker");
|
5311 | return fileSystem.resolve(workerScriptPath);
|
5312 | }
|
5313 |
|
5314 |
|
5315 | var ClusterExecutor = class {
|
5316 | constructor(workerCount, fileSystem, logger, fileWriter, pkgJsonUpdater, lockFile, createTaskCompletedCallback) {
|
5317 | this.workerCount = workerCount;
|
5318 | this.fileSystem = fileSystem;
|
5319 | this.logger = logger;
|
5320 | this.fileWriter = fileWriter;
|
5321 | this.pkgJsonUpdater = pkgJsonUpdater;
|
5322 | this.lockFile = lockFile;
|
5323 | this.createTaskCompletedCallback = createTaskCompletedCallback;
|
5324 | }
|
5325 | async execute(analyzeEntryPoints, _createCompileFn) {
|
5326 | return this.lockFile.lock(async () => {
|
5327 | this.logger.debug(`Running ngcc on ${this.constructor.name} (using ${this.workerCount} worker processes).`);
|
5328 | const master = new ClusterMaster(this.workerCount, this.fileSystem, this.logger, this.fileWriter, this.pkgJsonUpdater, analyzeEntryPoints, this.createTaskCompletedCallback);
|
5329 | return await master.run();
|
5330 | });
|
5331 | }
|
5332 | };
|
5333 |
|
5334 |
|
5335 | import ts61 from "typescript";
|
5336 |
|
5337 |
|
5338 | var ErrorCode;
|
5339 | (function(ErrorCode2) {
|
5340 | ErrorCode2[ErrorCode2["DECORATOR_ARG_NOT_LITERAL"] = 1001] = "DECORATOR_ARG_NOT_LITERAL";
|
5341 | ErrorCode2[ErrorCode2["DECORATOR_ARITY_WRONG"] = 1002] = "DECORATOR_ARITY_WRONG";
|
5342 | ErrorCode2[ErrorCode2["DECORATOR_NOT_CALLED"] = 1003] = "DECORATOR_NOT_CALLED";
|
5343 | ErrorCode2[ErrorCode2["DECORATOR_ON_ANONYMOUS_CLASS"] = 1004] = "DECORATOR_ON_ANONYMOUS_CLASS";
|
5344 | ErrorCode2[ErrorCode2["DECORATOR_UNEXPECTED"] = 1005] = "DECORATOR_UNEXPECTED";
|
5345 | ErrorCode2[ErrorCode2["DECORATOR_COLLISION"] = 1006] = "DECORATOR_COLLISION";
|
5346 | ErrorCode2[ErrorCode2["VALUE_HAS_WRONG_TYPE"] = 1010] = "VALUE_HAS_WRONG_TYPE";
|
5347 | ErrorCode2[ErrorCode2["VALUE_NOT_LITERAL"] = 1011] = "VALUE_NOT_LITERAL";
|
5348 | ErrorCode2[ErrorCode2["COMPONENT_MISSING_TEMPLATE"] = 2001] = "COMPONENT_MISSING_TEMPLATE";
|
5349 | ErrorCode2[ErrorCode2["PIPE_MISSING_NAME"] = 2002] = "PIPE_MISSING_NAME";
|
5350 | ErrorCode2[ErrorCode2["PARAM_MISSING_TOKEN"] = 2003] = "PARAM_MISSING_TOKEN";
|
5351 | ErrorCode2[ErrorCode2["DIRECTIVE_MISSING_SELECTOR"] = 2004] = "DIRECTIVE_MISSING_SELECTOR";
|
5352 | ErrorCode2[ErrorCode2["UNDECORATED_PROVIDER"] = 2005] = "UNDECORATED_PROVIDER";
|
5353 | ErrorCode2[ErrorCode2["DIRECTIVE_INHERITS_UNDECORATED_CTOR"] = 2006] = "DIRECTIVE_INHERITS_UNDECORATED_CTOR";
|
5354 | ErrorCode2[ErrorCode2["UNDECORATED_CLASS_USING_ANGULAR_FEATURES"] = 2007] = "UNDECORATED_CLASS_USING_ANGULAR_FEATURES";
|
5355 | ErrorCode2[ErrorCode2["COMPONENT_RESOURCE_NOT_FOUND"] = 2008] = "COMPONENT_RESOURCE_NOT_FOUND";
|
5356 | ErrorCode2[ErrorCode2["COMPONENT_INVALID_SHADOW_DOM_SELECTOR"] = 2009] = "COMPONENT_INVALID_SHADOW_DOM_SELECTOR";
|
5357 | ErrorCode2[ErrorCode2["SYMBOL_NOT_EXPORTED"] = 3001] = "SYMBOL_NOT_EXPORTED";
|
5358 | ErrorCode2[ErrorCode2["SYMBOL_EXPORTED_UNDER_DIFFERENT_NAME"] = 3002] = "SYMBOL_EXPORTED_UNDER_DIFFERENT_NAME";
|
5359 | ErrorCode2[ErrorCode2["IMPORT_CYCLE_DETECTED"] = 3003] = "IMPORT_CYCLE_DETECTED";
|
5360 | ErrorCode2[ErrorCode2["CONFIG_FLAT_MODULE_NO_INDEX"] = 4001] = "CONFIG_FLAT_MODULE_NO_INDEX";
|
5361 | ErrorCode2[ErrorCode2["CONFIG_STRICT_TEMPLATES_IMPLIES_FULL_TEMPLATE_TYPECHECK"] = 4002] = "CONFIG_STRICT_TEMPLATES_IMPLIES_FULL_TEMPLATE_TYPECHECK";
|
5362 | ErrorCode2[ErrorCode2["HOST_BINDING_PARSE_ERROR"] = 5001] = "HOST_BINDING_PARSE_ERROR";
|
5363 | ErrorCode2[ErrorCode2["TEMPLATE_PARSE_ERROR"] = 5002] = "TEMPLATE_PARSE_ERROR";
|
5364 | ErrorCode2[ErrorCode2["NGMODULE_INVALID_DECLARATION"] = 6001] = "NGMODULE_INVALID_DECLARATION";
|
5365 | ErrorCode2[ErrorCode2["NGMODULE_INVALID_IMPORT"] = 6002] = "NGMODULE_INVALID_IMPORT";
|
5366 | ErrorCode2[ErrorCode2["NGMODULE_INVALID_EXPORT"] = 6003] = "NGMODULE_INVALID_EXPORT";
|
5367 | ErrorCode2[ErrorCode2["NGMODULE_INVALID_REEXPORT"] = 6004] = "NGMODULE_INVALID_REEXPORT";
|
5368 | ErrorCode2[ErrorCode2["NGMODULE_MODULE_WITH_PROVIDERS_MISSING_GENERIC"] = 6005] = "NGMODULE_MODULE_WITH_PROVIDERS_MISSING_GENERIC";
|
5369 | ErrorCode2[ErrorCode2["NGMODULE_REEXPORT_NAME_COLLISION"] = 6006] = "NGMODULE_REEXPORT_NAME_COLLISION";
|
5370 | ErrorCode2[ErrorCode2["NGMODULE_DECLARATION_NOT_UNIQUE"] = 6007] = "NGMODULE_DECLARATION_NOT_UNIQUE";
|
5371 | ErrorCode2[ErrorCode2["NGMODULE_VE_DEPENDENCY_ON_IVY_LIB"] = 6999] = "NGMODULE_VE_DEPENDENCY_ON_IVY_LIB";
|
5372 | ErrorCode2[ErrorCode2["SCHEMA_INVALID_ELEMENT"] = 8001] = "SCHEMA_INVALID_ELEMENT";
|
5373 | ErrorCode2[ErrorCode2["SCHEMA_INVALID_ATTRIBUTE"] = 8002] = "SCHEMA_INVALID_ATTRIBUTE";
|
5374 | ErrorCode2[ErrorCode2["MISSING_REFERENCE_TARGET"] = 8003] = "MISSING_REFERENCE_TARGET";
|
5375 | ErrorCode2[ErrorCode2["MISSING_PIPE"] = 8004] = "MISSING_PIPE";
|
5376 | ErrorCode2[ErrorCode2["WRITE_TO_READ_ONLY_VARIABLE"] = 8005] = "WRITE_TO_READ_ONLY_VARIABLE";
|
5377 | ErrorCode2[ErrorCode2["DUPLICATE_VARIABLE_DECLARATION"] = 8006] = "DUPLICATE_VARIABLE_DECLARATION";
|
5378 | ErrorCode2[ErrorCode2["SPLIT_TWO_WAY_BINDING"] = 8007] = "SPLIT_TWO_WAY_BINDING";
|
5379 | ErrorCode2[ErrorCode2["INVALID_BANANA_IN_BOX"] = 8101] = "INVALID_BANANA_IN_BOX";
|
5380 | ErrorCode2[ErrorCode2["NULLISH_COALESCING_NOT_NULLABLE"] = 8102] = "NULLISH_COALESCING_NOT_NULLABLE";
|
5381 | ErrorCode2[ErrorCode2["INLINE_TCB_REQUIRED"] = 8900] = "INLINE_TCB_REQUIRED";
|
5382 | ErrorCode2[ErrorCode2["INLINE_TYPE_CTOR_REQUIRED"] = 8901] = "INLINE_TYPE_CTOR_REQUIRED";
|
5383 | ErrorCode2[ErrorCode2["INJECTABLE_DUPLICATE_PROV"] = 9001] = "INJECTABLE_DUPLICATE_PROV";
|
5384 | ErrorCode2[ErrorCode2["SUGGEST_STRICT_TEMPLATES"] = 10001] = "SUGGEST_STRICT_TEMPLATES";
|
5385 | ErrorCode2[ErrorCode2["SUGGEST_SUBOPTIMAL_TYPE_INFERENCE"] = 10002] = "SUGGEST_SUBOPTIMAL_TYPE_INFERENCE";
|
5386 | })(ErrorCode || (ErrorCode = {}));
|
5387 |
|
5388 |
|
5389 | var COMPILER_ERRORS_WITH_GUIDES = new Set([
|
5390 | ErrorCode.DECORATOR_ARG_NOT_LITERAL,
|
5391 | ErrorCode.IMPORT_CYCLE_DETECTED,
|
5392 | ErrorCode.PARAM_MISSING_TOKEN,
|
5393 | ErrorCode.SCHEMA_INVALID_ELEMENT,
|
5394 | ErrorCode.SCHEMA_INVALID_ATTRIBUTE,
|
5395 | ErrorCode.MISSING_REFERENCE_TARGET,
|
5396 | ErrorCode.COMPONENT_INVALID_SHADOW_DOM_SELECTOR
|
5397 | ]);
|
5398 |
|
5399 |
|
5400 | import ts17 from "typescript";
|
5401 |
|
5402 |
|
5403 | var ERROR_CODE_MATCHER = /(\u001b\[\d+m ?)TS-99(\d+: ?\u001b\[\d+m)/g;
|
5404 | function replaceTsWithNgInErrors(errors) {
|
5405 | return errors.replace(ERROR_CODE_MATCHER, "$1NG$2");
|
5406 | }
|
5407 | function ngErrorCode(code) {
|
5408 | return parseInt("-99" + code);
|
5409 | }
|
5410 |
|
5411 |
|
5412 | var FatalDiagnosticError = class {
|
5413 | constructor(code, node, message, relatedInformation) {
|
5414 | this.code = code;
|
5415 | this.node = node;
|
5416 | this.message = message;
|
5417 | this.relatedInformation = relatedInformation;
|
5418 | this._isFatalDiagnosticError = true;
|
5419 | }
|
5420 | toDiagnostic() {
|
5421 | return makeDiagnostic(this.code, this.node, this.message, this.relatedInformation);
|
5422 | }
|
5423 | };
|
5424 | function makeDiagnostic(code, node, messageText, relatedInformation) {
|
5425 | node = ts17.getOriginalNode(node);
|
5426 | return {
|
5427 | category: ts17.DiagnosticCategory.Error,
|
5428 | code: ngErrorCode(code),
|
5429 | file: ts17.getOriginalNode(node).getSourceFile(),
|
5430 | start: node.getStart(void 0, false),
|
5431 | length: node.getWidth(),
|
5432 | messageText,
|
5433 | relatedInformation
|
5434 | };
|
5435 | }
|
5436 | function makeRelatedInformation(node, messageText) {
|
5437 | node = ts17.getOriginalNode(node);
|
5438 | return {
|
5439 | category: ts17.DiagnosticCategory.Message,
|
5440 | code: 0,
|
5441 | file: node.getSourceFile(),
|
5442 | start: node.getStart(),
|
5443 | length: node.getWidth(),
|
5444 | messageText
|
5445 | };
|
5446 | }
|
5447 | function isFatalDiagnosticError(err) {
|
5448 | return err._isFatalDiagnosticError === true;
|
5449 | }
|
5450 |
|
5451 |
|
5452 | import ts19 from "typescript";
|
5453 |
|
5454 |
|
5455 | import ts18 from "typescript";
|
5456 | function patchTsGetExpandoInitializer() {
|
5457 | if (isTs31778GetExpandoInitializerFixed()) {
|
5458 | return null;
|
5459 | }
|
5460 | const originalGetExpandoInitializer = ts18.getExpandoInitializer;
|
5461 | if (originalGetExpandoInitializer === void 0) {
|
5462 | throw makeUnsupportedTypeScriptError();
|
5463 | }
|
5464 | ts18.getExpandoInitializer = (initializer, isPrototypeAssignment) => {
|
5465 | if (ts18.isParenthesizedExpression(initializer) && ts18.isCallExpression(initializer.expression)) {
|
5466 | initializer = initializer.expression;
|
5467 | }
|
5468 | return originalGetExpandoInitializer(initializer, isPrototypeAssignment);
|
5469 | };
|
5470 | return originalGetExpandoInitializer;
|
5471 | }
|
5472 | function restoreGetExpandoInitializer(originalGetExpandoInitializer) {
|
5473 | if (originalGetExpandoInitializer !== null) {
|
5474 | ts18.getExpandoInitializer = originalGetExpandoInitializer;
|
5475 | }
|
5476 | }
|
5477 | var ts31778FixedResult = null;
|
5478 | function isTs31778GetExpandoInitializerFixed() {
|
5479 | if (ts31778FixedResult !== null) {
|
5480 | return ts31778FixedResult;
|
5481 | }
|
5482 | ts31778FixedResult = checkIfExpandoPropertyIsPresent();
|
5483 | if (!ts31778FixedResult) {
|
5484 | const originalGetExpandoInitializer = patchTsGetExpandoInitializer();
|
5485 | try {
|
5486 | const patchIsSuccessful = checkIfExpandoPropertyIsPresent();
|
5487 | if (!patchIsSuccessful) {
|
5488 | throw makeUnsupportedTypeScriptError();
|
5489 | }
|
5490 | } finally {
|
5491 | restoreGetExpandoInitializer(originalGetExpandoInitializer);
|
5492 | }
|
5493 | }
|
5494 | return ts31778FixedResult;
|
5495 | }
|
5496 | function checkIfExpandoPropertyIsPresent() {
|
5497 | const sourceText = `
|
5498 | (function() {
|
5499 | var A = (function() {
|
5500 | function A() {}
|
5501 | return A;
|
5502 | }());
|
5503 | A.expando = true;
|
5504 | }());`;
|
5505 | const sourceFile = ts18.createSourceFile("test.js", sourceText, ts18.ScriptTarget.ES5, true, ts18.ScriptKind.JS);
|
5506 | const host = {
|
5507 | getSourceFile() {
|
5508 | return sourceFile;
|
5509 | },
|
5510 | fileExists() {
|
5511 | return true;
|
5512 | },
|
5513 | readFile() {
|
5514 | return "";
|
5515 | },
|
5516 | writeFile() {
|
5517 | },
|
5518 | getDefaultLibFileName() {
|
5519 | return "";
|
5520 | },
|
5521 | getCurrentDirectory() {
|
5522 | return "";
|
5523 | },
|
5524 | getDirectories() {
|
5525 | return [];
|
5526 | },
|
5527 | getCanonicalFileName(fileName) {
|
5528 | return fileName;
|
5529 | },
|
5530 | useCaseSensitiveFileNames() {
|
5531 | return true;
|
5532 | },
|
5533 | getNewLine() {
|
5534 | return "\n";
|
5535 | }
|
5536 | };
|
5537 | const options = { noResolve: true, noLib: true, noEmit: true, allowJs: true };
|
5538 | const program = ts18.createProgram(["test.js"], options, host);
|
5539 | function visitor(node) {
|
5540 | if (ts18.isVariableDeclaration(node) && hasNameIdentifier(node) && node.name.text === "A") {
|
5541 | return node;
|
5542 | }
|
5543 | return ts18.forEachChild(node, visitor);
|
5544 | }
|
5545 | const declaration = ts18.forEachChild(sourceFile, visitor);
|
5546 | if (declaration === void 0) {
|
5547 | throw new Error("Unable to find declaration of outer A");
|
5548 | }
|
5549 | const symbol = program.getTypeChecker().getSymbolAtLocation(declaration.name);
|
5550 | if (symbol === void 0) {
|
5551 | throw new Error("Unable to resolve symbol of outer A");
|
5552 | }
|
5553 | return symbol.exports !== void 0 && symbol.exports.has("expando");
|
5554 | }
|
5555 | function makeUnsupportedTypeScriptError() {
|
5556 | return new Error("The TypeScript version used is not supported by ngcc.");
|
5557 | }
|
5558 |
|
5559 |
|
5560 | function makeBundleProgram(fs5, isCore, pkg, path7, r3FileName, options, host, additionalFiles = []) {
|
5561 | const r3SymbolsPath = isCore ? findR3SymbolsPath(fs5, fs5.dirname(path7), r3FileName) : null;
|
5562 | let rootPaths = r3SymbolsPath ? [path7, r3SymbolsPath, ...additionalFiles] : [path7, ...additionalFiles];
|
5563 | const originalGetExpandoInitializer = patchTsGetExpandoInitializer();
|
5564 | const program = ts19.createProgram(rootPaths, options, host);
|
5565 | program.getTypeChecker();
|
5566 | restoreGetExpandoInitializer(originalGetExpandoInitializer);
|
5567 | const file = program.getSourceFile(path7);
|
5568 | const r3SymbolsFile = r3SymbolsPath && program.getSourceFile(r3SymbolsPath) || null;
|
5569 | return { program, options, host, package: pkg, path: path7, file, r3SymbolsPath, r3SymbolsFile };
|
5570 | }
|
5571 | function findR3SymbolsPath(fs5, directory, filename) {
|
5572 | const r3SymbolsFilePath = fs5.resolve(directory, filename);
|
5573 | if (fs5.exists(r3SymbolsFilePath)) {
|
5574 | return r3SymbolsFilePath;
|
5575 | }
|
5576 | const subDirectories = fs5.readdir(directory).filter((p2) => !p2.startsWith(".")).filter((p2) => p2 !== "node_modules").filter((p2) => {
|
5577 | const stat = fs5.lstat(fs5.resolve(directory, p2));
|
5578 | return stat.isDirectory() && !stat.isSymbolicLink();
|
5579 | });
|
5580 | for (const subDirectory of subDirectories) {
|
5581 | const r3SymbolsFilePath2 = findR3SymbolsPath(fs5, fs5.resolve(directory, subDirectory), filename);
|
5582 | if (r3SymbolsFilePath2) {
|
5583 | return r3SymbolsFilePath2;
|
5584 | }
|
5585 | }
|
5586 | return null;
|
5587 | }
|
5588 |
|
5589 |
|
5590 | import ts20 from "typescript";
|
5591 | var NgccSourcesCompilerHost = class extends NgtscCompilerHost {
|
5592 | constructor(fs5, options, cache, moduleResolutionCache, packagePath) {
|
5593 | super(fs5, options);
|
5594 | this.cache = cache;
|
5595 | this.moduleResolutionCache = moduleResolutionCache;
|
5596 | this.packagePath = packagePath;
|
5597 | }
|
5598 | getSourceFile(fileName, languageVersion) {
|
5599 | return this.cache.getCachedSourceFile(fileName, languageVersion);
|
5600 | }
|
5601 | resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference) {
|
5602 | return moduleNames.map((moduleName) => {
|
5603 | const { resolvedModule } = ts20.resolveModuleName(moduleName, containingFile, this.options, this, this.moduleResolutionCache, redirectedReference);
|
5604 | if ((resolvedModule == null ? void 0 : resolvedModule.extension) === ts20.Extension.Dts && containingFile.endsWith(".js") && isRelativePath(moduleName)) {
|
5605 | const jsFile = resolvedModule.resolvedFileName.replace(/\.d\.ts$/, ".js");
|
5606 | if (this.fileExists(jsFile)) {
|
5607 | return __spreadProps(__spreadValues({}, resolvedModule), { resolvedFileName: jsFile, extension: ts20.Extension.Js });
|
5608 | }
|
5609 | }
|
5610 | if ((resolvedModule == null ? void 0 : resolvedModule.extension) === ts20.Extension.Js && !isWithinPackage(this.packagePath, this.fs.resolve(resolvedModule.resolvedFileName))) {
|
5611 | return void 0;
|
5612 | }
|
5613 | return resolvedModule;
|
5614 | });
|
5615 | }
|
5616 | };
|
5617 | var NgccDtsCompilerHost = class extends NgtscCompilerHost {
|
5618 | constructor(fs5, options, cache, moduleResolutionCache) {
|
5619 | super(fs5, options);
|
5620 | this.cache = cache;
|
5621 | this.moduleResolutionCache = moduleResolutionCache;
|
5622 | }
|
5623 | getSourceFile(fileName, languageVersion) {
|
5624 | return this.cache.getCachedSourceFile(fileName, languageVersion);
|
5625 | }
|
5626 | resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference) {
|
5627 | return moduleNames.map((moduleName) => {
|
5628 | const { resolvedModule } = ts20.resolveModuleName(moduleName, containingFile, this.options, this, this.moduleResolutionCache, redirectedReference);
|
5629 | return resolvedModule;
|
5630 | });
|
5631 | }
|
5632 | };
|
5633 |
|
5634 |
|
5635 | import ts21 from "typescript";
|
5636 | var SharedFileCache = class {
|
5637 | constructor(fs5) {
|
5638 | this.fs = fs5;
|
5639 | this.sfCache = new Map();
|
5640 | }
|
5641 | getCachedSourceFile(fileName) {
|
5642 | const absPath = this.fs.resolve(fileName);
|
5643 | if (isDefaultLibrary(absPath, this.fs)) {
|
5644 | return this.getStableCachedFile(absPath);
|
5645 | } else if (isAngularDts(absPath, this.fs)) {
|
5646 | return this.getVolatileCachedFile(absPath);
|
5647 | } else {
|
5648 | return void 0;
|
5649 | }
|
5650 | }
|
5651 | getStableCachedFile(absPath) {
|
5652 | if (!this.sfCache.has(absPath)) {
|
5653 | const content = readFile(absPath, this.fs);
|
5654 | if (content === void 0) {
|
5655 | return void 0;
|
5656 | }
|
5657 | const sf = ts21.createSourceFile(absPath, content, ts21.ScriptTarget.ES2015);
|
5658 | this.sfCache.set(absPath, sf);
|
5659 | }
|
5660 | return this.sfCache.get(absPath);
|
5661 | }
|
5662 | getVolatileCachedFile(absPath) {
|
5663 | const content = readFile(absPath, this.fs);
|
5664 | if (content === void 0) {
|
5665 | return void 0;
|
5666 | }
|
5667 | if (!this.sfCache.has(absPath) || this.sfCache.get(absPath).text !== content) {
|
5668 | const sf = ts21.createSourceFile(absPath, content, ts21.ScriptTarget.ES2015);
|
5669 | this.sfCache.set(absPath, sf);
|
5670 | }
|
5671 | return this.sfCache.get(absPath);
|
5672 | }
|
5673 | };
|
5674 | var DEFAULT_LIB_PATTERN = ["node_modules", "typescript", "lib", /^lib\..+\.d\.ts$/];
|
5675 | function isDefaultLibrary(absPath, fs5) {
|
5676 | return isFile(absPath, DEFAULT_LIB_PATTERN, fs5);
|
5677 | }
|
5678 | var ANGULAR_DTS_PATTERN = ["node_modules", "@angular", /./, /\.d\.ts$/];
|
5679 | function isAngularDts(absPath, fs5) {
|
5680 | return isFile(absPath, ANGULAR_DTS_PATTERN, fs5);
|
5681 | }
|
5682 | function isFile(path7, segments, fs5) {
|
5683 | for (let i = segments.length - 1; i >= 0; i--) {
|
5684 | const pattern = segments[i];
|
5685 | const segment = fs5.basename(path7);
|
5686 | if (typeof pattern === "string") {
|
5687 | if (pattern !== segment) {
|
5688 | return false;
|
5689 | }
|
5690 | } else {
|
5691 | if (!pattern.test(segment)) {
|
5692 | return false;
|
5693 | }
|
5694 | }
|
5695 | path7 = fs5.dirname(path7);
|
5696 | }
|
5697 | return true;
|
5698 | }
|
5699 | var EntryPointFileCache = class {
|
5700 | constructor(fs5, sharedFileCache) {
|
5701 | this.fs = fs5;
|
5702 | this.sharedFileCache = sharedFileCache;
|
5703 | this.sfCache = new Map();
|
5704 | }
|
5705 | getCachedSourceFile(fileName, languageVersion) {
|
5706 | const staticSf = this.sharedFileCache.getCachedSourceFile(fileName);
|
5707 | if (staticSf !== void 0) {
|
5708 | return staticSf;
|
5709 | }
|
5710 | const absPath = this.fs.resolve(fileName);
|
5711 | if (this.sfCache.has(absPath)) {
|
5712 | return this.sfCache.get(absPath);
|
5713 | }
|
5714 | const content = readFile(absPath, this.fs);
|
5715 | if (content === void 0) {
|
5716 | return void 0;
|
5717 | }
|
5718 | const sf = ts21.createSourceFile(fileName, content, languageVersion);
|
5719 | this.sfCache.set(absPath, sf);
|
5720 | return sf;
|
5721 | }
|
5722 | };
|
5723 | function readFile(absPath, fs5) {
|
5724 | if (!fs5.exists(absPath) || !fs5.stat(absPath).isFile()) {
|
5725 | return void 0;
|
5726 | }
|
5727 | return fs5.readFile(absPath);
|
5728 | }
|
5729 | function createModuleResolutionCache(fs5) {
|
5730 | return ts21.createModuleResolutionCache(fs5.pwd(), (fileName) => {
|
5731 | return fs5.isCaseSensitive() ? fileName : fileName.toLowerCase();
|
5732 | });
|
5733 | }
|
5734 |
|
5735 |
|
5736 | function makeEntryPointBundle(fs5, entryPoint, sharedFileCache, moduleResolutionCache, formatPath, isCore, format, dtsProcessing, pathMappings, mirrorDtsFromSrc = false, enableI18nLegacyMessageIdFormat = true) {
|
5737 | const rootDir = entryPoint.packagePath;
|
5738 | const options = __spreadValues({ allowJs: true, maxNodeModuleJsDepth: Infinity, rootDir }, pathMappings);
|
5739 | const entryPointCache = new EntryPointFileCache(fs5, sharedFileCache);
|
5740 | const dtsHost = new NgccDtsCompilerHost(fs5, options, entryPointCache, moduleResolutionCache);
|
5741 | const srcHost = new NgccSourcesCompilerHost(fs5, options, entryPointCache, moduleResolutionCache, entryPoint.packagePath);
|
5742 | const absFormatPath = fs5.resolve(entryPoint.path, formatPath);
|
5743 | const typingsPath = fs5.resolve(entryPoint.path, entryPoint.typings);
|
5744 | const src = makeBundleProgram(fs5, isCore, entryPoint.packagePath, absFormatPath, "r3_symbols.js", options, srcHost);
|
5745 | const additionalDtsFiles = dtsProcessing !== DtsProcessing.No && mirrorDtsFromSrc ? computePotentialDtsFilesFromJsFiles(fs5, src.program, absFormatPath, typingsPath) : [];
|
5746 | const dts = dtsProcessing !== DtsProcessing.No ? makeBundleProgram(fs5, isCore, entryPoint.packagePath, typingsPath, "r3_symbols.d.ts", __spreadProps(__spreadValues({}, options), { allowJs: false }), dtsHost, additionalDtsFiles) : null;
|
5747 | const isFlatCore = isCore && src.r3SymbolsFile === null;
|
5748 | return {
|
5749 | entryPoint,
|
5750 | format,
|
5751 | rootDirs: [rootDir],
|
5752 | isCore,
|
5753 | isFlatCore,
|
5754 | src,
|
5755 | dts,
|
5756 | dtsProcessing,
|
5757 | enableI18nLegacyMessageIdFormat
|
5758 | };
|
5759 | }
|
5760 | function computePotentialDtsFilesFromJsFiles(fs5, srcProgram, formatPath, typingsPath) {
|
5761 | const formatRoot = fs5.dirname(formatPath);
|
5762 | const typingsRoot = fs5.dirname(typingsPath);
|
5763 | const additionalFiles = [];
|
5764 | for (const sf of srcProgram.getSourceFiles()) {
|
5765 | if (!sf.fileName.endsWith(".js")) {
|
5766 | continue;
|
5767 | }
|
5768 | const mirroredDtsPath = fs5.resolve(typingsRoot, fs5.relative(formatRoot, sf.fileName.replace(/\.js$/, ".d.ts")));
|
5769 | if (fs5.exists(mirroredDtsPath)) {
|
5770 | additionalFiles.push(mirroredDtsPath);
|
5771 | }
|
5772 | }
|
5773 | return additionalFiles;
|
5774 | }
|
5775 |
|
5776 |
|
5777 | import ts60 from "typescript";
|
5778 |
|
5779 |
|
5780 | import { ConstantPool as ConstantPool2 } from "@angular/compiler";
|
5781 |
|
5782 |
|
5783 | import { compileClassMetadata as compileClassMetadata3, compileComponentFromMetadata, compileDeclareClassMetadata as compileDeclareClassMetadata3, compileDeclareComponentFromMetadata, CssSelector, DEFAULT_INTERPOLATION_CONFIG, DomElementSchemaRegistry, ExternalExpr as ExternalExpr7, FactoryTarget as FactoryTarget3, InterpolationConfig, makeBindingParser as makeBindingParser2, ParseSourceFile as ParseSourceFile2, parseTemplate, R3TargetBinder, SelectorMatcher, ViewEncapsulation, WrappedNodeExpr as WrappedNodeExpr6 } from "@angular/compiler";
|
5784 | import ts45 from "typescript";
|
5785 |
|
5786 |
|
5787 | import { ExternalExpr as ExternalExpr2 } from "@angular/compiler";
|
5788 |
|
5789 |
|
5790 | import { ExternalExpr, ExternalReference, WrappedNodeExpr } from "@angular/compiler";
|
5791 | import ts23 from "typescript";
|
5792 |
|
5793 |
|
5794 | import ts22 from "typescript";
|
5795 | function findExportedNameOfNode(target, file, reflector) {
|
5796 | const exports = reflector.getExportsOfModule(file);
|
5797 | if (exports === null) {
|
5798 | return null;
|
5799 | }
|
5800 | const declaredName = isNamedDeclaration(target) ? target.name.text : null;
|
5801 | let foundExportName = null;
|
5802 | for (const [exportName, declaration] of exports) {
|
5803 | if (declaration.node !== target) {
|
5804 | continue;
|
5805 | }
|
5806 | if (exportName === declaredName) {
|
5807 | return exportName;
|
5808 | }
|
5809 | foundExportName = exportName;
|
5810 | }
|
5811 | if (foundExportName === null) {
|
5812 | throw new Error(`Failed to find exported name of node (${target.getText()}) in '${file.fileName}'.`);
|
5813 | }
|
5814 | return foundExportName;
|
5815 | }
|
5816 |
|
5817 |
|
5818 | var ImportFlags;
|
5819 | (function(ImportFlags2) {
|
5820 | ImportFlags2[ImportFlags2["None"] = 0] = "None";
|
5821 | ImportFlags2[ImportFlags2["ForceNewImport"] = 1] = "ForceNewImport";
|
5822 | ImportFlags2[ImportFlags2["NoAliasing"] = 2] = "NoAliasing";
|
5823 | ImportFlags2[ImportFlags2["AllowTypeImports"] = 4] = "AllowTypeImports";
|
5824 | })(ImportFlags || (ImportFlags = {}));
|
5825 | var ReferenceEmitter = class {
|
5826 | constructor(strategies) {
|
5827 | this.strategies = strategies;
|
5828 | }
|
5829 | emit(ref, context, importFlags = ImportFlags.None) {
|
5830 | for (const strategy of this.strategies) {
|
5831 | const emitted = strategy.emit(ref, context, importFlags);
|
5832 | if (emitted !== null) {
|
5833 | return emitted;
|
5834 | }
|
5835 | }
|
5836 | throw new Error(`Unable to write a reference to ${nodeNameForError(ref.node)} in ${ref.node.getSourceFile().fileName} from ${context.fileName}`);
|
5837 | }
|
5838 | };
|
5839 | var LocalIdentifierStrategy = class {
|
5840 | emit(ref, context, importFlags) {
|
5841 | const refSf = getSourceFile(ref.node);
|
5842 | if (importFlags & ImportFlags.ForceNewImport && refSf !== context) {
|
5843 | return null;
|
5844 | }
|
5845 | if (!isDeclaration(ref.node) && refSf === context) {
|
5846 | return {
|
5847 | expression: new WrappedNodeExpr(ref.node),
|
5848 | importedFile: null
|
5849 | };
|
5850 | }
|
5851 | const identifier = ref.getIdentityIn(context);
|
5852 | if (identifier !== null) {
|
5853 | return {
|
5854 | expression: new WrappedNodeExpr(identifier),
|
5855 | importedFile: null
|
5856 | };
|
5857 | } else {
|
5858 | return null;
|
5859 | }
|
5860 | }
|
5861 | };
|
5862 | var AbsoluteModuleStrategy = class {
|
5863 | constructor(program, checker, moduleResolver, reflectionHost) {
|
5864 | this.program = program;
|
5865 | this.checker = checker;
|
5866 | this.moduleResolver = moduleResolver;
|
5867 | this.reflectionHost = reflectionHost;
|
5868 | this.moduleExportsCache = new Map();
|
5869 | }
|
5870 | emit(ref, context, importFlags) {
|
5871 | if (ref.bestGuessOwningModule === null) {
|
5872 | return null;
|
5873 | } else if (!isDeclaration(ref.node)) {
|
5874 | throw new Error(`Debug assert: unable to import a Reference to non-declaration of type ${ts23.SyntaxKind[ref.node.kind]}.`);
|
5875 | } else if ((importFlags & ImportFlags.AllowTypeImports) === 0 && isTypeDeclaration(ref.node)) {
|
5876 | throw new Error(`Importing a type-only declaration of type ${ts23.SyntaxKind[ref.node.kind]} in a value position is not allowed.`);
|
5877 | }
|
5878 | const { specifier, resolutionContext } = ref.bestGuessOwningModule;
|
5879 | const exports = this.getExportsOfModule(specifier, resolutionContext);
|
5880 | if (exports === null || !exports.exportMap.has(ref.node)) {
|
5881 | throw new Error(`Symbol ${ref.debugName} declared in ${getSourceFile(ref.node).fileName} is not exported from ${specifier} (import into ${context.fileName})`);
|
5882 | }
|
5883 | const symbolName = exports.exportMap.get(ref.node);
|
5884 | return {
|
5885 | expression: new ExternalExpr(new ExternalReference(specifier, symbolName)),
|
5886 | importedFile: exports.module
|
5887 | };
|
5888 | }
|
5889 | getExportsOfModule(moduleName, fromFile) {
|
5890 | if (!this.moduleExportsCache.has(moduleName)) {
|
5891 | this.moduleExportsCache.set(moduleName, this.enumerateExportsOfModule(moduleName, fromFile));
|
5892 | }
|
5893 | return this.moduleExportsCache.get(moduleName);
|
5894 | }
|
5895 | enumerateExportsOfModule(specifier, fromFile) {
|
5896 | const entryPointFile = this.moduleResolver.resolveModule(specifier, fromFile);
|
5897 | if (entryPointFile === null) {
|
5898 | return null;
|
5899 | }
|
5900 | const exports = this.reflectionHost.getExportsOfModule(entryPointFile);
|
5901 | if (exports === null) {
|
5902 | return null;
|
5903 | }
|
5904 | const exportMap = new Map();
|
5905 | for (const [name, declaration] of exports) {
|
5906 | if (exportMap.has(declaration.node)) {
|
5907 | const existingExport = exportMap.get(declaration.node);
|
5908 | if (isNamedDeclaration(declaration.node) && declaration.node.name.text === existingExport) {
|
5909 | continue;
|
5910 | }
|
5911 | }
|
5912 | exportMap.set(declaration.node, name);
|
5913 | }
|
5914 | return { module: entryPointFile, exportMap };
|
5915 | }
|
5916 | };
|
5917 | var LogicalProjectStrategy = class {
|
5918 | constructor(reflector, logicalFs) {
|
5919 | this.reflector = reflector;
|
5920 | this.logicalFs = logicalFs;
|
5921 | }
|
5922 | emit(ref, context) {
|
5923 | const destSf = getSourceFile(ref.node);
|
5924 | const destPath = this.logicalFs.logicalPathOfSf(destSf);
|
5925 | if (destPath === null) {
|
5926 | return null;
|
5927 | }
|
5928 | const originPath = this.logicalFs.logicalPathOfSf(context);
|
5929 | if (originPath === null) {
|
5930 | throw new Error(`Debug assert: attempt to import from ${context.fileName} but it's outside the program?`);
|
5931 | }
|
5932 | if (destPath === originPath) {
|
5933 | return null;
|
5934 | }
|
5935 | const name = findExportedNameOfNode(ref.node, destSf, this.reflector);
|
5936 | if (name === null) {
|
5937 | return null;
|
5938 | }
|
5939 | const moduleName = LogicalProjectPath.relativePathBetween(originPath, destPath);
|
5940 | return {
|
5941 | expression: new ExternalExpr({ moduleName, name }),
|
5942 | importedFile: destSf
|
5943 | };
|
5944 | }
|
5945 | };
|
5946 |
|
5947 |
|
5948 | var PrivateExportAliasingHost = class {
|
5949 | constructor(host) {
|
5950 | this.host = host;
|
5951 | this.aliasExportsInDts = true;
|
5952 | }
|
5953 | maybeAliasSymbolAs(ref, context, ngModuleName) {
|
5954 | if (ref.hasOwningModuleGuess) {
|
5955 | return null;
|
5956 | }
|
5957 | const exports = this.host.getExportsOfModule(context);
|
5958 | if (exports === null) {
|
5959 | throw new Error(`Could not determine the exports of: ${context.fileName}`);
|
5960 | }
|
5961 | let found = false;
|
5962 | exports.forEach((value) => {
|
5963 | if (value.node === ref.node) {
|
5964 | found = true;
|
5965 | }
|
5966 | });
|
5967 | if (found) {
|
5968 | return null;
|
5969 | }
|
5970 | return `\u0275ngExport\u0275${ngModuleName}\u0275${ref.node.name.text}`;
|
5971 | }
|
5972 | getAliasIn() {
|
5973 | return null;
|
5974 | }
|
5975 | };
|
5976 |
|
5977 |
|
5978 | function relativePathBetween(from, to) {
|
5979 | const relativePath = stripExtension(relative(dirname(resolve(from)), resolve(to)));
|
5980 | return relativePath !== "" ? toRelativeImport(relativePath) : null;
|
5981 | }
|
5982 |
|
5983 |
|
5984 | var NoopImportRewriter = class {
|
5985 | shouldImportSymbol(symbol, specifier) {
|
5986 | return true;
|
5987 | }
|
5988 | rewriteSymbol(symbol, specifier) {
|
5989 | return symbol;
|
5990 | }
|
5991 | rewriteSpecifier(specifier, inContextOfFile) {
|
5992 | return specifier;
|
5993 | }
|
5994 | };
|
5995 | var CORE_SUPPORTED_SYMBOLS = new Map([
|
5996 | ["\u0275\u0275defineInjectable", "\u0275\u0275defineInjectable"],
|
5997 | ["\u0275\u0275defineInjector", "\u0275\u0275defineInjector"],
|
5998 | ["\u0275\u0275defineNgModule", "\u0275\u0275defineNgModule"],
|
5999 | ["\u0275\u0275setNgModuleScope", "\u0275\u0275setNgModuleScope"],
|
6000 | ["\u0275\u0275inject", "\u0275\u0275inject"],
|
6001 | ["\u0275\u0275FactoryDeclaration", "\u0275\u0275FactoryDeclaration"],
|
6002 | ["\u0275setClassMetadata", "setClassMetadata"],
|
6003 | ["\u0275\u0275InjectableDeclaration", "\u0275\u0275InjectableDeclaration"],
|
6004 | ["\u0275\u0275InjectorDeclaration", "\u0275\u0275InjectorDeclaration"],
|
6005 | ["\u0275\u0275NgModuleDeclaration", "\u0275\u0275NgModuleDeclaration"],
|
6006 | ["\u0275NgModuleFactory", "NgModuleFactory"],
|
6007 | ["\u0275noSideEffects", "\u0275noSideEffects"]
|
6008 | ]);
|
6009 | var CORE_MODULE = "@angular/core";
|
6010 | var R3SymbolsImportRewriter = class {
|
6011 | constructor(r3SymbolsPath) {
|
6012 | this.r3SymbolsPath = r3SymbolsPath;
|
6013 | }
|
6014 | shouldImportSymbol(symbol, specifier) {
|
6015 | return true;
|
6016 | }
|
6017 | rewriteSymbol(symbol, specifier) {
|
6018 | if (specifier !== CORE_MODULE) {
|
6019 | return symbol;
|
6020 | }
|
6021 | return validateAndRewriteCoreSymbol(symbol);
|
6022 | }
|
6023 | rewriteSpecifier(specifier, inContextOfFile) {
|
6024 | if (specifier !== CORE_MODULE) {
|
6025 | return specifier;
|
6026 | }
|
6027 | const relativePathToR3Symbols = relativePathBetween(inContextOfFile, this.r3SymbolsPath);
|
6028 | if (relativePathToR3Symbols === null) {
|
6029 | throw new Error(`Failed to rewrite import inside ${CORE_MODULE}: ${inContextOfFile} -> ${this.r3SymbolsPath}`);
|
6030 | }
|
6031 | return relativePathToR3Symbols;
|
6032 | }
|
6033 | };
|
6034 | function validateAndRewriteCoreSymbol(name) {
|
6035 | if (!CORE_SUPPORTED_SYMBOLS.has(name)) {
|
6036 | throw new Error(`Importing unexpected symbol ${name} while compiling ${CORE_MODULE}`);
|
6037 | }
|
6038 | return CORE_SUPPORTED_SYMBOLS.get(name);
|
6039 | }
|
6040 |
|
6041 |
|
6042 | import ts24 from "typescript";
|
6043 | var DefaultImportDeclaration = Symbol("DefaultImportDeclaration");
|
6044 | function attachDefaultImportDeclaration(expr, importDecl) {
|
6045 | expr[DefaultImportDeclaration] = importDecl;
|
6046 | }
|
6047 |
|
6048 |
|
6049 | var Reference = class {
|
6050 | constructor(node, bestGuessOwningModule = null) {
|
6051 | this.node = node;
|
6052 | this.identifiers = [];
|
6053 | this.synthetic = false;
|
6054 | this._alias = null;
|
6055 | this.bestGuessOwningModule = bestGuessOwningModule;
|
6056 | const id = identifierOfNode(node);
|
6057 | if (id !== null) {
|
6058 | this.identifiers.push(id);
|
6059 | }
|
6060 | }
|
6061 | get ownedByModuleGuess() {
|
6062 | if (this.bestGuessOwningModule !== null) {
|
6063 | return this.bestGuessOwningModule.specifier;
|
6064 | } else {
|
6065 | return null;
|
6066 | }
|
6067 | }
|
6068 | get hasOwningModuleGuess() {
|
6069 | return this.bestGuessOwningModule !== null;
|
6070 | }
|
6071 | get debugName() {
|
6072 | const id = identifierOfNode(this.node);
|
6073 | return id !== null ? id.text : null;
|
6074 | }
|
6075 | get alias() {
|
6076 | return this._alias;
|
6077 | }
|
6078 | addIdentifier(identifier) {
|
6079 | this.identifiers.push(identifier);
|
6080 | }
|
6081 | getIdentityIn(context) {
|
6082 | return this.identifiers.find((id) => id.getSourceFile() === context) || null;
|
6083 | }
|
6084 | getIdentityInExpression(expr) {
|
6085 | const sf = expr.getSourceFile();
|
6086 | return this.identifiers.find((id) => {
|
6087 | if (id.getSourceFile() !== sf) {
|
6088 | return false;
|
6089 | }
|
6090 | return id.pos >= expr.pos && id.end <= expr.end;
|
6091 | }) || null;
|
6092 | }
|
6093 | getOriginForDiagnostics(container, fallback = container) {
|
6094 | const id = this.getIdentityInExpression(container);
|
6095 | return id !== null ? id : fallback;
|
6096 | }
|
6097 | cloneWithAlias(alias) {
|
6098 | const ref = new Reference(this.node, this.bestGuessOwningModule);
|
6099 | ref.identifiers = [...this.identifiers];
|
6100 | ref._alias = alias;
|
6101 | return ref;
|
6102 | }
|
6103 | cloneWithNoIdentifiers() {
|
6104 | const ref = new Reference(this.node, this.bestGuessOwningModule);
|
6105 | ref._alias = this._alias;
|
6106 | ref.identifiers = [];
|
6107 | return ref;
|
6108 | }
|
6109 | };
|
6110 |
|
6111 |
|
6112 | var ModuleResolver2 = class {
|
6113 | constructor(program, compilerOptions, host, moduleResolutionCache) {
|
6114 | this.program = program;
|
6115 | this.compilerOptions = compilerOptions;
|
6116 | this.host = host;
|
6117 | this.moduleResolutionCache = moduleResolutionCache;
|
6118 | }
|
6119 | resolveModule(moduleName, containingFile) {
|
6120 | const resolved = resolveModuleName(moduleName, containingFile, this.compilerOptions, this.host, this.moduleResolutionCache);
|
6121 | if (resolved === void 0) {
|
6122 | return null;
|
6123 | }
|
6124 | return getSourceFileOrNull(this.program, absoluteFrom(resolved.resolvedFileName));
|
6125 | }
|
6126 | };
|
6127 |
|
6128 |
|
6129 | import ts25 from "typescript";
|
6130 | var SemanticSymbol = class {
|
6131 | constructor(decl) {
|
6132 | this.decl = decl;
|
6133 | this.path = absoluteFromSourceFile(decl.getSourceFile());
|
6134 | this.identifier = getSymbolIdentifier(decl);
|
6135 | }
|
6136 | };
|
6137 | function getSymbolIdentifier(decl) {
|
6138 | if (!ts25.isSourceFile(decl.parent)) {
|
6139 | return null;
|
6140 | }
|
6141 | return decl.name.text;
|
6142 | }
|
6143 |
|
6144 |
|
6145 | import { ExternalExpr as ExternalExpr3 } from "@angular/compiler";
|
6146 |
|
6147 |
|
6148 | import ts26 from "typescript";
|
6149 |
|
6150 |
|
6151 | function isSymbolEqual(a, b) {
|
6152 | if (a.decl === b.decl) {
|
6153 | return true;
|
6154 | }
|
6155 | if (a.identifier === null || b.identifier === null) {
|
6156 | return false;
|
6157 | }
|
6158 | return a.path === b.path && a.identifier === b.identifier;
|
6159 | }
|
6160 | function isReferenceEqual(a, b) {
|
6161 | if (!isSymbolEqual(a.symbol, b.symbol)) {
|
6162 | return false;
|
6163 | }
|
6164 | return a.importPath === b.importPath;
|
6165 | }
|
6166 | function referenceEquality(a, b) {
|
6167 | return a === b;
|
6168 | }
|
6169 | function isArrayEqual(a, b, equalityTester = referenceEquality) {
|
6170 | if (a === null || b === null) {
|
6171 | return a === b;
|
6172 | }
|
6173 | if (a.length !== b.length) {
|
6174 | return false;
|
6175 | }
|
6176 | return !a.some((item, index) => !equalityTester(item, b[index]));
|
6177 | }
|
6178 | function isSetEqual(a, b, equalityTester = referenceEquality) {
|
6179 | if (a === null || b === null) {
|
6180 | return a === b;
|
6181 | }
|
6182 | if (a.size !== b.size) {
|
6183 | return false;
|
6184 | }
|
6185 | for (const itemA of a) {
|
6186 | let found = false;
|
6187 | for (const itemB of b) {
|
6188 | if (equalityTester(itemA, itemB)) {
|
6189 | found = true;
|
6190 | break;
|
6191 | }
|
6192 | }
|
6193 | if (!found) {
|
6194 | return false;
|
6195 | }
|
6196 | }
|
6197 | return true;
|
6198 | }
|
6199 |
|
6200 |
|
6201 | function extractSemanticTypeParameters(node) {
|
6202 | if (!ts26.isClassDeclaration(node) || node.typeParameters === void 0) {
|
6203 | return null;
|
6204 | }
|
6205 | return node.typeParameters.map((typeParam) => ({ hasGenericTypeBound: typeParam.constraint !== void 0 }));
|
6206 | }
|
6207 | function areTypeParametersEqual(current, previous) {
|
6208 | if (!isArrayEqual(current, previous, isTypeParameterEqual)) {
|
6209 | return false;
|
6210 | }
|
6211 | if (current !== null && current.some((typeParam) => typeParam.hasGenericTypeBound)) {
|
6212 | return false;
|
6213 | }
|
6214 | return true;
|
6215 | }
|
6216 | function isTypeParameterEqual(a, b) {
|
6217 | return a.hasGenericTypeBound === b.hasGenericTypeBound;
|
6218 | }
|
6219 |
|
6220 |
|
6221 | var MetaType;
|
6222 | (function(MetaType2) {
|
6223 | MetaType2[MetaType2["Pipe"] = 0] = "Pipe";
|
6224 | MetaType2[MetaType2["Directive"] = 1] = "Directive";
|
6225 | })(MetaType || (MetaType = {}));
|
6226 |
|
6227 |
|
6228 | import ts28 from "typescript";
|
6229 |
|
6230 |
|
6231 | var ClassPropertyMapping = class {
|
6232 | constructor(forwardMap) {
|
6233 | this.forwardMap = forwardMap;
|
6234 | this.reverseMap = reverseMapFromForwardMap(forwardMap);
|
6235 | }
|
6236 | static empty() {
|
6237 | return new ClassPropertyMapping(new Map());
|
6238 | }
|
6239 | static fromMappedObject(obj) {
|
6240 | const forwardMap = new Map();
|
6241 | for (const classPropertyName of Object.keys(obj)) {
|
6242 | const value = obj[classPropertyName];
|
6243 | const bindingPropertyName = Array.isArray(value) ? value[0] : value;
|
6244 | const inputOrOutput = { classPropertyName, bindingPropertyName };
|
6245 | forwardMap.set(classPropertyName, inputOrOutput);
|
6246 | }
|
6247 | return new ClassPropertyMapping(forwardMap);
|
6248 | }
|
6249 | static merge(a, b) {
|
6250 | const forwardMap = new Map(a.forwardMap.entries());
|
6251 | for (const [classPropertyName, inputOrOutput] of b.forwardMap) {
|
6252 | forwardMap.set(classPropertyName, inputOrOutput);
|
6253 | }
|
6254 | return new ClassPropertyMapping(forwardMap);
|
6255 | }
|
6256 | get classPropertyNames() {
|
6257 | return Array.from(this.forwardMap.keys());
|
6258 | }
|
6259 | get propertyNames() {
|
6260 | return Array.from(this.reverseMap.keys());
|
6261 | }
|
6262 | hasBindingPropertyName(propertyName) {
|
6263 | return this.reverseMap.has(propertyName);
|
6264 | }
|
6265 | getByBindingPropertyName(propertyName) {
|
6266 | return this.reverseMap.has(propertyName) ? this.reverseMap.get(propertyName) : null;
|
6267 | }
|
6268 | getByClassPropertyName(classPropertyName) {
|
6269 | return this.forwardMap.has(classPropertyName) ? this.forwardMap.get(classPropertyName) : null;
|
6270 | }
|
6271 | toDirectMappedObject() {
|
6272 | const obj = {};
|
6273 | for (const [classPropertyName, inputOrOutput] of this.forwardMap) {
|
6274 | obj[classPropertyName] = inputOrOutput.bindingPropertyName;
|
6275 | }
|
6276 | return obj;
|
6277 | }
|
6278 | toJointMappedObject() {
|
6279 | const obj = {};
|
6280 | for (const [classPropertyName, inputOrOutput] of this.forwardMap) {
|
6281 | if (inputOrOutput.bindingPropertyName === classPropertyName) {
|
6282 | obj[classPropertyName] = inputOrOutput.bindingPropertyName;
|
6283 | } else {
|
6284 | obj[classPropertyName] = [inputOrOutput.bindingPropertyName, classPropertyName];
|
6285 | }
|
6286 | }
|
6287 | return obj;
|
6288 | }
|
6289 | *[Symbol.iterator]() {
|
6290 | for (const [classPropertyName, inputOrOutput] of this.forwardMap.entries()) {
|
6291 | yield [classPropertyName, inputOrOutput.bindingPropertyName];
|
6292 | }
|
6293 | }
|
6294 | };
|
6295 | function reverseMapFromForwardMap(forwardMap) {
|
6296 | const reverseMap = new Map();
|
6297 | for (const [_, inputOrOutput] of forwardMap) {
|
6298 | if (!reverseMap.has(inputOrOutput.bindingPropertyName)) {
|
6299 | reverseMap.set(inputOrOutput.bindingPropertyName, []);
|
6300 | }
|
6301 | reverseMap.get(inputOrOutput.bindingPropertyName).push(inputOrOutput);
|
6302 | }
|
6303 | return reverseMap;
|
6304 | }
|
6305 |
|
6306 |
|
6307 | import ts27 from "typescript";
|
6308 | function extractReferencesFromType(checker, def, bestGuessOwningModule) {
|
6309 | if (!ts27.isTupleTypeNode(def)) {
|
6310 | return [];
|
6311 | }
|
6312 | return def.elements.map((element) => {
|
6313 | if (!ts27.isTypeQueryNode(element)) {
|
6314 | throw new Error(`Expected TypeQueryNode: ${nodeDebugInfo(element)}`);
|
6315 | }
|
6316 | const type = element.exprName;
|
6317 | const { node, from } = reflectTypeEntityToDeclaration(type, checker);
|
6318 | if (!isNamedClassDeclaration(node)) {
|
6319 | throw new Error(`Expected named ClassDeclaration: ${nodeDebugInfo(node)}`);
|
6320 | }
|
6321 | if (from !== null && !from.startsWith(".")) {
|
6322 | return new Reference(node, { specifier: from, resolutionContext: def.getSourceFile().fileName });
|
6323 | } else {
|
6324 | return new Reference(node, bestGuessOwningModule);
|
6325 | }
|
6326 | });
|
6327 | }
|
6328 | function readStringType(type) {
|
6329 | if (!ts27.isLiteralTypeNode(type) || !ts27.isStringLiteral(type.literal)) {
|
6330 | return null;
|
6331 | }
|
6332 | return type.literal.text;
|
6333 | }
|
6334 | function readStringMapType(type) {
|
6335 | if (!ts27.isTypeLiteralNode(type)) {
|
6336 | return {};
|
6337 | }
|
6338 | const obj = {};
|
6339 | type.members.forEach((member) => {
|
6340 | if (!ts27.isPropertySignature(member) || member.type === void 0 || member.name === void 0 || !ts27.isStringLiteral(member.name)) {
|
6341 | return;
|
6342 | }
|
6343 | const value = readStringType(member.type);
|
6344 | if (value === null) {
|
6345 | return null;
|
6346 | }
|
6347 | obj[member.name.text] = value;
|
6348 | });
|
6349 | return obj;
|
6350 | }
|
6351 | function readStringArrayType(type) {
|
6352 | if (!ts27.isTupleTypeNode(type)) {
|
6353 | return [];
|
6354 | }
|
6355 | const res = [];
|
6356 | type.elements.forEach((el) => {
|
6357 | if (!ts27.isLiteralTypeNode(el) || !ts27.isStringLiteral(el.literal)) {
|
6358 | return;
|
6359 | }
|
6360 | res.push(el.literal.text);
|
6361 | });
|
6362 | return res;
|
6363 | }
|
6364 | function extractDirectiveTypeCheckMeta(node, inputs, reflector) {
|
6365 | const members = reflector.getMembersOfClass(node);
|
6366 | const staticMembers = members.filter((member) => member.isStatic);
|
6367 | const ngTemplateGuards = staticMembers.map(extractTemplateGuard).filter((guard) => guard !== null);
|
6368 | const hasNgTemplateContextGuard = staticMembers.some((member) => member.kind === ClassMemberKind.Method && member.name === "ngTemplateContextGuard");
|
6369 | const coercedInputFields = new Set(staticMembers.map(extractCoercedInput).filter((inputName) => inputName !== null));
|
6370 | const restrictedInputFields = new Set();
|
6371 | const stringLiteralInputFields = new Set();
|
6372 | const undeclaredInputFields = new Set();
|
6373 | for (const classPropertyName of inputs.classPropertyNames) {
|
6374 | const field = members.find((member) => member.name === classPropertyName);
|
6375 | if (field === void 0 || field.node === null) {
|
6376 | undeclaredInputFields.add(classPropertyName);
|
6377 | continue;
|
6378 | }
|
6379 | if (isRestricted(field.node)) {
|
6380 | restrictedInputFields.add(classPropertyName);
|
6381 | }
|
6382 | if (field.nameNode !== null && ts27.isStringLiteral(field.nameNode)) {
|
6383 | stringLiteralInputFields.add(classPropertyName);
|
6384 | }
|
6385 | }
|
6386 | const arity = reflector.getGenericArityOfClass(node);
|
6387 | return {
|
6388 | hasNgTemplateContextGuard,
|
6389 | ngTemplateGuards,
|
6390 | coercedInputFields,
|
6391 | restrictedInputFields,
|
6392 | stringLiteralInputFields,
|
6393 | undeclaredInputFields,
|
6394 | isGeneric: arity !== null && arity > 0
|
6395 | };
|
6396 | }
|
6397 | function isRestricted(node) {
|
6398 | if (node.modifiers === void 0) {
|
6399 | return false;
|
6400 | }
|
6401 | return node.modifiers.some((modifier) => modifier.kind === ts27.SyntaxKind.PrivateKeyword || modifier.kind === ts27.SyntaxKind.ProtectedKeyword || modifier.kind === ts27.SyntaxKind.ReadonlyKeyword);
|
6402 | }
|
6403 | function extractTemplateGuard(member) {
|
6404 | if (!member.name.startsWith("ngTemplateGuard_")) {
|
6405 | return null;
|
6406 | }
|
6407 | const inputName = afterUnderscore(member.name);
|
6408 | if (member.kind === ClassMemberKind.Property) {
|
6409 | let type = null;
|
6410 | if (member.type !== null && ts27.isLiteralTypeNode(member.type) && ts27.isStringLiteral(member.type.literal)) {
|
6411 | type = member.type.literal.text;
|
6412 | }
|
6413 | if (type !== "binding") {
|
6414 | return null;
|
6415 | }
|
6416 | return { inputName, type };
|
6417 | } else if (member.kind === ClassMemberKind.Method) {
|
6418 | return { inputName, type: "invocation" };
|
6419 | } else {
|
6420 | return null;
|
6421 | }
|
6422 | }
|
6423 | function extractCoercedInput(member) {
|
6424 | if (member.kind !== ClassMemberKind.Property || !member.name.startsWith("ngAcceptInputType_")) {
|
6425 | return null;
|
6426 | }
|
6427 | return afterUnderscore(member.name);
|
6428 | }
|
6429 | var CompoundMetadataReader = class {
|
6430 | constructor(readers) {
|
6431 | this.readers = readers;
|
6432 | }
|
6433 | getDirectiveMetadata(node) {
|
6434 | for (const reader of this.readers) {
|
6435 | const meta = reader.getDirectiveMetadata(node);
|
6436 | if (meta !== null) {
|
6437 | return meta;
|
6438 | }
|
6439 | }
|
6440 | return null;
|
6441 | }
|
6442 | getNgModuleMetadata(node) {
|
6443 | for (const reader of this.readers) {
|
6444 | const meta = reader.getNgModuleMetadata(node);
|
6445 | if (meta !== null) {
|
6446 | return meta;
|
6447 | }
|
6448 | }
|
6449 | return null;
|
6450 | }
|
6451 | getPipeMetadata(node) {
|
6452 | for (const reader of this.readers) {
|
6453 | const meta = reader.getPipeMetadata(node);
|
6454 | if (meta !== null) {
|
6455 | return meta;
|
6456 | }
|
6457 | }
|
6458 | return null;
|
6459 | }
|
6460 | };
|
6461 | function afterUnderscore(str) {
|
6462 | const pos = str.indexOf("_");
|
6463 | if (pos === -1) {
|
6464 | throw new Error(`Expected '${str}' to contain '_'`);
|
6465 | }
|
6466 | return str.substr(pos + 1);
|
6467 | }
|
6468 | function hasInjectableFields(clazz, host) {
|
6469 | const members = host.getMembersOfClass(clazz);
|
6470 | return members.some(({ isStatic, name }) => isStatic && (name === "\u0275prov" || name === "\u0275fac"));
|
6471 | }
|
6472 |
|
6473 |
|
6474 | var DtsMetadataReader = class {
|
6475 | constructor(checker, reflector) {
|
6476 | this.checker = checker;
|
6477 | this.reflector = reflector;
|
6478 | }
|
6479 | getNgModuleMetadata(ref) {
|
6480 | const clazz = ref.node;
|
6481 | const ngModuleDef = this.reflector.getMembersOfClass(clazz).find((member) => member.name === "\u0275mod" && member.isStatic);
|
6482 | if (ngModuleDef === void 0) {
|
6483 | return null;
|
6484 | } else if (ngModuleDef.type === null || !ts28.isTypeReferenceNode(ngModuleDef.type) || ngModuleDef.type.typeArguments === void 0 || ngModuleDef.type.typeArguments.length !== 4) {
|
6485 | return null;
|
6486 | }
|
6487 | const [_, declarationMetadata, importMetadata, exportMetadata] = ngModuleDef.type.typeArguments;
|
6488 | return {
|
6489 | ref,
|
6490 | declarations: extractReferencesFromType(this.checker, declarationMetadata, ref.bestGuessOwningModule),
|
6491 | exports: extractReferencesFromType(this.checker, exportMetadata, ref.bestGuessOwningModule),
|
6492 | imports: extractReferencesFromType(this.checker, importMetadata, ref.bestGuessOwningModule),
|
6493 | schemas: [],
|
6494 | rawDeclarations: null
|
6495 | };
|
6496 | }
|
6497 | getDirectiveMetadata(ref) {
|
6498 | const clazz = ref.node;
|
6499 | const def = this.reflector.getMembersOfClass(clazz).find((field) => field.isStatic && (field.name === "\u0275cmp" || field.name === "\u0275dir"));
|
6500 | if (def === void 0) {
|
6501 | return null;
|
6502 | } else if (def.type === null || !ts28.isTypeReferenceNode(def.type) || def.type.typeArguments === void 0 || def.type.typeArguments.length < 2) {
|
6503 | return null;
|
6504 | }
|
6505 | const isComponent = def.name === "\u0275cmp";
|
6506 | const ctorParams = this.reflector.getConstructorParameters(clazz);
|
6507 | const isStructural = !isComponent && ctorParams !== null && ctorParams.some((param) => {
|
6508 | return param.typeValueReference.kind === 1 && param.typeValueReference.moduleName === "@angular/core" && param.typeValueReference.importedName === "TemplateRef";
|
6509 | });
|
6510 | const inputs = ClassPropertyMapping.fromMappedObject(readStringMapType(def.type.typeArguments[3]));
|
6511 | const outputs = ClassPropertyMapping.fromMappedObject(readStringMapType(def.type.typeArguments[4]));
|
6512 | return __spreadProps(__spreadValues({
|
6513 | type: MetaType.Directive,
|
6514 | ref,
|
6515 | name: clazz.name.text,
|
6516 | isComponent,
|
6517 | selector: readStringType(def.type.typeArguments[1]),
|
6518 | exportAs: readStringArrayType(def.type.typeArguments[2]),
|
6519 | inputs,
|
6520 | outputs,
|
6521 | queries: readStringArrayType(def.type.typeArguments[5])
|
6522 | }, extractDirectiveTypeCheckMeta(clazz, inputs, this.reflector)), {
|
6523 | baseClass: readBaseClass(clazz, this.checker, this.reflector),
|
6524 | isPoisoned: false,
|
6525 | isStructural
|
6526 | });
|
6527 | }
|
6528 | getPipeMetadata(ref) {
|
6529 | const def = this.reflector.getMembersOfClass(ref.node).find((field) => field.isStatic && field.name === "\u0275pipe");
|
6530 | if (def === void 0) {
|
6531 | return null;
|
6532 | } else if (def.type === null || !ts28.isTypeReferenceNode(def.type) || def.type.typeArguments === void 0 || def.type.typeArguments.length < 2) {
|
6533 | return null;
|
6534 | }
|
6535 | const type = def.type.typeArguments[1];
|
6536 | if (!ts28.isLiteralTypeNode(type) || !ts28.isStringLiteral(type.literal)) {
|
6537 | return null;
|
6538 | }
|
6539 | const name = type.literal.text;
|
6540 | return {
|
6541 | type: MetaType.Pipe,
|
6542 | ref,
|
6543 | name,
|
6544 | nameExpr: null
|
6545 | };
|
6546 | }
|
6547 | };
|
6548 | function readBaseClass(clazz, checker, reflector) {
|
6549 | if (!isNamedClassDeclaration(clazz)) {
|
6550 | return reflector.hasBaseClass(clazz) ? "dynamic" : null;
|
6551 | }
|
6552 | if (clazz.heritageClauses !== void 0) {
|
6553 | for (const clause of clazz.heritageClauses) {
|
6554 | if (clause.token === ts28.SyntaxKind.ExtendsKeyword) {
|
6555 | const baseExpr = clause.types[0].expression;
|
6556 | let symbol = checker.getSymbolAtLocation(baseExpr);
|
6557 | if (symbol === void 0) {
|
6558 | return "dynamic";
|
6559 | } else if (symbol.flags & ts28.SymbolFlags.Alias) {
|
6560 | symbol = checker.getAliasedSymbol(symbol);
|
6561 | }
|
6562 | if (symbol.valueDeclaration !== void 0 && isNamedClassDeclaration(symbol.valueDeclaration)) {
|
6563 | return new Reference(symbol.valueDeclaration);
|
6564 | } else {
|
6565 | return "dynamic";
|
6566 | }
|
6567 | }
|
6568 | }
|
6569 | }
|
6570 | return null;
|
6571 | }
|
6572 |
|
6573 |
|
6574 | function flattenInheritedDirectiveMetadata(reader, dir) {
|
6575 | const topMeta = reader.getDirectiveMetadata(dir);
|
6576 | if (topMeta === null) {
|
6577 | throw new Error(`Metadata not found for directive: ${dir.debugName}`);
|
6578 | }
|
6579 | if (topMeta.baseClass === null) {
|
6580 | return topMeta;
|
6581 | }
|
6582 | const coercedInputFields = new Set();
|
6583 | const undeclaredInputFields = new Set();
|
6584 | const restrictedInputFields = new Set();
|
6585 | const stringLiteralInputFields = new Set();
|
6586 | let isDynamic = false;
|
6587 | let inputs = ClassPropertyMapping.empty();
|
6588 | let outputs = ClassPropertyMapping.empty();
|
6589 | let isStructural = false;
|
6590 | const addMetadata = (meta) => {
|
6591 | if (meta.baseClass === "dynamic") {
|
6592 | isDynamic = true;
|
6593 | } else if (meta.baseClass !== null) {
|
6594 | const baseMeta = reader.getDirectiveMetadata(meta.baseClass);
|
6595 | if (baseMeta !== null) {
|
6596 | addMetadata(baseMeta);
|
6597 | } else {
|
6598 | isDynamic = true;
|
6599 | }
|
6600 | }
|
6601 | isStructural = isStructural || meta.isStructural;
|
6602 | inputs = ClassPropertyMapping.merge(inputs, meta.inputs);
|
6603 | outputs = ClassPropertyMapping.merge(outputs, meta.outputs);
|
6604 | for (const coercedInputField of meta.coercedInputFields) {
|
6605 | coercedInputFields.add(coercedInputField);
|
6606 | }
|
6607 | for (const undeclaredInputField of meta.undeclaredInputFields) {
|
6608 | undeclaredInputFields.add(undeclaredInputField);
|
6609 | }
|
6610 | for (const restrictedInputField of meta.restrictedInputFields) {
|
6611 | restrictedInputFields.add(restrictedInputField);
|
6612 | }
|
6613 | for (const field of meta.stringLiteralInputFields) {
|
6614 | stringLiteralInputFields.add(field);
|
6615 | }
|
6616 | };
|
6617 | addMetadata(topMeta);
|
6618 | return __spreadProps(__spreadValues({}, topMeta), {
|
6619 | inputs,
|
6620 | outputs,
|
6621 | coercedInputFields,
|
6622 | undeclaredInputFields,
|
6623 | restrictedInputFields,
|
6624 | stringLiteralInputFields,
|
6625 | baseClass: isDynamic ? "dynamic" : null,
|
6626 | isStructural
|
6627 | });
|
6628 | }
|
6629 |
|
6630 |
|
6631 | var LocalMetadataRegistry = class {
|
6632 | constructor() {
|
6633 | this.directives = new Map();
|
6634 | this.ngModules = new Map();
|
6635 | this.pipes = new Map();
|
6636 | }
|
6637 | getDirectiveMetadata(ref) {
|
6638 | return this.directives.has(ref.node) ? this.directives.get(ref.node) : null;
|
6639 | }
|
6640 | getNgModuleMetadata(ref) {
|
6641 | return this.ngModules.has(ref.node) ? this.ngModules.get(ref.node) : null;
|
6642 | }
|
6643 | getPipeMetadata(ref) {
|
6644 | return this.pipes.has(ref.node) ? this.pipes.get(ref.node) : null;
|
6645 | }
|
6646 | registerDirectiveMetadata(meta) {
|
6647 | this.directives.set(meta.ref.node, meta);
|
6648 | }
|
6649 | registerNgModuleMetadata(meta) {
|
6650 | this.ngModules.set(meta.ref.node, meta);
|
6651 | }
|
6652 | registerPipeMetadata(meta) {
|
6653 | this.pipes.set(meta.ref.node, meta);
|
6654 | }
|
6655 | };
|
6656 | var CompoundMetadataRegistry = class {
|
6657 | constructor(registries) {
|
6658 | this.registries = registries;
|
6659 | }
|
6660 | registerDirectiveMetadata(meta) {
|
6661 | for (const registry of this.registries) {
|
6662 | registry.registerDirectiveMetadata(meta);
|
6663 | }
|
6664 | }
|
6665 | registerNgModuleMetadata(meta) {
|
6666 | for (const registry of this.registries) {
|
6667 | registry.registerNgModuleMetadata(meta);
|
6668 | }
|
6669 | }
|
6670 | registerPipeMetadata(meta) {
|
6671 | for (const registry of this.registries) {
|
6672 | registry.registerPipeMetadata(meta);
|
6673 | }
|
6674 | }
|
6675 | };
|
6676 | var InjectableClassRegistry = class {
|
6677 | constructor(host) {
|
6678 | this.host = host;
|
6679 | this.classes = new Set();
|
6680 | }
|
6681 | registerInjectable(declaration) {
|
6682 | this.classes.add(declaration);
|
6683 | }
|
6684 | isInjectable(declaration) {
|
6685 | return this.classes.has(declaration) || hasInjectableFields(declaration, this.host);
|
6686 | }
|
6687 | };
|
6688 |
|
6689 |
|
6690 | var ResourceRegistry = class {
|
6691 | constructor() {
|
6692 | this.externalTemplateToComponentsMap = new Map();
|
6693 | this.componentToTemplateMap = new Map();
|
6694 | this.componentToStylesMap = new Map();
|
6695 | this.externalStyleToComponentsMap = new Map();
|
6696 | }
|
6697 | getComponentsWithTemplate(template) {
|
6698 | if (!this.externalTemplateToComponentsMap.has(template)) {
|
6699 | return new Set();
|
6700 | }
|
6701 | return this.externalTemplateToComponentsMap.get(template);
|
6702 | }
|
6703 | registerResources(resources, component) {
|
6704 | if (resources.template !== null) {
|
6705 | this.registerTemplate(resources.template, component);
|
6706 | }
|
6707 | for (const style of resources.styles) {
|
6708 | this.registerStyle(style, component);
|
6709 | }
|
6710 | }
|
6711 | registerTemplate(templateResource, component) {
|
6712 | const { path: path7 } = templateResource;
|
6713 | if (path7 !== null) {
|
6714 | if (!this.externalTemplateToComponentsMap.has(path7)) {
|
6715 | this.externalTemplateToComponentsMap.set(path7, new Set());
|
6716 | }
|
6717 | this.externalTemplateToComponentsMap.get(path7).add(component);
|
6718 | }
|
6719 | this.componentToTemplateMap.set(component, templateResource);
|
6720 | }
|
6721 | getTemplate(component) {
|
6722 | if (!this.componentToTemplateMap.has(component)) {
|
6723 | return null;
|
6724 | }
|
6725 | return this.componentToTemplateMap.get(component);
|
6726 | }
|
6727 | registerStyle(styleResource, component) {
|
6728 | const { path: path7 } = styleResource;
|
6729 | if (!this.componentToStylesMap.has(component)) {
|
6730 | this.componentToStylesMap.set(component, new Set());
|
6731 | }
|
6732 | if (path7 !== null) {
|
6733 | if (!this.externalStyleToComponentsMap.has(path7)) {
|
6734 | this.externalStyleToComponentsMap.set(path7, new Set());
|
6735 | }
|
6736 | this.externalStyleToComponentsMap.get(path7).add(component);
|
6737 | }
|
6738 | this.componentToStylesMap.get(component).add(styleResource);
|
6739 | }
|
6740 | getStyles(component) {
|
6741 | if (!this.componentToStylesMap.has(component)) {
|
6742 | return new Set();
|
6743 | }
|
6744 | return this.componentToStylesMap.get(component);
|
6745 | }
|
6746 | getComponentsWithStyle(styleUrl) {
|
6747 | if (!this.externalStyleToComponentsMap.has(styleUrl)) {
|
6748 | return new Set();
|
6749 | }
|
6750 | return this.externalStyleToComponentsMap.get(styleUrl);
|
6751 | }
|
6752 | };
|
6753 |
|
6754 |
|
6755 | import ts29 from "typescript";
|
6756 |
|
6757 |
|
6758 | var DynamicValue = class {
|
6759 | constructor(node, reason, code) {
|
6760 | this.node = node;
|
6761 | this.reason = reason;
|
6762 | this.code = code;
|
6763 | }
|
6764 | static fromDynamicInput(node, input) {
|
6765 | return new DynamicValue(node, input, 0);
|
6766 | }
|
6767 | static fromDynamicString(node) {
|
6768 | return new DynamicValue(node, void 0, 1);
|
6769 | }
|
6770 | static fromExternalReference(node, ref) {
|
6771 | return new DynamicValue(node, ref, 2);
|
6772 | }
|
6773 | static fromUnsupportedSyntax(node) {
|
6774 | return new DynamicValue(node, void 0, 3);
|
6775 | }
|
6776 | static fromUnknownIdentifier(node) {
|
6777 | return new DynamicValue(node, void 0, 4);
|
6778 | }
|
6779 | static fromInvalidExpressionType(node, value) {
|
6780 | return new DynamicValue(node, value, 5);
|
6781 | }
|
6782 | static fromComplexFunctionCall(node, fn) {
|
6783 | return new DynamicValue(node, fn, 6);
|
6784 | }
|
6785 | static fromDynamicType(node) {
|
6786 | return new DynamicValue(node, void 0, 7);
|
6787 | }
|
6788 | static fromUnknown(node) {
|
6789 | return new DynamicValue(node, void 0, 8);
|
6790 | }
|
6791 | isFromDynamicInput() {
|
6792 | return this.code === 0;
|
6793 | }
|
6794 | isFromDynamicString() {
|
6795 | return this.code === 1;
|
6796 | }
|
6797 | isFromExternalReference() {
|
6798 | return this.code === 2;
|
6799 | }
|
6800 | isFromUnsupportedSyntax() {
|
6801 | return this.code === 3;
|
6802 | }
|
6803 | isFromUnknownIdentifier() {
|
6804 | return this.code === 4;
|
6805 | }
|
6806 | isFromInvalidExpressionType() {
|
6807 | return this.code === 5;
|
6808 | }
|
6809 | isFromComplexFunctionCall() {
|
6810 | return this.code === 6;
|
6811 | }
|
6812 | isFromDynamicType() {
|
6813 | return this.code === 7;
|
6814 | }
|
6815 | isFromUnknown() {
|
6816 | return this.code === 8;
|
6817 | }
|
6818 | accept(visitor) {
|
6819 | switch (this.code) {
|
6820 | case 0:
|
6821 | return visitor.visitDynamicInput(this);
|
6822 | case 1:
|
6823 | return visitor.visitDynamicString(this);
|
6824 | case 2:
|
6825 | return visitor.visitExternalReference(this);
|
6826 | case 3:
|
6827 | return visitor.visitUnsupportedSyntax(this);
|
6828 | case 4:
|
6829 | return visitor.visitUnknownIdentifier(this);
|
6830 | case 5:
|
6831 | return visitor.visitInvalidExpressionType(this);
|
6832 | case 6:
|
6833 | return visitor.visitComplexFunctionCall(this);
|
6834 | case 7:
|
6835 | return visitor.visitDynamicType(this);
|
6836 | case 8:
|
6837 | return visitor.visitUnknown(this);
|
6838 | }
|
6839 | }
|
6840 | };
|
6841 |
|
6842 |
|
6843 | var ResolvedModule = class {
|
6844 | constructor(exports, evaluate) {
|
6845 | this.exports = exports;
|
6846 | this.evaluate = evaluate;
|
6847 | }
|
6848 | getExport(name) {
|
6849 | if (!this.exports.has(name)) {
|
6850 | return void 0;
|
6851 | }
|
6852 | return this.evaluate(this.exports.get(name));
|
6853 | }
|
6854 | getExports() {
|
6855 | const map = new Map();
|
6856 | this.exports.forEach((decl, name) => {
|
6857 | map.set(name, this.evaluate(decl));
|
6858 | });
|
6859 | return map;
|
6860 | }
|
6861 | };
|
6862 | var EnumValue = class {
|
6863 | constructor(enumRef, name, resolved) {
|
6864 | this.enumRef = enumRef;
|
6865 | this.name = name;
|
6866 | this.resolved = resolved;
|
6867 | }
|
6868 | };
|
6869 | var KnownFn = class {
|
6870 | };
|
6871 |
|
6872 |
|
6873 | function describeResolvedType(value, maxDepth = 1) {
|
6874 | var _a, _b;
|
6875 | if (value === null) {
|
6876 | return "null";
|
6877 | } else if (value === void 0) {
|
6878 | return "undefined";
|
6879 | } else if (typeof value === "number" || typeof value === "boolean" || typeof value === "string") {
|
6880 | return typeof value;
|
6881 | } else if (value instanceof Map) {
|
6882 | if (maxDepth === 0) {
|
6883 | return "object";
|
6884 | }
|
6885 | const entries = Array.from(value.entries()).map(([key, v]) => {
|
6886 | return `${quoteKey(key)}: ${describeResolvedType(v, maxDepth - 1)}`;
|
6887 | });
|
6888 | return entries.length > 0 ? `{ ${entries.join("; ")} }` : "{}";
|
6889 | } else if (value instanceof ResolvedModule) {
|
6890 | return "(module)";
|
6891 | } else if (value instanceof EnumValue) {
|
6892 | return (_a = value.enumRef.debugName) != null ? _a : "(anonymous)";
|
6893 | } else if (value instanceof Reference) {
|
6894 | return (_b = value.debugName) != null ? _b : "(anonymous)";
|
6895 | } else if (Array.isArray(value)) {
|
6896 | if (maxDepth === 0) {
|
6897 | return "Array";
|
6898 | }
|
6899 | return `[${value.map((v) => describeResolvedType(v, maxDepth - 1)).join(", ")}]`;
|
6900 | } else if (value instanceof DynamicValue) {
|
6901 | return "(not statically analyzable)";
|
6902 | } else if (value instanceof KnownFn) {
|
6903 | return "Function";
|
6904 | } else {
|
6905 | return "unknown";
|
6906 | }
|
6907 | }
|
6908 | function quoteKey(key) {
|
6909 | if (/^[a-z0-9_]+$/i.test(key)) {
|
6910 | return key;
|
6911 | } else {
|
6912 | return `'${key.replace(/'/g, "\\'")}'`;
|
6913 | }
|
6914 | }
|
6915 | function traceDynamicValue(node, value) {
|
6916 | return value.accept(new TraceDynamicValueVisitor(node));
|
6917 | }
|
6918 | var TraceDynamicValueVisitor = class {
|
6919 | constructor(node) {
|
6920 | this.node = node;
|
6921 | this.currentContainerNode = null;
|
6922 | }
|
6923 | visitDynamicInput(value) {
|
6924 | const trace = value.reason.accept(this);
|
6925 | if (this.shouldTrace(value.node)) {
|
6926 | const info = makeRelatedInformation(value.node, "Unable to evaluate this expression statically.");
|
6927 | trace.unshift(info);
|
6928 | }
|
6929 | return trace;
|
6930 | }
|
6931 | visitDynamicString(value) {
|
6932 | return [makeRelatedInformation(value.node, "A string value could not be determined statically.")];
|
6933 | }
|
6934 | visitExternalReference(value) {
|
6935 | const name = value.reason.debugName;
|
6936 | const description = name !== null ? `'${name}'` : "an anonymous declaration";
|
6937 | return [makeRelatedInformation(value.node, `A value for ${description} cannot be determined statically, as it is an external declaration.`)];
|
6938 | }
|
6939 | visitComplexFunctionCall(value) {
|
6940 | return [
|
6941 | makeRelatedInformation(value.node, "Unable to evaluate function call of complex function. A function must have exactly one return statement."),
|
6942 | makeRelatedInformation(value.reason.node, "Function is declared here.")
|
6943 | ];
|
6944 | }
|
6945 | visitInvalidExpressionType(value) {
|
6946 | return [makeRelatedInformation(value.node, "Unable to evaluate an invalid expression.")];
|
6947 | }
|
6948 | visitUnknown(value) {
|
6949 | return [makeRelatedInformation(value.node, "Unable to evaluate statically.")];
|
6950 | }
|
6951 | visitUnknownIdentifier(value) {
|
6952 | return [makeRelatedInformation(value.node, "Unknown reference.")];
|
6953 | }
|
6954 | visitDynamicType(value) {
|
6955 | return [makeRelatedInformation(value.node, "Dynamic type.")];
|
6956 | }
|
6957 | visitUnsupportedSyntax(value) {
|
6958 | return [makeRelatedInformation(value.node, "This syntax is not supported.")];
|
6959 | }
|
6960 | shouldTrace(node) {
|
6961 | if (node === this.node) {
|
6962 | return false;
|
6963 | }
|
6964 | const container = getContainerNode(node);
|
6965 | if (container === this.currentContainerNode) {
|
6966 | return false;
|
6967 | }
|
6968 | this.currentContainerNode = container;
|
6969 | return true;
|
6970 | }
|
6971 | };
|
6972 | function getContainerNode(node) {
|
6973 | let currentNode = node;
|
6974 | while (currentNode !== void 0) {
|
6975 | switch (currentNode.kind) {
|
6976 | case ts29.SyntaxKind.ExpressionStatement:
|
6977 | case ts29.SyntaxKind.VariableStatement:
|
6978 | case ts29.SyntaxKind.ReturnStatement:
|
6979 | case ts29.SyntaxKind.IfStatement:
|
6980 | case ts29.SyntaxKind.SwitchStatement:
|
6981 | case ts29.SyntaxKind.DoStatement:
|
6982 | case ts29.SyntaxKind.WhileStatement:
|
6983 | case ts29.SyntaxKind.ForStatement:
|
6984 | case ts29.SyntaxKind.ForInStatement:
|
6985 | case ts29.SyntaxKind.ForOfStatement:
|
6986 | case ts29.SyntaxKind.ContinueStatement:
|
6987 | case ts29.SyntaxKind.BreakStatement:
|
6988 | case ts29.SyntaxKind.ThrowStatement:
|
6989 | case ts29.SyntaxKind.ObjectBindingPattern:
|
6990 | case ts29.SyntaxKind.ArrayBindingPattern:
|
6991 | return currentNode;
|
6992 | }
|
6993 | currentNode = currentNode.parent;
|
6994 | }
|
6995 | return node.getSourceFile();
|
6996 | }
|
6997 |
|
6998 |
|
6999 | import ts30 from "typescript";
|
7000 |
|
7001 |
|
7002 | var ArraySliceBuiltinFn = class extends KnownFn {
|
7003 | constructor(lhs) {
|
7004 | super();
|
7005 | this.lhs = lhs;
|
7006 | }
|
7007 | evaluate(node, args) {
|
7008 | if (args.length === 0) {
|
7009 | return this.lhs;
|
7010 | } else {
|
7011 | return DynamicValue.fromUnknown(node);
|
7012 | }
|
7013 | }
|
7014 | };
|
7015 | var ArrayConcatBuiltinFn = class extends KnownFn {
|
7016 | constructor(lhs) {
|
7017 | super();
|
7018 | this.lhs = lhs;
|
7019 | }
|
7020 | evaluate(node, args) {
|
7021 | const result = [...this.lhs];
|
7022 | for (const arg of args) {
|
7023 | if (arg instanceof DynamicValue) {
|
7024 | result.push(DynamicValue.fromDynamicInput(node, arg));
|
7025 | } else if (Array.isArray(arg)) {
|
7026 | result.push(...arg);
|
7027 | } else {
|
7028 | result.push(arg);
|
7029 | }
|
7030 | }
|
7031 | return result;
|
7032 | }
|
7033 | };
|
7034 | var StringConcatBuiltinFn = class extends KnownFn {
|
7035 | constructor(lhs) {
|
7036 | super();
|
7037 | this.lhs = lhs;
|
7038 | }
|
7039 | evaluate(node, args) {
|
7040 | let result = this.lhs;
|
7041 | for (const arg of args) {
|
7042 | const resolved = arg instanceof EnumValue ? arg.resolved : arg;
|
7043 | if (typeof resolved === "string" || typeof resolved === "number" || typeof resolved === "boolean" || resolved == null) {
|
7044 | result = result.concat(resolved);
|
7045 | } else {
|
7046 | return DynamicValue.fromUnknown(node);
|
7047 | }
|
7048 | }
|
7049 | return result;
|
7050 | }
|
7051 | };
|
7052 | var ObjectAssignBuiltinFn = class extends KnownFn {
|
7053 | evaluate(node, args) {
|
7054 | if (args.length === 0) {
|
7055 | return DynamicValue.fromUnsupportedSyntax(node);
|
7056 | }
|
7057 | for (const arg of args) {
|
7058 | if (arg instanceof DynamicValue) {
|
7059 | return DynamicValue.fromDynamicInput(node, arg);
|
7060 | } else if (!(arg instanceof Map)) {
|
7061 | return DynamicValue.fromUnsupportedSyntax(node);
|
7062 | }
|
7063 | }
|
7064 | const [target, ...sources] = args;
|
7065 | for (const source of sources) {
|
7066 | source.forEach((value, key) => target.set(key, value));
|
7067 | }
|
7068 | return target;
|
7069 | }
|
7070 | };
|
7071 |
|
7072 |
|
7073 | var AssignHelperFn = class extends ObjectAssignBuiltinFn {
|
7074 | };
|
7075 | var SpreadHelperFn = class extends KnownFn {
|
7076 | evaluate(node, args) {
|
7077 | const result = [];
|
7078 | for (const arg of args) {
|
7079 | if (arg instanceof DynamicValue) {
|
7080 | result.push(DynamicValue.fromDynamicInput(node, arg));
|
7081 | } else if (Array.isArray(arg)) {
|
7082 | result.push(...arg);
|
7083 | } else {
|
7084 | result.push(arg);
|
7085 | }
|
7086 | }
|
7087 | return result;
|
7088 | }
|
7089 | };
|
7090 | var SpreadArrayHelperFn = class extends KnownFn {
|
7091 | evaluate(node, args) {
|
7092 | if (args.length !== 2 && args.length !== 3) {
|
7093 | return DynamicValue.fromUnknown(node);
|
7094 | }
|
7095 | const [to, from] = args;
|
7096 | if (to instanceof DynamicValue) {
|
7097 | return DynamicValue.fromDynamicInput(node, to);
|
7098 | } else if (from instanceof DynamicValue) {
|
7099 | return DynamicValue.fromDynamicInput(node, from);
|
7100 | }
|
7101 | if (!Array.isArray(to)) {
|
7102 | return DynamicValue.fromInvalidExpressionType(node, to);
|
7103 | } else if (!Array.isArray(from)) {
|
7104 | return DynamicValue.fromInvalidExpressionType(node, from);
|
7105 | }
|
7106 | return to.concat(from);
|
7107 | }
|
7108 | };
|
7109 | var ReadHelperFn = class extends KnownFn {
|
7110 | evaluate(node, args) {
|
7111 | if (args.length !== 1) {
|
7112 | return DynamicValue.fromUnknown(node);
|
7113 | }
|
7114 | const [value] = args;
|
7115 | if (value instanceof DynamicValue) {
|
7116 | return DynamicValue.fromDynamicInput(node, value);
|
7117 | }
|
7118 | if (!Array.isArray(value)) {
|
7119 | return DynamicValue.fromInvalidExpressionType(node, value);
|
7120 | }
|
7121 | return value;
|
7122 | }
|
7123 | };
|
7124 |
|
7125 |
|
7126 | var jsGlobalObjectValue = new Map([["assign", new ObjectAssignBuiltinFn()]]);
|
7127 | var assignTsHelperFn = new AssignHelperFn();
|
7128 | var spreadTsHelperFn = new SpreadHelperFn();
|
7129 | var spreadArrayTsHelperFn = new SpreadArrayHelperFn();
|
7130 | var readTsHelperFn = new ReadHelperFn();
|
7131 | function resolveKnownDeclaration(decl) {
|
7132 | switch (decl) {
|
7133 | case KnownDeclaration.JsGlobalObject:
|
7134 | return jsGlobalObjectValue;
|
7135 | case KnownDeclaration.TsHelperAssign:
|
7136 | return assignTsHelperFn;
|
7137 | case KnownDeclaration.TsHelperSpread:
|
7138 | case KnownDeclaration.TsHelperSpreadArrays:
|
7139 | return spreadTsHelperFn;
|
7140 | case KnownDeclaration.TsHelperSpreadArray:
|
7141 | return spreadArrayTsHelperFn;
|
7142 | case KnownDeclaration.TsHelperRead:
|
7143 | return readTsHelperFn;
|
7144 | default:
|
7145 | throw new Error(`Cannot resolve known declaration. Received: ${KnownDeclaration[decl]}.`);
|
7146 | }
|
7147 | }
|
7148 |
|
7149 |
|
7150 | function literalBinaryOp(op) {
|
7151 | return { op, literal: true };
|
7152 | }
|
7153 | function referenceBinaryOp(op) {
|
7154 | return { op, literal: false };
|
7155 | }
|
7156 | var BINARY_OPERATORS = new Map([
|
7157 | [ts30.SyntaxKind.PlusToken, literalBinaryOp((a, b) => a + b)],
|
7158 | [ts30.SyntaxKind.MinusToken, literalBinaryOp((a, b) => a - b)],
|
7159 | [ts30.SyntaxKind.AsteriskToken, literalBinaryOp((a, b) => a * b)],
|
7160 | [ts30.SyntaxKind.SlashToken, literalBinaryOp((a, b) => a / b)],
|
7161 | [ts30.SyntaxKind.PercentToken, literalBinaryOp((a, b) => a % b)],
|
7162 | [ts30.SyntaxKind.AmpersandToken, literalBinaryOp((a, b) => a & b)],
|
7163 | [ts30.SyntaxKind.BarToken, literalBinaryOp((a, b) => a | b)],
|
7164 | [ts30.SyntaxKind.CaretToken, literalBinaryOp((a, b) => a ^ b)],
|
7165 | [ts30.SyntaxKind.LessThanToken, literalBinaryOp((a, b) => a < b)],
|
7166 | [ts30.SyntaxKind.LessThanEqualsToken, literalBinaryOp((a, b) => a <= b)],
|
7167 | [ts30.SyntaxKind.GreaterThanToken, literalBinaryOp((a, b) => a > b)],
|
7168 | [ts30.SyntaxKind.GreaterThanEqualsToken, literalBinaryOp((a, b) => a >= b)],
|
7169 | [ts30.SyntaxKind.EqualsEqualsToken, literalBinaryOp((a, b) => a == b)],
|
7170 | [ts30.SyntaxKind.EqualsEqualsEqualsToken, literalBinaryOp((a, b) => a === b)],
|
7171 | [ts30.SyntaxKind.ExclamationEqualsToken, literalBinaryOp((a, b) => a != b)],
|
7172 | [ts30.SyntaxKind.ExclamationEqualsEqualsToken, literalBinaryOp((a, b) => a !== b)],
|
7173 | [ts30.SyntaxKind.LessThanLessThanToken, literalBinaryOp((a, b) => a << b)],
|
7174 | [ts30.SyntaxKind.GreaterThanGreaterThanToken, literalBinaryOp((a, b) => a >> b)],
|
7175 | [ts30.SyntaxKind.GreaterThanGreaterThanGreaterThanToken, literalBinaryOp((a, b) => a >>> b)],
|
7176 | [ts30.SyntaxKind.AsteriskAsteriskToken, literalBinaryOp((a, b) => Math.pow(a, b))],
|
7177 | [ts30.SyntaxKind.AmpersandAmpersandToken, referenceBinaryOp((a, b) => a && b)],
|
7178 | [ts30.SyntaxKind.BarBarToken, referenceBinaryOp((a, b) => a || b)]
|
7179 | ]);
|
7180 | var UNARY_OPERATORS = new Map([
|
7181 | [ts30.SyntaxKind.TildeToken, (a) => ~a],
|
7182 | [ts30.SyntaxKind.MinusToken, (a) => -a],
|
7183 | [ts30.SyntaxKind.PlusToken, (a) => +a],
|
7184 | [ts30.SyntaxKind.ExclamationToken, (a) => !a]
|
7185 | ]);
|
7186 | var StaticInterpreter = class {
|
7187 | constructor(host, checker, dependencyTracker) {
|
7188 | this.host = host;
|
7189 | this.checker = checker;
|
7190 | this.dependencyTracker = dependencyTracker;
|
7191 | }
|
7192 | visit(node, context) {
|
7193 | return this.visitExpression(node, context);
|
7194 | }
|
7195 | visitExpression(node, context) {
|
7196 | let result;
|
7197 | if (node.kind === ts30.SyntaxKind.TrueKeyword) {
|
7198 | return true;
|
7199 | } else if (node.kind === ts30.SyntaxKind.FalseKeyword) {
|
7200 | return false;
|
7201 | } else if (node.kind === ts30.SyntaxKind.NullKeyword) {
|
7202 | return null;
|
7203 | } else if (ts30.isStringLiteral(node)) {
|
7204 | return node.text;
|
7205 | } else if (ts30.isNoSubstitutionTemplateLiteral(node)) {
|
7206 | return node.text;
|
7207 | } else if (ts30.isTemplateExpression(node)) {
|
7208 | result = this.visitTemplateExpression(node, context);
|
7209 | } else if (ts30.isNumericLiteral(node)) {
|
7210 | return parseFloat(node.text);
|
7211 | } else if (ts30.isObjectLiteralExpression(node)) {
|
7212 | result = this.visitObjectLiteralExpression(node, context);
|
7213 | } else if (ts30.isIdentifier(node)) {
|
7214 | result = this.visitIdentifier(node, context);
|
7215 | } else if (ts30.isPropertyAccessExpression(node)) {
|
7216 | result = this.visitPropertyAccessExpression(node, context);
|
7217 | } else if (ts30.isCallExpression(node)) {
|
7218 | result = this.visitCallExpression(node, context);
|
7219 | } else if (ts30.isConditionalExpression(node)) {
|
7220 | result = this.visitConditionalExpression(node, context);
|
7221 | } else if (ts30.isPrefixUnaryExpression(node)) {
|
7222 | result = this.visitPrefixUnaryExpression(node, context);
|
7223 | } else if (ts30.isBinaryExpression(node)) {
|
7224 | result = this.visitBinaryExpression(node, context);
|
7225 | } else if (ts30.isArrayLiteralExpression(node)) {
|
7226 | result = this.visitArrayLiteralExpression(node, context);
|
7227 | } else if (ts30.isParenthesizedExpression(node)) {
|
7228 | result = this.visitParenthesizedExpression(node, context);
|
7229 | } else if (ts30.isElementAccessExpression(node)) {
|
7230 | result = this.visitElementAccessExpression(node, context);
|
7231 | } else if (ts30.isAsExpression(node)) {
|
7232 | result = this.visitExpression(node.expression, context);
|
7233 | } else if (ts30.isNonNullExpression(node)) {
|
7234 | result = this.visitExpression(node.expression, context);
|
7235 | } else if (this.host.isClass(node)) {
|
7236 | result = this.visitDeclaration(node, context);
|
7237 | } else {
|
7238 | return DynamicValue.fromUnsupportedSyntax(node);
|
7239 | }
|
7240 | if (result instanceof DynamicValue && result.node !== node) {
|
7241 | return DynamicValue.fromDynamicInput(node, result);
|
7242 | }
|
7243 | return result;
|
7244 | }
|
7245 | visitArrayLiteralExpression(node, context) {
|
7246 | const array = [];
|
7247 | for (let i = 0; i < node.elements.length; i++) {
|
7248 | const element = node.elements[i];
|
7249 | if (ts30.isSpreadElement(element)) {
|
7250 | array.push(...this.visitSpreadElement(element, context));
|
7251 | } else {
|
7252 | array.push(this.visitExpression(element, context));
|
7253 | }
|
7254 | }
|
7255 | return array;
|
7256 | }
|
7257 | visitObjectLiteralExpression(node, context) {
|
7258 | const map = new Map();
|
7259 | for (let i = 0; i < node.properties.length; i++) {
|
7260 | const property2 = node.properties[i];
|
7261 | if (ts30.isPropertyAssignment(property2)) {
|
7262 | const name = this.stringNameFromPropertyName(property2.name, context);
|
7263 | if (name === void 0) {
|
7264 | return DynamicValue.fromDynamicInput(node, DynamicValue.fromDynamicString(property2.name));
|
7265 | }
|
7266 | map.set(name, this.visitExpression(property2.initializer, context));
|
7267 | } else if (ts30.isShorthandPropertyAssignment(property2)) {
|
7268 | const symbol = this.checker.getShorthandAssignmentValueSymbol(property2);
|
7269 | if (symbol === void 0 || symbol.valueDeclaration === void 0) {
|
7270 | map.set(property2.name.text, DynamicValue.fromUnknown(property2));
|
7271 | } else {
|
7272 | map.set(property2.name.text, this.visitDeclaration(symbol.valueDeclaration, context));
|
7273 | }
|
7274 | } else if (ts30.isSpreadAssignment(property2)) {
|
7275 | const spread = this.visitExpression(property2.expression, context);
|
7276 | if (spread instanceof DynamicValue) {
|
7277 | return DynamicValue.fromDynamicInput(node, spread);
|
7278 | } else if (spread instanceof Map) {
|
7279 | spread.forEach((value, key) => map.set(key, value));
|
7280 | } else if (spread instanceof ResolvedModule) {
|
7281 | spread.getExports().forEach((value, key) => map.set(key, value));
|
7282 | } else {
|
7283 | return DynamicValue.fromDynamicInput(node, DynamicValue.fromInvalidExpressionType(property2, spread));
|
7284 | }
|
7285 | } else {
|
7286 | return DynamicValue.fromUnknown(node);
|
7287 | }
|
7288 | }
|
7289 | return map;
|
7290 | }
|
7291 | visitTemplateExpression(node, context) {
|
7292 | const pieces = [node.head.text];
|
7293 | for (let i = 0; i < node.templateSpans.length; i++) {
|
7294 | const span = node.templateSpans[i];
|
7295 | const value = literal(this.visit(span.expression, context), () => DynamicValue.fromDynamicString(span.expression));
|
7296 | if (value instanceof DynamicValue) {
|
7297 | return DynamicValue.fromDynamicInput(node, value);
|
7298 | }
|
7299 | pieces.push(`${value}`, span.literal.text);
|
7300 | }
|
7301 | return pieces.join("");
|
7302 | }
|
7303 | visitIdentifier(node, context) {
|
7304 | const decl = this.host.getDeclarationOfIdentifier(node);
|
7305 | if (decl === null) {
|
7306 | if (node.originalKeywordKind === ts30.SyntaxKind.UndefinedKeyword) {
|
7307 | return void 0;
|
7308 | } else {
|
7309 | if (this.dependencyTracker !== null && this.host.getImportOfIdentifier(node) !== null) {
|
7310 | this.dependencyTracker.recordDependencyAnalysisFailure(context.originatingFile);
|
7311 | }
|
7312 | return DynamicValue.fromUnknownIdentifier(node);
|
7313 | }
|
7314 | }
|
7315 | if (decl.known !== null) {
|
7316 | return resolveKnownDeclaration(decl.known);
|
7317 | } else if (isConcreteDeclaration(decl) && decl.identity !== null && decl.identity.kind === 0) {
|
7318 | return this.getResolvedEnum(decl.node, decl.identity.enumMembers, context);
|
7319 | }
|
7320 | const declContext = __spreadValues(__spreadValues({}, context), joinModuleContext(context, node, decl));
|
7321 | const result = this.visitAmbiguousDeclaration(decl, declContext);
|
7322 | if (result instanceof Reference) {
|
7323 | if (!result.synthetic) {
|
7324 | result.addIdentifier(node);
|
7325 | }
|
7326 | } else if (result instanceof DynamicValue) {
|
7327 | return DynamicValue.fromDynamicInput(node, result);
|
7328 | }
|
7329 | return result;
|
7330 | }
|
7331 | visitDeclaration(node, context) {
|
7332 | if (this.dependencyTracker !== null) {
|
7333 | this.dependencyTracker.addDependency(context.originatingFile, node.getSourceFile());
|
7334 | }
|
7335 | if (this.host.isClass(node)) {
|
7336 | return this.getReference(node, context);
|
7337 | } else if (ts30.isVariableDeclaration(node)) {
|
7338 | return this.visitVariableDeclaration(node, context);
|
7339 | } else if (ts30.isParameter(node) && context.scope.has(node)) {
|
7340 | return context.scope.get(node);
|
7341 | } else if (ts30.isExportAssignment(node)) {
|
7342 | return this.visitExpression(node.expression, context);
|
7343 | } else if (ts30.isEnumDeclaration(node)) {
|
7344 | return this.visitEnumDeclaration(node, context);
|
7345 | } else if (ts30.isSourceFile(node)) {
|
7346 | return this.visitSourceFile(node, context);
|
7347 | } else if (ts30.isBindingElement(node)) {
|
7348 | return this.visitBindingElement(node, context);
|
7349 | } else {
|
7350 | return this.getReference(node, context);
|
7351 | }
|
7352 | }
|
7353 | visitVariableDeclaration(node, context) {
|
7354 | const value = this.host.getVariableValue(node);
|
7355 | if (value !== null) {
|
7356 | return this.visitExpression(value, context);
|
7357 | } else if (isVariableDeclarationDeclared(node)) {
|
7358 | if (node.type !== void 0) {
|
7359 | const evaluatedType = this.visitType(node.type, context);
|
7360 | if (!(evaluatedType instanceof DynamicValue)) {
|
7361 | return evaluatedType;
|
7362 | }
|
7363 | }
|
7364 | return this.getReference(node, context);
|
7365 | } else {
|
7366 | return void 0;
|
7367 | }
|
7368 | }
|
7369 | visitEnumDeclaration(node, context) {
|
7370 | const enumRef = this.getReference(node, context);
|
7371 | const map = new Map();
|
7372 | node.members.forEach((member) => {
|
7373 | const name = this.stringNameFromPropertyName(member.name, context);
|
7374 | if (name !== void 0) {
|
7375 | const resolved = member.initializer && this.visit(member.initializer, context);
|
7376 | map.set(name, new EnumValue(enumRef, name, resolved));
|
7377 | }
|
7378 | });
|
7379 | return map;
|
7380 | }
|
7381 | visitElementAccessExpression(node, context) {
|
7382 | const lhs = this.visitExpression(node.expression, context);
|
7383 | if (lhs instanceof DynamicValue) {
|
7384 | return DynamicValue.fromDynamicInput(node, lhs);
|
7385 | }
|
7386 | const rhs = this.visitExpression(node.argumentExpression, context);
|
7387 | if (rhs instanceof DynamicValue) {
|
7388 | return DynamicValue.fromDynamicInput(node, rhs);
|
7389 | }
|
7390 | if (typeof rhs !== "string" && typeof rhs !== "number") {
|
7391 | return DynamicValue.fromInvalidExpressionType(node, rhs);
|
7392 | }
|
7393 | return this.accessHelper(node, lhs, rhs, context);
|
7394 | }
|
7395 | visitPropertyAccessExpression(node, context) {
|
7396 | const lhs = this.visitExpression(node.expression, context);
|
7397 | const rhs = node.name.text;
|
7398 | if (lhs instanceof DynamicValue) {
|
7399 | return DynamicValue.fromDynamicInput(node, lhs);
|
7400 | }
|
7401 | return this.accessHelper(node, lhs, rhs, context);
|
7402 | }
|
7403 | visitSourceFile(node, context) {
|
7404 | const declarations = this.host.getExportsOfModule(node);
|
7405 | if (declarations === null) {
|
7406 | return DynamicValue.fromUnknown(node);
|
7407 | }
|
7408 | return new ResolvedModule(declarations, (decl) => {
|
7409 | if (decl.known !== null) {
|
7410 | return resolveKnownDeclaration(decl.known);
|
7411 | }
|
7412 | const declContext = __spreadValues(__spreadValues({}, context), joinModuleContext(context, node, decl));
|
7413 | return this.visitAmbiguousDeclaration(decl, declContext);
|
7414 | });
|
7415 | }
|
7416 | visitAmbiguousDeclaration(decl, declContext) {
|
7417 | return decl.kind === 1 && decl.implementation !== void 0 && !isDeclaration(decl.implementation) ? this.visitExpression(decl.implementation, declContext) : this.visitDeclaration(decl.node, declContext);
|
7418 | }
|
7419 | accessHelper(node, lhs, rhs, context) {
|
7420 | const strIndex = `${rhs}`;
|
7421 | if (lhs instanceof Map) {
|
7422 | if (lhs.has(strIndex)) {
|
7423 | return lhs.get(strIndex);
|
7424 | } else {
|
7425 | return void 0;
|
7426 | }
|
7427 | } else if (lhs instanceof ResolvedModule) {
|
7428 | return lhs.getExport(strIndex);
|
7429 | } else if (Array.isArray(lhs)) {
|
7430 | if (rhs === "length") {
|
7431 | return lhs.length;
|
7432 | } else if (rhs === "slice") {
|
7433 | return new ArraySliceBuiltinFn(lhs);
|
7434 | } else if (rhs === "concat") {
|
7435 | return new ArrayConcatBuiltinFn(lhs);
|
7436 | }
|
7437 | if (typeof rhs !== "number" || !Number.isInteger(rhs)) {
|
7438 | return DynamicValue.fromInvalidExpressionType(node, rhs);
|
7439 | }
|
7440 | return lhs[rhs];
|
7441 | } else if (typeof lhs === "string" && rhs === "concat") {
|
7442 | return new StringConcatBuiltinFn(lhs);
|
7443 | } else if (lhs instanceof Reference) {
|
7444 | const ref = lhs.node;
|
7445 | if (this.host.isClass(ref)) {
|
7446 | const module7 = owningModule(context, lhs.bestGuessOwningModule);
|
7447 | let value = void 0;
|
7448 | const member = this.host.getMembersOfClass(ref).find((member2) => member2.isStatic && member2.name === strIndex);
|
7449 | if (member !== void 0) {
|
7450 | if (member.value !== null) {
|
7451 | value = this.visitExpression(member.value, context);
|
7452 | } else if (member.implementation !== null) {
|
7453 | value = new Reference(member.implementation, module7);
|
7454 | } else if (member.node) {
|
7455 | value = new Reference(member.node, module7);
|
7456 | }
|
7457 | }
|
7458 | return value;
|
7459 | } else if (isDeclaration(ref)) {
|
7460 | return DynamicValue.fromDynamicInput(node, DynamicValue.fromExternalReference(ref, lhs));
|
7461 | }
|
7462 | } else if (lhs instanceof DynamicValue) {
|
7463 | return DynamicValue.fromDynamicInput(node, lhs);
|
7464 | }
|
7465 | return DynamicValue.fromUnknown(node);
|
7466 | }
|
7467 | visitCallExpression(node, context) {
|
7468 | const lhs = this.visitExpression(node.expression, context);
|
7469 | if (lhs instanceof DynamicValue) {
|
7470 | return DynamicValue.fromDynamicInput(node, lhs);
|
7471 | }
|
7472 | if (lhs instanceof KnownFn) {
|
7473 | return lhs.evaluate(node, this.evaluateFunctionArguments(node, context));
|
7474 | }
|
7475 | if (!(lhs instanceof Reference)) {
|
7476 | return DynamicValue.fromInvalidExpressionType(node.expression, lhs);
|
7477 | }
|
7478 | const fn = this.host.getDefinitionOfFunction(lhs.node);
|
7479 | if (fn === null) {
|
7480 | return DynamicValue.fromInvalidExpressionType(node.expression, lhs);
|
7481 | }
|
7482 | if (!isFunctionOrMethodReference(lhs)) {
|
7483 | return DynamicValue.fromInvalidExpressionType(node.expression, lhs);
|
7484 | }
|
7485 | if (fn.body === null) {
|
7486 | let expr = null;
|
7487 | if (context.foreignFunctionResolver) {
|
7488 | expr = context.foreignFunctionResolver(lhs, node.arguments);
|
7489 | }
|
7490 | if (expr === null) {
|
7491 | return DynamicValue.fromDynamicInput(node, DynamicValue.fromExternalReference(node.expression, lhs));
|
7492 | }
|
7493 | if (expr.getSourceFile() !== node.expression.getSourceFile() && lhs.bestGuessOwningModule !== null) {
|
7494 | context = __spreadProps(__spreadValues({}, context), {
|
7495 | absoluteModuleName: lhs.bestGuessOwningModule.specifier,
|
7496 | resolutionContext: lhs.bestGuessOwningModule.resolutionContext
|
7497 | });
|
7498 | }
|
7499 | return this.visitFfrExpression(expr, context);
|
7500 | }
|
7501 | let res = this.visitFunctionBody(node, fn, context);
|
7502 | if (res instanceof DynamicValue && context.foreignFunctionResolver !== void 0) {
|
7503 | const ffrExpr = context.foreignFunctionResolver(lhs, node.arguments);
|
7504 | if (ffrExpr !== null) {
|
7505 | const ffrRes = this.visitFfrExpression(ffrExpr, context);
|
7506 | if (!(ffrRes instanceof DynamicValue)) {
|
7507 | res = ffrRes;
|
7508 | }
|
7509 | }
|
7510 | }
|
7511 | return res;
|
7512 | }
|
7513 | visitFfrExpression(expr, context) {
|
7514 | const res = this.visitExpression(expr, context);
|
7515 | if (res instanceof Reference) {
|
7516 | res.synthetic = true;
|
7517 | }
|
7518 | return res;
|
7519 | }
|
7520 | visitFunctionBody(node, fn, context) {
|
7521 | if (fn.body === null) {
|
7522 | return DynamicValue.fromUnknown(node);
|
7523 | } else if (fn.body.length !== 1 || !ts30.isReturnStatement(fn.body[0])) {
|
7524 | return DynamicValue.fromComplexFunctionCall(node, fn);
|
7525 | }
|
7526 | const ret = fn.body[0];
|
7527 | const args = this.evaluateFunctionArguments(node, context);
|
7528 | const newScope = new Map();
|
7529 | const calleeContext = __spreadProps(__spreadValues({}, context), { scope: newScope });
|
7530 | fn.parameters.forEach((param, index) => {
|
7531 | let arg = args[index];
|
7532 | if (param.node.dotDotDotToken !== void 0) {
|
7533 | arg = args.slice(index);
|
7534 | }
|
7535 | if (arg === void 0 && param.initializer !== null) {
|
7536 | arg = this.visitExpression(param.initializer, calleeContext);
|
7537 | }
|
7538 | newScope.set(param.node, arg);
|
7539 | });
|
7540 | return ret.expression !== void 0 ? this.visitExpression(ret.expression, calleeContext) : void 0;
|
7541 | }
|
7542 | visitConditionalExpression(node, context) {
|
7543 | const condition = this.visitExpression(node.condition, context);
|
7544 | if (condition instanceof DynamicValue) {
|
7545 | return DynamicValue.fromDynamicInput(node, condition);
|
7546 | }
|
7547 | if (condition) {
|
7548 | return this.visitExpression(node.whenTrue, context);
|
7549 | } else {
|
7550 | return this.visitExpression(node.whenFalse, context);
|
7551 | }
|
7552 | }
|
7553 | visitPrefixUnaryExpression(node, context) {
|
7554 | const operatorKind = node.operator;
|
7555 | if (!UNARY_OPERATORS.has(operatorKind)) {
|
7556 | return DynamicValue.fromUnsupportedSyntax(node);
|
7557 | }
|
7558 | const op = UNARY_OPERATORS.get(operatorKind);
|
7559 | const value = this.visitExpression(node.operand, context);
|
7560 | if (value instanceof DynamicValue) {
|
7561 | return DynamicValue.fromDynamicInput(node, value);
|
7562 | } else {
|
7563 | return op(value);
|
7564 | }
|
7565 | }
|
7566 | visitBinaryExpression(node, context) {
|
7567 | const tokenKind = node.operatorToken.kind;
|
7568 | if (!BINARY_OPERATORS.has(tokenKind)) {
|
7569 | return DynamicValue.fromUnsupportedSyntax(node);
|
7570 | }
|
7571 | const opRecord = BINARY_OPERATORS.get(tokenKind);
|
7572 | let lhs, rhs;
|
7573 | if (opRecord.literal) {
|
7574 | lhs = literal(this.visitExpression(node.left, context), (value) => DynamicValue.fromInvalidExpressionType(node.left, value));
|
7575 | rhs = literal(this.visitExpression(node.right, context), (value) => DynamicValue.fromInvalidExpressionType(node.right, value));
|
7576 | } else {
|
7577 | lhs = this.visitExpression(node.left, context);
|
7578 | rhs = this.visitExpression(node.right, context);
|
7579 | }
|
7580 | if (lhs instanceof DynamicValue) {
|
7581 | return DynamicValue.fromDynamicInput(node, lhs);
|
7582 | } else if (rhs instanceof DynamicValue) {
|
7583 | return DynamicValue.fromDynamicInput(node, rhs);
|
7584 | } else {
|
7585 | return opRecord.op(lhs, rhs);
|
7586 | }
|
7587 | }
|
7588 | visitParenthesizedExpression(node, context) {
|
7589 | return this.visitExpression(node.expression, context);
|
7590 | }
|
7591 | evaluateFunctionArguments(node, context) {
|
7592 | const args = [];
|
7593 | for (const arg of node.arguments) {
|
7594 | if (ts30.isSpreadElement(arg)) {
|
7595 | args.push(...this.visitSpreadElement(arg, context));
|
7596 | } else {
|
7597 | args.push(this.visitExpression(arg, context));
|
7598 | }
|
7599 | }
|
7600 | return args;
|
7601 | }
|
7602 | visitSpreadElement(node, context) {
|
7603 | const spread = this.visitExpression(node.expression, context);
|
7604 | if (spread instanceof DynamicValue) {
|
7605 | return [DynamicValue.fromDynamicInput(node, spread)];
|
7606 | } else if (!Array.isArray(spread)) {
|
7607 | return [DynamicValue.fromInvalidExpressionType(node, spread)];
|
7608 | } else {
|
7609 | return spread;
|
7610 | }
|
7611 | }
|
7612 | visitBindingElement(node, context) {
|
7613 | const path7 = [];
|
7614 | let closestDeclaration = node;
|
7615 | while (ts30.isBindingElement(closestDeclaration) || ts30.isArrayBindingPattern(closestDeclaration) || ts30.isObjectBindingPattern(closestDeclaration)) {
|
7616 | if (ts30.isBindingElement(closestDeclaration)) {
|
7617 | path7.unshift(closestDeclaration);
|
7618 | }
|
7619 | closestDeclaration = closestDeclaration.parent;
|
7620 | }
|
7621 | if (!ts30.isVariableDeclaration(closestDeclaration) || closestDeclaration.initializer === void 0) {
|
7622 | return DynamicValue.fromUnknown(node);
|
7623 | }
|
7624 | let value = this.visit(closestDeclaration.initializer, context);
|
7625 | for (const element of path7) {
|
7626 | let key;
|
7627 | if (ts30.isArrayBindingPattern(element.parent)) {
|
7628 | key = element.parent.elements.indexOf(element);
|
7629 | } else {
|
7630 | const name = element.propertyName || element.name;
|
7631 | if (ts30.isIdentifier(name)) {
|
7632 | key = name.text;
|
7633 | } else {
|
7634 | return DynamicValue.fromUnknown(element);
|
7635 | }
|
7636 | }
|
7637 | value = this.accessHelper(element, value, key, context);
|
7638 | if (value instanceof DynamicValue) {
|
7639 | return value;
|
7640 | }
|
7641 | }
|
7642 | return value;
|
7643 | }
|
7644 | stringNameFromPropertyName(node, context) {
|
7645 | if (ts30.isIdentifier(node) || ts30.isStringLiteral(node) || ts30.isNumericLiteral(node)) {
|
7646 | return node.text;
|
7647 | } else if (ts30.isComputedPropertyName(node)) {
|
7648 | const literal2 = this.visitExpression(node.expression, context);
|
7649 | return typeof literal2 === "string" ? literal2 : void 0;
|
7650 | } else {
|
7651 | return void 0;
|
7652 | }
|
7653 | }
|
7654 | getResolvedEnum(node, enumMembers, context) {
|
7655 | const enumRef = this.getReference(node, context);
|
7656 | const map = new Map();
|
7657 | enumMembers.forEach((member) => {
|
7658 | const name = this.stringNameFromPropertyName(member.name, context);
|
7659 | if (name !== void 0) {
|
7660 | const resolved = this.visit(member.initializer, context);
|
7661 | map.set(name, new EnumValue(enumRef, name, resolved));
|
7662 | }
|
7663 | });
|
7664 | return map;
|
7665 | }
|
7666 | getReference(node, context) {
|
7667 | return new Reference(node, owningModule(context));
|
7668 | }
|
7669 | visitType(node, context) {
|
7670 | if (ts30.isLiteralTypeNode(node)) {
|
7671 | return this.visitExpression(node.literal, context);
|
7672 | } else if (ts30.isTupleTypeNode(node)) {
|
7673 | return this.visitTupleType(node, context);
|
7674 | } else if (ts30.isNamedTupleMember(node)) {
|
7675 | return this.visitType(node.type, context);
|
7676 | }
|
7677 | return DynamicValue.fromDynamicType(node);
|
7678 | }
|
7679 | visitTupleType(node, context) {
|
7680 | const res = [];
|
7681 | for (const elem of node.elements) {
|
7682 | res.push(this.visitType(elem, context));
|
7683 | }
|
7684 | return res;
|
7685 | }
|
7686 | };
|
7687 | function isFunctionOrMethodReference(ref) {
|
7688 | return ts30.isFunctionDeclaration(ref.node) || ts30.isMethodDeclaration(ref.node) || ts30.isFunctionExpression(ref.node);
|
7689 | }
|
7690 | function literal(value, reject) {
|
7691 | if (value instanceof EnumValue) {
|
7692 | value = value.resolved;
|
7693 | }
|
7694 | if (value instanceof DynamicValue || value === null || value === void 0 || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
7695 | return value;
|
7696 | }
|
7697 | return reject(value);
|
7698 | }
|
7699 | function isVariableDeclarationDeclared(node) {
|
7700 | if (node.parent === void 0 || !ts30.isVariableDeclarationList(node.parent)) {
|
7701 | return false;
|
7702 | }
|
7703 | const declList = node.parent;
|
7704 | if (declList.parent === void 0 || !ts30.isVariableStatement(declList.parent)) {
|
7705 | return false;
|
7706 | }
|
7707 | const varStmt = declList.parent;
|
7708 | return varStmt.modifiers !== void 0 && varStmt.modifiers.some((mod) => mod.kind === ts30.SyntaxKind.DeclareKeyword);
|
7709 | }
|
7710 | var EMPTY = {};
|
7711 | function joinModuleContext(existing, node, decl) {
|
7712 | if (decl.viaModule !== null && decl.viaModule !== existing.absoluteModuleName) {
|
7713 | return {
|
7714 | absoluteModuleName: decl.viaModule,
|
7715 | resolutionContext: node.getSourceFile().fileName
|
7716 | };
|
7717 | } else {
|
7718 | return EMPTY;
|
7719 | }
|
7720 | }
|
7721 | function owningModule(context, override = null) {
|
7722 | let specifier = context.absoluteModuleName;
|
7723 | if (override !== null) {
|
7724 | specifier = override.specifier;
|
7725 | }
|
7726 | if (specifier !== null) {
|
7727 | return {
|
7728 | specifier,
|
7729 | resolutionContext: context.resolutionContext
|
7730 | };
|
7731 | } else {
|
7732 | return null;
|
7733 | }
|
7734 | }
|
7735 |
|
7736 |
|
7737 | var PartialEvaluator = class {
|
7738 | constructor(host, checker, dependencyTracker) {
|
7739 | this.host = host;
|
7740 | this.checker = checker;
|
7741 | this.dependencyTracker = dependencyTracker;
|
7742 | }
|
7743 | evaluate(expr, foreignFunctionResolver) {
|
7744 | const interpreter = new StaticInterpreter(this.host, this.checker, this.dependencyTracker);
|
7745 | const sourceFile = expr.getSourceFile();
|
7746 | return interpreter.visit(expr, {
|
7747 | originatingFile: sourceFile,
|
7748 | absoluteModuleName: null,
|
7749 | resolutionContext: sourceFile.fileName,
|
7750 | scope: new Map(),
|
7751 | foreignFunctionResolver
|
7752 | });
|
7753 | }
|
7754 | };
|
7755 |
|
7756 |
|
7757 | var PerfPhase;
|
7758 | (function(PerfPhase2) {
|
7759 | PerfPhase2[PerfPhase2["Unaccounted"] = 0] = "Unaccounted";
|
7760 | PerfPhase2[PerfPhase2["Setup"] = 1] = "Setup";
|
7761 | PerfPhase2[PerfPhase2["TypeScriptProgramCreate"] = 2] = "TypeScriptProgramCreate";
|
7762 | PerfPhase2[PerfPhase2["Reconciliation"] = 3] = "Reconciliation";
|
7763 | PerfPhase2[PerfPhase2["ResourceUpdate"] = 4] = "ResourceUpdate";
|
7764 | PerfPhase2[PerfPhase2["TypeScriptDiagnostics"] = 5] = "TypeScriptDiagnostics";
|
7765 | PerfPhase2[PerfPhase2["Analysis"] = 6] = "Analysis";
|
7766 | PerfPhase2[PerfPhase2["Resolve"] = 7] = "Resolve";
|
7767 | PerfPhase2[PerfPhase2["CycleDetection"] = 8] = "CycleDetection";
|
7768 | PerfPhase2[PerfPhase2["TcbGeneration"] = 9] = "TcbGeneration";
|
7769 | PerfPhase2[PerfPhase2["TcbUpdateProgram"] = 10] = "TcbUpdateProgram";
|
7770 | PerfPhase2[PerfPhase2["TypeScriptEmit"] = 11] = "TypeScriptEmit";
|
7771 | PerfPhase2[PerfPhase2["Compile"] = 12] = "Compile";
|
7772 | PerfPhase2[PerfPhase2["TtcAutocompletion"] = 13] = "TtcAutocompletion";
|
7773 | PerfPhase2[PerfPhase2["TtcDiagnostics"] = 14] = "TtcDiagnostics";
|
7774 | PerfPhase2[PerfPhase2["TtcSymbol"] = 15] = "TtcSymbol";
|
7775 | PerfPhase2[PerfPhase2["LsReferencesAndRenames"] = 16] = "LsReferencesAndRenames";
|
7776 | PerfPhase2[PerfPhase2["LsQuickInfo"] = 17] = "LsQuickInfo";
|
7777 | PerfPhase2[PerfPhase2["LsDefinition"] = 18] = "LsDefinition";
|
7778 | PerfPhase2[PerfPhase2["LsCompletions"] = 19] = "LsCompletions";
|
7779 | PerfPhase2[PerfPhase2["LsTcb"] = 20] = "LsTcb";
|
7780 | PerfPhase2[PerfPhase2["LsDiagnostics"] = 21] = "LsDiagnostics";
|
7781 | PerfPhase2[PerfPhase2["LsComponentLocations"] = 22] = "LsComponentLocations";
|
7782 | PerfPhase2[PerfPhase2["LsSignatureHelp"] = 23] = "LsSignatureHelp";
|
7783 | PerfPhase2[PerfPhase2["LAST"] = 24] = "LAST";
|
7784 | })(PerfPhase || (PerfPhase = {}));
|
7785 | var PerfEvent;
|
7786 | (function(PerfEvent2) {
|
7787 | PerfEvent2[PerfEvent2["InputDtsFile"] = 0] = "InputDtsFile";
|
7788 | PerfEvent2[PerfEvent2["InputTsFile"] = 1] = "InputTsFile";
|
7789 | PerfEvent2[PerfEvent2["AnalyzeComponent"] = 2] = "AnalyzeComponent";
|
7790 | PerfEvent2[PerfEvent2["AnalyzeDirective"] = 3] = "AnalyzeDirective";
|
7791 | PerfEvent2[PerfEvent2["AnalyzeInjectable"] = 4] = "AnalyzeInjectable";
|
7792 | PerfEvent2[PerfEvent2["AnalyzeNgModule"] = 5] = "AnalyzeNgModule";
|
7793 | PerfEvent2[PerfEvent2["AnalyzePipe"] = 6] = "AnalyzePipe";
|
7794 | PerfEvent2[PerfEvent2["TraitAnalyze"] = 7] = "TraitAnalyze";
|
7795 | PerfEvent2[PerfEvent2["TraitReuseAnalysis"] = 8] = "TraitReuseAnalysis";
|
7796 | PerfEvent2[PerfEvent2["SourceFilePhysicalChange"] = 9] = "SourceFilePhysicalChange";
|
7797 | PerfEvent2[PerfEvent2["SourceFileLogicalChange"] = 10] = "SourceFileLogicalChange";
|
7798 | PerfEvent2[PerfEvent2["SourceFileReuseAnalysis"] = 11] = "SourceFileReuseAnalysis";
|
7799 | PerfEvent2[PerfEvent2["GenerateTcb"] = 12] = "GenerateTcb";
|
7800 | PerfEvent2[PerfEvent2["SkipGenerateTcbNoInline"] = 13] = "SkipGenerateTcbNoInline";
|
7801 | PerfEvent2[PerfEvent2["ReuseTypeCheckFile"] = 14] = "ReuseTypeCheckFile";
|
7802 | PerfEvent2[PerfEvent2["UpdateTypeCheckProgram"] = 15] = "UpdateTypeCheckProgram";
|
7803 | PerfEvent2[PerfEvent2["EmitSkipSourceFile"] = 16] = "EmitSkipSourceFile";
|
7804 | PerfEvent2[PerfEvent2["EmitSourceFile"] = 17] = "EmitSourceFile";
|
7805 | PerfEvent2[PerfEvent2["LAST"] = 18] = "LAST";
|
7806 | })(PerfEvent || (PerfEvent = {}));
|
7807 | var PerfCheckpoint;
|
7808 | (function(PerfCheckpoint2) {
|
7809 | PerfCheckpoint2[PerfCheckpoint2["Initial"] = 0] = "Initial";
|
7810 | PerfCheckpoint2[PerfCheckpoint2["TypeScriptProgramCreate"] = 1] = "TypeScriptProgramCreate";
|
7811 | PerfCheckpoint2[PerfCheckpoint2["PreAnalysis"] = 2] = "PreAnalysis";
|
7812 | PerfCheckpoint2[PerfCheckpoint2["Analysis"] = 3] = "Analysis";
|
7813 | PerfCheckpoint2[PerfCheckpoint2["Resolve"] = 4] = "Resolve";
|
7814 | PerfCheckpoint2[PerfCheckpoint2["TtcGeneration"] = 5] = "TtcGeneration";
|
7815 | PerfCheckpoint2[PerfCheckpoint2["TtcUpdateProgram"] = 6] = "TtcUpdateProgram";
|
7816 | PerfCheckpoint2[PerfCheckpoint2["PreEmit"] = 7] = "PreEmit";
|
7817 | PerfCheckpoint2[PerfCheckpoint2["Emit"] = 8] = "Emit";
|
7818 | PerfCheckpoint2[PerfCheckpoint2["LAST"] = 9] = "LAST";
|
7819 | })(PerfCheckpoint || (PerfCheckpoint = {}));
|
7820 |
|
7821 |
|
7822 | var NoopPerfRecorder = class {
|
7823 | eventCount() {
|
7824 | }
|
7825 | memory() {
|
7826 | }
|
7827 | phase() {
|
7828 | return PerfPhase.Unaccounted;
|
7829 | }
|
7830 | inPhase(phase, fn) {
|
7831 | return fn();
|
7832 | }
|
7833 | reset() {
|
7834 | }
|
7835 | };
|
7836 | var NOOP_PERF_RECORDER = new NoopPerfRecorder();
|
7837 |
|
7838 |
|
7839 | var CompilationMode;
|
7840 | (function(CompilationMode2) {
|
7841 | CompilationMode2[CompilationMode2["FULL"] = 0] = "FULL";
|
7842 | CompilationMode2[CompilationMode2["PARTIAL"] = 1] = "PARTIAL";
|
7843 | })(CompilationMode || (CompilationMode = {}));
|
7844 | var HandlerPrecedence;
|
7845 | (function(HandlerPrecedence2) {
|
7846 | HandlerPrecedence2[HandlerPrecedence2["PRIMARY"] = 0] = "PRIMARY";
|
7847 | HandlerPrecedence2[HandlerPrecedence2["SHARED"] = 1] = "SHARED";
|
7848 | HandlerPrecedence2[HandlerPrecedence2["WEAK"] = 2] = "WEAK";
|
7849 | })(HandlerPrecedence || (HandlerPrecedence = {}));
|
7850 | var HandlerFlags;
|
7851 | (function(HandlerFlags2) {
|
7852 | HandlerFlags2[HandlerFlags2["NONE"] = 0] = "NONE";
|
7853 | HandlerFlags2[HandlerFlags2["FULL_INHERITANCE"] = 1] = "FULL_INHERITANCE";
|
7854 | })(HandlerFlags || (HandlerFlags = {}));
|
7855 |
|
7856 |
|
7857 | import ts31 from "typescript";
|
7858 |
|
7859 |
|
7860 | import ts32 from "typescript";
|
7861 |
|
7862 |
|
7863 | var TraitState;
|
7864 | (function(TraitState2) {
|
7865 | TraitState2[TraitState2["Pending"] = 0] = "Pending";
|
7866 | TraitState2[TraitState2["Analyzed"] = 1] = "Analyzed";
|
7867 | TraitState2[TraitState2["Resolved"] = 2] = "Resolved";
|
7868 | TraitState2[TraitState2["Skipped"] = 3] = "Skipped";
|
7869 | })(TraitState || (TraitState = {}));
|
7870 | var Trait = {
|
7871 | pending: (handler, detected) => TraitImpl.pending(handler, detected)
|
7872 | };
|
7873 | var TraitImpl = class {
|
7874 | constructor(handler, detected) {
|
7875 | this.state = TraitState.Pending;
|
7876 | this.analysis = null;
|
7877 | this.symbol = null;
|
7878 | this.resolution = null;
|
7879 | this.analysisDiagnostics = null;
|
7880 | this.resolveDiagnostics = null;
|
7881 | this.handler = handler;
|
7882 | this.detected = detected;
|
7883 | }
|
7884 | toAnalyzed(analysis, diagnostics, symbol) {
|
7885 | this.assertTransitionLegal(TraitState.Pending, TraitState.Analyzed);
|
7886 | this.analysis = analysis;
|
7887 | this.analysisDiagnostics = diagnostics;
|
7888 | this.symbol = symbol;
|
7889 | this.state = TraitState.Analyzed;
|
7890 | return this;
|
7891 | }
|
7892 | toResolved(resolution, diagnostics) {
|
7893 | this.assertTransitionLegal(TraitState.Analyzed, TraitState.Resolved);
|
7894 | if (this.analysis === null) {
|
7895 | throw new Error(`Cannot transition an Analyzed trait with a null analysis to Resolved`);
|
7896 | }
|
7897 | this.resolution = resolution;
|
7898 | this.state = TraitState.Resolved;
|
7899 | this.resolveDiagnostics = diagnostics;
|
7900 | return this;
|
7901 | }
|
7902 | toSkipped() {
|
7903 | this.assertTransitionLegal(TraitState.Pending, TraitState.Skipped);
|
7904 | this.state = TraitState.Skipped;
|
7905 | return this;
|
7906 | }
|
7907 | assertTransitionLegal(allowedState, transitionTo) {
|
7908 | if (!(this.state === allowedState)) {
|
7909 | throw new Error(`Assertion failure: cannot transition from ${TraitState[this.state]} to ${TraitState[transitionTo]}.`);
|
7910 | }
|
7911 | }
|
7912 | static pending(handler, detected) {
|
7913 | return new TraitImpl(handler, detected);
|
7914 | }
|
7915 | };
|
7916 |
|
7917 |
|
7918 | var TraitCompiler = class {
|
7919 | constructor(handlers, reflector, perf, incrementalBuild, compileNonExportedClasses, compilationMode, dtsTransforms, semanticDepGraphUpdater) {
|
7920 | this.handlers = handlers;
|
7921 | this.reflector = reflector;
|
7922 | this.perf = perf;
|
7923 | this.incrementalBuild = incrementalBuild;
|
7924 | this.compileNonExportedClasses = compileNonExportedClasses;
|
7925 | this.compilationMode = compilationMode;
|
7926 | this.dtsTransforms = dtsTransforms;
|
7927 | this.semanticDepGraphUpdater = semanticDepGraphUpdater;
|
7928 | this.classes = new Map();
|
7929 | this.fileToClasses = new Map();
|
7930 | this.filesWithoutTraits = new Set();
|
7931 | this.reexportMap = new Map();
|
7932 | this.handlersByName = new Map();
|
7933 | for (const handler of handlers) {
|
7934 | this.handlersByName.set(handler.name, handler);
|
7935 | }
|
7936 | }
|
7937 | analyzeSync(sf) {
|
7938 | this.analyze(sf, false);
|
7939 | }
|
7940 | analyzeAsync(sf) {
|
7941 | return this.analyze(sf, true);
|
7942 | }
|
7943 | analyze(sf, preanalyze) {
|
7944 | if (sf.isDeclarationFile) {
|
7945 | return void 0;
|
7946 | }
|
7947 | const promises = [];
|
7948 | const priorWork = this.incrementalBuild.priorAnalysisFor(sf);
|
7949 | if (priorWork !== null) {
|
7950 | this.perf.eventCount(PerfEvent.SourceFileReuseAnalysis);
|
7951 | if (priorWork.length > 0) {
|
7952 | for (const priorRecord of priorWork) {
|
7953 | this.adopt(priorRecord);
|
7954 | }
|
7955 | this.perf.eventCount(PerfEvent.TraitReuseAnalysis, priorWork.length);
|
7956 | } else {
|
7957 | this.filesWithoutTraits.add(sf);
|
7958 | }
|
7959 | return;
|
7960 | }
|
7961 | const visit2 = (node) => {
|
7962 | if (this.reflector.isClass(node)) {
|
7963 | this.analyzeClass(node, preanalyze ? promises : null);
|
7964 | }
|
7965 | ts32.forEachChild(node, visit2);
|
7966 | };
|
7967 | visit2(sf);
|
7968 | if (preanalyze && promises.length > 0) {
|
7969 | return Promise.all(promises).then(() => void 0);
|
7970 | } else {
|
7971 | return void 0;
|
7972 | }
|
7973 | }
|
7974 | recordFor(clazz) {
|
7975 | if (this.classes.has(clazz)) {
|
7976 | return this.classes.get(clazz);
|
7977 | } else {
|
7978 | return null;
|
7979 | }
|
7980 | }
|
7981 | recordsFor(sf) {
|
7982 | if (!this.fileToClasses.has(sf)) {
|
7983 | return null;
|
7984 | }
|
7985 | const records = [];
|
7986 | for (const clazz of this.fileToClasses.get(sf)) {
|
7987 | records.push(this.classes.get(clazz));
|
7988 | }
|
7989 | return records;
|
7990 | }
|
7991 | getAnalyzedRecords() {
|
7992 | const result = new Map();
|
7993 | for (const [sf, classes] of this.fileToClasses) {
|
7994 | const records = [];
|
7995 | for (const clazz of classes) {
|
7996 | records.push(this.classes.get(clazz));
|
7997 | }
|
7998 | result.set(sf, records);
|
7999 | }
|
8000 | for (const sf of this.filesWithoutTraits) {
|
8001 | result.set(sf, []);
|
8002 | }
|
8003 | return result;
|
8004 | }
|
8005 | adopt(priorRecord) {
|
8006 | const record = {
|
8007 | hasPrimaryHandler: priorRecord.hasPrimaryHandler,
|
8008 | hasWeakHandlers: priorRecord.hasWeakHandlers,
|
8009 | metaDiagnostics: priorRecord.metaDiagnostics,
|
8010 | node: priorRecord.node,
|
8011 | traits: []
|
8012 | };
|
8013 | for (const priorTrait of priorRecord.traits) {
|
8014 | const handler = this.handlersByName.get(priorTrait.handler.name);
|
8015 | let trait = Trait.pending(handler, priorTrait.detected);
|
8016 | if (priorTrait.state === TraitState.Analyzed || priorTrait.state === TraitState.Resolved) {
|
8017 | const symbol = this.makeSymbolForTrait(handler, record.node, priorTrait.analysis);
|
8018 | trait = trait.toAnalyzed(priorTrait.analysis, priorTrait.analysisDiagnostics, symbol);
|
8019 | if (trait.analysis !== null && trait.handler.register !== void 0) {
|
8020 | trait.handler.register(record.node, trait.analysis);
|
8021 | }
|
8022 | } else if (priorTrait.state === TraitState.Skipped) {
|
8023 | trait = trait.toSkipped();
|
8024 | }
|
8025 | record.traits.push(trait);
|
8026 | }
|
8027 | this.classes.set(record.node, record);
|
8028 | const sf = record.node.getSourceFile();
|
8029 | if (!this.fileToClasses.has(sf)) {
|
8030 | this.fileToClasses.set(sf, new Set());
|
8031 | }
|
8032 | this.fileToClasses.get(sf).add(record.node);
|
8033 | }
|
8034 | scanClassForTraits(clazz) {
|
8035 | if (!this.compileNonExportedClasses && !this.reflector.isStaticallyExported(clazz)) {
|
8036 | return null;
|
8037 | }
|
8038 | const decorators = this.reflector.getDecoratorsOfDeclaration(clazz);
|
8039 | return this.detectTraits(clazz, decorators);
|
8040 | }
|
8041 | detectTraits(clazz, decorators) {
|
8042 | let record = this.recordFor(clazz);
|
8043 | let foundTraits = [];
|
8044 | for (const handler of this.handlers) {
|
8045 | const result = handler.detect(clazz, decorators);
|
8046 | if (result === void 0) {
|
8047 | continue;
|
8048 | }
|
8049 | const isPrimaryHandler = handler.precedence === HandlerPrecedence.PRIMARY;
|
8050 | const isWeakHandler = handler.precedence === HandlerPrecedence.WEAK;
|
8051 | const trait = Trait.pending(handler, result);
|
8052 | foundTraits.push(trait);
|
8053 | if (record === null) {
|
8054 | record = {
|
8055 | node: clazz,
|
8056 | traits: [trait],
|
8057 | metaDiagnostics: null,
|
8058 | hasPrimaryHandler: isPrimaryHandler,
|
8059 | hasWeakHandlers: isWeakHandler
|
8060 | };
|
8061 | this.classes.set(clazz, record);
|
8062 | const sf = clazz.getSourceFile();
|
8063 | if (!this.fileToClasses.has(sf)) {
|
8064 | this.fileToClasses.set(sf, new Set());
|
8065 | }
|
8066 | this.fileToClasses.get(sf).add(clazz);
|
8067 | } else {
|
8068 | if (!isWeakHandler && record.hasWeakHandlers) {
|
8069 | record.traits = record.traits.filter((field) => field.handler.precedence !== HandlerPrecedence.WEAK);
|
8070 | record.hasWeakHandlers = false;
|
8071 | } else if (isWeakHandler && !record.hasWeakHandlers) {
|
8072 | continue;
|
8073 | }
|
8074 | if (isPrimaryHandler && record.hasPrimaryHandler) {
|
8075 | record.metaDiagnostics = [{
|
8076 | category: ts32.DiagnosticCategory.Error,
|
8077 | code: Number("-99" + ErrorCode.DECORATOR_COLLISION),
|
8078 | file: getSourceFile(clazz),
|
8079 | start: clazz.getStart(void 0, false),
|
8080 | length: clazz.getWidth(),
|
8081 | messageText: "Two incompatible decorators on class"
|
8082 | }];
|
8083 | record.traits = foundTraits = [];
|
8084 | break;
|
8085 | }
|
8086 | record.traits.push(trait);
|
8087 | record.hasPrimaryHandler = record.hasPrimaryHandler || isPrimaryHandler;
|
8088 | }
|
8089 | }
|
8090 | return foundTraits.length > 0 ? foundTraits : null;
|
8091 | }
|
8092 | makeSymbolForTrait(handler, decl, analysis) {
|
8093 | if (analysis === null) {
|
8094 | return null;
|
8095 | }
|
8096 | const symbol = handler.symbol(decl, analysis);
|
8097 | if (symbol !== null && this.semanticDepGraphUpdater !== null) {
|
8098 | const isPrimary = handler.precedence === HandlerPrecedence.PRIMARY;
|
8099 | if (!isPrimary) {
|
8100 | throw new Error(`AssertionError: ${handler.name} returned a symbol but is not a primary handler.`);
|
8101 | }
|
8102 | this.semanticDepGraphUpdater.registerSymbol(symbol);
|
8103 | }
|
8104 | return symbol;
|
8105 | }
|
8106 | analyzeClass(clazz, preanalyzeQueue) {
|
8107 | const traits = this.scanClassForTraits(clazz);
|
8108 | if (traits === null) {
|
8109 | return;
|
8110 | }
|
8111 | for (const trait of traits) {
|
8112 | const analyze = () => this.analyzeTrait(clazz, trait);
|
8113 | let preanalysis = null;
|
8114 | if (preanalyzeQueue !== null && trait.handler.preanalyze !== void 0) {
|
8115 | try {
|
8116 | preanalysis = trait.handler.preanalyze(clazz, trait.detected.metadata) || null;
|
8117 | } catch (err) {
|
8118 | if (err instanceof FatalDiagnosticError) {
|
8119 | trait.toAnalyzed(null, [err.toDiagnostic()], null);
|
8120 | return;
|
8121 | } else {
|
8122 | throw err;
|
8123 | }
|
8124 | }
|
8125 | }
|
8126 | if (preanalysis !== null) {
|
8127 | preanalyzeQueue.push(preanalysis.then(analyze));
|
8128 | } else {
|
8129 | analyze();
|
8130 | }
|
8131 | }
|
8132 | }
|
8133 | analyzeTrait(clazz, trait, flags) {
|
8134 | var _a, _b, _c;
|
8135 | if (trait.state !== TraitState.Pending) {
|
8136 | throw new Error(`Attempt to analyze trait of ${clazz.name.text} in state ${TraitState[trait.state]} (expected DETECTED)`);
|
8137 | }
|
8138 | this.perf.eventCount(PerfEvent.TraitAnalyze);
|
8139 | let result;
|
8140 | try {
|
8141 | result = trait.handler.analyze(clazz, trait.detected.metadata, flags);
|
8142 | } catch (err) {
|
8143 | if (err instanceof FatalDiagnosticError) {
|
8144 | trait.toAnalyzed(null, [err.toDiagnostic()], null);
|
8145 | return;
|
8146 | } else {
|
8147 | throw err;
|
8148 | }
|
8149 | }
|
8150 | const symbol = this.makeSymbolForTrait(trait.handler, clazz, (_a = result.analysis) != null ? _a : null);
|
8151 | if (result.analysis !== void 0 && trait.handler.register !== void 0) {
|
8152 | trait.handler.register(clazz, result.analysis);
|
8153 | }
|
8154 | trait = trait.toAnalyzed((_b = result.analysis) != null ? _b : null, (_c = result.diagnostics) != null ? _c : null, symbol);
|
8155 | }
|
8156 | resolve() {
|
8157 | var _a, _b;
|
8158 | const classes = Array.from(this.classes.keys());
|
8159 | for (const clazz of classes) {
|
8160 | const record = this.classes.get(clazz);
|
8161 | for (let trait of record.traits) {
|
8162 | const handler = trait.handler;
|
8163 | switch (trait.state) {
|
8164 | case TraitState.Skipped:
|
8165 | continue;
|
8166 | case TraitState.Pending:
|
8167 | throw new Error(`Resolving a trait that hasn't been analyzed: ${clazz.name.text} / ${Object.getPrototypeOf(trait.handler).constructor.name}`);
|
8168 | case TraitState.Resolved:
|
8169 | throw new Error(`Resolving an already resolved trait`);
|
8170 | }
|
8171 | if (trait.analysis === null) {
|
8172 | continue;
|
8173 | }
|
8174 | if (handler.resolve === void 0) {
|
8175 | trait = trait.toResolved(null, null);
|
8176 | continue;
|
8177 | }
|
8178 | let result;
|
8179 | try {
|
8180 | result = handler.resolve(clazz, trait.analysis, trait.symbol);
|
8181 | } catch (err) {
|
8182 | if (err instanceof FatalDiagnosticError) {
|
8183 | trait = trait.toResolved(null, [err.toDiagnostic()]);
|
8184 | continue;
|
8185 | } else {
|
8186 | throw err;
|
8187 | }
|
8188 | }
|
8189 | trait = trait.toResolved((_a = result.data) != null ? _a : null, (_b = result.diagnostics) != null ? _b : null);
|
8190 | if (result.reexports !== void 0) {
|
8191 | const fileName = clazz.getSourceFile().fileName;
|
8192 | if (!this.reexportMap.has(fileName)) {
|
8193 | this.reexportMap.set(fileName, new Map());
|
8194 | }
|
8195 | const fileReexports = this.reexportMap.get(fileName);
|
8196 | for (const reexport of result.reexports) {
|
8197 | fileReexports.set(reexport.asAlias, [reexport.fromModule, reexport.symbolName]);
|
8198 | }
|
8199 | }
|
8200 | }
|
8201 | }
|
8202 | }
|
8203 | typeCheck(sf, ctx) {
|
8204 | if (!this.fileToClasses.has(sf)) {
|
8205 | return;
|
8206 | }
|
8207 | for (const clazz of this.fileToClasses.get(sf)) {
|
8208 | const record = this.classes.get(clazz);
|
8209 | for (const trait of record.traits) {
|
8210 | if (trait.state !== TraitState.Resolved) {
|
8211 | continue;
|
8212 | } else if (trait.handler.typeCheck === void 0) {
|
8213 | continue;
|
8214 | }
|
8215 | if (trait.resolution !== null) {
|
8216 | trait.handler.typeCheck(ctx, clazz, trait.analysis, trait.resolution);
|
8217 | }
|
8218 | }
|
8219 | }
|
8220 | }
|
8221 | extendedTemplateCheck(sf, extendedTemplateChecker) {
|
8222 | const classes = this.fileToClasses.get(sf);
|
8223 | if (classes === void 0) {
|
8224 | return [];
|
8225 | }
|
8226 | const diagnostics = [];
|
8227 | for (const clazz of classes) {
|
8228 | if (!isNamedClassDeclaration(clazz)) {
|
8229 | continue;
|
8230 | }
|
8231 | const record = this.classes.get(clazz);
|
8232 | for (const trait of record.traits) {
|
8233 | if (trait.handler.extendedTemplateCheck === void 0) {
|
8234 | continue;
|
8235 | }
|
8236 | diagnostics.push(...trait.handler.extendedTemplateCheck(clazz, extendedTemplateChecker));
|
8237 | }
|
8238 | }
|
8239 | return diagnostics;
|
8240 | }
|
8241 | index(ctx) {
|
8242 | for (const clazz of this.classes.keys()) {
|
8243 | const record = this.classes.get(clazz);
|
8244 | for (const trait of record.traits) {
|
8245 | if (trait.state !== TraitState.Resolved) {
|
8246 | continue;
|
8247 | } else if (trait.handler.index === void 0) {
|
8248 | continue;
|
8249 | }
|
8250 | if (trait.resolution !== null) {
|
8251 | trait.handler.index(ctx, clazz, trait.analysis, trait.resolution);
|
8252 | }
|
8253 | }
|
8254 | }
|
8255 | }
|
8256 | xi18n(bundle) {
|
8257 | for (const clazz of this.classes.keys()) {
|
8258 | const record = this.classes.get(clazz);
|
8259 | for (const trait of record.traits) {
|
8260 | if (trait.state !== TraitState.Analyzed && trait.state !== TraitState.Resolved) {
|
8261 | continue;
|
8262 | } else if (trait.handler.xi18n === void 0) {
|
8263 | continue;
|
8264 | }
|
8265 | if (trait.analysis !== null) {
|
8266 | trait.handler.xi18n(bundle, clazz, trait.analysis);
|
8267 | }
|
8268 | }
|
8269 | }
|
8270 | }
|
8271 | updateResources(clazz) {
|
8272 | if (!this.reflector.isClass(clazz) || !this.classes.has(clazz)) {
|
8273 | return;
|
8274 | }
|
8275 | const record = this.classes.get(clazz);
|
8276 | for (const trait of record.traits) {
|
8277 | if (trait.state !== TraitState.Resolved || trait.handler.updateResources === void 0) {
|
8278 | continue;
|
8279 | }
|
8280 | trait.handler.updateResources(clazz, trait.analysis, trait.resolution);
|
8281 | }
|
8282 | }
|
8283 | compile(clazz, constantPool) {
|
8284 | const original = ts32.getOriginalNode(clazz);
|
8285 | if (!this.reflector.isClass(clazz) || !this.reflector.isClass(original) || !this.classes.has(original)) {
|
8286 | return null;
|
8287 | }
|
8288 | const record = this.classes.get(original);
|
8289 | let res = [];
|
8290 | for (const trait of record.traits) {
|
8291 | if (trait.state !== TraitState.Resolved || trait.analysisDiagnostics !== null || trait.resolveDiagnostics !== null) {
|
8292 | continue;
|
8293 | }
|
8294 | let compileRes;
|
8295 | if (this.compilationMode === CompilationMode.PARTIAL && trait.handler.compilePartial !== void 0) {
|
8296 | compileRes = trait.handler.compilePartial(clazz, trait.analysis, trait.resolution);
|
8297 | } else {
|
8298 | compileRes = trait.handler.compileFull(clazz, trait.analysis, trait.resolution, constantPool);
|
8299 | }
|
8300 | const compileMatchRes = compileRes;
|
8301 | if (Array.isArray(compileMatchRes)) {
|
8302 | for (const result of compileMatchRes) {
|
8303 | if (!res.some((r) => r.name === result.name)) {
|
8304 | res.push(result);
|
8305 | }
|
8306 | }
|
8307 | } else if (!res.some((result) => result.name === compileMatchRes.name)) {
|
8308 | res.push(compileMatchRes);
|
8309 | }
|
8310 | }
|
8311 | this.dtsTransforms.getIvyDeclarationTransform(original.getSourceFile()).addFields(original, res);
|
8312 | return res.length > 0 ? res : null;
|
8313 | }
|
8314 | decoratorsFor(node) {
|
8315 | const original = ts32.getOriginalNode(node);
|
8316 | if (!this.reflector.isClass(original) || !this.classes.has(original)) {
|
8317 | return [];
|
8318 | }
|
8319 | const record = this.classes.get(original);
|
8320 | const decorators = [];
|
8321 | for (const trait of record.traits) {
|
8322 | if (trait.state !== TraitState.Resolved) {
|
8323 | continue;
|
8324 | }
|
8325 | if (trait.detected.trigger !== null && ts32.isDecorator(trait.detected.trigger)) {
|
8326 | decorators.push(trait.detected.trigger);
|
8327 | }
|
8328 | }
|
8329 | return decorators;
|
8330 | }
|
8331 | get diagnostics() {
|
8332 | const diagnostics = [];
|
8333 | for (const clazz of this.classes.keys()) {
|
8334 | const record = this.classes.get(clazz);
|
8335 | if (record.metaDiagnostics !== null) {
|
8336 | diagnostics.push(...record.metaDiagnostics);
|
8337 | }
|
8338 | for (const trait of record.traits) {
|
8339 | if ((trait.state === TraitState.Analyzed || trait.state === TraitState.Resolved) && trait.analysisDiagnostics !== null) {
|
8340 | diagnostics.push(...trait.analysisDiagnostics);
|
8341 | }
|
8342 | if (trait.state === TraitState.Resolved && trait.resolveDiagnostics !== null) {
|
8343 | diagnostics.push(...trait.resolveDiagnostics);
|
8344 | }
|
8345 | }
|
8346 | }
|
8347 | return diagnostics;
|
8348 | }
|
8349 | get exportStatements() {
|
8350 | return this.reexportMap;
|
8351 | }
|
8352 | };
|
8353 |
|
8354 |
|
8355 | import ts37 from "typescript";
|
8356 |
|
8357 |
|
8358 | var Context = class {
|
8359 | constructor(isStatement) {
|
8360 | this.isStatement = isStatement;
|
8361 | }
|
8362 | get withExpressionMode() {
|
8363 | return this.isStatement ? new Context(false) : this;
|
8364 | }
|
8365 | get withStatementMode() {
|
8366 | return !this.isStatement ? new Context(true) : this;
|
8367 | }
|
8368 | };
|
8369 |
|
8370 |
|
8371 | import ts33 from "typescript";
|
8372 | var ImportManager = class {
|
8373 | constructor(rewriter = new NoopImportRewriter(), prefix = "i") {
|
8374 | this.rewriter = rewriter;
|
8375 | this.prefix = prefix;
|
8376 | this.specifierToIdentifier = new Map();
|
8377 | this.nextIndex = 0;
|
8378 | }
|
8379 | generateNamespaceImport(moduleName) {
|
8380 | if (!this.specifierToIdentifier.has(moduleName)) {
|
8381 | this.specifierToIdentifier.set(moduleName, ts33.createIdentifier(`${this.prefix}${this.nextIndex++}`));
|
8382 | }
|
8383 | return this.specifierToIdentifier.get(moduleName);
|
8384 | }
|
8385 | generateNamedImport(moduleName, originalSymbol) {
|
8386 | const symbol = this.rewriter.rewriteSymbol(originalSymbol, moduleName);
|
8387 | if (!this.rewriter.shouldImportSymbol(symbol, moduleName)) {
|
8388 | return { moduleImport: null, symbol };
|
8389 | }
|
8390 | const moduleImport = this.generateNamespaceImport(moduleName);
|
8391 | return { moduleImport, symbol };
|
8392 | }
|
8393 | getAllImports(contextPath) {
|
8394 | const imports = [];
|
8395 | for (const [originalSpecifier, qualifier] of this.specifierToIdentifier) {
|
8396 | const specifier = this.rewriter.rewriteSpecifier(originalSpecifier, contextPath);
|
8397 | imports.push({
|
8398 | specifier,
|
8399 | qualifier
|
8400 | });
|
8401 | }
|
8402 | return imports;
|
8403 | }
|
8404 | };
|
8405 |
|
8406 |
|
8407 | import {
|
8408 | BinaryOperator,
|
8409 | ConditionalExpr,
|
8410 | StmtModifier,
|
8411 | UnaryOperator
|
8412 | } from "@angular/compiler";
|
8413 | var UNARY_OPERATORS2 = new Map([
|
8414 | [UnaryOperator.Minus, "-"],
|
8415 | [UnaryOperator.Plus, "+"]
|
8416 | ]);
|
8417 | var BINARY_OPERATORS2 = new Map([
|
8418 | [BinaryOperator.And, "&&"],
|
8419 | [BinaryOperator.Bigger, ">"],
|
8420 | [BinaryOperator.BiggerEquals, ">="],
|
8421 | [BinaryOperator.BitwiseAnd, "&"],
|
8422 | [BinaryOperator.Divide, "/"],
|
8423 | [BinaryOperator.Equals, "=="],
|
8424 | [BinaryOperator.Identical, "==="],
|
8425 | [BinaryOperator.Lower, "<"],
|
8426 | [BinaryOperator.LowerEquals, "<="],
|
8427 | [BinaryOperator.Minus, "-"],
|
8428 | [BinaryOperator.Modulo, "%"],
|
8429 | [BinaryOperator.Multiply, "*"],
|
8430 | [BinaryOperator.NotEquals, "!="],
|
8431 | [BinaryOperator.NotIdentical, "!=="],
|
8432 | [BinaryOperator.Or, "||"],
|
8433 | [BinaryOperator.Plus, "+"],
|
8434 | [BinaryOperator.NullishCoalesce, "??"]
|
8435 | ]);
|
8436 | var ExpressionTranslatorVisitor = class {
|
8437 | constructor(factory, imports, options) {
|
8438 | this.factory = factory;
|
8439 | this.imports = imports;
|
8440 | this.downlevelTaggedTemplates = options.downlevelTaggedTemplates === true;
|
8441 | this.downlevelVariableDeclarations = options.downlevelVariableDeclarations === true;
|
8442 | this.recordWrappedNode = options.recordWrappedNode || (() => {
|
8443 | });
|
8444 | }
|
8445 | visitDeclareVarStmt(stmt, context) {
|
8446 | var _a;
|
8447 | const varType = this.downlevelVariableDeclarations ? "var" : stmt.hasModifier(StmtModifier.Final) ? "const" : "let";
|
8448 | return this.attachComments(this.factory.createVariableDeclaration(stmt.name, (_a = stmt.value) == null ? void 0 : _a.visitExpression(this, context.withExpressionMode), varType), stmt.leadingComments);
|
8449 | }
|
8450 | visitDeclareFunctionStmt(stmt, context) {
|
8451 | 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);
|
8452 | }
|
8453 | visitExpressionStmt(stmt, context) {
|
8454 | return this.attachComments(this.factory.createExpressionStatement(stmt.expr.visitExpression(this, context.withStatementMode)), stmt.leadingComments);
|
8455 | }
|
8456 | visitReturnStmt(stmt, context) {
|
8457 | return this.attachComments(this.factory.createReturnStatement(stmt.value.visitExpression(this, context.withExpressionMode)), stmt.leadingComments);
|
8458 | }
|
8459 | visitDeclareClassStmt(_stmt, _context) {
|
8460 | throw new Error("Method not implemented.");
|
8461 | }
|
8462 | visitIfStmt(stmt, context) {
|
8463 | 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);
|
8464 | }
|
8465 | visitTryCatchStmt(_stmt, _context) {
|
8466 | throw new Error("Method not implemented.");
|
8467 | }
|
8468 | visitThrowStmt(stmt, context) {
|
8469 | return this.attachComments(this.factory.createThrowStatement(stmt.error.visitExpression(this, context.withExpressionMode)), stmt.leadingComments);
|
8470 | }
|
8471 | visitReadVarExpr(ast, _context) {
|
8472 | const identifier = this.factory.createIdentifier(ast.name);
|
8473 | this.setSourceMapRange(identifier, ast.sourceSpan);
|
8474 | return identifier;
|
8475 | }
|
8476 | visitWriteVarExpr(expr, context) {
|
8477 | const assignment = this.factory.createAssignment(this.setSourceMapRange(this.factory.createIdentifier(expr.name), expr.sourceSpan), expr.value.visitExpression(this, context));
|
8478 | return context.isStatement ? assignment : this.factory.createParenthesizedExpression(assignment);
|
8479 | }
|
8480 | visitWriteKeyExpr(expr, context) {
|
8481 | const exprContext = context.withExpressionMode;
|
8482 | const target = this.factory.createElementAccess(expr.receiver.visitExpression(this, exprContext), expr.index.visitExpression(this, exprContext));
|
8483 | const assignment = this.factory.createAssignment(target, expr.value.visitExpression(this, exprContext));
|
8484 | return context.isStatement ? assignment : this.factory.createParenthesizedExpression(assignment);
|
8485 | }
|
8486 | visitWritePropExpr(expr, context) {
|
8487 | const target = this.factory.createPropertyAccess(expr.receiver.visitExpression(this, context), expr.name);
|
8488 | return this.factory.createAssignment(target, expr.value.visitExpression(this, context));
|
8489 | }
|
8490 | visitInvokeFunctionExpr(ast, context) {
|
8491 | return this.setSourceMapRange(this.factory.createCallExpression(ast.fn.visitExpression(this, context), ast.args.map((arg) => arg.visitExpression(this, context)), ast.pure), ast.sourceSpan);
|
8492 | }
|
8493 | visitTaggedTemplateExpr(ast, context) {
|
8494 | return this.setSourceMapRange(this.createTaggedTemplateExpression(ast.tag.visitExpression(this, context), {
|
8495 | elements: ast.template.elements.map((e) => {
|
8496 | var _a;
|
8497 | return createTemplateElement({
|
8498 | cooked: e.text,
|
8499 | raw: e.rawText,
|
8500 | range: (_a = e.sourceSpan) != null ? _a : ast.sourceSpan
|
8501 | });
|
8502 | }),
|
8503 | expressions: ast.template.expressions.map((e) => e.visitExpression(this, context))
|
8504 | }), ast.sourceSpan);
|
8505 | }
|
8506 | visitInstantiateExpr(ast, context) {
|
8507 | return this.factory.createNewExpression(ast.classExpr.visitExpression(this, context), ast.args.map((arg) => arg.visitExpression(this, context)));
|
8508 | }
|
8509 | visitLiteralExpr(ast, _context) {
|
8510 | return this.setSourceMapRange(this.factory.createLiteral(ast.value), ast.sourceSpan);
|
8511 | }
|
8512 | visitLocalizedString(ast, context) {
|
8513 | const elements = [createTemplateElement(ast.serializeI18nHead())];
|
8514 | const expressions = [];
|
8515 | for (let i = 0; i < ast.expressions.length; i++) {
|
8516 | const placeholder = this.setSourceMapRange(ast.expressions[i].visitExpression(this, context), ast.getPlaceholderSourceSpan(i));
|
8517 | expressions.push(placeholder);
|
8518 | elements.push(createTemplateElement(ast.serializeI18nTemplatePart(i + 1)));
|
8519 | }
|
8520 | const localizeTag = this.factory.createIdentifier("$localize");
|
8521 | return this.setSourceMapRange(this.createTaggedTemplateExpression(localizeTag, { elements, expressions }), ast.sourceSpan);
|
8522 | }
|
8523 | createTaggedTemplateExpression(tag, template) {
|
8524 | return this.downlevelTaggedTemplates ? this.createES5TaggedTemplateFunctionCall(tag, template) : this.factory.createTaggedTemplate(tag, template);
|
8525 | }
|
8526 | createES5TaggedTemplateFunctionCall(tagHandler, { elements, expressions }) {
|
8527 | const { moduleImport, symbol } = this.imports.generateNamedImport("tslib", "__makeTemplateObject");
|
8528 | const __makeTemplateObjectHelper = moduleImport === null ? this.factory.createIdentifier(symbol) : this.factory.createPropertyAccess(moduleImport, symbol);
|
8529 | const cooked = [];
|
8530 | const raw = [];
|
8531 | for (const element of elements) {
|
8532 | cooked.push(this.factory.setSourceMapRange(this.factory.createLiteral(element.cooked), element.range));
|
8533 | raw.push(this.factory.setSourceMapRange(this.factory.createLiteral(element.raw), element.range));
|
8534 | }
|
8535 | const templateHelperCall = this.factory.createCallExpression(__makeTemplateObjectHelper, [this.factory.createArrayLiteral(cooked), this.factory.createArrayLiteral(raw)], false);
|
8536 | return this.factory.createCallExpression(tagHandler, [templateHelperCall, ...expressions], false);
|
8537 | }
|
8538 | visitExternalExpr(ast, _context) {
|
8539 | if (ast.value.name === null) {
|
8540 | if (ast.value.moduleName === null) {
|
8541 | throw new Error("Invalid import without name nor moduleName");
|
8542 | }
|
8543 | return this.imports.generateNamespaceImport(ast.value.moduleName);
|
8544 | }
|
8545 | if (ast.value.moduleName !== null) {
|
8546 | const { moduleImport, symbol } = this.imports.generateNamedImport(ast.value.moduleName, ast.value.name);
|
8547 | if (moduleImport === null) {
|
8548 | return this.factory.createIdentifier(symbol);
|
8549 | } else {
|
8550 | return this.factory.createPropertyAccess(moduleImport, symbol);
|
8551 | }
|
8552 | } else {
|
8553 | return this.factory.createIdentifier(ast.value.name);
|
8554 | }
|
8555 | }
|
8556 | visitConditionalExpr(ast, context) {
|
8557 | let cond = ast.condition.visitExpression(this, context);
|
8558 | if (ast.condition instanceof ConditionalExpr) {
|
8559 | cond = this.factory.createParenthesizedExpression(cond);
|
8560 | }
|
8561 | return this.factory.createConditional(cond, ast.trueCase.visitExpression(this, context), ast.falseCase.visitExpression(this, context));
|
8562 | }
|
8563 | visitNotExpr(ast, context) {
|
8564 | return this.factory.createUnaryExpression("!", ast.condition.visitExpression(this, context));
|
8565 | }
|
8566 | visitAssertNotNullExpr(ast, context) {
|
8567 | return ast.condition.visitExpression(this, context);
|
8568 | }
|
8569 | visitCastExpr(ast, context) {
|
8570 | return ast.value.visitExpression(this, context);
|
8571 | }
|
8572 | visitFunctionExpr(ast, context) {
|
8573 | var _a;
|
8574 | return this.factory.createFunctionExpression((_a = ast.name) != null ? _a : null, ast.params.map((param) => param.name), this.factory.createBlock(this.visitStatements(ast.statements, context)));
|
8575 | }
|
8576 | visitBinaryOperatorExpr(ast, context) {
|
8577 | if (!BINARY_OPERATORS2.has(ast.operator)) {
|
8578 | throw new Error(`Unknown binary operator: ${BinaryOperator[ast.operator]}`);
|
8579 | }
|
8580 | return this.factory.createBinaryExpression(ast.lhs.visitExpression(this, context), BINARY_OPERATORS2.get(ast.operator), ast.rhs.visitExpression(this, context));
|
8581 | }
|
8582 | visitReadPropExpr(ast, context) {
|
8583 | return this.factory.createPropertyAccess(ast.receiver.visitExpression(this, context), ast.name);
|
8584 | }
|
8585 | visitReadKeyExpr(ast, context) {
|
8586 | return this.factory.createElementAccess(ast.receiver.visitExpression(this, context), ast.index.visitExpression(this, context));
|
8587 | }
|
8588 | visitLiteralArrayExpr(ast, context) {
|
8589 | return this.factory.createArrayLiteral(ast.entries.map((expr) => this.setSourceMapRange(expr.visitExpression(this, context), ast.sourceSpan)));
|
8590 | }
|
8591 | visitLiteralMapExpr(ast, context) {
|
8592 | const properties = ast.entries.map((entry) => {
|
8593 | return {
|
8594 | propertyName: entry.key,
|
8595 | quoted: entry.quoted,
|
8596 | value: entry.value.visitExpression(this, context)
|
8597 | };
|
8598 | });
|
8599 | return this.setSourceMapRange(this.factory.createObjectLiteral(properties), ast.sourceSpan);
|
8600 | }
|
8601 | visitCommaExpr(ast, context) {
|
8602 | throw new Error("Method not implemented.");
|
8603 | }
|
8604 | visitWrappedNodeExpr(ast, _context) {
|
8605 | this.recordWrappedNode(ast);
|
8606 | return ast.node;
|
8607 | }
|
8608 | visitTypeofExpr(ast, context) {
|
8609 | return this.factory.createTypeOfExpression(ast.expr.visitExpression(this, context));
|
8610 | }
|
8611 | visitUnaryOperatorExpr(ast, context) {
|
8612 | if (!UNARY_OPERATORS2.has(ast.operator)) {
|
8613 | throw new Error(`Unknown unary operator: ${UnaryOperator[ast.operator]}`);
|
8614 | }
|
8615 | return this.factory.createUnaryExpression(UNARY_OPERATORS2.get(ast.operator), ast.expr.visitExpression(this, context));
|
8616 | }
|
8617 | visitStatements(statements, context) {
|
8618 | return statements.map((stmt) => stmt.visitStatement(this, context)).filter((stmt) => stmt !== void 0);
|
8619 | }
|
8620 | setSourceMapRange(ast, span) {
|
8621 | return this.factory.setSourceMapRange(ast, createRange(span));
|
8622 | }
|
8623 | attachComments(statement, leadingComments) {
|
8624 | if (leadingComments !== void 0) {
|
8625 | this.factory.attachComments(statement, leadingComments);
|
8626 | }
|
8627 | return statement;
|
8628 | }
|
8629 | };
|
8630 | function createTemplateElement({ cooked, raw, range }) {
|
8631 | return { cooked, raw, range: createRange(range) };
|
8632 | }
|
8633 | function createRange(span) {
|
8634 | if (span === null) {
|
8635 | return null;
|
8636 | }
|
8637 | const { start, end } = span;
|
8638 | const { url, content } = start.file;
|
8639 | if (!url) {
|
8640 | return null;
|
8641 | }
|
8642 | return {
|
8643 | url,
|
8644 | content,
|
8645 | start: { offset: start.offset, line: start.line, column: start.col },
|
8646 | end: { offset: end.offset, line: end.line, column: end.col }
|
8647 | };
|
8648 | }
|
8649 |
|
8650 |
|
8651 | import {
|
8652 | BuiltinTypeName
|
8653 | } from "@angular/compiler";
|
8654 | import ts34 from "typescript";
|
8655 | function translateType(type, imports) {
|
8656 | return type.visitType(new TypeTranslatorVisitor(imports), new Context(false));
|
8657 | }
|
8658 | var TypeTranslatorVisitor = class {
|
8659 | constructor(imports) {
|
8660 | this.imports = imports;
|
8661 | }
|
8662 | visitBuiltinType(type, context) {
|
8663 | switch (type.name) {
|
8664 | case BuiltinTypeName.Bool:
|
8665 | return ts34.createKeywordTypeNode(ts34.SyntaxKind.BooleanKeyword);
|
8666 | case BuiltinTypeName.Dynamic:
|
8667 | return ts34.createKeywordTypeNode(ts34.SyntaxKind.AnyKeyword);
|
8668 | case BuiltinTypeName.Int:
|
8669 | case BuiltinTypeName.Number:
|
8670 | return ts34.createKeywordTypeNode(ts34.SyntaxKind.NumberKeyword);
|
8671 | case BuiltinTypeName.String:
|
8672 | return ts34.createKeywordTypeNode(ts34.SyntaxKind.StringKeyword);
|
8673 | case BuiltinTypeName.None:
|
8674 | return ts34.createKeywordTypeNode(ts34.SyntaxKind.NeverKeyword);
|
8675 | default:
|
8676 | throw new Error(`Unsupported builtin type: ${BuiltinTypeName[type.name]}`);
|
8677 | }
|
8678 | }
|
8679 | visitExpressionType(type, context) {
|
8680 | const typeNode = this.translateExpression(type.value, context);
|
8681 | if (type.typeParams === null) {
|
8682 | return typeNode;
|
8683 | }
|
8684 | if (!ts34.isTypeReferenceNode(typeNode)) {
|
8685 | throw new Error("An ExpressionType with type arguments must translate into a TypeReferenceNode");
|
8686 | } else if (typeNode.typeArguments !== void 0) {
|
8687 | throw new Error(`An ExpressionType with type arguments cannot have multiple levels of type arguments`);
|
8688 | }
|
8689 | const typeArgs = type.typeParams.map((param) => this.translateType(param, context));
|
8690 | return ts34.createTypeReferenceNode(typeNode.typeName, typeArgs);
|
8691 | }
|
8692 | visitArrayType(type, context) {
|
8693 | return ts34.createArrayTypeNode(this.translateType(type.of, context));
|
8694 | }
|
8695 | visitMapType(type, context) {
|
8696 | const parameter = ts34.createParameter(void 0, void 0, void 0, "key", void 0, ts34.createKeywordTypeNode(ts34.SyntaxKind.StringKeyword));
|
8697 | const typeArgs = type.valueType !== null ? this.translateType(type.valueType, context) : ts34.createKeywordTypeNode(ts34.SyntaxKind.UnknownKeyword);
|
8698 | const indexSignature = ts34.createIndexSignature(void 0, void 0, [parameter], typeArgs);
|
8699 | return ts34.createTypeLiteralNode([indexSignature]);
|
8700 | }
|
8701 | visitReadVarExpr(ast, context) {
|
8702 | if (ast.name === null) {
|
8703 | throw new Error(`ReadVarExpr with no variable name in type`);
|
8704 | }
|
8705 | return ts34.createTypeQueryNode(ts34.createIdentifier(ast.name));
|
8706 | }
|
8707 | visitWriteVarExpr(expr, context) {
|
8708 | throw new Error("Method not implemented.");
|
8709 | }
|
8710 | visitWriteKeyExpr(expr, context) {
|
8711 | throw new Error("Method not implemented.");
|
8712 | }
|
8713 | visitWritePropExpr(expr, context) {
|
8714 | throw new Error("Method not implemented.");
|
8715 | }
|
8716 | visitInvokeFunctionExpr(ast, context) {
|
8717 | throw new Error("Method not implemented.");
|
8718 | }
|
8719 | visitTaggedTemplateExpr(ast, context) {
|
8720 | throw new Error("Method not implemented.");
|
8721 | }
|
8722 | visitInstantiateExpr(ast, context) {
|
8723 | throw new Error("Method not implemented.");
|
8724 | }
|
8725 | visitLiteralExpr(ast, context) {
|
8726 | if (ast.value === null) {
|
8727 | return ts34.createLiteralTypeNode(ts34.createNull());
|
8728 | } else if (ast.value === void 0) {
|
8729 | return ts34.createKeywordTypeNode(ts34.SyntaxKind.UndefinedKeyword);
|
8730 | } else if (typeof ast.value === "boolean") {
|
8731 | return ts34.createLiteralTypeNode(ts34.createLiteral(ast.value));
|
8732 | } else if (typeof ast.value === "number") {
|
8733 | return ts34.createLiteralTypeNode(ts34.createLiteral(ast.value));
|
8734 | } else {
|
8735 | return ts34.createLiteralTypeNode(ts34.createLiteral(ast.value));
|
8736 | }
|
8737 | }
|
8738 | visitLocalizedString(ast, context) {
|
8739 | throw new Error("Method not implemented.");
|
8740 | }
|
8741 | visitExternalExpr(ast, context) {
|
8742 | if (ast.value.moduleName === null || ast.value.name === null) {
|
8743 | throw new Error(`Import unknown module or symbol`);
|
8744 | }
|
8745 | const { moduleImport, symbol } = this.imports.generateNamedImport(ast.value.moduleName, ast.value.name);
|
8746 | const symbolIdentifier = ts34.createIdentifier(symbol);
|
8747 | const typeName = moduleImport ? ts34.createQualifiedName(moduleImport, symbolIdentifier) : symbolIdentifier;
|
8748 | const typeArguments = ast.typeParams !== null ? ast.typeParams.map((type) => this.translateType(type, context)) : void 0;
|
8749 | return ts34.createTypeReferenceNode(typeName, typeArguments);
|
8750 | }
|
8751 | visitConditionalExpr(ast, context) {
|
8752 | throw new Error("Method not implemented.");
|
8753 | }
|
8754 | visitNotExpr(ast, context) {
|
8755 | throw new Error("Method not implemented.");
|
8756 | }
|
8757 | visitAssertNotNullExpr(ast, context) {
|
8758 | throw new Error("Method not implemented.");
|
8759 | }
|
8760 | visitCastExpr(ast, context) {
|
8761 | throw new Error("Method not implemented.");
|
8762 | }
|
8763 | visitFunctionExpr(ast, context) {
|
8764 | throw new Error("Method not implemented.");
|
8765 | }
|
8766 | visitUnaryOperatorExpr(ast, context) {
|
8767 | throw new Error("Method not implemented.");
|
8768 | }
|
8769 | visitBinaryOperatorExpr(ast, context) {
|
8770 | throw new Error("Method not implemented.");
|
8771 | }
|
8772 | visitReadPropExpr(ast, context) {
|
8773 | throw new Error("Method not implemented.");
|
8774 | }
|
8775 | visitReadKeyExpr(ast, context) {
|
8776 | throw new Error("Method not implemented.");
|
8777 | }
|
8778 | visitLiteralArrayExpr(ast, context) {
|
8779 | const values = ast.entries.map((expr) => this.translateExpression(expr, context));
|
8780 | return ts34.createTupleTypeNode(values);
|
8781 | }
|
8782 | visitLiteralMapExpr(ast, context) {
|
8783 | const entries = ast.entries.map((entry) => {
|
8784 | const { key, quoted } = entry;
|
8785 | const type = this.translateExpression(entry.value, context);
|
8786 | return ts34.createPropertySignature(void 0, quoted ? ts34.createStringLiteral(key) : key, void 0, type, void 0);
|
8787 | });
|
8788 | return ts34.createTypeLiteralNode(entries);
|
8789 | }
|
8790 | visitCommaExpr(ast, context) {
|
8791 | throw new Error("Method not implemented.");
|
8792 | }
|
8793 | visitWrappedNodeExpr(ast, context) {
|
8794 | const node = ast.node;
|
8795 | if (ts34.isEntityName(node)) {
|
8796 | return ts34.createTypeReferenceNode(node, void 0);
|
8797 | } else if (ts34.isTypeNode(node)) {
|
8798 | return node;
|
8799 | } else if (ts34.isLiteralExpression(node)) {
|
8800 | return ts34.createLiteralTypeNode(node);
|
8801 | } else {
|
8802 | throw new Error(`Unsupported WrappedNodeExpr in TypeTranslatorVisitor: ${ts34.SyntaxKind[node.kind]}`);
|
8803 | }
|
8804 | }
|
8805 | visitTypeofExpr(ast, context) {
|
8806 | const typeNode = this.translateExpression(ast.expr, context);
|
8807 | if (!ts34.isTypeReferenceNode(typeNode)) {
|
8808 | throw new Error(`The target of a typeof expression must be a type reference, but it was
|
8809 | ${ts34.SyntaxKind[typeNode.kind]}`);
|
8810 | }
|
8811 | return ts34.createTypeQueryNode(typeNode.typeName);
|
8812 | }
|
8813 | translateType(type, context) {
|
8814 | const typeNode = type.visitType(this, context);
|
8815 | if (!ts34.isTypeNode(typeNode)) {
|
8816 | throw new Error(`A Type must translate to a TypeNode, but was ${ts34.SyntaxKind[typeNode.kind]}`);
|
8817 | }
|
8818 | return typeNode;
|
8819 | }
|
8820 | translateExpression(expr, context) {
|
8821 | const typeNode = expr.visitExpression(this, context);
|
8822 | if (!ts34.isTypeNode(typeNode)) {
|
8823 | throw new Error(`An Expression must translate to a TypeNode, but was ${ts34.SyntaxKind[typeNode.kind]}`);
|
8824 | }
|
8825 | return typeNode;
|
8826 | }
|
8827 | };
|
8828 |
|
8829 |
|
8830 | import ts35 from "typescript";
|
8831 | var PureAnnotation;
|
8832 | (function(PureAnnotation2) {
|
8833 | PureAnnotation2["CLOSURE"] = "* @pureOrBreakMyCode ";
|
8834 | PureAnnotation2["TERSER"] = "@__PURE__";
|
8835 | })(PureAnnotation || (PureAnnotation = {}));
|
8836 | var UNARY_OPERATORS3 = {
|
8837 | "+": ts35.SyntaxKind.PlusToken,
|
8838 | "-": ts35.SyntaxKind.MinusToken,
|
8839 | "!": ts35.SyntaxKind.ExclamationToken
|
8840 | };
|
8841 | var BINARY_OPERATORS3 = {
|
8842 | "&&": ts35.SyntaxKind.AmpersandAmpersandToken,
|
8843 | ">": ts35.SyntaxKind.GreaterThanToken,
|
8844 | ">=": ts35.SyntaxKind.GreaterThanEqualsToken,
|
8845 | "&": ts35.SyntaxKind.AmpersandToken,
|
8846 | "/": ts35.SyntaxKind.SlashToken,
|
8847 | "==": ts35.SyntaxKind.EqualsEqualsToken,
|
8848 | "===": ts35.SyntaxKind.EqualsEqualsEqualsToken,
|
8849 | "<": ts35.SyntaxKind.LessThanToken,
|
8850 | "<=": ts35.SyntaxKind.LessThanEqualsToken,
|
8851 | "-": ts35.SyntaxKind.MinusToken,
|
8852 | "%": ts35.SyntaxKind.PercentToken,
|
8853 | "*": ts35.SyntaxKind.AsteriskToken,
|
8854 | "!=": ts35.SyntaxKind.ExclamationEqualsToken,
|
8855 | "!==": ts35.SyntaxKind.ExclamationEqualsEqualsToken,
|
8856 | "||": ts35.SyntaxKind.BarBarToken,
|
8857 | "+": ts35.SyntaxKind.PlusToken,
|
8858 | "??": ts35.SyntaxKind.QuestionQuestionToken
|
8859 | };
|
8860 | var VAR_TYPES = {
|
8861 | "const": ts35.NodeFlags.Const,
|
8862 | "let": ts35.NodeFlags.Let,
|
8863 | "var": ts35.NodeFlags.None
|
8864 | };
|
8865 | var TypeScriptAstFactory = class {
|
8866 | constructor(annotateForClosureCompiler) {
|
8867 | this.annotateForClosureCompiler = annotateForClosureCompiler;
|
8868 | this.externalSourceFiles = new Map();
|
8869 | this.attachComments = attachComments;
|
8870 | this.createArrayLiteral = ts35.createArrayLiteral;
|
8871 | this.createConditional = ts35.createConditional;
|
8872 | this.createElementAccess = ts35.createElementAccess;
|
8873 | this.createExpressionStatement = ts35.createExpressionStatement;
|
8874 | this.createIdentifier = ts35.createIdentifier;
|
8875 | this.createParenthesizedExpression = ts35.createParen;
|
8876 | this.createPropertyAccess = ts35.createPropertyAccess;
|
8877 | this.createThrowStatement = ts35.createThrow;
|
8878 | this.createTypeOfExpression = ts35.createTypeOf;
|
8879 | }
|
8880 | createAssignment(target, value) {
|
8881 | return ts35.createBinary(target, ts35.SyntaxKind.EqualsToken, value);
|
8882 | }
|
8883 | createBinaryExpression(leftOperand, operator, rightOperand) {
|
8884 | return ts35.createBinary(leftOperand, BINARY_OPERATORS3[operator], rightOperand);
|
8885 | }
|
8886 | createBlock(body) {
|
8887 | return ts35.createBlock(body);
|
8888 | }
|
8889 | createCallExpression(callee, args, pure) {
|
8890 | const call = ts35.createCall(callee, void 0, args);
|
8891 | if (pure) {
|
8892 | ts35.addSyntheticLeadingComment(call, ts35.SyntaxKind.MultiLineCommentTrivia, this.annotateForClosureCompiler ? PureAnnotation.CLOSURE : PureAnnotation.TERSER, false);
|
8893 | }
|
8894 | return call;
|
8895 | }
|
8896 | createFunctionDeclaration(functionName, parameters, body) {
|
8897 | if (!ts35.isBlock(body)) {
|
8898 | throw new Error(`Invalid syntax, expected a block, but got ${ts35.SyntaxKind[body.kind]}.`);
|
8899 | }
|
8900 | return ts35.createFunctionDeclaration(void 0, void 0, void 0, functionName, void 0, parameters.map((param) => ts35.createParameter(void 0, void 0, void 0, param)), void 0, body);
|
8901 | }
|
8902 | createFunctionExpression(functionName, parameters, body) {
|
8903 | if (!ts35.isBlock(body)) {
|
8904 | throw new Error(`Invalid syntax, expected a block, but got ${ts35.SyntaxKind[body.kind]}.`);
|
8905 | }
|
8906 | return ts35.createFunctionExpression(void 0, void 0, functionName != null ? functionName : void 0, void 0, parameters.map((param) => ts35.createParameter(void 0, void 0, void 0, param)), void 0, body);
|
8907 | }
|
8908 | createIfStatement(condition, thenStatement, elseStatement) {
|
8909 | return ts35.createIf(condition, thenStatement, elseStatement != null ? elseStatement : void 0);
|
8910 | }
|
8911 | createLiteral(value) {
|
8912 | if (value === void 0) {
|
8913 | return ts35.createIdentifier("undefined");
|
8914 | } else if (value === null) {
|
8915 | return ts35.createNull();
|
8916 | } else {
|
8917 | return ts35.createLiteral(value);
|
8918 | }
|
8919 | }
|
8920 | createNewExpression(expression, args) {
|
8921 | return ts35.createNew(expression, void 0, args);
|
8922 | }
|
8923 | createObjectLiteral(properties) {
|
8924 | return ts35.createObjectLiteral(properties.map((prop) => ts35.createPropertyAssignment(prop.quoted ? ts35.createLiteral(prop.propertyName) : ts35.createIdentifier(prop.propertyName), prop.value)));
|
8925 | }
|
8926 | createReturnStatement(expression) {
|
8927 | return ts35.createReturn(expression != null ? expression : void 0);
|
8928 | }
|
8929 | createTaggedTemplate(tag, template) {
|
8930 | let templateLiteral;
|
8931 | const length = template.elements.length;
|
8932 | const head = template.elements[0];
|
8933 | if (length === 1) {
|
8934 | templateLiteral = ts35.createNoSubstitutionTemplateLiteral(head.cooked, head.raw);
|
8935 | } else {
|
8936 | const spans = [];
|
8937 | for (let i = 1; i < length - 1; i++) {
|
8938 | const { cooked, raw, range } = template.elements[i];
|
8939 | const middle = createTemplateMiddle(cooked, raw);
|
8940 | if (range !== null) {
|
8941 | this.setSourceMapRange(middle, range);
|
8942 | }
|
8943 | spans.push(ts35.createTemplateSpan(template.expressions[i - 1], middle));
|
8944 | }
|
8945 | const resolvedExpression = template.expressions[length - 2];
|
8946 | const templatePart = template.elements[length - 1];
|
8947 | const templateTail = createTemplateTail(templatePart.cooked, templatePart.raw);
|
8948 | if (templatePart.range !== null) {
|
8949 | this.setSourceMapRange(templateTail, templatePart.range);
|
8950 | }
|
8951 | spans.push(ts35.createTemplateSpan(resolvedExpression, templateTail));
|
8952 | templateLiteral = ts35.createTemplateExpression(ts35.createTemplateHead(head.cooked, head.raw), spans);
|
8953 | }
|
8954 | if (head.range !== null) {
|
8955 | this.setSourceMapRange(templateLiteral, head.range);
|
8956 | }
|
8957 | return ts35.createTaggedTemplate(tag, templateLiteral);
|
8958 | }
|
8959 | createUnaryExpression(operator, operand) {
|
8960 | return ts35.createPrefix(UNARY_OPERATORS3[operator], operand);
|
8961 | }
|
8962 | createVariableDeclaration(variableName, initializer, type) {
|
8963 | return ts35.createVariableStatement(void 0, ts35.createVariableDeclarationList([ts35.createVariableDeclaration(variableName, void 0, initializer != null ? initializer : void 0)], VAR_TYPES[type]));
|
8964 | }
|
8965 | setSourceMapRange(node, sourceMapRange) {
|
8966 | if (sourceMapRange === null) {
|
8967 | return node;
|
8968 | }
|
8969 | const url = sourceMapRange.url;
|
8970 | if (!this.externalSourceFiles.has(url)) {
|
8971 | this.externalSourceFiles.set(url, ts35.createSourceMapSource(url, sourceMapRange.content, (pos) => pos));
|
8972 | }
|
8973 | const source = this.externalSourceFiles.get(url);
|
8974 | ts35.setSourceMapRange(node, { pos: sourceMapRange.start.offset, end: sourceMapRange.end.offset, source });
|
8975 | return node;
|
8976 | }
|
8977 | };
|
8978 | function createTemplateMiddle(cooked, raw) {
|
8979 | const node = ts35.createTemplateHead(cooked, raw);
|
8980 | node.kind = ts35.SyntaxKind.TemplateMiddle;
|
8981 | return node;
|
8982 | }
|
8983 | function createTemplateTail(cooked, raw) {
|
8984 | const node = ts35.createTemplateHead(cooked, raw);
|
8985 | node.kind = ts35.SyntaxKind.TemplateTail;
|
8986 | return node;
|
8987 | }
|
8988 | function attachComments(statement, leadingComments) {
|
8989 | for (const comment of leadingComments) {
|
8990 | const commentKind = comment.multiline ? ts35.SyntaxKind.MultiLineCommentTrivia : ts35.SyntaxKind.SingleLineCommentTrivia;
|
8991 | if (comment.multiline) {
|
8992 | ts35.addSyntheticLeadingComment(statement, commentKind, comment.toString(), comment.trailingNewline);
|
8993 | } else {
|
8994 | for (const line of comment.toString().split("\n")) {
|
8995 | ts35.addSyntheticLeadingComment(statement, commentKind, line, comment.trailingNewline);
|
8996 | }
|
8997 | }
|
8998 | }
|
8999 | }
|
9000 |
|
9001 |
|
9002 | function translateStatement(statement, imports, options = {}) {
|
9003 | return statement.visitStatement(new ExpressionTranslatorVisitor(new TypeScriptAstFactory(options.annotateForClosureCompiler === true), imports, options), new Context(true));
|
9004 | }
|
9005 |
|
9006 |
|
9007 | import ts36 from "typescript";
|
9008 |
|
9009 |
|
9010 | var DtsTransformRegistry = class {
|
9011 | constructor() {
|
9012 | this.ivyDeclarationTransforms = new Map();
|
9013 | }
|
9014 | getIvyDeclarationTransform(sf) {
|
9015 | if (!this.ivyDeclarationTransforms.has(sf)) {
|
9016 | this.ivyDeclarationTransforms.set(sf, new IvyDeclarationDtsTransform());
|
9017 | }
|
9018 | return this.ivyDeclarationTransforms.get(sf);
|
9019 | }
|
9020 | getAllTransforms(sf) {
|
9021 | if (!sf.isDeclarationFile) {
|
9022 | return null;
|
9023 | }
|
9024 | const originalSf = ts37.getOriginalNode(sf);
|
9025 | let transforms = null;
|
9026 | if (this.ivyDeclarationTransforms.has(originalSf)) {
|
9027 | transforms = [];
|
9028 | transforms.push(this.ivyDeclarationTransforms.get(originalSf));
|
9029 | }
|
9030 | return transforms;
|
9031 | }
|
9032 | };
|
9033 | var IvyDeclarationDtsTransform = class {
|
9034 | constructor() {
|
9035 | this.declarationFields = new Map();
|
9036 | }
|
9037 | addFields(decl, fields) {
|
9038 | this.declarationFields.set(decl, fields);
|
9039 | }
|
9040 | transformClass(clazz, members, imports) {
|
9041 | const original = ts37.getOriginalNode(clazz);
|
9042 | if (!this.declarationFields.has(original)) {
|
9043 | return clazz;
|
9044 | }
|
9045 | const fields = this.declarationFields.get(original);
|
9046 | const newMembers = fields.map((decl) => {
|
9047 | const modifiers = [ts37.createModifier(ts37.SyntaxKind.StaticKeyword)];
|
9048 | const typeRef = translateType(decl.type, imports);
|
9049 | markForEmitAsSingleLine(typeRef);
|
9050 | return ts37.createProperty(void 0, modifiers, decl.name, void 0, typeRef, void 0);
|
9051 | });
|
9052 | return ts37.updateClassDeclaration(clazz, clazz.decorators, clazz.modifiers, clazz.name, clazz.typeParameters, clazz.heritageClauses, [...members, ...newMembers]);
|
9053 | }
|
9054 | };
|
9055 | function markForEmitAsSingleLine(node) {
|
9056 | ts37.setEmitFlags(node, ts37.EmitFlags.SingleLine);
|
9057 | ts37.forEachChild(node, markForEmitAsSingleLine);
|
9058 | }
|
9059 |
|
9060 |
|
9061 | import { ConstantPool } from "@angular/compiler";
|
9062 | import ts39 from "typescript";
|
9063 |
|
9064 |
|
9065 | import ts38 from "typescript";
|
9066 |
|
9067 |
|
9068 | var NO_DECORATORS = new Set();
|
9069 |
|
9070 |
|
9071 | import ts41 from "typescript";
|
9072 |
|
9073 |
|
9074 | import { ExternalExpr as ExternalExpr4, LiteralExpr, ParseLocation, ParseSourceFile, ParseSourceSpan, ReadPropExpr, WrappedNodeExpr as WrappedNodeExpr2 } from "@angular/compiler";
|
9075 | import ts40 from "typescript";
|
9076 | function getConstructorDependencies(clazz, reflector, isCore) {
|
9077 | const deps = [];
|
9078 | const errors = [];
|
9079 | let ctorParams = reflector.getConstructorParameters(clazz);
|
9080 | if (ctorParams === null) {
|
9081 | if (reflector.hasBaseClass(clazz)) {
|
9082 | return null;
|
9083 | } else {
|
9084 | ctorParams = [];
|
9085 | }
|
9086 | }
|
9087 | ctorParams.forEach((param, idx) => {
|
9088 | let token = valueReferenceToExpression(param.typeValueReference);
|
9089 | let attributeNameType = null;
|
9090 | let optional = false, self = false, skipSelf = false, host = false;
|
9091 | (param.decorators || []).filter((dec) => isCore || isAngularCore(dec)).forEach((dec) => {
|
9092 | const name = isCore || dec.import === null ? dec.name : dec.import.name;
|
9093 | if (name === "Inject") {
|
9094 | if (dec.args === null || dec.args.length !== 1) {
|
9095 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, Decorator.nodeForError(dec), `Unexpected number of arguments to @Inject().`);
|
9096 | }
|
9097 | token = new WrappedNodeExpr2(dec.args[0]);
|
9098 | } else if (name === "Optional") {
|
9099 | optional = true;
|
9100 | } else if (name === "SkipSelf") {
|
9101 | skipSelf = true;
|
9102 | } else if (name === "Self") {
|
9103 | self = true;
|
9104 | } else if (name === "Host") {
|
9105 | host = true;
|
9106 | } else if (name === "Attribute") {
|
9107 | if (dec.args === null || dec.args.length !== 1) {
|
9108 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, Decorator.nodeForError(dec), `Unexpected number of arguments to @Attribute().`);
|
9109 | }
|
9110 | const attributeName = dec.args[0];
|
9111 | token = new WrappedNodeExpr2(attributeName);
|
9112 | if (ts40.isStringLiteralLike(attributeName)) {
|
9113 | attributeNameType = new LiteralExpr(attributeName.text);
|
9114 | } else {
|
9115 | attributeNameType = new WrappedNodeExpr2(ts40.createKeywordTypeNode(ts40.SyntaxKind.UnknownKeyword));
|
9116 | }
|
9117 | } else {
|
9118 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_UNEXPECTED, Decorator.nodeForError(dec), `Unexpected decorator ${name} on parameter.`);
|
9119 | }
|
9120 | });
|
9121 | if (token === null) {
|
9122 | if (param.typeValueReference.kind !== 2) {
|
9123 | throw new Error("Illegal state: expected value reference to be unavailable if no token is present");
|
9124 | }
|
9125 | errors.push({
|
9126 | index: idx,
|
9127 | param,
|
9128 | reason: param.typeValueReference.reason
|
9129 | });
|
9130 | } else {
|
9131 | deps.push({ token, attributeNameType, optional, self, skipSelf, host });
|
9132 | }
|
9133 | });
|
9134 | if (errors.length === 0) {
|
9135 | return { deps };
|
9136 | } else {
|
9137 | return { deps: null, errors };
|
9138 | }
|
9139 | }
|
9140 | function valueReferenceToExpression(valueRef) {
|
9141 | if (valueRef.kind === 2) {
|
9142 | return null;
|
9143 | } else if (valueRef.kind === 0) {
|
9144 | const expr = new WrappedNodeExpr2(valueRef.expression);
|
9145 | if (valueRef.defaultImportStatement !== null) {
|
9146 | attachDefaultImportDeclaration(expr, valueRef.defaultImportStatement);
|
9147 | }
|
9148 | return expr;
|
9149 | } else {
|
9150 | let importExpr = new ExternalExpr4({ moduleName: valueRef.moduleName, name: valueRef.importedName });
|
9151 | if (valueRef.nestedPath !== null) {
|
9152 | for (const property2 of valueRef.nestedPath) {
|
9153 | importExpr = new ReadPropExpr(importExpr, property2);
|
9154 | }
|
9155 | }
|
9156 | return importExpr;
|
9157 | }
|
9158 | }
|
9159 | function unwrapConstructorDependencies(deps) {
|
9160 | if (deps === null) {
|
9161 | return null;
|
9162 | } else if (deps.deps !== null) {
|
9163 | return deps.deps;
|
9164 | } else {
|
9165 | return "invalid";
|
9166 | }
|
9167 | }
|
9168 | function getValidConstructorDependencies(clazz, reflector, isCore) {
|
9169 | return validateConstructorDependencies(clazz, getConstructorDependencies(clazz, reflector, isCore));
|
9170 | }
|
9171 | function validateConstructorDependencies(clazz, deps) {
|
9172 | if (deps === null) {
|
9173 | return null;
|
9174 | } else if (deps.deps !== null) {
|
9175 | return deps.deps;
|
9176 | } else {
|
9177 | const error2 = deps.errors[0];
|
9178 | throw createUnsuitableInjectionTokenError(clazz, error2);
|
9179 | }
|
9180 | }
|
9181 | function createUnsuitableInjectionTokenError(clazz, error2) {
|
9182 | const { param, index, reason } = error2;
|
9183 | let chainMessage = void 0;
|
9184 | let hints = void 0;
|
9185 | switch (reason.kind) {
|
9186 | case 5:
|
9187 | chainMessage = "Consider using the @Inject decorator to specify an injection token.";
|
9188 | hints = [
|
9189 | makeRelatedInformation(reason.typeNode, "This type is not supported as injection token.")
|
9190 | ];
|
9191 | break;
|
9192 | case 1:
|
9193 | chainMessage = "Consider using the @Inject decorator to specify an injection token.";
|
9194 | hints = [
|
9195 | makeRelatedInformation(reason.typeNode, "This type does not have a value, so it cannot be used as injection token.")
|
9196 | ];
|
9197 | if (reason.decl !== null) {
|
9198 | hints.push(makeRelatedInformation(reason.decl, "The type is declared here."));
|
9199 | }
|
9200 | break;
|
9201 | case 2:
|
9202 | chainMessage = "Consider changing the type-only import to a regular import, or use the @Inject decorator to specify an injection token.";
|
9203 | hints = [
|
9204 | makeRelatedInformation(reason.typeNode, "This type is imported using a type-only import, which prevents it from being usable as an injection token."),
|
9205 | makeRelatedInformation(reason.importClause, "The type-only import occurs here.")
|
9206 | ];
|
9207 | break;
|
9208 | case 4:
|
9209 | chainMessage = "Consider using the @Inject decorator to specify an injection token.";
|
9210 | hints = [
|
9211 | makeRelatedInformation(reason.typeNode, "This type corresponds with a namespace, which cannot be used as injection token."),
|
9212 | makeRelatedInformation(reason.importClause, "The namespace import occurs here.")
|
9213 | ];
|
9214 | break;
|
9215 | case 3:
|
9216 | chainMessage = "The type should reference a known declaration.";
|
9217 | hints = [makeRelatedInformation(reason.typeNode, "This type could not be resolved.")];
|
9218 | break;
|
9219 | case 0:
|
9220 | chainMessage = "Consider adding a type to the parameter or use the @Inject decorator to specify an injection token.";
|
9221 | break;
|
9222 | }
|
9223 | const chain = {
|
9224 | messageText: `No suitable injection token for parameter '${param.name || index}' of class '${clazz.name.text}'.`,
|
9225 | category: ts40.DiagnosticCategory.Error,
|
9226 | code: 0,
|
9227 | next: [{
|
9228 | messageText: chainMessage,
|
9229 | category: ts40.DiagnosticCategory.Message,
|
9230 | code: 0
|
9231 | }]
|
9232 | };
|
9233 | return new FatalDiagnosticError(ErrorCode.PARAM_MISSING_TOKEN, param.nameNode, chain, hints);
|
9234 | }
|
9235 | function toR3Reference(valueRef, typeRef, valueContext, typeContext, refEmitter) {
|
9236 | return {
|
9237 | value: refEmitter.emit(valueRef, valueContext).expression,
|
9238 | type: refEmitter.emit(typeRef, typeContext, ImportFlags.ForceNewImport | ImportFlags.AllowTypeImports).expression
|
9239 | };
|
9240 | }
|
9241 | function isAngularCore(decorator) {
|
9242 | return decorator.import !== null && decorator.import.from === "@angular/core";
|
9243 | }
|
9244 | function isAngularCoreReference(reference, symbolName) {
|
9245 | return reference.ownedByModuleGuess === "@angular/core" && reference.debugName === symbolName;
|
9246 | }
|
9247 | function findAngularDecorator(decorators, name, isCore) {
|
9248 | return decorators.find((decorator) => isAngularDecorator(decorator, name, isCore));
|
9249 | }
|
9250 | function isAngularDecorator(decorator, name, isCore) {
|
9251 | if (isCore) {
|
9252 | return decorator.name === name;
|
9253 | } else if (isAngularCore(decorator)) {
|
9254 | return decorator.import.name === name;
|
9255 | }
|
9256 | return false;
|
9257 | }
|
9258 | function unwrapExpression(node) {
|
9259 | while (ts40.isAsExpression(node) || ts40.isParenthesizedExpression(node)) {
|
9260 | node = node.expression;
|
9261 | }
|
9262 | return node;
|
9263 | }
|
9264 | function expandForwardRef(arg) {
|
9265 | arg = unwrapExpression(arg);
|
9266 | if (!ts40.isArrowFunction(arg) && !ts40.isFunctionExpression(arg)) {
|
9267 | return null;
|
9268 | }
|
9269 | const body = arg.body;
|
9270 | if (ts40.isBlock(body)) {
|
9271 | if (body.statements.length !== 1) {
|
9272 | return null;
|
9273 | }
|
9274 | const stmt = body.statements[0];
|
9275 | if (!ts40.isReturnStatement(stmt) || stmt.expression === void 0) {
|
9276 | return null;
|
9277 | }
|
9278 | return stmt.expression;
|
9279 | } else {
|
9280 | return body;
|
9281 | }
|
9282 | }
|
9283 | function tryUnwrapForwardRef(node, reflector) {
|
9284 | node = unwrapExpression(node);
|
9285 | if (!ts40.isCallExpression(node) || node.arguments.length !== 1) {
|
9286 | return null;
|
9287 | }
|
9288 | const fn = ts40.isPropertyAccessExpression(node.expression) ? node.expression.name : node.expression;
|
9289 | if (!ts40.isIdentifier(fn)) {
|
9290 | return null;
|
9291 | }
|
9292 | const expr = expandForwardRef(node.arguments[0]);
|
9293 | if (expr === null) {
|
9294 | return null;
|
9295 | }
|
9296 | const imp = reflector.getImportOfIdentifier(fn);
|
9297 | if (imp === null || imp.from !== "@angular/core" || imp.name !== "forwardRef") {
|
9298 | return null;
|
9299 | }
|
9300 | return expr;
|
9301 | }
|
9302 | function forwardRefResolver(ref, args) {
|
9303 | if (!isAngularCoreReference(ref, "forwardRef") || args.length !== 1) {
|
9304 | return null;
|
9305 | }
|
9306 | return expandForwardRef(args[0]);
|
9307 | }
|
9308 | function combineResolvers(resolvers) {
|
9309 | return (ref, args) => {
|
9310 | for (const resolver of resolvers) {
|
9311 | const resolved = resolver(ref, args);
|
9312 | if (resolved !== null) {
|
9313 | return resolved;
|
9314 | }
|
9315 | }
|
9316 | return null;
|
9317 | };
|
9318 | }
|
9319 | function isExpressionForwardReference(expr, context, contextSource) {
|
9320 | if (isWrappedTsNodeExpr(expr)) {
|
9321 | const node = ts40.getOriginalNode(expr.node);
|
9322 | return node.getSourceFile() === contextSource && context.pos < node.pos;
|
9323 | } else {
|
9324 | return false;
|
9325 | }
|
9326 | }
|
9327 | function isWrappedTsNodeExpr(expr) {
|
9328 | return expr instanceof WrappedNodeExpr2;
|
9329 | }
|
9330 | function readBaseClass2(node, reflector, evaluator) {
|
9331 | const baseExpression = reflector.getBaseClassExpression(node);
|
9332 | if (baseExpression !== null) {
|
9333 | const baseClass = evaluator.evaluate(baseExpression);
|
9334 | if (baseClass instanceof Reference && reflector.isClass(baseClass.node)) {
|
9335 | return baseClass;
|
9336 | } else {
|
9337 | return "dynamic";
|
9338 | }
|
9339 | }
|
9340 | return null;
|
9341 | }
|
9342 | var parensWrapperTransformerFactory = (context) => {
|
9343 | const visitor = (node) => {
|
9344 | const visited = ts40.visitEachChild(node, visitor, context);
|
9345 | if (ts40.isArrowFunction(visited) || ts40.isFunctionExpression(visited)) {
|
9346 | return ts40.createParen(visited);
|
9347 | }
|
9348 | return visited;
|
9349 | };
|
9350 | return (node) => ts40.visitEachChild(node, visitor, context);
|
9351 | };
|
9352 | function wrapFunctionExpressionsInParens(expression) {
|
9353 | return ts40.transform(expression, [parensWrapperTransformerFactory]).transformed[0];
|
9354 | }
|
9355 | function makeDuplicateDeclarationError(node, data, kind) {
|
9356 | const context = [];
|
9357 | for (const decl of data) {
|
9358 | if (decl.rawDeclarations === null) {
|
9359 | continue;
|
9360 | }
|
9361 | const contextNode = decl.ref.getOriginForDiagnostics(decl.rawDeclarations, decl.ngModule.name);
|
9362 | context.push(makeRelatedInformation(contextNode, `'${node.name.text}' is listed in the declarations of the NgModule '${decl.ngModule.name.text}'.`));
|
9363 | }
|
9364 | return makeDiagnostic(ErrorCode.NGMODULE_DECLARATION_NOT_UNIQUE, node.name, `The ${kind} '${node.name.text}' is declared by more than one NgModule.`, context);
|
9365 | }
|
9366 | function resolveProvidersRequiringFactory(rawProviders, reflector, evaluator) {
|
9367 | const providers = new Set();
|
9368 | const resolvedProviders = evaluator.evaluate(rawProviders);
|
9369 | if (!Array.isArray(resolvedProviders)) {
|
9370 | return providers;
|
9371 | }
|
9372 | resolvedProviders.forEach(function processProviders(provider) {
|
9373 | let tokenClass = null;
|
9374 | if (Array.isArray(provider)) {
|
9375 | provider.forEach(processProviders);
|
9376 | } else if (provider instanceof Reference) {
|
9377 | tokenClass = provider;
|
9378 | } else if (provider instanceof Map && provider.has("useClass") && !provider.has("deps")) {
|
9379 | const useExisting = provider.get("useClass");
|
9380 | if (useExisting instanceof Reference) {
|
9381 | tokenClass = useExisting;
|
9382 | }
|
9383 | }
|
9384 | if (tokenClass !== null && !tokenClass.node.getSourceFile().isDeclarationFile && reflector.isClass(tokenClass.node)) {
|
9385 | const constructorParameters = reflector.getConstructorParameters(tokenClass.node);
|
9386 | if (constructorParameters !== null && constructorParameters.length > 0) {
|
9387 | providers.add(tokenClass);
|
9388 | }
|
9389 | }
|
9390 | });
|
9391 | return providers;
|
9392 | }
|
9393 | function wrapTypeReference(reflector, clazz) {
|
9394 | const dtsClass = reflector.getDtsDeclaration(clazz);
|
9395 | const value = new WrappedNodeExpr2(clazz.name);
|
9396 | const type = dtsClass !== null && isNamedClassDeclaration(dtsClass) ? new WrappedNodeExpr2(dtsClass.name) : value;
|
9397 | return { value, type };
|
9398 | }
|
9399 | function createSourceSpan(node) {
|
9400 | const sf = node.getSourceFile();
|
9401 | const [startOffset, endOffset] = [node.getStart(), node.getEnd()];
|
9402 | const { line: startLine, character: startCol } = sf.getLineAndCharacterOfPosition(startOffset);
|
9403 | const { line: endLine, character: endCol } = sf.getLineAndCharacterOfPosition(endOffset);
|
9404 | const parseSf = new ParseSourceFile(sf.getFullText(), sf.fileName);
|
9405 | return new ParseSourceSpan(new ParseLocation(parseSf, startOffset, startLine + 1, startCol + 1), new ParseLocation(parseSf, endOffset, endLine + 1, endCol + 1));
|
9406 | }
|
9407 | function compileResults(fac, def, metadataStmt, propName) {
|
9408 | const statements = def.statements;
|
9409 | if (metadataStmt !== null) {
|
9410 | statements.push(metadataStmt);
|
9411 | }
|
9412 | return [
|
9413 | fac,
|
9414 | {
|
9415 | name: propName,
|
9416 | initializer: def.expression,
|
9417 | statements: def.statements,
|
9418 | type: def.type
|
9419 | }
|
9420 | ];
|
9421 | }
|
9422 | function toFactoryMetadata(meta, target) {
|
9423 | return {
|
9424 | name: meta.name,
|
9425 | type: meta.type,
|
9426 | internalType: meta.internalType,
|
9427 | typeArgumentCount: meta.typeArgumentCount,
|
9428 | deps: meta.deps,
|
9429 | target
|
9430 | };
|
9431 | }
|
9432 |
|
9433 |
|
9434 | function createValueHasWrongTypeError(node, value, messageText) {
|
9435 | var _a;
|
9436 | let chainedMessage;
|
9437 | let relatedInformation;
|
9438 | if (value instanceof DynamicValue) {
|
9439 | chainedMessage = "Value could not be determined statically.";
|
9440 | relatedInformation = traceDynamicValue(node, value);
|
9441 | } else if (value instanceof Reference) {
|
9442 | const target = value.debugName !== null ? `'${value.debugName}'` : "an anonymous declaration";
|
9443 | chainedMessage = `Value is a reference to ${target}.`;
|
9444 | const referenceNode = (_a = identifierOfNode(value.node)) != null ? _a : value.node;
|
9445 | relatedInformation = [makeRelatedInformation(referenceNode, "Reference is declared here.")];
|
9446 | } else {
|
9447 | chainedMessage = `Value is of type '${describeResolvedType(value)}'.`;
|
9448 | }
|
9449 | const chain = {
|
9450 | messageText,
|
9451 | category: ts41.DiagnosticCategory.Error,
|
9452 | code: 0,
|
9453 | next: [{
|
9454 | messageText: chainedMessage,
|
9455 | category: ts41.DiagnosticCategory.Message,
|
9456 | code: 0
|
9457 | }]
|
9458 | };
|
9459 | return new FatalDiagnosticError(ErrorCode.VALUE_HAS_WRONG_TYPE, node, chain, relatedInformation);
|
9460 | }
|
9461 | function getProviderDiagnostics(providerClasses, providersDeclaration, registry) {
|
9462 | const diagnostics = [];
|
9463 | for (const provider of providerClasses) {
|
9464 | if (registry.isInjectable(provider.node)) {
|
9465 | continue;
|
9466 | }
|
9467 | const contextNode = provider.getOriginForDiagnostics(providersDeclaration);
|
9468 | 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.
|
9469 |
|
9470 | Either add the @Injectable() decorator to '${provider.node.name.text}', or configure a different provider (such as a provider with 'useFactory').
|
9471 | `, [makeRelatedInformation(provider.node, `'${provider.node.name.text}' is declared here.`)]));
|
9472 | }
|
9473 | return diagnostics;
|
9474 | }
|
9475 | function getDirectiveDiagnostics(node, reader, evaluator, reflector, scopeRegistry, kind) {
|
9476 | let diagnostics = [];
|
9477 | const addDiagnostics = (more) => {
|
9478 | if (more === null) {
|
9479 | return;
|
9480 | } else if (diagnostics === null) {
|
9481 | diagnostics = Array.isArray(more) ? more : [more];
|
9482 | } else if (Array.isArray(more)) {
|
9483 | diagnostics.push(...more);
|
9484 | } else {
|
9485 | diagnostics.push(more);
|
9486 | }
|
9487 | };
|
9488 | const duplicateDeclarations = scopeRegistry.getDuplicateDeclarations(node);
|
9489 | if (duplicateDeclarations !== null) {
|
9490 | addDiagnostics(makeDuplicateDeclarationError(node, duplicateDeclarations, kind));
|
9491 | }
|
9492 | addDiagnostics(checkInheritanceOfDirective(node, reader, reflector, evaluator));
|
9493 | return diagnostics;
|
9494 | }
|
9495 | function getUndecoratedClassWithAngularFeaturesDiagnostic(node) {
|
9496 | 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.`);
|
9497 | }
|
9498 | function checkInheritanceOfDirective(node, reader, reflector, evaluator) {
|
9499 | if (!reflector.isClass(node) || reflector.getConstructorParameters(node) !== null) {
|
9500 | return null;
|
9501 | }
|
9502 | let baseClass = readBaseClass2(node, reflector, evaluator);
|
9503 | while (baseClass !== null) {
|
9504 | if (baseClass === "dynamic") {
|
9505 | return null;
|
9506 | }
|
9507 | const baseClassMeta = reader.getDirectiveMetadata(baseClass);
|
9508 | if (baseClassMeta !== null) {
|
9509 | return null;
|
9510 | }
|
9511 | const baseClassConstructorParams = reflector.getConstructorParameters(baseClass.node);
|
9512 | const newParentClass = readBaseClass2(baseClass.node, reflector, evaluator);
|
9513 | if (baseClassConstructorParams !== null && baseClassConstructorParams.length > 0) {
|
9514 | return getInheritedUndecoratedCtorDiagnostic(node, baseClass, reader);
|
9515 | } else if (baseClassConstructorParams !== null || newParentClass === null) {
|
9516 | return null;
|
9517 | }
|
9518 | baseClass = newParentClass;
|
9519 | }
|
9520 | return null;
|
9521 | }
|
9522 | function getInheritedUndecoratedCtorDiagnostic(node, baseClass, reader) {
|
9523 | const subclassMeta = reader.getDirectiveMetadata(new Reference(node));
|
9524 | const dirOrComp = subclassMeta.isComponent ? "Component" : "Directive";
|
9525 | const baseClassName = baseClass.debugName;
|
9526 | return makeDiagnostic(ErrorCode.DIRECTIVE_INHERITS_UNDECORATED_CTOR, node.name, `The ${dirOrComp.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 @Directive decorator to ${baseClassName}, or add an explicit constructor to ${node.name.text}.`);
|
9527 | }
|
9528 |
|
9529 |
|
9530 | import { compileClassMetadata, compileDeclareClassMetadata, compileDeclareDirectiveFromMetadata, compileDirectiveFromMetadata, createMayBeForwardRefExpression, emitDistinctChangesOnlyDefaultValue, ExternalExpr as ExternalExpr5, FactoryTarget, getSafePropertyAccessString, makeBindingParser, parseHostBindings, verifyHostBindings, WrappedNodeExpr as WrappedNodeExpr4 } from "@angular/compiler";
|
9531 | import ts43 from "typescript";
|
9532 |
|
9533 |
|
9534 | import { compileDeclareFactoryFunction, compileFactoryFunction } from "@angular/compiler";
|
9535 | function compileNgFactoryDefField(metadata) {
|
9536 | const res = compileFactoryFunction(metadata);
|
9537 | return { name: "\u0275fac", initializer: res.expression, statements: res.statements, type: res.type };
|
9538 | }
|
9539 | function compileDeclareFactory(metadata) {
|
9540 | const res = compileDeclareFactoryFunction(metadata);
|
9541 | return { name: "\u0275fac", initializer: res.expression, statements: res.statements, type: res.type };
|
9542 | }
|
9543 |
|
9544 |
|
9545 | import { FunctionExpr, LiteralArrayExpr, LiteralExpr as LiteralExpr2, literalMap, ReturnStatement, WrappedNodeExpr as WrappedNodeExpr3 } from "@angular/compiler";
|
9546 | import ts42 from "typescript";
|
9547 | function extractClassMetadata(clazz, reflection, isCore, annotateForClosureCompiler, angularDecoratorTransform = (dec) => dec) {
|
9548 | if (!reflection.isClass(clazz)) {
|
9549 | return null;
|
9550 | }
|
9551 | const id = reflection.getAdjacentNameOfClass(clazz);
|
9552 | const classDecorators = reflection.getDecoratorsOfDeclaration(clazz);
|
9553 | if (classDecorators === null) {
|
9554 | return null;
|
9555 | }
|
9556 | const ngClassDecorators = classDecorators.filter((dec) => isAngularDecorator2(dec, isCore)).map((decorator) => decoratorToMetadata(angularDecoratorTransform(decorator), annotateForClosureCompiler)).map((decorator) => removeIdentifierReferences(decorator, id.text));
|
9557 | if (ngClassDecorators.length === 0) {
|
9558 | return null;
|
9559 | }
|
9560 | const metaDecorators = new WrappedNodeExpr3(ts42.createArrayLiteral(ngClassDecorators));
|
9561 | let metaCtorParameters = null;
|
9562 | const classCtorParameters = reflection.getConstructorParameters(clazz);
|
9563 | if (classCtorParameters !== null) {
|
9564 | const ctorParameters = classCtorParameters.map((param) => ctorParameterToMetadata(param, isCore));
|
9565 | metaCtorParameters = new FunctionExpr([], [
|
9566 | new ReturnStatement(new LiteralArrayExpr(ctorParameters))
|
9567 | ]);
|
9568 | }
|
9569 | let metaPropDecorators = null;
|
9570 | const classMembers = reflection.getMembersOfClass(clazz).filter((member) => !member.isStatic && member.decorators !== null && member.decorators.length > 0);
|
9571 | const duplicateDecoratedMemberNames = classMembers.map((member) => member.name).filter((name, i, arr) => arr.indexOf(name) < i);
|
9572 | if (duplicateDecoratedMemberNames.length > 0) {
|
9573 | throw new Error(`Duplicate decorated properties found on class '${clazz.name.text}': ` + duplicateDecoratedMemberNames.join(", "));
|
9574 | }
|
9575 | const decoratedMembers = classMembers.map((member) => {
|
9576 | var _a;
|
9577 | return classMemberToMetadata((_a = member.nameNode) != null ? _a : member.name, member.decorators, isCore);
|
9578 | });
|
9579 | if (decoratedMembers.length > 0) {
|
9580 | metaPropDecorators = new WrappedNodeExpr3(ts42.createObjectLiteral(decoratedMembers));
|
9581 | }
|
9582 | return {
|
9583 | type: new WrappedNodeExpr3(id),
|
9584 | decorators: metaDecorators,
|
9585 | ctorParameters: metaCtorParameters,
|
9586 | propDecorators: metaPropDecorators
|
9587 | };
|
9588 | }
|
9589 | function ctorParameterToMetadata(param, isCore) {
|
9590 | const type = param.typeValueReference.kind !== 2 ? valueReferenceToExpression(param.typeValueReference) : new LiteralExpr2(void 0);
|
9591 | const mapEntries = [
|
9592 | { key: "type", value: type, quoted: false }
|
9593 | ];
|
9594 | if (param.decorators !== null) {
|
9595 | const ngDecorators = param.decorators.filter((dec) => isAngularDecorator2(dec, isCore)).map((decorator) => decoratorToMetadata(decorator));
|
9596 | const value = new WrappedNodeExpr3(ts42.createArrayLiteral(ngDecorators));
|
9597 | mapEntries.push({ key: "decorators", value, quoted: false });
|
9598 | }
|
9599 | return literalMap(mapEntries);
|
9600 | }
|
9601 | function classMemberToMetadata(name, decorators, isCore) {
|
9602 | const ngDecorators = decorators.filter((dec) => isAngularDecorator2(dec, isCore)).map((decorator) => decoratorToMetadata(decorator));
|
9603 | const decoratorMeta = ts42.createArrayLiteral(ngDecorators);
|
9604 | return ts42.createPropertyAssignment(name, decoratorMeta);
|
9605 | }
|
9606 | function decoratorToMetadata(decorator, wrapFunctionsInParens) {
|
9607 | if (decorator.identifier === null) {
|
9608 | throw new Error("Illegal state: synthesized decorator cannot be emitted in class metadata.");
|
9609 | }
|
9610 | const properties = [
|
9611 | ts42.createPropertyAssignment("type", ts42.getMutableClone(decorator.identifier))
|
9612 | ];
|
9613 | if (decorator.args !== null && decorator.args.length > 0) {
|
9614 | const args = decorator.args.map((arg) => {
|
9615 | const expr = ts42.getMutableClone(arg);
|
9616 | return wrapFunctionsInParens ? wrapFunctionExpressionsInParens(expr) : expr;
|
9617 | });
|
9618 | properties.push(ts42.createPropertyAssignment("args", ts42.createArrayLiteral(args)));
|
9619 | }
|
9620 | return ts42.createObjectLiteral(properties, true);
|
9621 | }
|
9622 | function isAngularDecorator2(decorator, isCore) {
|
9623 | return isCore || decorator.import !== null && decorator.import.from === "@angular/core";
|
9624 | }
|
9625 | function removeIdentifierReferences(node, name) {
|
9626 | const result = ts42.transform(node, [(context) => (root) => ts42.visitNode(root, function walk(current) {
|
9627 | return ts42.isIdentifier(current) && current.text === name ? ts42.createIdentifier(current.text) : ts42.visitEachChild(current, walk, context);
|
9628 | })]);
|
9629 | return result.transformed[0];
|
9630 | }
|
9631 |
|
9632 |
|
9633 | var EMPTY_OBJECT = {};
|
9634 | var FIELD_DECORATORS = [
|
9635 | "Input",
|
9636 | "Output",
|
9637 | "ViewChild",
|
9638 | "ViewChildren",
|
9639 | "ContentChild",
|
9640 | "ContentChildren",
|
9641 | "HostBinding",
|
9642 | "HostListener"
|
9643 | ];
|
9644 | var LIFECYCLE_HOOKS = new Set([
|
9645 | "ngOnChanges",
|
9646 | "ngOnInit",
|
9647 | "ngOnDestroy",
|
9648 | "ngDoCheck",
|
9649 | "ngAfterViewInit",
|
9650 | "ngAfterViewChecked",
|
9651 | "ngAfterContentInit",
|
9652 | "ngAfterContentChecked"
|
9653 | ]);
|
9654 | var DirectiveSymbol = class extends SemanticSymbol {
|
9655 | constructor(decl, selector, inputs, outputs, exportAs, typeCheckMeta, typeParameters) {
|
9656 | super(decl);
|
9657 | this.selector = selector;
|
9658 | this.inputs = inputs;
|
9659 | this.outputs = outputs;
|
9660 | this.exportAs = exportAs;
|
9661 | this.typeCheckMeta = typeCheckMeta;
|
9662 | this.typeParameters = typeParameters;
|
9663 | this.baseClass = null;
|
9664 | }
|
9665 | isPublicApiAffected(previousSymbol) {
|
9666 | if (!(previousSymbol instanceof DirectiveSymbol)) {
|
9667 | return true;
|
9668 | }
|
9669 | return this.selector !== previousSymbol.selector || !isArrayEqual(this.inputs.propertyNames, previousSymbol.inputs.propertyNames) || !isArrayEqual(this.outputs.propertyNames, previousSymbol.outputs.propertyNames) || !isArrayEqual(this.exportAs, previousSymbol.exportAs);
|
9670 | }
|
9671 | isTypeCheckApiAffected(previousSymbol) {
|
9672 | if (this.isPublicApiAffected(previousSymbol)) {
|
9673 | return true;
|
9674 | }
|
9675 | if (!(previousSymbol instanceof DirectiveSymbol)) {
|
9676 | return true;
|
9677 | }
|
9678 | if (!isArrayEqual(Array.from(this.inputs), Array.from(previousSymbol.inputs), isInputMappingEqual) || !isArrayEqual(Array.from(this.outputs), Array.from(previousSymbol.outputs), isInputMappingEqual)) {
|
9679 | return true;
|
9680 | }
|
9681 | if (!areTypeParametersEqual(this.typeParameters, previousSymbol.typeParameters)) {
|
9682 | return true;
|
9683 | }
|
9684 | if (!isTypeCheckMetaEqual(this.typeCheckMeta, previousSymbol.typeCheckMeta)) {
|
9685 | return true;
|
9686 | }
|
9687 | if (!isBaseClassEqual(this.baseClass, previousSymbol.baseClass)) {
|
9688 | return true;
|
9689 | }
|
9690 | return false;
|
9691 | }
|
9692 | };
|
9693 | function isInputMappingEqual(current, previous) {
|
9694 | return current[0] === previous[0] && current[1] === previous[1];
|
9695 | }
|
9696 | function isTypeCheckMetaEqual(current, previous) {
|
9697 | if (current.hasNgTemplateContextGuard !== previous.hasNgTemplateContextGuard) {
|
9698 | return false;
|
9699 | }
|
9700 | if (current.isGeneric !== previous.isGeneric) {
|
9701 | return false;
|
9702 | }
|
9703 | if (!isArrayEqual(current.ngTemplateGuards, previous.ngTemplateGuards, isTemplateGuardEqual)) {
|
9704 | return false;
|
9705 | }
|
9706 | if (!isSetEqual(current.coercedInputFields, previous.coercedInputFields)) {
|
9707 | return false;
|
9708 | }
|
9709 | if (!isSetEqual(current.restrictedInputFields, previous.restrictedInputFields)) {
|
9710 | return false;
|
9711 | }
|
9712 | if (!isSetEqual(current.stringLiteralInputFields, previous.stringLiteralInputFields)) {
|
9713 | return false;
|
9714 | }
|
9715 | if (!isSetEqual(current.undeclaredInputFields, previous.undeclaredInputFields)) {
|
9716 | return false;
|
9717 | }
|
9718 | return true;
|
9719 | }
|
9720 | function isTemplateGuardEqual(current, previous) {
|
9721 | return current.inputName === previous.inputName && current.type === previous.type;
|
9722 | }
|
9723 | function isBaseClassEqual(current, previous) {
|
9724 | if (current === null || previous === null) {
|
9725 | return current === previous;
|
9726 | }
|
9727 | return isSymbolEqual(current, previous);
|
9728 | }
|
9729 | var DirectiveDecoratorHandler = class {
|
9730 | constructor(reflector, evaluator, metaRegistry, scopeRegistry, metaReader, injectableRegistry, isCore, semanticDepGraphUpdater, annotateForClosureCompiler, compileUndecoratedClassesWithAngularFeatures, perf) {
|
9731 | this.reflector = reflector;
|
9732 | this.evaluator = evaluator;
|
9733 | this.metaRegistry = metaRegistry;
|
9734 | this.scopeRegistry = scopeRegistry;
|
9735 | this.metaReader = metaReader;
|
9736 | this.injectableRegistry = injectableRegistry;
|
9737 | this.isCore = isCore;
|
9738 | this.semanticDepGraphUpdater = semanticDepGraphUpdater;
|
9739 | this.annotateForClosureCompiler = annotateForClosureCompiler;
|
9740 | this.compileUndecoratedClassesWithAngularFeatures = compileUndecoratedClassesWithAngularFeatures;
|
9741 | this.perf = perf;
|
9742 | this.precedence = HandlerPrecedence.PRIMARY;
|
9743 | this.name = DirectiveDecoratorHandler.name;
|
9744 | }
|
9745 | detect(node, decorators) {
|
9746 | if (!decorators) {
|
9747 | const angularField = this.findClassFieldWithAngularFeatures(node);
|
9748 | return angularField ? { trigger: angularField.node, decorator: null, metadata: null } : void 0;
|
9749 | } else {
|
9750 | const decorator = findAngularDecorator(decorators, "Directive", this.isCore);
|
9751 | return decorator ? { trigger: decorator.node, decorator, metadata: decorator } : void 0;
|
9752 | }
|
9753 | }
|
9754 | analyze(node, decorator, flags = HandlerFlags.NONE) {
|
9755 | if (this.compileUndecoratedClassesWithAngularFeatures === false && decorator === null) {
|
9756 | return { diagnostics: [getUndecoratedClassWithAngularFeaturesDiagnostic(node)] };
|
9757 | }
|
9758 | this.perf.eventCount(PerfEvent.AnalyzeDirective);
|
9759 | const directiveResult = extractDirectiveMetadata(node, decorator, this.reflector, this.evaluator, this.isCore, flags, this.annotateForClosureCompiler);
|
9760 | if (directiveResult === void 0) {
|
9761 | return {};
|
9762 | }
|
9763 | const analysis = directiveResult.metadata;
|
9764 | let providersRequiringFactory = null;
|
9765 | if (directiveResult !== void 0 && directiveResult.decorator.has("providers")) {
|
9766 | providersRequiringFactory = resolveProvidersRequiringFactory(directiveResult.decorator.get("providers"), this.reflector, this.evaluator);
|
9767 | }
|
9768 | return {
|
9769 | analysis: {
|
9770 | inputs: directiveResult.inputs,
|
9771 | outputs: directiveResult.outputs,
|
9772 | meta: analysis,
|
9773 | classMetadata: extractClassMetadata(node, this.reflector, this.isCore, this.annotateForClosureCompiler),
|
9774 | baseClass: readBaseClass2(node, this.reflector, this.evaluator),
|
9775 | typeCheckMeta: extractDirectiveTypeCheckMeta(node, directiveResult.inputs, this.reflector),
|
9776 | providersRequiringFactory,
|
9777 | isPoisoned: false,
|
9778 | isStructural: directiveResult.isStructural
|
9779 | }
|
9780 | };
|
9781 | }
|
9782 | symbol(node, analysis) {
|
9783 | const typeParameters = extractSemanticTypeParameters(node);
|
9784 | return new DirectiveSymbol(node, analysis.meta.selector, analysis.inputs, analysis.outputs, analysis.meta.exportAs, analysis.typeCheckMeta, typeParameters);
|
9785 | }
|
9786 | register(node, analysis) {
|
9787 | const ref = new Reference(node);
|
9788 | this.metaRegistry.registerDirectiveMetadata(__spreadProps(__spreadValues({
|
9789 | type: MetaType.Directive,
|
9790 | ref,
|
9791 | name: node.name.text,
|
9792 | selector: analysis.meta.selector,
|
9793 | exportAs: analysis.meta.exportAs,
|
9794 | inputs: analysis.inputs,
|
9795 | outputs: analysis.outputs,
|
9796 | queries: analysis.meta.queries.map((query) => query.propertyName),
|
9797 | isComponent: false,
|
9798 | baseClass: analysis.baseClass
|
9799 | }, analysis.typeCheckMeta), {
|
9800 | isPoisoned: analysis.isPoisoned,
|
9801 | isStructural: analysis.isStructural
|
9802 | }));
|
9803 | this.injectableRegistry.registerInjectable(node);
|
9804 | }
|
9805 | resolve(node, analysis, symbol) {
|
9806 | if (this.semanticDepGraphUpdater !== null && analysis.baseClass instanceof Reference) {
|
9807 | symbol.baseClass = this.semanticDepGraphUpdater.getSymbol(analysis.baseClass.node);
|
9808 | }
|
9809 | const diagnostics = [];
|
9810 | if (analysis.providersRequiringFactory !== null && analysis.meta.providers instanceof WrappedNodeExpr4) {
|
9811 | const providerDiagnostics = getProviderDiagnostics(analysis.providersRequiringFactory, analysis.meta.providers.node, this.injectableRegistry);
|
9812 | diagnostics.push(...providerDiagnostics);
|
9813 | }
|
9814 | const directiveDiagnostics = getDirectiveDiagnostics(node, this.metaReader, this.evaluator, this.reflector, this.scopeRegistry, "Directive");
|
9815 | if (directiveDiagnostics !== null) {
|
9816 | diagnostics.push(...directiveDiagnostics);
|
9817 | }
|
9818 | return { diagnostics: diagnostics.length > 0 ? diagnostics : void 0 };
|
9819 | }
|
9820 | compileFull(node, analysis, resolution, pool) {
|
9821 | const fac = compileNgFactoryDefField(toFactoryMetadata(analysis.meta, FactoryTarget.Directive));
|
9822 | const def = compileDirectiveFromMetadata(analysis.meta, pool, makeBindingParser());
|
9823 | const classMetadata = analysis.classMetadata !== null ? compileClassMetadata(analysis.classMetadata).toStmt() : null;
|
9824 | return compileResults(fac, def, classMetadata, "\u0275dir");
|
9825 | }
|
9826 | compilePartial(node, analysis, resolution) {
|
9827 | const fac = compileDeclareFactory(toFactoryMetadata(analysis.meta, FactoryTarget.Directive));
|
9828 | const def = compileDeclareDirectiveFromMetadata(analysis.meta);
|
9829 | const classMetadata = analysis.classMetadata !== null ? compileDeclareClassMetadata(analysis.classMetadata).toStmt() : null;
|
9830 | return compileResults(fac, def, classMetadata, "\u0275dir");
|
9831 | }
|
9832 | findClassFieldWithAngularFeatures(node) {
|
9833 | return this.reflector.getMembersOfClass(node).find((member) => {
|
9834 | if (!member.isStatic && member.kind === ClassMemberKind.Method && LIFECYCLE_HOOKS.has(member.name)) {
|
9835 | return true;
|
9836 | }
|
9837 | if (member.decorators) {
|
9838 | return member.decorators.some((decorator) => FIELD_DECORATORS.some((decoratorName) => isAngularDecorator(decorator, decoratorName, this.isCore)));
|
9839 | }
|
9840 | return false;
|
9841 | });
|
9842 | }
|
9843 | };
|
9844 | function extractDirectiveMetadata(clazz, decorator, reflector, evaluator, isCore, flags, annotateForClosureCompiler, defaultSelector = null) {
|
9845 | let directive;
|
9846 | if (decorator === null || decorator.args === null || decorator.args.length === 0) {
|
9847 | directive = new Map();
|
9848 | } else if (decorator.args.length !== 1) {
|
9849 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, Decorator.nodeForError(decorator), `Incorrect number of arguments to @${decorator.name} decorator`);
|
9850 | } else {
|
9851 | const meta = unwrapExpression(decorator.args[0]);
|
9852 | if (!ts43.isObjectLiteralExpression(meta)) {
|
9853 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARG_NOT_LITERAL, meta, `@${decorator.name} argument must be an object literal`);
|
9854 | }
|
9855 | directive = reflectObjectLiteral(meta);
|
9856 | }
|
9857 | if (directive.has("jit")) {
|
9858 | return void 0;
|
9859 | }
|
9860 | const members = reflector.getMembersOfClass(clazz);
|
9861 | const decoratedElements = members.filter((member) => !member.isStatic && member.decorators !== null);
|
9862 | const coreModule = isCore ? void 0 : "@angular/core";
|
9863 | const inputsFromMeta = parseFieldToPropertyMapping(directive, "inputs", evaluator);
|
9864 | const inputsFromFields = parseDecoratedFields(filterToMembersWithDecorator(decoratedElements, "Input", coreModule), evaluator, resolveInput);
|
9865 | const outputsFromMeta = parseFieldToPropertyMapping(directive, "outputs", evaluator);
|
9866 | const outputsFromFields = parseDecoratedFields(filterToMembersWithDecorator(decoratedElements, "Output", coreModule), evaluator, resolveOutput);
|
9867 | const contentChildFromFields = queriesFromFields(filterToMembersWithDecorator(decoratedElements, "ContentChild", coreModule), reflector, evaluator);
|
9868 | const contentChildrenFromFields = queriesFromFields(filterToMembersWithDecorator(decoratedElements, "ContentChildren", coreModule), reflector, evaluator);
|
9869 | const queries = [...contentChildFromFields, ...contentChildrenFromFields];
|
9870 | const viewChildFromFields = queriesFromFields(filterToMembersWithDecorator(decoratedElements, "ViewChild", coreModule), reflector, evaluator);
|
9871 | const viewChildrenFromFields = queriesFromFields(filterToMembersWithDecorator(decoratedElements, "ViewChildren", coreModule), reflector, evaluator);
|
9872 | const viewQueries = [...viewChildFromFields, ...viewChildrenFromFields];
|
9873 | if (directive.has("queries")) {
|
9874 | const queriesFromDecorator = extractQueriesFromDecorator(directive.get("queries"), reflector, evaluator, isCore);
|
9875 | queries.push(...queriesFromDecorator.content);
|
9876 | viewQueries.push(...queriesFromDecorator.view);
|
9877 | }
|
9878 | let selector = defaultSelector;
|
9879 | if (directive.has("selector")) {
|
9880 | const expr = directive.get("selector");
|
9881 | const resolved = evaluator.evaluate(expr);
|
9882 | if (typeof resolved !== "string") {
|
9883 | throw createValueHasWrongTypeError(expr, resolved, `selector must be a string`);
|
9884 | }
|
9885 | selector = resolved === "" ? defaultSelector : resolved;
|
9886 | if (!selector) {
|
9887 | throw new FatalDiagnosticError(ErrorCode.DIRECTIVE_MISSING_SELECTOR, expr, `Directive ${clazz.name.text} has no selector, please add it!`);
|
9888 | }
|
9889 | }
|
9890 | const host = extractHostBindings(decoratedElements, evaluator, coreModule, directive);
|
9891 | const providers = directive.has("providers") ? new WrappedNodeExpr4(annotateForClosureCompiler ? wrapFunctionExpressionsInParens(directive.get("providers")) : directive.get("providers")) : null;
|
9892 | const usesOnChanges = members.some((member) => !member.isStatic && member.kind === ClassMemberKind.Method && member.name === "ngOnChanges");
|
9893 | let exportAs = null;
|
9894 | if (directive.has("exportAs")) {
|
9895 | const expr = directive.get("exportAs");
|
9896 | const resolved = evaluator.evaluate(expr);
|
9897 | if (typeof resolved !== "string") {
|
9898 | throw createValueHasWrongTypeError(expr, resolved, `exportAs must be a string`);
|
9899 | }
|
9900 | exportAs = resolved.split(",").map((part) => part.trim());
|
9901 | }
|
9902 | const rawCtorDeps = getConstructorDependencies(clazz, reflector, isCore);
|
9903 | const ctorDeps = selector !== null ? validateConstructorDependencies(clazz, rawCtorDeps) : unwrapConstructorDependencies(rawCtorDeps);
|
9904 | const isStructural = ctorDeps !== null && ctorDeps !== "invalid" && ctorDeps.some((dep) => dep.token instanceof ExternalExpr5 && dep.token.value.moduleName === "@angular/core" && dep.token.value.name === "TemplateRef");
|
9905 | const usesInheritance = reflector.hasBaseClass(clazz);
|
9906 | const type = wrapTypeReference(reflector, clazz);
|
9907 | const internalType = new WrappedNodeExpr4(reflector.getInternalNameOfClass(clazz));
|
9908 | const inputs = ClassPropertyMapping.fromMappedObject(__spreadValues(__spreadValues({}, inputsFromMeta), inputsFromFields));
|
9909 | const outputs = ClassPropertyMapping.fromMappedObject(__spreadValues(__spreadValues({}, outputsFromMeta), outputsFromFields));
|
9910 | const metadata = {
|
9911 | name: clazz.name.text,
|
9912 | deps: ctorDeps,
|
9913 | host,
|
9914 | lifecycle: {
|
9915 | usesOnChanges
|
9916 | },
|
9917 | inputs: inputs.toJointMappedObject(),
|
9918 | outputs: outputs.toDirectMappedObject(),
|
9919 | queries,
|
9920 | viewQueries,
|
9921 | selector,
|
9922 | fullInheritance: !!(flags & HandlerFlags.FULL_INHERITANCE),
|
9923 | type,
|
9924 | internalType,
|
9925 | typeArgumentCount: reflector.getGenericArityOfClass(clazz) || 0,
|
9926 | typeSourceSpan: createSourceSpan(clazz.name),
|
9927 | usesInheritance,
|
9928 | exportAs,
|
9929 | providers
|
9930 | };
|
9931 | return {
|
9932 | decorator: directive,
|
9933 | metadata,
|
9934 | inputs,
|
9935 | outputs,
|
9936 | isStructural
|
9937 | };
|
9938 | }
|
9939 | function extractQueryMetadata(exprNode, name, args, propertyName, reflector, evaluator) {
|
9940 | if (args.length === 0) {
|
9941 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, exprNode, `@${name} must have arguments`);
|
9942 | }
|
9943 | const first = name === "ViewChild" || name === "ContentChild";
|
9944 | const forwardReferenceTarget = tryUnwrapForwardRef(args[0], reflector);
|
9945 | const node = forwardReferenceTarget != null ? forwardReferenceTarget : args[0];
|
9946 | const arg = evaluator.evaluate(node);
|
9947 | let isStatic = false;
|
9948 | let predicate = null;
|
9949 | if (arg instanceof Reference || arg instanceof DynamicValue) {
|
9950 | predicate = createMayBeForwardRefExpression(new WrappedNodeExpr4(node), forwardReferenceTarget !== null ? 2 : 0);
|
9951 | } else if (typeof arg === "string") {
|
9952 | predicate = [arg];
|
9953 | } else if (isStringArrayOrDie(arg, `@${name} predicate`, node)) {
|
9954 | predicate = arg;
|
9955 | } else {
|
9956 | throw createValueHasWrongTypeError(node, arg, `@${name} predicate cannot be interpreted`);
|
9957 | }
|
9958 | let read = null;
|
9959 | let descendants = name !== "ContentChildren";
|
9960 | let emitDistinctChangesOnly = emitDistinctChangesOnlyDefaultValue;
|
9961 | if (args.length === 2) {
|
9962 | const optionsExpr = unwrapExpression(args[1]);
|
9963 | if (!ts43.isObjectLiteralExpression(optionsExpr)) {
|
9964 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARG_NOT_LITERAL, optionsExpr, `@${name} options must be an object literal`);
|
9965 | }
|
9966 | const options = reflectObjectLiteral(optionsExpr);
|
9967 | if (options.has("read")) {
|
9968 | read = new WrappedNodeExpr4(options.get("read"));
|
9969 | }
|
9970 | if (options.has("descendants")) {
|
9971 | const descendantsExpr = options.get("descendants");
|
9972 | const descendantsValue = evaluator.evaluate(descendantsExpr);
|
9973 | if (typeof descendantsValue !== "boolean") {
|
9974 | throw createValueHasWrongTypeError(descendantsExpr, descendantsValue, `@${name} options.descendants must be a boolean`);
|
9975 | }
|
9976 | descendants = descendantsValue;
|
9977 | }
|
9978 | if (options.has("emitDistinctChangesOnly")) {
|
9979 | const emitDistinctChangesOnlyExpr = options.get("emitDistinctChangesOnly");
|
9980 | const emitDistinctChangesOnlyValue = evaluator.evaluate(emitDistinctChangesOnlyExpr);
|
9981 | if (typeof emitDistinctChangesOnlyValue !== "boolean") {
|
9982 | throw createValueHasWrongTypeError(emitDistinctChangesOnlyExpr, emitDistinctChangesOnlyValue, `@${name} options.emitDistinctChangesOnly must be a boolean`);
|
9983 | }
|
9984 | emitDistinctChangesOnly = emitDistinctChangesOnlyValue;
|
9985 | }
|
9986 | if (options.has("static")) {
|
9987 | const staticValue = evaluator.evaluate(options.get("static"));
|
9988 | if (typeof staticValue !== "boolean") {
|
9989 | throw createValueHasWrongTypeError(node, staticValue, `@${name} options.static must be a boolean`);
|
9990 | }
|
9991 | isStatic = staticValue;
|
9992 | }
|
9993 | } else if (args.length > 2) {
|
9994 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, node, `@${name} has too many arguments`);
|
9995 | }
|
9996 | return {
|
9997 | propertyName,
|
9998 | predicate,
|
9999 | first,
|
10000 | descendants,
|
10001 | read,
|
10002 | static: isStatic,
|
10003 | emitDistinctChangesOnly
|
10004 | };
|
10005 | }
|
10006 | function extractQueriesFromDecorator(queryData, reflector, evaluator, isCore) {
|
10007 | const content = [], view = [];
|
10008 | if (!ts43.isObjectLiteralExpression(queryData)) {
|
10009 | throw new FatalDiagnosticError(ErrorCode.VALUE_HAS_WRONG_TYPE, queryData, "Decorator queries metadata must be an object literal");
|
10010 | }
|
10011 | reflectObjectLiteral(queryData).forEach((queryExpr, propertyName) => {
|
10012 | queryExpr = unwrapExpression(queryExpr);
|
10013 | if (!ts43.isNewExpression(queryExpr)) {
|
10014 | throw new FatalDiagnosticError(ErrorCode.VALUE_HAS_WRONG_TYPE, queryData, "Decorator query metadata must be an instance of a query type");
|
10015 | }
|
10016 | const queryType = ts43.isPropertyAccessExpression(queryExpr.expression) ? queryExpr.expression.name : queryExpr.expression;
|
10017 | if (!ts43.isIdentifier(queryType)) {
|
10018 | throw new FatalDiagnosticError(ErrorCode.VALUE_HAS_WRONG_TYPE, queryData, "Decorator query metadata must be an instance of a query type");
|
10019 | }
|
10020 | const type = reflector.getImportOfIdentifier(queryType);
|
10021 | if (type === null || !isCore && type.from !== "@angular/core" || !QUERY_TYPES.has(type.name)) {
|
10022 | throw new FatalDiagnosticError(ErrorCode.VALUE_HAS_WRONG_TYPE, queryData, "Decorator query metadata must be an instance of a query type");
|
10023 | }
|
10024 | const query = extractQueryMetadata(queryExpr, type.name, queryExpr.arguments || [], propertyName, reflector, evaluator);
|
10025 | if (type.name.startsWith("Content")) {
|
10026 | content.push(query);
|
10027 | } else {
|
10028 | view.push(query);
|
10029 | }
|
10030 | });
|
10031 | return { content, view };
|
10032 | }
|
10033 | function isStringArrayOrDie(value, name, node) {
|
10034 | if (!Array.isArray(value)) {
|
10035 | return false;
|
10036 | }
|
10037 | for (let i = 0; i < value.length; i++) {
|
10038 | if (typeof value[i] !== "string") {
|
10039 | throw createValueHasWrongTypeError(node, value[i], `Failed to resolve ${name} at position ${i} to a string`);
|
10040 | }
|
10041 | }
|
10042 | return true;
|
10043 | }
|
10044 | function parseFieldArrayValue(directive, field, evaluator) {
|
10045 | if (!directive.has(field)) {
|
10046 | return null;
|
10047 | }
|
10048 | const expression = directive.get(field);
|
10049 | const value = evaluator.evaluate(expression);
|
10050 | if (!isStringArrayOrDie(value, field, expression)) {
|
10051 | throw createValueHasWrongTypeError(expression, value, `Failed to resolve @Directive.${field} to a string array`);
|
10052 | }
|
10053 | return value;
|
10054 | }
|
10055 | function parseFieldToPropertyMapping(directive, field, evaluator) {
|
10056 | const metaValues = parseFieldArrayValue(directive, field, evaluator);
|
10057 | if (!metaValues) {
|
10058 | return EMPTY_OBJECT;
|
10059 | }
|
10060 | return metaValues.reduce((results, value) => {
|
10061 | const [field2, property2] = value.split(":", 2).map((str) => str.trim());
|
10062 | results[field2] = property2 || field2;
|
10063 | return results;
|
10064 | }, {});
|
10065 | }
|
10066 | function parseDecoratedFields(fields, evaluator, mapValueResolver) {
|
10067 | return fields.reduce((results, field) => {
|
10068 | const fieldName = field.member.name;
|
10069 | field.decorators.forEach((decorator) => {
|
10070 | if (decorator.args == null || decorator.args.length === 0) {
|
10071 | results[fieldName] = fieldName;
|
10072 | } else if (decorator.args.length === 1) {
|
10073 | const property2 = evaluator.evaluate(decorator.args[0]);
|
10074 | if (typeof property2 !== "string") {
|
10075 | throw createValueHasWrongTypeError(Decorator.nodeForError(decorator), property2, `@${decorator.name} decorator argument must resolve to a string`);
|
10076 | }
|
10077 | results[fieldName] = mapValueResolver(property2, fieldName);
|
10078 | } else {
|
10079 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, Decorator.nodeForError(decorator), `@${decorator.name} can have at most one argument, got ${decorator.args.length} argument(s)`);
|
10080 | }
|
10081 | });
|
10082 | return results;
|
10083 | }, {});
|
10084 | }
|
10085 | function resolveInput(publicName, internalName) {
|
10086 | return [publicName, internalName];
|
10087 | }
|
10088 | function resolveOutput(publicName, internalName) {
|
10089 | return publicName;
|
10090 | }
|
10091 | function queriesFromFields(fields, reflector, evaluator) {
|
10092 | return fields.map(({ member, decorators }) => {
|
10093 | const decorator = decorators[0];
|
10094 | const node = member.node || Decorator.nodeForError(decorator);
|
10095 | if (member.decorators.some((v) => v.name === "Input")) {
|
10096 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_COLLISION, node, "Cannot combine @Input decorators with query decorators");
|
10097 | }
|
10098 | if (decorators.length !== 1) {
|
10099 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_COLLISION, node, "Cannot have multiple query decorators on the same class member");
|
10100 | } else if (!isPropertyTypeMember(member)) {
|
10101 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_UNEXPECTED, node, "Query decorator must go on a property-type member");
|
10102 | }
|
10103 | return extractQueryMetadata(node, decorator.name, decorator.args || [], member.name, reflector, evaluator);
|
10104 | });
|
10105 | }
|
10106 | function isPropertyTypeMember(member) {
|
10107 | return member.kind === ClassMemberKind.Getter || member.kind === ClassMemberKind.Setter || member.kind === ClassMemberKind.Property;
|
10108 | }
|
10109 | function evaluateHostExpressionBindings(hostExpr, evaluator) {
|
10110 | const hostMetaMap = evaluator.evaluate(hostExpr);
|
10111 | if (!(hostMetaMap instanceof Map)) {
|
10112 | throw createValueHasWrongTypeError(hostExpr, hostMetaMap, `Decorator host metadata must be an object`);
|
10113 | }
|
10114 | const hostMetadata = {};
|
10115 | hostMetaMap.forEach((value, key) => {
|
10116 | if (value instanceof EnumValue) {
|
10117 | value = value.resolved;
|
10118 | }
|
10119 | if (typeof key !== "string") {
|
10120 | throw createValueHasWrongTypeError(hostExpr, key, `Decorator host metadata must be a string -> string object, but found unparseable key`);
|
10121 | }
|
10122 | if (typeof value == "string") {
|
10123 | hostMetadata[key] = value;
|
10124 | } else if (value instanceof DynamicValue) {
|
10125 | hostMetadata[key] = new WrappedNodeExpr4(value.node);
|
10126 | } else {
|
10127 | throw createValueHasWrongTypeError(hostExpr, value, `Decorator host metadata must be a string -> string object, but found unparseable value`);
|
10128 | }
|
10129 | });
|
10130 | const bindings = parseHostBindings(hostMetadata);
|
10131 | const errors = verifyHostBindings(bindings, createSourceSpan(hostExpr));
|
10132 | if (errors.length > 0) {
|
10133 | throw new FatalDiagnosticError(ErrorCode.HOST_BINDING_PARSE_ERROR, hostExpr, errors.map((error2) => error2.msg).join("\n"));
|
10134 | }
|
10135 | return bindings;
|
10136 | }
|
10137 | function extractHostBindings(members, evaluator, coreModule, metadata) {
|
10138 | let bindings;
|
10139 | if (metadata && metadata.has("host")) {
|
10140 | bindings = evaluateHostExpressionBindings(metadata.get("host"), evaluator);
|
10141 | } else {
|
10142 | bindings = parseHostBindings({});
|
10143 | }
|
10144 | filterToMembersWithDecorator(members, "HostBinding", coreModule).forEach(({ member, decorators }) => {
|
10145 | decorators.forEach((decorator) => {
|
10146 | let hostPropertyName = member.name;
|
10147 | if (decorator.args !== null && decorator.args.length > 0) {
|
10148 | if (decorator.args.length !== 1) {
|
10149 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, Decorator.nodeForError(decorator), `@HostBinding can have at most one argument, got ${decorator.args.length} argument(s)`);
|
10150 | }
|
10151 | const resolved = evaluator.evaluate(decorator.args[0]);
|
10152 | if (typeof resolved !== "string") {
|
10153 | throw createValueHasWrongTypeError(Decorator.nodeForError(decorator), resolved, `@HostBinding's argument must be a string`);
|
10154 | }
|
10155 | hostPropertyName = resolved;
|
10156 | }
|
10157 | bindings.properties[hostPropertyName] = getSafePropertyAccessString("this", member.name);
|
10158 | });
|
10159 | });
|
10160 | filterToMembersWithDecorator(members, "HostListener", coreModule).forEach(({ member, decorators }) => {
|
10161 | decorators.forEach((decorator) => {
|
10162 | let eventName = member.name;
|
10163 | let args = [];
|
10164 | if (decorator.args !== null && decorator.args.length > 0) {
|
10165 | if (decorator.args.length > 2) {
|
10166 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, decorator.args[2], `@HostListener can have at most two arguments`);
|
10167 | }
|
10168 | const resolved = evaluator.evaluate(decorator.args[0]);
|
10169 | if (typeof resolved !== "string") {
|
10170 | throw createValueHasWrongTypeError(decorator.args[0], resolved, `@HostListener's event name argument must be a string`);
|
10171 | }
|
10172 | eventName = resolved;
|
10173 | if (decorator.args.length === 2) {
|
10174 | const expression = decorator.args[1];
|
10175 | const resolvedArgs = evaluator.evaluate(decorator.args[1]);
|
10176 | if (!isStringArrayOrDie(resolvedArgs, "@HostListener.args", expression)) {
|
10177 | throw createValueHasWrongTypeError(decorator.args[1], resolvedArgs, `@HostListener's second argument must be a string array`);
|
10178 | }
|
10179 | args = resolvedArgs;
|
10180 | }
|
10181 | }
|
10182 | bindings.listeners[eventName] = `${member.name}(${args.join(",")})`;
|
10183 | });
|
10184 | });
|
10185 | return bindings;
|
10186 | }
|
10187 | var QUERY_TYPES = new Set([
|
10188 | "ContentChild",
|
10189 | "ContentChildren",
|
10190 | "ViewChild",
|
10191 | "ViewChildren"
|
10192 | ]);
|
10193 |
|
10194 |
|
10195 | import { compileClassMetadata as compileClassMetadata2, compileDeclareClassMetadata as compileDeclareClassMetadata2, compileDeclareInjectorFromMetadata, compileDeclareNgModuleFromMetadata, compileInjector, compileNgModule, CUSTOM_ELEMENTS_SCHEMA, ExternalExpr as ExternalExpr6, FactoryTarget as FactoryTarget2, InvokeFunctionExpr, LiteralArrayExpr as LiteralArrayExpr2, NO_ERRORS_SCHEMA, R3Identifiers, WrappedNodeExpr as WrappedNodeExpr5 } from "@angular/compiler";
|
10196 | import ts44 from "typescript";
|
10197 | var NgModuleSymbol = class extends SemanticSymbol {
|
10198 | constructor() {
|
10199 | super(...arguments);
|
10200 | this.remotelyScopedComponents = [];
|
10201 | }
|
10202 | isPublicApiAffected(previousSymbol) {
|
10203 | if (!(previousSymbol instanceof NgModuleSymbol)) {
|
10204 | return true;
|
10205 | }
|
10206 | return false;
|
10207 | }
|
10208 | isEmitAffected(previousSymbol) {
|
10209 | if (!(previousSymbol instanceof NgModuleSymbol)) {
|
10210 | return true;
|
10211 | }
|
10212 | if (previousSymbol.remotelyScopedComponents.length !== this.remotelyScopedComponents.length) {
|
10213 | return true;
|
10214 | }
|
10215 | for (const currEntry of this.remotelyScopedComponents) {
|
10216 | const prevEntry = previousSymbol.remotelyScopedComponents.find((prevEntry2) => {
|
10217 | return isSymbolEqual(prevEntry2.component, currEntry.component);
|
10218 | });
|
10219 | if (prevEntry === void 0) {
|
10220 | return true;
|
10221 | }
|
10222 | if (!isArrayEqual(currEntry.usedDirectives, prevEntry.usedDirectives, isReferenceEqual)) {
|
10223 | return true;
|
10224 | }
|
10225 | if (!isArrayEqual(currEntry.usedPipes, prevEntry.usedPipes, isReferenceEqual)) {
|
10226 | return true;
|
10227 | }
|
10228 | }
|
10229 | return false;
|
10230 | }
|
10231 | isTypeCheckApiAffected(previousSymbol) {
|
10232 | if (!(previousSymbol instanceof NgModuleSymbol)) {
|
10233 | return true;
|
10234 | }
|
10235 | return false;
|
10236 | }
|
10237 | addRemotelyScopedComponent(component, usedDirectives, usedPipes) {
|
10238 | this.remotelyScopedComponents.push({ component, usedDirectives, usedPipes });
|
10239 | }
|
10240 | };
|
10241 | var NgModuleDecoratorHandler = class {
|
10242 | constructor(reflector, evaluator, metaReader, metaRegistry, scopeRegistry, referencesRegistry, isCore, refEmitter, factoryTracker, annotateForClosureCompiler, injectableRegistry, perf) {
|
10243 | this.reflector = reflector;
|
10244 | this.evaluator = evaluator;
|
10245 | this.metaReader = metaReader;
|
10246 | this.metaRegistry = metaRegistry;
|
10247 | this.scopeRegistry = scopeRegistry;
|
10248 | this.referencesRegistry = referencesRegistry;
|
10249 | this.isCore = isCore;
|
10250 | this.refEmitter = refEmitter;
|
10251 | this.factoryTracker = factoryTracker;
|
10252 | this.annotateForClosureCompiler = annotateForClosureCompiler;
|
10253 | this.injectableRegistry = injectableRegistry;
|
10254 | this.perf = perf;
|
10255 | this.precedence = HandlerPrecedence.PRIMARY;
|
10256 | this.name = NgModuleDecoratorHandler.name;
|
10257 | }
|
10258 | detect(node, decorators) {
|
10259 | if (!decorators) {
|
10260 | return void 0;
|
10261 | }
|
10262 | const decorator = findAngularDecorator(decorators, "NgModule", this.isCore);
|
10263 | if (decorator !== void 0) {
|
10264 | return {
|
10265 | trigger: decorator.node,
|
10266 | decorator,
|
10267 | metadata: decorator
|
10268 | };
|
10269 | } else {
|
10270 | return void 0;
|
10271 | }
|
10272 | }
|
10273 | analyze(node, decorator) {
|
10274 | this.perf.eventCount(PerfEvent.AnalyzeNgModule);
|
10275 | const name = node.name.text;
|
10276 | if (decorator.args === null || decorator.args.length > 1) {
|
10277 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, Decorator.nodeForError(decorator), `Incorrect number of arguments to @NgModule decorator`);
|
10278 | }
|
10279 | const meta = decorator.args.length === 1 ? unwrapExpression(decorator.args[0]) : ts44.createObjectLiteral([]);
|
10280 | if (!ts44.isObjectLiteralExpression(meta)) {
|
10281 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARG_NOT_LITERAL, meta, "@NgModule argument must be an object literal");
|
10282 | }
|
10283 | const ngModule = reflectObjectLiteral(meta);
|
10284 | if (ngModule.has("jit")) {
|
10285 | return {};
|
10286 | }
|
10287 | const moduleResolvers = combineResolvers([
|
10288 | (ref) => this._extractModuleFromModuleWithProvidersFn(ref.node),
|
10289 | forwardRefResolver
|
10290 | ]);
|
10291 | const diagnostics = [];
|
10292 | let declarationRefs = [];
|
10293 | let rawDeclarations = null;
|
10294 | if (ngModule.has("declarations")) {
|
10295 | rawDeclarations = ngModule.get("declarations");
|
10296 | const declarationMeta = this.evaluator.evaluate(rawDeclarations, forwardRefResolver);
|
10297 | declarationRefs = this.resolveTypeList(rawDeclarations, declarationMeta, name, "declarations");
|
10298 | for (const ref of declarationRefs) {
|
10299 | if (ref.node.getSourceFile().isDeclarationFile) {
|
10300 | const errorNode = ref.getOriginForDiagnostics(rawDeclarations);
|
10301 | 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.`)]));
|
10302 | }
|
10303 | }
|
10304 | }
|
10305 | if (diagnostics.length > 0) {
|
10306 | return { diagnostics };
|
10307 | }
|
10308 | let importRefs = [];
|
10309 | if (ngModule.has("imports")) {
|
10310 | const rawImports = ngModule.get("imports");
|
10311 | const importsMeta = this.evaluator.evaluate(rawImports, moduleResolvers);
|
10312 | importRefs = this.resolveTypeList(rawImports, importsMeta, name, "imports");
|
10313 | }
|
10314 | let exportRefs = [];
|
10315 | if (ngModule.has("exports")) {
|
10316 | const rawExports = ngModule.get("exports");
|
10317 | const exportsMeta = this.evaluator.evaluate(rawExports, moduleResolvers);
|
10318 | exportRefs = this.resolveTypeList(rawExports, exportsMeta, name, "exports");
|
10319 | this.referencesRegistry.add(node, ...exportRefs);
|
10320 | }
|
10321 | let bootstrapRefs = [];
|
10322 | if (ngModule.has("bootstrap")) {
|
10323 | const expr = ngModule.get("bootstrap");
|
10324 | const bootstrapMeta = this.evaluator.evaluate(expr, forwardRefResolver);
|
10325 | bootstrapRefs = this.resolveTypeList(expr, bootstrapMeta, name, "bootstrap");
|
10326 | }
|
10327 | const schemas = [];
|
10328 | if (ngModule.has("schemas")) {
|
10329 | const rawExpr = ngModule.get("schemas");
|
10330 | const result = this.evaluator.evaluate(rawExpr);
|
10331 | if (!Array.isArray(result)) {
|
10332 | throw createValueHasWrongTypeError(rawExpr, result, `NgModule.schemas must be an array`);
|
10333 | }
|
10334 | for (const schemaRef of result) {
|
10335 | if (!(schemaRef instanceof Reference)) {
|
10336 | throw createValueHasWrongTypeError(rawExpr, result, "NgModule.schemas must be an array of schemas");
|
10337 | }
|
10338 | const id2 = schemaRef.getIdentityIn(schemaRef.node.getSourceFile());
|
10339 | if (id2 === null || schemaRef.ownedByModuleGuess !== "@angular/core") {
|
10340 | throw createValueHasWrongTypeError(rawExpr, result, "NgModule.schemas must be an array of schemas");
|
10341 | }
|
10342 | switch (id2.text) {
|
10343 | case "CUSTOM_ELEMENTS_SCHEMA":
|
10344 | schemas.push(CUSTOM_ELEMENTS_SCHEMA);
|
10345 | break;
|
10346 | case "NO_ERRORS_SCHEMA":
|
10347 | schemas.push(NO_ERRORS_SCHEMA);
|
10348 | break;
|
10349 | default:
|
10350 | throw createValueHasWrongTypeError(rawExpr, schemaRef, `'${schemaRef.debugName}' is not a valid NgModule schema`);
|
10351 | }
|
10352 | }
|
10353 | }
|
10354 | const id = ngModule.has("id") ? new WrappedNodeExpr5(ngModule.get("id")) : null;
|
10355 | const valueContext = node.getSourceFile();
|
10356 | let typeContext = valueContext;
|
10357 | const typeNode = this.reflector.getDtsDeclaration(node);
|
10358 | if (typeNode !== null) {
|
10359 | typeContext = typeNode.getSourceFile();
|
10360 | }
|
10361 | const bootstrap = bootstrapRefs.map((bootstrap2) => this._toR3Reference(bootstrap2, valueContext, typeContext));
|
10362 | const declarations = declarationRefs.map((decl) => this._toR3Reference(decl, valueContext, typeContext));
|
10363 | const imports = importRefs.map((imp) => this._toR3Reference(imp, valueContext, typeContext));
|
10364 | const exports = exportRefs.map((exp) => this._toR3Reference(exp, valueContext, typeContext));
|
10365 | const isForwardReference = (ref) => isExpressionForwardReference(ref.value, node.name, valueContext);
|
10366 | const containsForwardDecls = bootstrap.some(isForwardReference) || declarations.some(isForwardReference) || imports.some(isForwardReference) || exports.some(isForwardReference);
|
10367 | const type = wrapTypeReference(this.reflector, node);
|
10368 | const internalType = new WrappedNodeExpr5(this.reflector.getInternalNameOfClass(node));
|
10369 | const adjacentType = new WrappedNodeExpr5(this.reflector.getAdjacentNameOfClass(node));
|
10370 | const ngModuleMetadata = {
|
10371 | type,
|
10372 | internalType,
|
10373 | adjacentType,
|
10374 | bootstrap,
|
10375 | declarations,
|
10376 | exports,
|
10377 | imports,
|
10378 | containsForwardDecls,
|
10379 | id,
|
10380 | emitInline: false,
|
10381 | schemas: []
|
10382 | };
|
10383 | const rawProviders = ngModule.has("providers") ? ngModule.get("providers") : null;
|
10384 | const wrapperProviders = rawProviders !== null ? new WrappedNodeExpr5(this.annotateForClosureCompiler ? wrapFunctionExpressionsInParens(rawProviders) : rawProviders) : null;
|
10385 | const injectorImports = [];
|
10386 | if (ngModule.has("imports")) {
|
10387 | injectorImports.push(new WrappedNodeExpr5(ngModule.get("imports")));
|
10388 | }
|
10389 | const injectorMetadata = {
|
10390 | name,
|
10391 | type,
|
10392 | internalType,
|
10393 | providers: wrapperProviders,
|
10394 | imports: injectorImports
|
10395 | };
|
10396 | const factoryMetadata = {
|
10397 | name,
|
10398 | type,
|
10399 | internalType,
|
10400 | typeArgumentCount: 0,
|
10401 | deps: getValidConstructorDependencies(node, this.reflector, this.isCore),
|
10402 | target: FactoryTarget2.NgModule
|
10403 | };
|
10404 | return {
|
10405 | analysis: {
|
10406 | id,
|
10407 | schemas,
|
10408 | mod: ngModuleMetadata,
|
10409 | inj: injectorMetadata,
|
10410 | fac: factoryMetadata,
|
10411 | declarations: declarationRefs,
|
10412 | rawDeclarations,
|
10413 | imports: importRefs,
|
10414 | exports: exportRefs,
|
10415 | providers: rawProviders,
|
10416 | providersRequiringFactory: rawProviders ? resolveProvidersRequiringFactory(rawProviders, this.reflector, this.evaluator) : null,
|
10417 | classMetadata: extractClassMetadata(node, this.reflector, this.isCore, this.annotateForClosureCompiler),
|
10418 | factorySymbolName: node.name.text
|
10419 | }
|
10420 | };
|
10421 | }
|
10422 | symbol(node) {
|
10423 | return new NgModuleSymbol(node);
|
10424 | }
|
10425 | register(node, analysis) {
|
10426 | this.metaRegistry.registerNgModuleMetadata({
|
10427 | ref: new Reference(node),
|
10428 | schemas: analysis.schemas,
|
10429 | declarations: analysis.declarations,
|
10430 | imports: analysis.imports,
|
10431 | exports: analysis.exports,
|
10432 | rawDeclarations: analysis.rawDeclarations
|
10433 | });
|
10434 | if (this.factoryTracker !== null) {
|
10435 | this.factoryTracker.track(node.getSourceFile(), {
|
10436 | name: analysis.factorySymbolName,
|
10437 | hasId: analysis.id !== null
|
10438 | });
|
10439 | }
|
10440 | this.injectableRegistry.registerInjectable(node);
|
10441 | }
|
10442 | resolve(node, analysis) {
|
10443 | const scope = this.scopeRegistry.getScopeOfModule(node);
|
10444 | const diagnostics = [];
|
10445 | const scopeDiagnostics = this.scopeRegistry.getDiagnosticsOfModule(node);
|
10446 | if (scopeDiagnostics !== null) {
|
10447 | diagnostics.push(...scopeDiagnostics);
|
10448 | }
|
10449 | if (analysis.providersRequiringFactory !== null) {
|
10450 | const providerDiagnostics = getProviderDiagnostics(analysis.providersRequiringFactory, analysis.providers, this.injectableRegistry);
|
10451 | diagnostics.push(...providerDiagnostics);
|
10452 | }
|
10453 | const data = {
|
10454 | injectorImports: []
|
10455 | };
|
10456 | if (scope !== null && !scope.compilation.isPoisoned) {
|
10457 | const context = getSourceFile(node);
|
10458 | for (const exportRef of analysis.exports) {
|
10459 | if (isNgModule(exportRef.node, scope.compilation)) {
|
10460 | data.injectorImports.push(this.refEmitter.emit(exportRef, context).expression);
|
10461 | }
|
10462 | }
|
10463 | for (const decl of analysis.declarations) {
|
10464 | const metadata = this.metaReader.getDirectiveMetadata(decl);
|
10465 | if (metadata !== null && metadata.selector === null) {
|
10466 | throw new FatalDiagnosticError(ErrorCode.DIRECTIVE_MISSING_SELECTOR, decl.node, `Directive ${decl.node.name.text} has no selector, please add it!`);
|
10467 | }
|
10468 | }
|
10469 | }
|
10470 | if (diagnostics.length > 0) {
|
10471 | return { diagnostics };
|
10472 | }
|
10473 | if (scope === null || scope.compilation.isPoisoned || scope.exported.isPoisoned || scope.reexports === null) {
|
10474 | return { data };
|
10475 | } else {
|
10476 | return {
|
10477 | data,
|
10478 | reexports: scope.reexports
|
10479 | };
|
10480 | }
|
10481 | }
|
10482 | compileFull(node, { inj, mod, fac, classMetadata, declarations }, { injectorImports }) {
|
10483 | const factoryFn = compileNgFactoryDefField(fac);
|
10484 | const ngInjectorDef = compileInjector(this.mergeInjectorImports(inj, injectorImports));
|
10485 | const ngModuleDef = compileNgModule(mod);
|
10486 | const statements = ngModuleDef.statements;
|
10487 | const metadata = classMetadata !== null ? compileClassMetadata2(classMetadata) : null;
|
10488 | this.insertMetadataStatement(statements, metadata);
|
10489 | this.appendRemoteScopingStatements(statements, node, declarations);
|
10490 | return this.compileNgModule(factoryFn, ngInjectorDef, ngModuleDef);
|
10491 | }
|
10492 | compilePartial(node, { inj, fac, mod, classMetadata }, { injectorImports }) {
|
10493 | const factoryFn = compileDeclareFactory(fac);
|
10494 | const injectorDef = compileDeclareInjectorFromMetadata(this.mergeInjectorImports(inj, injectorImports));
|
10495 | const ngModuleDef = compileDeclareNgModuleFromMetadata(mod);
|
10496 | const metadata = classMetadata !== null ? compileDeclareClassMetadata2(classMetadata) : null;
|
10497 | this.insertMetadataStatement(ngModuleDef.statements, metadata);
|
10498 | return this.compileNgModule(factoryFn, injectorDef, ngModuleDef);
|
10499 | }
|
10500 | mergeInjectorImports(inj, injectorImports) {
|
10501 | return __spreadProps(__spreadValues({}, inj), { imports: [...inj.imports, ...injectorImports] });
|
10502 | }
|
10503 | insertMetadataStatement(ngModuleStatements, metadata) {
|
10504 | if (metadata !== null) {
|
10505 | ngModuleStatements.unshift(metadata.toStmt());
|
10506 | }
|
10507 | }
|
10508 | appendRemoteScopingStatements(ngModuleStatements, node, declarations) {
|
10509 | const context = getSourceFile(node);
|
10510 | for (const decl of declarations) {
|
10511 | const remoteScope = this.scopeRegistry.getRemoteScope(decl.node);
|
10512 | if (remoteScope !== null) {
|
10513 | const directives = remoteScope.directives.map((directive) => this.refEmitter.emit(directive, context).expression);
|
10514 | const pipes = remoteScope.pipes.map((pipe) => this.refEmitter.emit(pipe, context).expression);
|
10515 | const directiveArray = new LiteralArrayExpr2(directives);
|
10516 | const pipesArray = new LiteralArrayExpr2(pipes);
|
10517 | const declExpr = this.refEmitter.emit(decl, context).expression;
|
10518 | const setComponentScope = new ExternalExpr6(R3Identifiers.setComponentScope);
|
10519 | const callExpr = new InvokeFunctionExpr(setComponentScope, [declExpr, directiveArray, pipesArray]);
|
10520 | ngModuleStatements.push(callExpr.toStmt());
|
10521 | }
|
10522 | }
|
10523 | }
|
10524 | compileNgModule(factoryFn, injectorDef, ngModuleDef) {
|
10525 | const res = [
|
10526 | factoryFn,
|
10527 | {
|
10528 | name: "\u0275mod",
|
10529 | initializer: ngModuleDef.expression,
|
10530 | statements: ngModuleDef.statements,
|
10531 | type: ngModuleDef.type
|
10532 | },
|
10533 | {
|
10534 | name: "\u0275inj",
|
10535 | initializer: injectorDef.expression,
|
10536 | statements: injectorDef.statements,
|
10537 | type: injectorDef.type
|
10538 | }
|
10539 | ];
|
10540 | return res;
|
10541 | }
|
10542 | _toR3Reference(valueRef, valueContext, typeContext) {
|
10543 | if (valueRef.hasOwningModuleGuess) {
|
10544 | return toR3Reference(valueRef, valueRef, valueContext, valueContext, this.refEmitter);
|
10545 | } else {
|
10546 | let typeRef = valueRef;
|
10547 | let typeNode = this.reflector.getDtsDeclaration(typeRef.node);
|
10548 | if (typeNode !== null && isNamedClassDeclaration(typeNode)) {
|
10549 | typeRef = new Reference(typeNode);
|
10550 | }
|
10551 | return toR3Reference(valueRef, typeRef, valueContext, typeContext, this.refEmitter);
|
10552 | }
|
10553 | }
|
10554 | _extractModuleFromModuleWithProvidersFn(node) {
|
10555 | const type = node.type || null;
|
10556 | return type && (this._reflectModuleFromTypeParam(type, node) || this._reflectModuleFromLiteralType(type));
|
10557 | }
|
10558 | _reflectModuleFromTypeParam(type, node) {
|
10559 | if (!ts44.isTypeReferenceNode(type)) {
|
10560 | return null;
|
10561 | }
|
10562 | const typeName = type && (ts44.isIdentifier(type.typeName) && type.typeName || ts44.isQualifiedName(type.typeName) && type.typeName.right) || null;
|
10563 | if (typeName === null) {
|
10564 | return null;
|
10565 | }
|
10566 | const id = this.reflector.getImportOfIdentifier(typeName);
|
10567 | if (id === null || id.name !== "ModuleWithProviders") {
|
10568 | return null;
|
10569 | }
|
10570 | if (!this.isCore && id.from !== "@angular/core") {
|
10571 | return null;
|
10572 | }
|
10573 | if (type.typeArguments === void 0 || type.typeArguments.length !== 1) {
|
10574 | const parent = ts44.isMethodDeclaration(node) && ts44.isClassDeclaration(node.parent) ? node.parent : null;
|
10575 | const symbolName = (parent && parent.name ? parent.name.getText() + "." : "") + (node.name ? node.name.getText() : "anonymous");
|
10576 | 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.`);
|
10577 | }
|
10578 | const arg = type.typeArguments[0];
|
10579 | return typeNodeToValueExpr(arg);
|
10580 | }
|
10581 | _reflectModuleFromLiteralType(type) {
|
10582 | if (!ts44.isIntersectionTypeNode(type)) {
|
10583 | return null;
|
10584 | }
|
10585 | for (const t of type.types) {
|
10586 | if (ts44.isTypeLiteralNode(t)) {
|
10587 | for (const m of t.members) {
|
10588 | const ngModuleType = ts44.isPropertySignature(m) && ts44.isIdentifier(m.name) && m.name.text === "ngModule" && m.type || null;
|
10589 | const ngModuleExpression = ngModuleType && typeNodeToValueExpr(ngModuleType);
|
10590 | if (ngModuleExpression) {
|
10591 | return ngModuleExpression;
|
10592 | }
|
10593 | }
|
10594 | }
|
10595 | }
|
10596 | return null;
|
10597 | }
|
10598 | isClassDeclarationReference(ref) {
|
10599 | return this.reflector.isClass(ref.node);
|
10600 | }
|
10601 | resolveTypeList(expr, resolvedList, className, arrayName) {
|
10602 | const refList = [];
|
10603 | if (!Array.isArray(resolvedList)) {
|
10604 | throw createValueHasWrongTypeError(expr, resolvedList, `Expected array when reading the NgModule.${arrayName} of ${className}`);
|
10605 | }
|
10606 | resolvedList.forEach((entry, idx) => {
|
10607 | if (entry instanceof Map && entry.has("ngModule")) {
|
10608 | entry = entry.get("ngModule");
|
10609 | }
|
10610 | if (Array.isArray(entry)) {
|
10611 | refList.push(...this.resolveTypeList(expr, entry, className, arrayName));
|
10612 | } else if (entry instanceof Reference) {
|
10613 | if (!this.isClassDeclarationReference(entry)) {
|
10614 | throw createValueHasWrongTypeError(entry.node, entry, `Value at position ${idx} in the NgModule.${arrayName} of ${className} is not a class`);
|
10615 | }
|
10616 | refList.push(entry);
|
10617 | } else {
|
10618 | throw createValueHasWrongTypeError(expr, entry, `Value at position ${idx} in the NgModule.${arrayName} of ${className} is not a reference`);
|
10619 | }
|
10620 | });
|
10621 | return refList;
|
10622 | }
|
10623 | };
|
10624 | function isNgModule(node, compilation) {
|
10625 | return !compilation.directives.some((directive) => directive.ref.node === node) && !compilation.pipes.some((pipe) => pipe.ref.node === node);
|
10626 | }
|
10627 |
|
10628 |
|
10629 | var EMPTY_MAP = new Map();
|
10630 | var EMPTY_ARRAY = [];
|
10631 | var ComponentSymbol = class extends DirectiveSymbol {
|
10632 | constructor() {
|
10633 | super(...arguments);
|
10634 | this.usedDirectives = [];
|
10635 | this.usedPipes = [];
|
10636 | this.isRemotelyScoped = false;
|
10637 | }
|
10638 | isEmitAffected(previousSymbol, publicApiAffected) {
|
10639 | if (!(previousSymbol instanceof ComponentSymbol)) {
|
10640 | return true;
|
10641 | }
|
10642 | const isSymbolUnaffected = (current, previous) => isReferenceEqual(current, previous) && !publicApiAffected.has(current.symbol);
|
10643 | return this.isRemotelyScoped !== previousSymbol.isRemotelyScoped || !isArrayEqual(this.usedDirectives, previousSymbol.usedDirectives, isSymbolUnaffected) || !isArrayEqual(this.usedPipes, previousSymbol.usedPipes, isSymbolUnaffected);
|
10644 | }
|
10645 | isTypeCheckBlockAffected(previousSymbol, typeCheckApiAffected) {
|
10646 | if (!(previousSymbol instanceof ComponentSymbol)) {
|
10647 | return true;
|
10648 | }
|
10649 | const isInheritanceChainAffected = (symbol) => {
|
10650 | let currentSymbol = symbol;
|
10651 | while (currentSymbol instanceof DirectiveSymbol) {
|
10652 | if (typeCheckApiAffected.has(currentSymbol)) {
|
10653 | return true;
|
10654 | }
|
10655 | currentSymbol = currentSymbol.baseClass;
|
10656 | }
|
10657 | return false;
|
10658 | };
|
10659 | const isDirectiveUnaffected = (current, previous) => isReferenceEqual(current, previous) && !isInheritanceChainAffected(current.symbol);
|
10660 | const isPipeUnaffected = (current, previous) => isReferenceEqual(current, previous) && !typeCheckApiAffected.has(current.symbol);
|
10661 | return !isArrayEqual(this.usedDirectives, previousSymbol.usedDirectives, isDirectiveUnaffected) || !isArrayEqual(this.usedPipes, previousSymbol.usedPipes, isPipeUnaffected);
|
10662 | }
|
10663 | };
|
10664 | var ComponentDecoratorHandler = class {
|
10665 | constructor(reflector, evaluator, metaRegistry, metaReader, scopeReader, scopeRegistry, typeCheckScopeRegistry, resourceRegistry, isCore, resourceLoader, rootDirs, defaultPreserveWhitespaces, i18nUseExternalIds, enableI18nLegacyMessageIdFormat, usePoisonedData, i18nNormalizeLineEndingsInICUs, moduleResolver, cycleAnalyzer, cycleHandlingStrategy, refEmitter, depTracker, injectableRegistry, semanticDepGraphUpdater, annotateForClosureCompiler, perf) {
|
10666 | this.reflector = reflector;
|
10667 | this.evaluator = evaluator;
|
10668 | this.metaRegistry = metaRegistry;
|
10669 | this.metaReader = metaReader;
|
10670 | this.scopeReader = scopeReader;
|
10671 | this.scopeRegistry = scopeRegistry;
|
10672 | this.typeCheckScopeRegistry = typeCheckScopeRegistry;
|
10673 | this.resourceRegistry = resourceRegistry;
|
10674 | this.isCore = isCore;
|
10675 | this.resourceLoader = resourceLoader;
|
10676 | this.rootDirs = rootDirs;
|
10677 | this.defaultPreserveWhitespaces = defaultPreserveWhitespaces;
|
10678 | this.i18nUseExternalIds = i18nUseExternalIds;
|
10679 | this.enableI18nLegacyMessageIdFormat = enableI18nLegacyMessageIdFormat;
|
10680 | this.usePoisonedData = usePoisonedData;
|
10681 | this.i18nNormalizeLineEndingsInICUs = i18nNormalizeLineEndingsInICUs;
|
10682 | this.moduleResolver = moduleResolver;
|
10683 | this.cycleAnalyzer = cycleAnalyzer;
|
10684 | this.cycleHandlingStrategy = cycleHandlingStrategy;
|
10685 | this.refEmitter = refEmitter;
|
10686 | this.depTracker = depTracker;
|
10687 | this.injectableRegistry = injectableRegistry;
|
10688 | this.semanticDepGraphUpdater = semanticDepGraphUpdater;
|
10689 | this.annotateForClosureCompiler = annotateForClosureCompiler;
|
10690 | this.perf = perf;
|
10691 | this.literalCache = new Map();
|
10692 | this.elementSchemaRegistry = new DomElementSchemaRegistry();
|
10693 | this.preanalyzeTemplateCache = new Map();
|
10694 | this.preanalyzeStylesCache = new Map();
|
10695 | this.precedence = HandlerPrecedence.PRIMARY;
|
10696 | this.name = ComponentDecoratorHandler.name;
|
10697 | }
|
10698 | detect(node, decorators) {
|
10699 | if (!decorators) {
|
10700 | return void 0;
|
10701 | }
|
10702 | const decorator = findAngularDecorator(decorators, "Component", this.isCore);
|
10703 | if (decorator !== void 0) {
|
10704 | return {
|
10705 | trigger: decorator.node,
|
10706 | decorator,
|
10707 | metadata: decorator
|
10708 | };
|
10709 | } else {
|
10710 | return void 0;
|
10711 | }
|
10712 | }
|
10713 | preanalyze(node, decorator) {
|
10714 | if (!this.resourceLoader.canPreload) {
|
10715 | return void 0;
|
10716 | }
|
10717 | const meta = this._resolveLiteral(decorator);
|
10718 | const component = reflectObjectLiteral(meta);
|
10719 | const containingFile = node.getSourceFile().fileName;
|
10720 | const resolveStyleUrl = (styleUrl) => {
|
10721 | try {
|
10722 | const resourceUrl = this.resourceLoader.resolve(styleUrl, containingFile);
|
10723 | return this.resourceLoader.preload(resourceUrl, { type: "style", containingFile });
|
10724 | } catch {
|
10725 | return void 0;
|
10726 | }
|
10727 | };
|
10728 | const templateAndTemplateStyleResources = this._preloadAndParseTemplate(node, decorator, component, containingFile).then((template) => {
|
10729 | if (template === null) {
|
10730 | return void 0;
|
10731 | }
|
10732 | return Promise.all(template.styleUrls.map((styleUrl) => resolveStyleUrl(styleUrl))).then(() => void 0);
|
10733 | });
|
10734 | const componentStyleUrls = this._extractComponentStyleUrls(component);
|
10735 | let inlineStyles;
|
10736 | if (component.has("styles")) {
|
10737 | const litStyles = parseFieldArrayValue(component, "styles", this.evaluator);
|
10738 | if (litStyles === null) {
|
10739 | this.preanalyzeStylesCache.set(node, null);
|
10740 | } else {
|
10741 | inlineStyles = Promise.all(litStyles.map((style) => this.resourceLoader.preprocessInline(style, { type: "style", containingFile }))).then((styles) => {
|
10742 | this.preanalyzeStylesCache.set(node, styles);
|
10743 | });
|
10744 | }
|
10745 | } else {
|
10746 | this.preanalyzeStylesCache.set(node, null);
|
10747 | }
|
10748 | return Promise.all([
|
10749 | templateAndTemplateStyleResources,
|
10750 | inlineStyles,
|
10751 | ...componentStyleUrls.map((styleUrl) => resolveStyleUrl(styleUrl.url))
|
10752 | ]).then(() => void 0);
|
10753 | }
|
10754 | analyze(node, decorator, flags = HandlerFlags.NONE) {
|
10755 | var _a, _b;
|
10756 | this.perf.eventCount(PerfEvent.AnalyzeComponent);
|
10757 | const containingFile = node.getSourceFile().fileName;
|
10758 | this.literalCache.delete(decorator);
|
10759 | let diagnostics;
|
10760 | let isPoisoned = false;
|
10761 | const directiveResult = extractDirectiveMetadata(node, decorator, this.reflector, this.evaluator, this.isCore, flags, this.annotateForClosureCompiler, this.elementSchemaRegistry.getDefaultComponentElementName());
|
10762 | if (directiveResult === void 0) {
|
10763 | return {};
|
10764 | }
|
10765 | const { decorator: component, metadata, inputs, outputs } = directiveResult;
|
10766 | const encapsulation = (_a = this._resolveEnumValue(component, "encapsulation", "ViewEncapsulation")) != null ? _a : ViewEncapsulation.Emulated;
|
10767 | const changeDetection = this._resolveEnumValue(component, "changeDetection", "ChangeDetectionStrategy");
|
10768 | let animations = null;
|
10769 | if (component.has("animations")) {
|
10770 | animations = new WrappedNodeExpr6(component.get("animations"));
|
10771 | }
|
10772 | const relativeContextFilePath = this.rootDirs.reduce((previous, rootDir) => {
|
10773 | const candidate = relative(absoluteFrom(rootDir), absoluteFrom(containingFile));
|
10774 | if (previous === void 0 || candidate.length < previous.length) {
|
10775 | return candidate;
|
10776 | } else {
|
10777 | return previous;
|
10778 | }
|
10779 | }, void 0);
|
10780 | let viewProvidersRequiringFactory = null;
|
10781 | let providersRequiringFactory = null;
|
10782 | let wrappedViewProviders = null;
|
10783 | if (component.has("viewProviders")) {
|
10784 | const viewProviders = component.get("viewProviders");
|
10785 | viewProvidersRequiringFactory = resolveProvidersRequiringFactory(viewProviders, this.reflector, this.evaluator);
|
10786 | wrappedViewProviders = new WrappedNodeExpr6(this.annotateForClosureCompiler ? wrapFunctionExpressionsInParens(viewProviders) : viewProviders);
|
10787 | }
|
10788 | if (component.has("providers")) {
|
10789 | providersRequiringFactory = resolveProvidersRequiringFactory(component.get("providers"), this.reflector, this.evaluator);
|
10790 | }
|
10791 | let template;
|
10792 | if (this.preanalyzeTemplateCache.has(node)) {
|
10793 | const preanalyzed = this.preanalyzeTemplateCache.get(node);
|
10794 | this.preanalyzeTemplateCache.delete(node);
|
10795 | template = preanalyzed;
|
10796 | } else {
|
10797 | const templateDecl = this.parseTemplateDeclaration(decorator, component, containingFile);
|
10798 | template = this.extractTemplate(node, templateDecl);
|
10799 | }
|
10800 | const templateResource = template.declaration.isInline ? { path: null, expression: component.get("template") } : {
|
10801 | path: absoluteFrom(template.declaration.resolvedTemplateUrl),
|
10802 | expression: template.sourceMapping.node
|
10803 | };
|
10804 | let styles = [];
|
10805 | const styleResources = this._extractStyleResources(component, containingFile);
|
10806 | const styleUrls = [
|
10807 | ...this._extractComponentStyleUrls(component),
|
10808 | ...this._extractTemplateStyleUrls(template)
|
10809 | ];
|
10810 | for (const styleUrl of styleUrls) {
|
10811 | try {
|
10812 | const resourceUrl = this.resourceLoader.resolve(styleUrl.url, containingFile);
|
10813 | const resourceStr = this.resourceLoader.load(resourceUrl);
|
10814 | styles.push(resourceStr);
|
10815 | if (this.depTracker !== null) {
|
10816 | this.depTracker.addResourceDependency(node.getSourceFile(), absoluteFrom(resourceUrl));
|
10817 | }
|
10818 | } catch {
|
10819 | if (diagnostics === void 0) {
|
10820 | diagnostics = [];
|
10821 | }
|
10822 | const resourceType = styleUrl.source === 2 ? 2 : 1;
|
10823 | diagnostics.push(this.makeResourceNotFoundError(styleUrl.url, styleUrl.nodeForError, resourceType).toDiagnostic());
|
10824 | }
|
10825 | }
|
10826 | if (encapsulation === ViewEncapsulation.ShadowDom && metadata.selector !== null) {
|
10827 | const selectorError = checkCustomElementSelectorForErrors(metadata.selector);
|
10828 | if (selectorError !== null) {
|
10829 | if (diagnostics === void 0) {
|
10830 | diagnostics = [];
|
10831 | }
|
10832 | diagnostics.push(makeDiagnostic(ErrorCode.COMPONENT_INVALID_SHADOW_DOM_SELECTOR, component.get("selector"), selectorError));
|
10833 | }
|
10834 | }
|
10835 | let inlineStyles = null;
|
10836 | if (this.preanalyzeStylesCache.has(node)) {
|
10837 | inlineStyles = this.preanalyzeStylesCache.get(node);
|
10838 | this.preanalyzeStylesCache.delete(node);
|
10839 | if (inlineStyles !== null) {
|
10840 | styles.push(...inlineStyles);
|
10841 | }
|
10842 | } else {
|
10843 | if (this.resourceLoader.canPreprocess) {
|
10844 | throw new Error("Inline resource processing requires asynchronous preanalyze.");
|
10845 | }
|
10846 | if (component.has("styles")) {
|
10847 | const litStyles = parseFieldArrayValue(component, "styles", this.evaluator);
|
10848 | if (litStyles !== null) {
|
10849 | inlineStyles = [...litStyles];
|
10850 | styles.push(...litStyles);
|
10851 | }
|
10852 | }
|
10853 | }
|
10854 | if (template.styles.length > 0) {
|
10855 | styles.push(...template.styles);
|
10856 | }
|
10857 | const output = {
|
10858 | analysis: {
|
10859 | baseClass: readBaseClass2(node, this.reflector, this.evaluator),
|
10860 | inputs,
|
10861 | outputs,
|
10862 | meta: __spreadProps(__spreadValues({}, metadata), {
|
10863 | template: {
|
10864 | nodes: template.nodes,
|
10865 | ngContentSelectors: template.ngContentSelectors
|
10866 | },
|
10867 | encapsulation,
|
10868 | interpolation: (_b = template.interpolationConfig) != null ? _b : DEFAULT_INTERPOLATION_CONFIG,
|
10869 | styles,
|
10870 | animations,
|
10871 | viewProviders: wrappedViewProviders,
|
10872 | i18nUseExternalIds: this.i18nUseExternalIds,
|
10873 | relativeContextFilePath
|
10874 | }),
|
10875 | typeCheckMeta: extractDirectiveTypeCheckMeta(node, inputs, this.reflector),
|
10876 | classMetadata: extractClassMetadata(node, this.reflector, this.isCore, this.annotateForClosureCompiler, (dec) => this._transformDecoratorToInlineResources(dec, component, styles, template)),
|
10877 | template,
|
10878 | providersRequiringFactory,
|
10879 | viewProvidersRequiringFactory,
|
10880 | inlineStyles,
|
10881 | styleUrls,
|
10882 | resources: {
|
10883 | styles: styleResources,
|
10884 | template: templateResource
|
10885 | },
|
10886 | isPoisoned
|
10887 | },
|
10888 | diagnostics
|
10889 | };
|
10890 | if (changeDetection !== null) {
|
10891 | output.analysis.meta.changeDetection = changeDetection;
|
10892 | }
|
10893 | return output;
|
10894 | }
|
10895 | symbol(node, analysis) {
|
10896 | const typeParameters = extractSemanticTypeParameters(node);
|
10897 | return new ComponentSymbol(node, analysis.meta.selector, analysis.inputs, analysis.outputs, analysis.meta.exportAs, analysis.typeCheckMeta, typeParameters);
|
10898 | }
|
10899 | register(node, analysis) {
|
10900 | const ref = new Reference(node);
|
10901 | this.metaRegistry.registerDirectiveMetadata(__spreadProps(__spreadValues({
|
10902 | type: MetaType.Directive,
|
10903 | ref,
|
10904 | name: node.name.text,
|
10905 | selector: analysis.meta.selector,
|
10906 | exportAs: analysis.meta.exportAs,
|
10907 | inputs: analysis.inputs,
|
10908 | outputs: analysis.outputs,
|
10909 | queries: analysis.meta.queries.map((query) => query.propertyName),
|
10910 | isComponent: true,
|
10911 | baseClass: analysis.baseClass
|
10912 | }, analysis.typeCheckMeta), {
|
10913 | isPoisoned: analysis.isPoisoned,
|
10914 | isStructural: false
|
10915 | }));
|
10916 | this.resourceRegistry.registerResources(analysis.resources, node);
|
10917 | this.injectableRegistry.registerInjectable(node);
|
10918 | }
|
10919 | index(context, node, analysis) {
|
10920 | if (analysis.isPoisoned && !this.usePoisonedData) {
|
10921 | return null;
|
10922 | }
|
10923 | const scope = this.scopeReader.getScopeForComponent(node);
|
10924 | const selector = analysis.meta.selector;
|
10925 | const matcher = new SelectorMatcher();
|
10926 | if (scope !== null) {
|
10927 | if ((scope.compilation.isPoisoned || scope.exported.isPoisoned) && !this.usePoisonedData) {
|
10928 | return null;
|
10929 | }
|
10930 | for (const directive of scope.compilation.directives) {
|
10931 | if (directive.selector !== null) {
|
10932 | matcher.addSelectables(CssSelector.parse(directive.selector), directive);
|
10933 | }
|
10934 | }
|
10935 | }
|
10936 | const binder = new R3TargetBinder(matcher);
|
10937 | const boundTemplate = binder.bind({ template: analysis.template.diagNodes });
|
10938 | context.addComponent({
|
10939 | declaration: node,
|
10940 | selector,
|
10941 | boundTemplate,
|
10942 | templateMeta: {
|
10943 | isInline: analysis.template.declaration.isInline,
|
10944 | file: analysis.template.file
|
10945 | }
|
10946 | });
|
10947 | }
|
10948 | typeCheck(ctx, node, meta) {
|
10949 | if (this.typeCheckScopeRegistry === null || !ts45.isClassDeclaration(node)) {
|
10950 | return;
|
10951 | }
|
10952 | if (meta.isPoisoned && !this.usePoisonedData) {
|
10953 | return;
|
10954 | }
|
10955 | const scope = this.typeCheckScopeRegistry.getTypeCheckScope(node);
|
10956 | if (scope.isPoisoned && !this.usePoisonedData) {
|
10957 | return;
|
10958 | }
|
10959 | const binder = new R3TargetBinder(scope.matcher);
|
10960 | ctx.addTemplate(new Reference(node), binder, meta.template.diagNodes, scope.pipes, scope.schemas, meta.template.sourceMapping, meta.template.file, meta.template.errors);
|
10961 | }
|
10962 | extendedTemplateCheck(component, extendedTemplateChecker) {
|
10963 | return extendedTemplateChecker.getDiagnosticsForComponent(component);
|
10964 | }
|
10965 | resolve(node, analysis, symbol) {
|
10966 | if (this.semanticDepGraphUpdater !== null && analysis.baseClass instanceof Reference) {
|
10967 | symbol.baseClass = this.semanticDepGraphUpdater.getSymbol(analysis.baseClass.node);
|
10968 | }
|
10969 | if (analysis.isPoisoned && !this.usePoisonedData) {
|
10970 | return {};
|
10971 | }
|
10972 | const context = node.getSourceFile();
|
10973 | const scope = this.scopeReader.getScopeForComponent(node);
|
10974 | let metadata = analysis.meta;
|
10975 | const data = {
|
10976 | directives: EMPTY_ARRAY,
|
10977 | pipes: EMPTY_MAP,
|
10978 | declarationListEmitMode: 0
|
10979 | };
|
10980 | if (scope !== null && (!scope.compilation.isPoisoned || this.usePoisonedData)) {
|
10981 | const matcher = new SelectorMatcher();
|
10982 | for (const dir of scope.compilation.directives) {
|
10983 | if (dir.selector !== null) {
|
10984 | matcher.addSelectables(CssSelector.parse(dir.selector), dir);
|
10985 | }
|
10986 | }
|
10987 | const pipes = new Map();
|
10988 | for (const pipe of scope.compilation.pipes) {
|
10989 | pipes.set(pipe.name, pipe.ref);
|
10990 | }
|
10991 | const binder = new R3TargetBinder(matcher);
|
10992 | const bound = binder.bind({ template: metadata.template.nodes });
|
10993 | const usedDirectives = bound.getUsedDirectives().map((directive) => {
|
10994 | const type = this.refEmitter.emit(directive.ref, context);
|
10995 | return {
|
10996 | ref: directive.ref,
|
10997 | type: type.expression,
|
10998 | importedFile: type.importedFile,
|
10999 | selector: directive.selector,
|
11000 | inputs: directive.inputs.propertyNames,
|
11001 | outputs: directive.outputs.propertyNames,
|
11002 | exportAs: directive.exportAs,
|
11003 | isComponent: directive.isComponent
|
11004 | };
|
11005 | });
|
11006 | const usedPipes = [];
|
11007 | for (const pipeName of bound.getUsedPipes()) {
|
11008 | if (!pipes.has(pipeName)) {
|
11009 | continue;
|
11010 | }
|
11011 | const pipe = pipes.get(pipeName);
|
11012 | const type = this.refEmitter.emit(pipe, context);
|
11013 | usedPipes.push({
|
11014 | ref: pipe,
|
11015 | pipeName,
|
11016 | expression: type.expression,
|
11017 | importedFile: type.importedFile
|
11018 | });
|
11019 | }
|
11020 | if (this.semanticDepGraphUpdater !== null) {
|
11021 | symbol.usedDirectives = usedDirectives.map((dir) => this.semanticDepGraphUpdater.getSemanticReference(dir.ref.node, dir.type));
|
11022 | symbol.usedPipes = usedPipes.map((pipe) => this.semanticDepGraphUpdater.getSemanticReference(pipe.ref.node, pipe.expression));
|
11023 | }
|
11024 | const cyclesFromDirectives = new Map();
|
11025 | for (const usedDirective of usedDirectives) {
|
11026 | const cycle = this._checkForCyclicImport(usedDirective.importedFile, usedDirective.type, context);
|
11027 | if (cycle !== null) {
|
11028 | cyclesFromDirectives.set(usedDirective, cycle);
|
11029 | }
|
11030 | }
|
11031 | const cyclesFromPipes = new Map();
|
11032 | for (const usedPipe of usedPipes) {
|
11033 | const cycle = this._checkForCyclicImport(usedPipe.importedFile, usedPipe.expression, context);
|
11034 | if (cycle !== null) {
|
11035 | cyclesFromPipes.set(usedPipe, cycle);
|
11036 | }
|
11037 | }
|
11038 | const cycleDetected = cyclesFromDirectives.size !== 0 || cyclesFromPipes.size !== 0;
|
11039 | if (!cycleDetected) {
|
11040 | for (const { type, importedFile } of usedDirectives) {
|
11041 | this._recordSyntheticImport(importedFile, type, context);
|
11042 | }
|
11043 | for (const { expression, importedFile } of usedPipes) {
|
11044 | this._recordSyntheticImport(importedFile, expression, context);
|
11045 | }
|
11046 | const wrapDirectivesAndPipesInClosure = usedDirectives.some((dir) => isExpressionForwardReference(dir.type, node.name, context)) || usedPipes.some((pipe) => isExpressionForwardReference(pipe.expression, node.name, context));
|
11047 | data.directives = usedDirectives;
|
11048 | data.pipes = new Map(usedPipes.map((pipe) => [pipe.pipeName, pipe.expression]));
|
11049 | data.declarationListEmitMode = wrapDirectivesAndPipesInClosure ? 1 : 0;
|
11050 | } else {
|
11051 | if (this.cycleHandlingStrategy === 0) {
|
11052 | this.scopeRegistry.setComponentRemoteScope(node, usedDirectives.map((dir) => dir.ref), usedPipes.map((pipe) => pipe.ref));
|
11053 | symbol.isRemotelyScoped = true;
|
11054 | if (this.semanticDepGraphUpdater !== null) {
|
11055 | const moduleSymbol = this.semanticDepGraphUpdater.getSymbol(scope.ngModule);
|
11056 | if (!(moduleSymbol instanceof NgModuleSymbol)) {
|
11057 | throw new Error(`AssertionError: Expected ${scope.ngModule.name} to be an NgModuleSymbol.`);
|
11058 | }
|
11059 | moduleSymbol.addRemotelyScopedComponent(symbol, symbol.usedDirectives, symbol.usedPipes);
|
11060 | }
|
11061 | } else {
|
11062 | const relatedMessages = [];
|
11063 | for (const [dir, cycle] of cyclesFromDirectives) {
|
11064 | relatedMessages.push(makeCyclicImportInfo(dir.ref, dir.isComponent ? "component" : "directive", cycle));
|
11065 | }
|
11066 | for (const [pipe, cycle] of cyclesFromPipes) {
|
11067 | relatedMessages.push(makeCyclicImportInfo(pipe.ref, "pipe", cycle));
|
11068 | }
|
11069 | 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);
|
11070 | }
|
11071 | }
|
11072 | }
|
11073 | const diagnostics = [];
|
11074 | if (analysis.providersRequiringFactory !== null && analysis.meta.providers instanceof WrappedNodeExpr6) {
|
11075 | const providerDiagnostics = getProviderDiagnostics(analysis.providersRequiringFactory, analysis.meta.providers.node, this.injectableRegistry);
|
11076 | diagnostics.push(...providerDiagnostics);
|
11077 | }
|
11078 | if (analysis.viewProvidersRequiringFactory !== null && analysis.meta.viewProviders instanceof WrappedNodeExpr6) {
|
11079 | const viewProviderDiagnostics = getProviderDiagnostics(analysis.viewProvidersRequiringFactory, analysis.meta.viewProviders.node, this.injectableRegistry);
|
11080 | diagnostics.push(...viewProviderDiagnostics);
|
11081 | }
|
11082 | const directiveDiagnostics = getDirectiveDiagnostics(node, this.metaReader, this.evaluator, this.reflector, this.scopeRegistry, "Component");
|
11083 | if (directiveDiagnostics !== null) {
|
11084 | diagnostics.push(...directiveDiagnostics);
|
11085 | }
|
11086 | if (diagnostics.length > 0) {
|
11087 | return { diagnostics };
|
11088 | }
|
11089 | return { data };
|
11090 | }
|
11091 | xi18n(ctx, node, analysis) {
|
11092 | var _a;
|
11093 | ctx.updateFromTemplate(analysis.template.content, analysis.template.declaration.resolvedTemplateUrl, (_a = analysis.template.interpolationConfig) != null ? _a : DEFAULT_INTERPOLATION_CONFIG);
|
11094 | }
|
11095 | updateResources(node, analysis) {
|
11096 | const containingFile = node.getSourceFile().fileName;
|
11097 | const templateDecl = analysis.template.declaration;
|
11098 | if (!templateDecl.isInline) {
|
11099 | analysis.template = this.extractTemplate(node, templateDecl);
|
11100 | }
|
11101 | let styles = [];
|
11102 | if (analysis.styleUrls !== null) {
|
11103 | for (const styleUrl of analysis.styleUrls) {
|
11104 | try {
|
11105 | const resolvedStyleUrl = this.resourceLoader.resolve(styleUrl.url, containingFile);
|
11106 | const styleText = this.resourceLoader.load(resolvedStyleUrl);
|
11107 | styles.push(styleText);
|
11108 | } catch (e) {
|
11109 | }
|
11110 | }
|
11111 | }
|
11112 | if (analysis.inlineStyles !== null) {
|
11113 | for (const styleText of analysis.inlineStyles) {
|
11114 | styles.push(styleText);
|
11115 | }
|
11116 | }
|
11117 | for (const styleText of analysis.template.styles) {
|
11118 | styles.push(styleText);
|
11119 | }
|
11120 | analysis.meta.styles = styles;
|
11121 | }
|
11122 | compileFull(node, analysis, resolution, pool) {
|
11123 | if (analysis.template.errors !== null && analysis.template.errors.length > 0) {
|
11124 | return [];
|
11125 | }
|
11126 | const meta = __spreadValues(__spreadValues({}, analysis.meta), resolution);
|
11127 | const fac = compileNgFactoryDefField(toFactoryMetadata(meta, FactoryTarget3.Component));
|
11128 | const def = compileComponentFromMetadata(meta, pool, makeBindingParser2());
|
11129 | const classMetadata = analysis.classMetadata !== null ? compileClassMetadata3(analysis.classMetadata).toStmt() : null;
|
11130 | return compileResults(fac, def, classMetadata, "\u0275cmp");
|
11131 | }
|
11132 | compilePartial(node, analysis, resolution) {
|
11133 | if (analysis.template.errors !== null && analysis.template.errors.length > 0) {
|
11134 | return [];
|
11135 | }
|
11136 | const templateInfo = {
|
11137 | content: analysis.template.content,
|
11138 | sourceUrl: analysis.template.declaration.resolvedTemplateUrl,
|
11139 | isInline: analysis.template.declaration.isInline,
|
11140 | inlineTemplateLiteralExpression: analysis.template.sourceMapping.type === "direct" ? new WrappedNodeExpr6(analysis.template.sourceMapping.node) : null
|
11141 | };
|
11142 | const meta = __spreadValues(__spreadValues({}, analysis.meta), resolution);
|
11143 | const fac = compileDeclareFactory(toFactoryMetadata(meta, FactoryTarget3.Component));
|
11144 | const def = compileDeclareComponentFromMetadata(meta, analysis.template, templateInfo);
|
11145 | const classMetadata = analysis.classMetadata !== null ? compileDeclareClassMetadata3(analysis.classMetadata).toStmt() : null;
|
11146 | return compileResults(fac, def, classMetadata, "\u0275cmp");
|
11147 | }
|
11148 | _transformDecoratorToInlineResources(dec, component, styles, template) {
|
11149 | if (dec.name !== "Component") {
|
11150 | return dec;
|
11151 | }
|
11152 | if (!component.has("templateUrl") && !component.has("styleUrls")) {
|
11153 | return dec;
|
11154 | }
|
11155 | const metadata = new Map(component);
|
11156 | if (metadata.has("templateUrl")) {
|
11157 | metadata.delete("templateUrl");
|
11158 | metadata.set("template", ts45.createStringLiteral(template.content));
|
11159 | }
|
11160 | if (metadata.has("styleUrls")) {
|
11161 | metadata.delete("styleUrls");
|
11162 | metadata.set("styles", ts45.createArrayLiteral(styles.map((s) => ts45.createStringLiteral(s))));
|
11163 | }
|
11164 | const newMetadataFields = [];
|
11165 | for (const [name, value] of metadata.entries()) {
|
11166 | newMetadataFields.push(ts45.createPropertyAssignment(name, value));
|
11167 | }
|
11168 | return __spreadProps(__spreadValues({}, dec), { args: [ts45.createObjectLiteral(newMetadataFields)] });
|
11169 | }
|
11170 | _resolveLiteral(decorator) {
|
11171 | if (this.literalCache.has(decorator)) {
|
11172 | return this.literalCache.get(decorator);
|
11173 | }
|
11174 | if (decorator.args === null || decorator.args.length !== 1) {
|
11175 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, Decorator.nodeForError(decorator), `Incorrect number of arguments to @Component decorator`);
|
11176 | }
|
11177 | const meta = unwrapExpression(decorator.args[0]);
|
11178 | if (!ts45.isObjectLiteralExpression(meta)) {
|
11179 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARG_NOT_LITERAL, meta, `Decorator argument must be literal.`);
|
11180 | }
|
11181 | this.literalCache.set(decorator, meta);
|
11182 | return meta;
|
11183 | }
|
11184 | _resolveEnumValue(component, field, enumSymbolName) {
|
11185 | let resolved = null;
|
11186 | if (component.has(field)) {
|
11187 | const expr = component.get(field);
|
11188 | const value = this.evaluator.evaluate(expr);
|
11189 | if (value instanceof EnumValue && isAngularCoreReference(value.enumRef, enumSymbolName)) {
|
11190 | resolved = value.resolved;
|
11191 | } else {
|
11192 | throw createValueHasWrongTypeError(expr, value, `${field} must be a member of ${enumSymbolName} enum from @angular/core`);
|
11193 | }
|
11194 | }
|
11195 | return resolved;
|
11196 | }
|
11197 | _extractComponentStyleUrls(component) {
|
11198 | if (!component.has("styleUrls")) {
|
11199 | return [];
|
11200 | }
|
11201 | return this._extractStyleUrlsFromExpression(component.get("styleUrls"));
|
11202 | }
|
11203 | _extractStyleUrlsFromExpression(styleUrlsExpr) {
|
11204 | const styleUrls = [];
|
11205 | if (ts45.isArrayLiteralExpression(styleUrlsExpr)) {
|
11206 | for (const styleUrlExpr of styleUrlsExpr.elements) {
|
11207 | if (ts45.isSpreadElement(styleUrlExpr)) {
|
11208 | styleUrls.push(...this._extractStyleUrlsFromExpression(styleUrlExpr.expression));
|
11209 | } else {
|
11210 | const styleUrl = this.evaluator.evaluate(styleUrlExpr);
|
11211 | if (typeof styleUrl !== "string") {
|
11212 | throw createValueHasWrongTypeError(styleUrlExpr, styleUrl, "styleUrl must be a string");
|
11213 | }
|
11214 | styleUrls.push({
|
11215 | url: styleUrl,
|
11216 | source: 2,
|
11217 | nodeForError: styleUrlExpr
|
11218 | });
|
11219 | }
|
11220 | }
|
11221 | } else {
|
11222 | const evaluatedStyleUrls = this.evaluator.evaluate(styleUrlsExpr);
|
11223 | if (!isStringArray(evaluatedStyleUrls)) {
|
11224 | throw createValueHasWrongTypeError(styleUrlsExpr, evaluatedStyleUrls, "styleUrls must be an array of strings");
|
11225 | }
|
11226 | for (const styleUrl of evaluatedStyleUrls) {
|
11227 | styleUrls.push({
|
11228 | url: styleUrl,
|
11229 | source: 2,
|
11230 | nodeForError: styleUrlsExpr
|
11231 | });
|
11232 | }
|
11233 | }
|
11234 | return styleUrls;
|
11235 | }
|
11236 | _extractStyleResources(component, containingFile) {
|
11237 | const styles = new Set();
|
11238 | function stringLiteralElements(array) {
|
11239 | return array.elements.filter((e) => ts45.isStringLiteralLike(e));
|
11240 | }
|
11241 | const styleUrlsExpr = component.get("styleUrls");
|
11242 | if (styleUrlsExpr !== void 0 && ts45.isArrayLiteralExpression(styleUrlsExpr)) {
|
11243 | for (const expression of stringLiteralElements(styleUrlsExpr)) {
|
11244 | try {
|
11245 | const resourceUrl = this.resourceLoader.resolve(expression.text, containingFile);
|
11246 | styles.add({ path: absoluteFrom(resourceUrl), expression });
|
11247 | } catch {
|
11248 | }
|
11249 | }
|
11250 | }
|
11251 | const stylesExpr = component.get("styles");
|
11252 | if (stylesExpr !== void 0 && ts45.isArrayLiteralExpression(stylesExpr)) {
|
11253 | for (const expression of stringLiteralElements(stylesExpr)) {
|
11254 | styles.add({ path: null, expression });
|
11255 | }
|
11256 | }
|
11257 | return styles;
|
11258 | }
|
11259 | _preloadAndParseTemplate(node, decorator, component, containingFile) {
|
11260 | if (component.has("templateUrl")) {
|
11261 | const templateUrlExpr = component.get("templateUrl");
|
11262 | const templateUrl = this.evaluator.evaluate(templateUrlExpr);
|
11263 | if (typeof templateUrl !== "string") {
|
11264 | throw createValueHasWrongTypeError(templateUrlExpr, templateUrl, "templateUrl must be a string");
|
11265 | }
|
11266 | try {
|
11267 | const resourceUrl = this.resourceLoader.resolve(templateUrl, containingFile);
|
11268 | const templatePromise = this.resourceLoader.preload(resourceUrl, { type: "template", containingFile });
|
11269 | if (templatePromise !== void 0) {
|
11270 | return templatePromise.then(() => {
|
11271 | const templateDecl = this.parseTemplateDeclaration(decorator, component, containingFile);
|
11272 | const template = this.extractTemplate(node, templateDecl);
|
11273 | this.preanalyzeTemplateCache.set(node, template);
|
11274 | return template;
|
11275 | });
|
11276 | } else {
|
11277 | return Promise.resolve(null);
|
11278 | }
|
11279 | } catch (e) {
|
11280 | throw this.makeResourceNotFoundError(templateUrl, templateUrlExpr, 0);
|
11281 | }
|
11282 | } else {
|
11283 | const templateDecl = this.parseTemplateDeclaration(decorator, component, containingFile);
|
11284 | const template = this.extractTemplate(node, templateDecl);
|
11285 | this.preanalyzeTemplateCache.set(node, template);
|
11286 | return Promise.resolve(template);
|
11287 | }
|
11288 | }
|
11289 | extractTemplate(node, template) {
|
11290 | if (template.isInline) {
|
11291 | let sourceStr;
|
11292 | let sourceParseRange = null;
|
11293 | let templateContent;
|
11294 | let sourceMapping;
|
11295 | let escapedString = false;
|
11296 | let sourceMapUrl;
|
11297 | if (ts45.isStringLiteral(template.expression) || ts45.isNoSubstitutionTemplateLiteral(template.expression)) {
|
11298 | sourceParseRange = getTemplateRange(template.expression);
|
11299 | sourceStr = template.expression.getSourceFile().text;
|
11300 | templateContent = template.expression.text;
|
11301 | escapedString = true;
|
11302 | sourceMapping = {
|
11303 | type: "direct",
|
11304 | node: template.expression
|
11305 | };
|
11306 | sourceMapUrl = template.resolvedTemplateUrl;
|
11307 | } else {
|
11308 | const resolvedTemplate = this.evaluator.evaluate(template.expression);
|
11309 | if (typeof resolvedTemplate !== "string") {
|
11310 | throw createValueHasWrongTypeError(template.expression, resolvedTemplate, "template must be a string");
|
11311 | }
|
11312 | sourceStr = resolvedTemplate;
|
11313 | templateContent = resolvedTemplate;
|
11314 | sourceMapping = {
|
11315 | type: "indirect",
|
11316 | node: template.expression,
|
11317 | componentClass: node,
|
11318 | template: templateContent
|
11319 | };
|
11320 | sourceMapUrl = null;
|
11321 | }
|
11322 | return __spreadProps(__spreadValues({}, this._parseTemplate(template, sourceStr, sourceParseRange, escapedString, sourceMapUrl)), {
|
11323 | content: templateContent,
|
11324 | sourceMapping,
|
11325 | declaration: template
|
11326 | });
|
11327 | } else {
|
11328 | const templateContent = this.resourceLoader.load(template.resolvedTemplateUrl);
|
11329 | if (this.depTracker !== null) {
|
11330 | this.depTracker.addResourceDependency(node.getSourceFile(), absoluteFrom(template.resolvedTemplateUrl));
|
11331 | }
|
11332 | return __spreadProps(__spreadValues({}, this._parseTemplate(template, templateContent, null, false, template.resolvedTemplateUrl)), {
|
11333 | content: templateContent,
|
11334 | sourceMapping: {
|
11335 | type: "external",
|
11336 | componentClass: node,
|
11337 | node: template.templateUrlExpression,
|
11338 | template: templateContent,
|
11339 | templateUrl: template.resolvedTemplateUrl
|
11340 | },
|
11341 | declaration: template
|
11342 | });
|
11343 | }
|
11344 | }
|
11345 | _parseTemplate(template, sourceStr, sourceParseRange, escapedString, sourceMapUrl) {
|
11346 | const i18nNormalizeLineEndingsInICUs = escapedString || this.i18nNormalizeLineEndingsInICUs;
|
11347 | const parsedTemplate = parseTemplate(sourceStr, sourceMapUrl != null ? sourceMapUrl : "", {
|
11348 | preserveWhitespaces: template.preserveWhitespaces,
|
11349 | interpolationConfig: template.interpolationConfig,
|
11350 | range: sourceParseRange != null ? sourceParseRange : void 0,
|
11351 | escapedString,
|
11352 | enableI18nLegacyMessageIdFormat: this.enableI18nLegacyMessageIdFormat,
|
11353 | i18nNormalizeLineEndingsInICUs,
|
11354 | alwaysAttemptHtmlToR3AstConversion: this.usePoisonedData
|
11355 | });
|
11356 | const { nodes: diagNodes } = parseTemplate(sourceStr, sourceMapUrl != null ? sourceMapUrl : "", {
|
11357 | preserveWhitespaces: true,
|
11358 | preserveLineEndings: true,
|
11359 | interpolationConfig: template.interpolationConfig,
|
11360 | range: sourceParseRange != null ? sourceParseRange : void 0,
|
11361 | escapedString,
|
11362 | enableI18nLegacyMessageIdFormat: this.enableI18nLegacyMessageIdFormat,
|
11363 | i18nNormalizeLineEndingsInICUs,
|
11364 | leadingTriviaChars: [],
|
11365 | alwaysAttemptHtmlToR3AstConversion: this.usePoisonedData
|
11366 | });
|
11367 | return __spreadProps(__spreadValues({}, parsedTemplate), {
|
11368 | diagNodes,
|
11369 | file: new ParseSourceFile2(sourceStr, sourceMapUrl != null ? sourceMapUrl : "")
|
11370 | });
|
11371 | }
|
11372 | parseTemplateDeclaration(decorator, component, containingFile) {
|
11373 | let preserveWhitespaces = this.defaultPreserveWhitespaces;
|
11374 | if (component.has("preserveWhitespaces")) {
|
11375 | const expr = component.get("preserveWhitespaces");
|
11376 | const value = this.evaluator.evaluate(expr);
|
11377 | if (typeof value !== "boolean") {
|
11378 | throw createValueHasWrongTypeError(expr, value, "preserveWhitespaces must be a boolean");
|
11379 | }
|
11380 | preserveWhitespaces = value;
|
11381 | }
|
11382 | let interpolationConfig = DEFAULT_INTERPOLATION_CONFIG;
|
11383 | if (component.has("interpolation")) {
|
11384 | const expr = component.get("interpolation");
|
11385 | const value = this.evaluator.evaluate(expr);
|
11386 | if (!Array.isArray(value) || value.length !== 2 || !value.every((element) => typeof element === "string")) {
|
11387 | throw createValueHasWrongTypeError(expr, value, "interpolation must be an array with 2 elements of string type");
|
11388 | }
|
11389 | interpolationConfig = InterpolationConfig.fromArray(value);
|
11390 | }
|
11391 | if (component.has("templateUrl")) {
|
11392 | const templateUrlExpr = component.get("templateUrl");
|
11393 | const templateUrl = this.evaluator.evaluate(templateUrlExpr);
|
11394 | if (typeof templateUrl !== "string") {
|
11395 | throw createValueHasWrongTypeError(templateUrlExpr, templateUrl, "templateUrl must be a string");
|
11396 | }
|
11397 | try {
|
11398 | const resourceUrl = this.resourceLoader.resolve(templateUrl, containingFile);
|
11399 | return {
|
11400 | isInline: false,
|
11401 | interpolationConfig,
|
11402 | preserveWhitespaces,
|
11403 | templateUrl,
|
11404 | templateUrlExpression: templateUrlExpr,
|
11405 | resolvedTemplateUrl: resourceUrl
|
11406 | };
|
11407 | } catch (e) {
|
11408 | throw this.makeResourceNotFoundError(templateUrl, templateUrlExpr, 0);
|
11409 | }
|
11410 | } else if (component.has("template")) {
|
11411 | return {
|
11412 | isInline: true,
|
11413 | interpolationConfig,
|
11414 | preserveWhitespaces,
|
11415 | expression: component.get("template"),
|
11416 | templateUrl: containingFile,
|
11417 | resolvedTemplateUrl: containingFile
|
11418 | };
|
11419 | } else {
|
11420 | throw new FatalDiagnosticError(ErrorCode.COMPONENT_MISSING_TEMPLATE, Decorator.nodeForError(decorator), "component is missing a template");
|
11421 | }
|
11422 | }
|
11423 | _resolveImportedFile(importedFile, expr, origin) {
|
11424 | if (importedFile !== "unknown") {
|
11425 | return importedFile;
|
11426 | }
|
11427 | if (!(expr instanceof ExternalExpr7)) {
|
11428 | return null;
|
11429 | }
|
11430 | return this.moduleResolver.resolveModule(expr.value.moduleName, origin.fileName);
|
11431 | }
|
11432 | _checkForCyclicImport(importedFile, expr, origin) {
|
11433 | const imported = this._resolveImportedFile(importedFile, expr, origin);
|
11434 | if (imported === null) {
|
11435 | return null;
|
11436 | }
|
11437 | return this.cycleAnalyzer.wouldCreateCycle(origin, imported);
|
11438 | }
|
11439 | _recordSyntheticImport(importedFile, expr, origin) {
|
11440 | const imported = this._resolveImportedFile(importedFile, expr, origin);
|
11441 | if (imported === null) {
|
11442 | return;
|
11443 | }
|
11444 | this.cycleAnalyzer.recordSyntheticImport(origin, imported);
|
11445 | }
|
11446 | makeResourceNotFoundError(file, nodeForError, resourceType) {
|
11447 | let errorText;
|
11448 | switch (resourceType) {
|
11449 | case 0:
|
11450 | errorText = `Could not find template file '${file}'.`;
|
11451 | break;
|
11452 | case 1:
|
11453 | errorText = `Could not find stylesheet file '${file}' linked from the template.`;
|
11454 | break;
|
11455 | case 2:
|
11456 | errorText = `Could not find stylesheet file '${file}'.`;
|
11457 | break;
|
11458 | }
|
11459 | return new FatalDiagnosticError(ErrorCode.COMPONENT_RESOURCE_NOT_FOUND, nodeForError, errorText);
|
11460 | }
|
11461 | _extractTemplateStyleUrls(template) {
|
11462 | if (template.styleUrls === null) {
|
11463 | return [];
|
11464 | }
|
11465 | const nodeForError = getTemplateDeclarationNodeForError(template.declaration);
|
11466 | return template.styleUrls.map((url) => ({ url, source: 1, nodeForError }));
|
11467 | }
|
11468 | };
|
11469 | function getTemplateRange(templateExpr) {
|
11470 | const startPos = templateExpr.getStart() + 1;
|
11471 | const { line, character } = ts45.getLineAndCharacterOfPosition(templateExpr.getSourceFile(), startPos);
|
11472 | return {
|
11473 | startPos,
|
11474 | startLine: line,
|
11475 | startCol: character,
|
11476 | endPos: templateExpr.getEnd() - 1
|
11477 | };
|
11478 | }
|
11479 | function isStringArray(resolvedValue) {
|
11480 | return Array.isArray(resolvedValue) && resolvedValue.every((elem) => typeof elem === "string");
|
11481 | }
|
11482 | function getTemplateDeclarationNodeForError(declaration) {
|
11483 | switch (declaration.isInline) {
|
11484 | case true:
|
11485 | return declaration.expression;
|
11486 | case false:
|
11487 | return declaration.templateUrlExpression;
|
11488 | }
|
11489 | }
|
11490 | function makeCyclicImportInfo(ref, type, cycle) {
|
11491 | const name = ref.debugName || "(unknown)";
|
11492 | const path7 = cycle.getPath().map((sf) => sf.fileName).join(" -> ");
|
11493 | const message = `The ${type} '${name}' is used in the template but importing it would create a cycle: `;
|
11494 | return makeRelatedInformation(ref.node, message + path7);
|
11495 | }
|
11496 | function checkCustomElementSelectorForErrors(selector) {
|
11497 | if (selector.includes(".") || selector.includes("[") && selector.includes("]")) {
|
11498 | return null;
|
11499 | }
|
11500 | if (!/^[a-z]/.test(selector)) {
|
11501 | return "Selector of a ShadowDom-encapsulated component must start with a lower case letter.";
|
11502 | }
|
11503 | if (/[A-Z]/.test(selector)) {
|
11504 | return "Selector of a ShadowDom-encapsulated component must all be in lower case.";
|
11505 | }
|
11506 | if (!selector.includes("-")) {
|
11507 | return "Selector of a component that uses ViewEncapsulation.ShadowDom must contain a hyphen.";
|
11508 | }
|
11509 | return null;
|
11510 | }
|
11511 |
|
11512 |
|
11513 | import { compileClassMetadata as compileClassMetadata4, compileDeclareClassMetadata as compileDeclareClassMetadata4, compileDeclareInjectableFromMetadata, compileInjectable, createMayBeForwardRefExpression as createMayBeForwardRefExpression2, FactoryTarget as FactoryTarget4, LiteralExpr as LiteralExpr3, WrappedNodeExpr as WrappedNodeExpr7 } from "@angular/compiler";
|
11514 | import ts46 from "typescript";
|
11515 | var InjectableDecoratorHandler = class {
|
11516 | constructor(reflector, isCore, strictCtorDeps, injectableRegistry, perf, errorOnDuplicateProv = true) {
|
11517 | this.reflector = reflector;
|
11518 | this.isCore = isCore;
|
11519 | this.strictCtorDeps = strictCtorDeps;
|
11520 | this.injectableRegistry = injectableRegistry;
|
11521 | this.perf = perf;
|
11522 | this.errorOnDuplicateProv = errorOnDuplicateProv;
|
11523 | this.precedence = HandlerPrecedence.SHARED;
|
11524 | this.name = InjectableDecoratorHandler.name;
|
11525 | }
|
11526 | detect(node, decorators) {
|
11527 | if (!decorators) {
|
11528 | return void 0;
|
11529 | }
|
11530 | const decorator = findAngularDecorator(decorators, "Injectable", this.isCore);
|
11531 | if (decorator !== void 0) {
|
11532 | return {
|
11533 | trigger: decorator.node,
|
11534 | decorator,
|
11535 | metadata: decorator
|
11536 | };
|
11537 | } else {
|
11538 | return void 0;
|
11539 | }
|
11540 | }
|
11541 | analyze(node, decorator) {
|
11542 | this.perf.eventCount(PerfEvent.AnalyzeInjectable);
|
11543 | const meta = extractInjectableMetadata(node, decorator, this.reflector);
|
11544 | const decorators = this.reflector.getDecoratorsOfDeclaration(node);
|
11545 | return {
|
11546 | analysis: {
|
11547 | meta,
|
11548 | ctorDeps: extractInjectableCtorDeps(node, meta, decorator, this.reflector, this.isCore, this.strictCtorDeps),
|
11549 | classMetadata: extractClassMetadata(node, this.reflector, this.isCore),
|
11550 | needsFactory: !decorators || decorators.every((current) => !isAngularCore(current) || current.name === "Injectable")
|
11551 | }
|
11552 | };
|
11553 | }
|
11554 | symbol() {
|
11555 | return null;
|
11556 | }
|
11557 | register(node) {
|
11558 | this.injectableRegistry.registerInjectable(node);
|
11559 | }
|
11560 | compileFull(node, analysis) {
|
11561 | return this.compile(compileNgFactoryDefField, (meta) => compileInjectable(meta, false), compileClassMetadata4, node, analysis);
|
11562 | }
|
11563 | compilePartial(node, analysis) {
|
11564 | return this.compile(compileDeclareFactory, compileDeclareInjectableFromMetadata, compileDeclareClassMetadata4, node, analysis);
|
11565 | }
|
11566 | compile(compileFactoryFn, compileInjectableFn, compileClassMetadataFn, node, analysis) {
|
11567 | const results = [];
|
11568 | if (analysis.needsFactory) {
|
11569 | const meta = analysis.meta;
|
11570 | const factoryRes = compileFactoryFn(toFactoryMetadata(__spreadProps(__spreadValues({}, meta), { deps: analysis.ctorDeps }), FactoryTarget4.Injectable));
|
11571 | if (analysis.classMetadata !== null) {
|
11572 | factoryRes.statements.push(compileClassMetadataFn(analysis.classMetadata).toStmt());
|
11573 | }
|
11574 | results.push(factoryRes);
|
11575 | }
|
11576 | const \u0275prov = this.reflector.getMembersOfClass(node).find((member) => member.name === "\u0275prov");
|
11577 | if (\u0275prov !== void 0 && this.errorOnDuplicateProv) {
|
11578 | 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.");
|
11579 | }
|
11580 | if (\u0275prov === void 0) {
|
11581 | const res = compileInjectableFn(analysis.meta);
|
11582 | results.push({ name: "\u0275prov", initializer: res.expression, statements: res.statements, type: res.type });
|
11583 | }
|
11584 | return results;
|
11585 | }
|
11586 | };
|
11587 | function extractInjectableMetadata(clazz, decorator, reflector) {
|
11588 | const name = clazz.name.text;
|
11589 | const type = wrapTypeReference(reflector, clazz);
|
11590 | const internalType = new WrappedNodeExpr7(reflector.getInternalNameOfClass(clazz));
|
11591 | const typeArgumentCount = reflector.getGenericArityOfClass(clazz) || 0;
|
11592 | if (decorator.args === null) {
|
11593 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_NOT_CALLED, Decorator.nodeForError(decorator), "@Injectable must be called");
|
11594 | }
|
11595 | if (decorator.args.length === 0) {
|
11596 | return {
|
11597 | name,
|
11598 | type,
|
11599 | typeArgumentCount,
|
11600 | internalType,
|
11601 | providedIn: createMayBeForwardRefExpression2(new LiteralExpr3(null), 0)
|
11602 | };
|
11603 | } else if (decorator.args.length === 1) {
|
11604 | const metaNode = decorator.args[0];
|
11605 | if (!ts46.isObjectLiteralExpression(metaNode)) {
|
11606 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARG_NOT_LITERAL, metaNode, `@Injectable argument must be an object literal`);
|
11607 | }
|
11608 | const meta = reflectObjectLiteral(metaNode);
|
11609 | const providedIn = meta.has("providedIn") ? getProviderExpression(meta.get("providedIn"), reflector) : createMayBeForwardRefExpression2(new LiteralExpr3(null), 0);
|
11610 | let deps = void 0;
|
11611 | if ((meta.has("useClass") || meta.has("useFactory")) && meta.has("deps")) {
|
11612 | const depsExpr = meta.get("deps");
|
11613 | if (!ts46.isArrayLiteralExpression(depsExpr)) {
|
11614 | throw new FatalDiagnosticError(ErrorCode.VALUE_NOT_LITERAL, depsExpr, `@Injectable deps metadata must be an inline array`);
|
11615 | }
|
11616 | deps = depsExpr.elements.map((dep) => getDep(dep, reflector));
|
11617 | }
|
11618 | const result = { name, type, typeArgumentCount, internalType, providedIn };
|
11619 | if (meta.has("useValue")) {
|
11620 | result.useValue = getProviderExpression(meta.get("useValue"), reflector);
|
11621 | } else if (meta.has("useExisting")) {
|
11622 | result.useExisting = getProviderExpression(meta.get("useExisting"), reflector);
|
11623 | } else if (meta.has("useClass")) {
|
11624 | result.useClass = getProviderExpression(meta.get("useClass"), reflector);
|
11625 | result.deps = deps;
|
11626 | } else if (meta.has("useFactory")) {
|
11627 | result.useFactory = new WrappedNodeExpr7(meta.get("useFactory"));
|
11628 | result.deps = deps;
|
11629 | }
|
11630 | return result;
|
11631 | } else {
|
11632 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, decorator.args[2], "Too many arguments to @Injectable");
|
11633 | }
|
11634 | }
|
11635 | function getProviderExpression(expression, reflector) {
|
11636 | const forwardRefValue = tryUnwrapForwardRef(expression, reflector);
|
11637 | return createMayBeForwardRefExpression2(new WrappedNodeExpr7(forwardRefValue != null ? forwardRefValue : expression), forwardRefValue !== null ? 2 : 0);
|
11638 | }
|
11639 | function extractInjectableCtorDeps(clazz, meta, decorator, reflector, isCore, strictCtorDeps) {
|
11640 | if (decorator.args === null) {
|
11641 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_NOT_CALLED, Decorator.nodeForError(decorator), "@Injectable must be called");
|
11642 | }
|
11643 | let ctorDeps = null;
|
11644 | if (decorator.args.length === 0) {
|
11645 | if (strictCtorDeps) {
|
11646 | ctorDeps = getValidConstructorDependencies(clazz, reflector, isCore);
|
11647 | } else {
|
11648 | ctorDeps = unwrapConstructorDependencies(getConstructorDependencies(clazz, reflector, isCore));
|
11649 | }
|
11650 | return ctorDeps;
|
11651 | } else if (decorator.args.length === 1) {
|
11652 | const rawCtorDeps = getConstructorDependencies(clazz, reflector, isCore);
|
11653 | if (strictCtorDeps && meta.useValue === void 0 && meta.useExisting === void 0 && meta.useClass === void 0 && meta.useFactory === void 0) {
|
11654 | ctorDeps = validateConstructorDependencies(clazz, rawCtorDeps);
|
11655 | } else {
|
11656 | ctorDeps = unwrapConstructorDependencies(rawCtorDeps);
|
11657 | }
|
11658 | }
|
11659 | return ctorDeps;
|
11660 | }
|
11661 | function getDep(dep, reflector) {
|
11662 | const meta = {
|
11663 | token: new WrappedNodeExpr7(dep),
|
11664 | attributeNameType: null,
|
11665 | host: false,
|
11666 | optional: false,
|
11667 | self: false,
|
11668 | skipSelf: false
|
11669 | };
|
11670 | function maybeUpdateDecorator(dec, reflector2, token) {
|
11671 | const source = reflector2.getImportOfIdentifier(dec);
|
11672 | if (source === null || source.from !== "@angular/core") {
|
11673 | return false;
|
11674 | }
|
11675 | switch (source.name) {
|
11676 | case "Inject":
|
11677 | if (token !== void 0) {
|
11678 | meta.token = new WrappedNodeExpr7(token);
|
11679 | }
|
11680 | break;
|
11681 | case "Optional":
|
11682 | meta.optional = true;
|
11683 | break;
|
11684 | case "SkipSelf":
|
11685 | meta.skipSelf = true;
|
11686 | break;
|
11687 | case "Self":
|
11688 | meta.self = true;
|
11689 | break;
|
11690 | default:
|
11691 | return false;
|
11692 | }
|
11693 | return true;
|
11694 | }
|
11695 | if (ts46.isArrayLiteralExpression(dep)) {
|
11696 | dep.elements.forEach((el) => {
|
11697 | let isDecorator = false;
|
11698 | if (ts46.isIdentifier(el)) {
|
11699 | isDecorator = maybeUpdateDecorator(el, reflector);
|
11700 | } else if (ts46.isNewExpression(el) && ts46.isIdentifier(el.expression)) {
|
11701 | const token = el.arguments && el.arguments.length > 0 && el.arguments[0] || void 0;
|
11702 | isDecorator = maybeUpdateDecorator(el.expression, reflector, token);
|
11703 | }
|
11704 | if (!isDecorator) {
|
11705 | meta.token = new WrappedNodeExpr7(el);
|
11706 | }
|
11707 | });
|
11708 | }
|
11709 | return meta;
|
11710 | }
|
11711 |
|
11712 |
|
11713 | import { compileClassMetadata as compileClassMetadata5, compileDeclareClassMetadata as compileDeclareClassMetadata5, compileDeclarePipeFromMetadata, compilePipeFromMetadata, FactoryTarget as FactoryTarget5, WrappedNodeExpr as WrappedNodeExpr8 } from "@angular/compiler";
|
11714 | import ts47 from "typescript";
|
11715 | var PipeSymbol = class extends SemanticSymbol {
|
11716 | constructor(decl, name) {
|
11717 | super(decl);
|
11718 | this.name = name;
|
11719 | }
|
11720 | isPublicApiAffected(previousSymbol) {
|
11721 | if (!(previousSymbol instanceof PipeSymbol)) {
|
11722 | return true;
|
11723 | }
|
11724 | return this.name !== previousSymbol.name;
|
11725 | }
|
11726 | isTypeCheckApiAffected(previousSymbol) {
|
11727 | return this.isPublicApiAffected(previousSymbol);
|
11728 | }
|
11729 | };
|
11730 | var PipeDecoratorHandler = class {
|
11731 | constructor(reflector, evaluator, metaRegistry, scopeRegistry, injectableRegistry, isCore, perf) {
|
11732 | this.reflector = reflector;
|
11733 | this.evaluator = evaluator;
|
11734 | this.metaRegistry = metaRegistry;
|
11735 | this.scopeRegistry = scopeRegistry;
|
11736 | this.injectableRegistry = injectableRegistry;
|
11737 | this.isCore = isCore;
|
11738 | this.perf = perf;
|
11739 | this.precedence = HandlerPrecedence.PRIMARY;
|
11740 | this.name = PipeDecoratorHandler.name;
|
11741 | }
|
11742 | detect(node, decorators) {
|
11743 | if (!decorators) {
|
11744 | return void 0;
|
11745 | }
|
11746 | const decorator = findAngularDecorator(decorators, "Pipe", this.isCore);
|
11747 | if (decorator !== void 0) {
|
11748 | return {
|
11749 | trigger: decorator.node,
|
11750 | decorator,
|
11751 | metadata: decorator
|
11752 | };
|
11753 | } else {
|
11754 | return void 0;
|
11755 | }
|
11756 | }
|
11757 | analyze(clazz, decorator) {
|
11758 | this.perf.eventCount(PerfEvent.AnalyzePipe);
|
11759 | const name = clazz.name.text;
|
11760 | const type = wrapTypeReference(this.reflector, clazz);
|
11761 | const internalType = new WrappedNodeExpr8(this.reflector.getInternalNameOfClass(clazz));
|
11762 | if (decorator.args === null) {
|
11763 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_NOT_CALLED, Decorator.nodeForError(decorator), `@Pipe must be called`);
|
11764 | }
|
11765 | if (decorator.args.length !== 1) {
|
11766 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, Decorator.nodeForError(decorator), "@Pipe must have exactly one argument");
|
11767 | }
|
11768 | const meta = unwrapExpression(decorator.args[0]);
|
11769 | if (!ts47.isObjectLiteralExpression(meta)) {
|
11770 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARG_NOT_LITERAL, meta, "@Pipe must have a literal argument");
|
11771 | }
|
11772 | const pipe = reflectObjectLiteral(meta);
|
11773 | if (!pipe.has("name")) {
|
11774 | throw new FatalDiagnosticError(ErrorCode.PIPE_MISSING_NAME, meta, `@Pipe decorator is missing name field`);
|
11775 | }
|
11776 | const pipeNameExpr = pipe.get("name");
|
11777 | const pipeName = this.evaluator.evaluate(pipeNameExpr);
|
11778 | if (typeof pipeName !== "string") {
|
11779 | throw createValueHasWrongTypeError(pipeNameExpr, pipeName, `@Pipe.name must be a string`);
|
11780 | }
|
11781 | let pure = true;
|
11782 | if (pipe.has("pure")) {
|
11783 | const expr = pipe.get("pure");
|
11784 | const pureValue = this.evaluator.evaluate(expr);
|
11785 | if (typeof pureValue !== "boolean") {
|
11786 | throw createValueHasWrongTypeError(expr, pureValue, `@Pipe.pure must be a boolean`);
|
11787 | }
|
11788 | pure = pureValue;
|
11789 | }
|
11790 | return {
|
11791 | analysis: {
|
11792 | meta: {
|
11793 | name,
|
11794 | type,
|
11795 | internalType,
|
11796 | typeArgumentCount: this.reflector.getGenericArityOfClass(clazz) || 0,
|
11797 | pipeName,
|
11798 | deps: getValidConstructorDependencies(clazz, this.reflector, this.isCore),
|
11799 | pure
|
11800 | },
|
11801 | classMetadata: extractClassMetadata(clazz, this.reflector, this.isCore),
|
11802 | pipeNameExpr
|
11803 | }
|
11804 | };
|
11805 | }
|
11806 | symbol(node, analysis) {
|
11807 | return new PipeSymbol(node, analysis.meta.name);
|
11808 | }
|
11809 | register(node, analysis) {
|
11810 | const ref = new Reference(node);
|
11811 | this.metaRegistry.registerPipeMetadata({ type: MetaType.Pipe, ref, name: analysis.meta.pipeName, nameExpr: analysis.pipeNameExpr });
|
11812 | this.injectableRegistry.registerInjectable(node);
|
11813 | }
|
11814 | resolve(node) {
|
11815 | const duplicateDeclData = this.scopeRegistry.getDuplicateDeclarations(node);
|
11816 | if (duplicateDeclData !== null) {
|
11817 | return {
|
11818 | diagnostics: [makeDuplicateDeclarationError(node, duplicateDeclData, "Pipe")]
|
11819 | };
|
11820 | }
|
11821 | return {};
|
11822 | }
|
11823 | compileFull(node, analysis) {
|
11824 | const fac = compileNgFactoryDefField(toFactoryMetadata(analysis.meta, FactoryTarget5.Pipe));
|
11825 | const def = compilePipeFromMetadata(analysis.meta);
|
11826 | const classMetadata = analysis.classMetadata !== null ? compileClassMetadata5(analysis.classMetadata).toStmt() : null;
|
11827 | return compileResults(fac, def, classMetadata, "\u0275pipe");
|
11828 | }
|
11829 | compilePartial(node, analysis) {
|
11830 | const fac = compileDeclareFactory(toFactoryMetadata(analysis.meta, FactoryTarget5.Pipe));
|
11831 | const def = compileDeclarePipeFromMetadata(analysis.meta);
|
11832 | const classMetadata = analysis.classMetadata !== null ? compileDeclareClassMetadata5(analysis.classMetadata).toStmt() : null;
|
11833 | return compileResults(fac, def, classMetadata, "\u0275pipe");
|
11834 | }
|
11835 | };
|
11836 |
|
11837 |
|
11838 | var CycleAnalyzer = class {
|
11839 | constructor(importGraph) {
|
11840 | this.importGraph = importGraph;
|
11841 | this.cachedResults = null;
|
11842 | }
|
11843 | wouldCreateCycle(from, to) {
|
11844 | if (this.cachedResults === null || this.cachedResults.from !== from) {
|
11845 | this.cachedResults = new CycleResults(from, this.importGraph);
|
11846 | }
|
11847 | return this.cachedResults.wouldBeCyclic(to) ? new Cycle(this.importGraph, from, to) : null;
|
11848 | }
|
11849 | recordSyntheticImport(from, to) {
|
11850 | this.cachedResults = null;
|
11851 | this.importGraph.addSyntheticImport(from, to);
|
11852 | }
|
11853 | };
|
11854 | var NgCyclicResult = Symbol("NgCyclicResult");
|
11855 | var CycleResults = class {
|
11856 | constructor(from, importGraph) {
|
11857 | this.from = from;
|
11858 | this.importGraph = importGraph;
|
11859 | this.cyclic = {};
|
11860 | this.acyclic = {};
|
11861 | }
|
11862 | wouldBeCyclic(sf) {
|
11863 | const cached = this.getCachedResult(sf);
|
11864 | if (cached !== null) {
|
11865 | return cached;
|
11866 | }
|
11867 | if (sf === this.from) {
|
11868 | return true;
|
11869 | }
|
11870 | this.markAcyclic(sf);
|
11871 | const imports = this.importGraph.importsOf(sf);
|
11872 | for (const imported of imports) {
|
11873 | if (this.wouldBeCyclic(imported)) {
|
11874 | this.markCyclic(sf);
|
11875 | return true;
|
11876 | }
|
11877 | }
|
11878 | return false;
|
11879 | }
|
11880 | getCachedResult(sf) {
|
11881 | const result = sf[NgCyclicResult];
|
11882 | if (result === this.cyclic) {
|
11883 | return true;
|
11884 | } else if (result === this.acyclic) {
|
11885 | return false;
|
11886 | } else {
|
11887 | return null;
|
11888 | }
|
11889 | }
|
11890 | markCyclic(sf) {
|
11891 | sf[NgCyclicResult] = this.cyclic;
|
11892 | }
|
11893 | markAcyclic(sf) {
|
11894 | sf[NgCyclicResult] = this.acyclic;
|
11895 | }
|
11896 | };
|
11897 | var Cycle = class {
|
11898 | constructor(importGraph, from, to) {
|
11899 | this.importGraph = importGraph;
|
11900 | this.from = from;
|
11901 | this.to = to;
|
11902 | }
|
11903 | getPath() {
|
11904 | return [this.from, ...this.importGraph.findPath(this.to, this.from)];
|
11905 | }
|
11906 | };
|
11907 |
|
11908 |
|
11909 | import ts48 from "typescript";
|
11910 | var ImportGraph = class {
|
11911 | constructor(checker, perf) {
|
11912 | this.checker = checker;
|
11913 | this.perf = perf;
|
11914 | this.imports = new Map();
|
11915 | }
|
11916 | importsOf(sf) {
|
11917 | if (!this.imports.has(sf)) {
|
11918 | this.imports.set(sf, this.scanImports(sf));
|
11919 | }
|
11920 | return this.imports.get(sf);
|
11921 | }
|
11922 | findPath(start, end) {
|
11923 | if (start === end) {
|
11924 | return [start];
|
11925 | }
|
11926 | const found = new Set([start]);
|
11927 | const queue = [new Found(start, null)];
|
11928 | while (queue.length > 0) {
|
11929 | const current = queue.shift();
|
11930 | const imports = this.importsOf(current.sourceFile);
|
11931 | for (const importedFile of imports) {
|
11932 | if (!found.has(importedFile)) {
|
11933 | const next = new Found(importedFile, current);
|
11934 | if (next.sourceFile === end) {
|
11935 | return next.toPath();
|
11936 | }
|
11937 | found.add(importedFile);
|
11938 | queue.push(next);
|
11939 | }
|
11940 | }
|
11941 | }
|
11942 | return null;
|
11943 | }
|
11944 | addSyntheticImport(sf, imported) {
|
11945 | if (isLocalFile(imported)) {
|
11946 | this.importsOf(sf).add(imported);
|
11947 | }
|
11948 | }
|
11949 | scanImports(sf) {
|
11950 | return this.perf.inPhase(PerfPhase.CycleDetection, () => {
|
11951 | const imports = new Set();
|
11952 | for (const stmt of sf.statements) {
|
11953 | if (!ts48.isImportDeclaration(stmt) && !ts48.isExportDeclaration(stmt) || stmt.moduleSpecifier === void 0) {
|
11954 | continue;
|
11955 | }
|
11956 | if (ts48.isImportDeclaration(stmt) && stmt.importClause !== void 0 && stmt.importClause.isTypeOnly) {
|
11957 | continue;
|
11958 | }
|
11959 | const symbol = this.checker.getSymbolAtLocation(stmt.moduleSpecifier);
|
11960 | if (symbol === void 0 || symbol.valueDeclaration === void 0) {
|
11961 | continue;
|
11962 | }
|
11963 | const moduleFile = symbol.valueDeclaration;
|
11964 | if (ts48.isSourceFile(moduleFile) && isLocalFile(moduleFile)) {
|
11965 | imports.add(moduleFile);
|
11966 | }
|
11967 | }
|
11968 | return imports;
|
11969 | });
|
11970 | }
|
11971 | };
|
11972 | function isLocalFile(sf) {
|
11973 | return !sf.isDeclarationFile;
|
11974 | }
|
11975 | var Found = class {
|
11976 | constructor(sourceFile, parent) {
|
11977 | this.sourceFile = sourceFile;
|
11978 | this.parent = parent;
|
11979 | }
|
11980 | toPath() {
|
11981 | const array = [];
|
11982 | let current = this;
|
11983 | while (current !== null) {
|
11984 | array.push(current.sourceFile);
|
11985 | current = current.parent;
|
11986 | }
|
11987 | return array.reverse();
|
11988 | }
|
11989 | };
|
11990 |
|
11991 |
|
11992 | var MetadataDtsModuleScopeResolver = class {
|
11993 | constructor(dtsMetaReader, aliasingHost) {
|
11994 | this.dtsMetaReader = dtsMetaReader;
|
11995 | this.aliasingHost = aliasingHost;
|
11996 | this.cache = new Map();
|
11997 | }
|
11998 | resolve(ref) {
|
11999 | const clazz = ref.node;
|
12000 | const sourceFile = clazz.getSourceFile();
|
12001 | if (!sourceFile.isDeclarationFile) {
|
12002 | throw new Error(`Debug error: DtsModuleScopeResolver.read(${ref.debugName} from ${sourceFile.fileName}), but not a .d.ts file`);
|
12003 | }
|
12004 | if (this.cache.has(clazz)) {
|
12005 | return this.cache.get(clazz);
|
12006 | }
|
12007 | const directives = [];
|
12008 | const pipes = [];
|
12009 | const ngModules = new Set([clazz]);
|
12010 | const meta = this.dtsMetaReader.getNgModuleMetadata(ref);
|
12011 | if (meta === null) {
|
12012 | this.cache.set(clazz, null);
|
12013 | return null;
|
12014 | }
|
12015 | const declarations = new Set();
|
12016 | for (const declRef of meta.declarations) {
|
12017 | declarations.add(declRef.node);
|
12018 | }
|
12019 | for (const exportRef of meta.exports) {
|
12020 | const directive = this.dtsMetaReader.getDirectiveMetadata(exportRef);
|
12021 | if (directive !== null) {
|
12022 | const isReExport = !declarations.has(exportRef.node);
|
12023 | directives.push(this.maybeAlias(directive, sourceFile, isReExport));
|
12024 | continue;
|
12025 | }
|
12026 | const pipe = this.dtsMetaReader.getPipeMetadata(exportRef);
|
12027 | if (pipe !== null) {
|
12028 | const isReExport = !declarations.has(exportRef.node);
|
12029 | pipes.push(this.maybeAlias(pipe, sourceFile, isReExport));
|
12030 | continue;
|
12031 | }
|
12032 | const exportScope2 = this.resolve(exportRef);
|
12033 | if (exportScope2 !== null) {
|
12034 | if (this.aliasingHost === null) {
|
12035 | directives.push(...exportScope2.exported.directives);
|
12036 | pipes.push(...exportScope2.exported.pipes);
|
12037 | } else {
|
12038 | for (const directive2 of exportScope2.exported.directives) {
|
12039 | directives.push(this.maybeAlias(directive2, sourceFile, true));
|
12040 | }
|
12041 | for (const pipe2 of exportScope2.exported.pipes) {
|
12042 | pipes.push(this.maybeAlias(pipe2, sourceFile, true));
|
12043 | }
|
12044 | for (const ngModule of exportScope2.exported.ngModules) {
|
12045 | ngModules.add(ngModule);
|
12046 | }
|
12047 | }
|
12048 | }
|
12049 | continue;
|
12050 | }
|
12051 | const exportScope = {
|
12052 | exported: {
|
12053 | directives,
|
12054 | pipes,
|
12055 | ngModules: Array.from(ngModules),
|
12056 | isPoisoned: false
|
12057 | }
|
12058 | };
|
12059 | this.cache.set(clazz, exportScope);
|
12060 | return exportScope;
|
12061 | }
|
12062 | maybeAlias(dirOrPipe, maybeAliasFrom, isReExport) {
|
12063 | const ref = dirOrPipe.ref;
|
12064 | if (this.aliasingHost === null || ref.node.getSourceFile() === maybeAliasFrom) {
|
12065 | return dirOrPipe;
|
12066 | }
|
12067 | const alias = this.aliasingHost.getAliasIn(ref.node, maybeAliasFrom, isReExport);
|
12068 | if (alias === null) {
|
12069 | return dirOrPipe;
|
12070 | }
|
12071 | return __spreadProps(__spreadValues({}, dirOrPipe), {
|
12072 | ref: ref.cloneWithAlias(alias)
|
12073 | });
|
12074 | }
|
12075 | };
|
12076 |
|
12077 |
|
12078 | import { ExternalExpr as ExternalExpr8 } from "@angular/compiler";
|
12079 | import ts49 from "typescript";
|
12080 | var LocalModuleScopeRegistry = class {
|
12081 | constructor(localReader, dependencyScopeReader, refEmitter, aliasingHost) {
|
12082 | this.localReader = localReader;
|
12083 | this.dependencyScopeReader = dependencyScopeReader;
|
12084 | this.refEmitter = refEmitter;
|
12085 | this.aliasingHost = aliasingHost;
|
12086 | this.sealed = false;
|
12087 | this.declarationToModule = new Map();
|
12088 | this.duplicateDeclarations = new Map();
|
12089 | this.moduleToRef = new Map();
|
12090 | this.cache = new Map();
|
12091 | this.remoteScoping = new Map();
|
12092 | this.scopeErrors = new Map();
|
12093 | this.modulesWithStructuralErrors = new Set();
|
12094 | }
|
12095 | registerNgModuleMetadata(data) {
|
12096 | this.assertCollecting();
|
12097 | const ngModule = data.ref.node;
|
12098 | this.moduleToRef.set(data.ref.node, data.ref);
|
12099 | for (const decl of data.declarations) {
|
12100 | this.registerDeclarationOfModule(ngModule, decl, data.rawDeclarations);
|
12101 | }
|
12102 | }
|
12103 | registerDirectiveMetadata(directive) {
|
12104 | }
|
12105 | registerPipeMetadata(pipe) {
|
12106 | }
|
12107 | getScopeForComponent(clazz) {
|
12108 | const scope = !this.declarationToModule.has(clazz) ? null : this.getScopeOfModule(this.declarationToModule.get(clazz).ngModule);
|
12109 | return scope;
|
12110 | }
|
12111 | getDuplicateDeclarations(node) {
|
12112 | if (!this.duplicateDeclarations.has(node)) {
|
12113 | return null;
|
12114 | }
|
12115 | return Array.from(this.duplicateDeclarations.get(node).values());
|
12116 | }
|
12117 | getScopeOfModule(clazz) {
|
12118 | return this.moduleToRef.has(clazz) ? this.getScopeOfModuleReference(this.moduleToRef.get(clazz)) : null;
|
12119 | }
|
12120 | getDiagnosticsOfModule(clazz) {
|
12121 | this.getScopeOfModule(clazz);
|
12122 | if (this.scopeErrors.has(clazz)) {
|
12123 | return this.scopeErrors.get(clazz);
|
12124 | } else {
|
12125 | return null;
|
12126 | }
|
12127 | }
|
12128 | registerDeclarationOfModule(ngModule, decl, rawDeclarations) {
|
12129 | const declData = {
|
12130 | ngModule,
|
12131 | ref: decl,
|
12132 | rawDeclarations
|
12133 | };
|
12134 | if (this.duplicateDeclarations.has(decl.node)) {
|
12135 | this.duplicateDeclarations.get(decl.node).set(ngModule, declData);
|
12136 | } else if (this.declarationToModule.has(decl.node) && this.declarationToModule.get(decl.node).ngModule !== ngModule) {
|
12137 | const duplicateDeclMap = new Map();
|
12138 | const firstDeclData = this.declarationToModule.get(decl.node);
|
12139 | this.modulesWithStructuralErrors.add(firstDeclData.ngModule);
|
12140 | this.modulesWithStructuralErrors.add(ngModule);
|
12141 | duplicateDeclMap.set(firstDeclData.ngModule, firstDeclData);
|
12142 | duplicateDeclMap.set(ngModule, declData);
|
12143 | this.duplicateDeclarations.set(decl.node, duplicateDeclMap);
|
12144 | this.declarationToModule.delete(decl.node);
|
12145 | } else {
|
12146 | this.declarationToModule.set(decl.node, declData);
|
12147 | }
|
12148 | }
|
12149 | getScopeOfModuleReference(ref) {
|
12150 | if (this.cache.has(ref.node)) {
|
12151 | return this.cache.get(ref.node);
|
12152 | }
|
12153 | this.sealed = true;
|
12154 | const ngModule = this.localReader.getNgModuleMetadata(ref);
|
12155 | if (ngModule === null) {
|
12156 | this.cache.set(ref.node, null);
|
12157 | return null;
|
12158 | }
|
12159 | const compilationModules = new Set([ngModule.ref.node]);
|
12160 | const exportedModules = new Set([ngModule.ref.node]);
|
12161 | const diagnostics = [];
|
12162 | const compilationDirectives = new Map();
|
12163 | const compilationPipes = new Map();
|
12164 | const declared = new Set();
|
12165 | const exportDirectives = new Map();
|
12166 | const exportPipes = new Map();
|
12167 | let isPoisoned = false;
|
12168 | if (this.modulesWithStructuralErrors.has(ngModule.ref.node)) {
|
12169 | isPoisoned = true;
|
12170 | }
|
12171 | for (const decl of ngModule.imports) {
|
12172 | const importScope = this.getExportedScope(decl, diagnostics, ref.node, "import");
|
12173 | if (importScope === null) {
|
12174 | diagnostics.push(invalidRef(ref.node, decl, "import"));
|
12175 | isPoisoned = true;
|
12176 | continue;
|
12177 | } else if (importScope === "invalid" || importScope.exported.isPoisoned) {
|
12178 | diagnostics.push(invalidTransitiveNgModuleRef(ref.node, decl, "import"));
|
12179 | isPoisoned = true;
|
12180 | if (importScope === "invalid") {
|
12181 | continue;
|
12182 | }
|
12183 | }
|
12184 | for (const directive of importScope.exported.directives) {
|
12185 | compilationDirectives.set(directive.ref.node, directive);
|
12186 | }
|
12187 | for (const pipe of importScope.exported.pipes) {
|
12188 | compilationPipes.set(pipe.ref.node, pipe);
|
12189 | }
|
12190 | for (const importedModule of importScope.exported.ngModules) {
|
12191 | compilationModules.add(importedModule);
|
12192 | }
|
12193 | }
|
12194 | for (const decl of ngModule.declarations) {
|
12195 | const directive = this.localReader.getDirectiveMetadata(decl);
|
12196 | const pipe = this.localReader.getPipeMetadata(decl);
|
12197 | if (directive !== null) {
|
12198 | compilationDirectives.set(decl.node, __spreadProps(__spreadValues({}, directive), { ref: decl }));
|
12199 | if (directive.isPoisoned) {
|
12200 | isPoisoned = true;
|
12201 | }
|
12202 | } else if (pipe !== null) {
|
12203 | compilationPipes.set(decl.node, __spreadProps(__spreadValues({}, pipe), { ref: decl }));
|
12204 | } else {
|
12205 | const errorNode = decl.getOriginForDiagnostics(ngModule.rawDeclarations);
|
12206 | 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.`)]));
|
12207 | isPoisoned = true;
|
12208 | continue;
|
12209 | }
|
12210 | declared.add(decl.node);
|
12211 | }
|
12212 | for (const decl of ngModule.exports) {
|
12213 | const exportScope = this.getExportedScope(decl, diagnostics, ref.node, "export");
|
12214 | if (exportScope === "invalid" || exportScope !== null && exportScope.exported.isPoisoned) {
|
12215 | diagnostics.push(invalidTransitiveNgModuleRef(ref.node, decl, "export"));
|
12216 | isPoisoned = true;
|
12217 | if (exportScope === "invalid") {
|
12218 | continue;
|
12219 | }
|
12220 | } else if (exportScope !== null) {
|
12221 | for (const directive of exportScope.exported.directives) {
|
12222 | exportDirectives.set(directive.ref.node, directive);
|
12223 | }
|
12224 | for (const pipe of exportScope.exported.pipes) {
|
12225 | exportPipes.set(pipe.ref.node, pipe);
|
12226 | }
|
12227 | for (const exportedModule of exportScope.exported.ngModules) {
|
12228 | exportedModules.add(exportedModule);
|
12229 | }
|
12230 | } else if (compilationDirectives.has(decl.node)) {
|
12231 | const directive = compilationDirectives.get(decl.node);
|
12232 | exportDirectives.set(decl.node, directive);
|
12233 | } else if (compilationPipes.has(decl.node)) {
|
12234 | const pipe = compilationPipes.get(decl.node);
|
12235 | exportPipes.set(decl.node, pipe);
|
12236 | } else {
|
12237 | if (this.localReader.getDirectiveMetadata(decl) !== null || this.localReader.getPipeMetadata(decl) !== null) {
|
12238 | diagnostics.push(invalidReexport(ref.node, decl));
|
12239 | } else {
|
12240 | diagnostics.push(invalidRef(ref.node, decl, "export"));
|
12241 | }
|
12242 | isPoisoned = true;
|
12243 | continue;
|
12244 | }
|
12245 | }
|
12246 | const exported = {
|
12247 | directives: Array.from(exportDirectives.values()),
|
12248 | pipes: Array.from(exportPipes.values()),
|
12249 | ngModules: Array.from(exportedModules),
|
12250 | isPoisoned
|
12251 | };
|
12252 | const reexports = this.getReexports(ngModule, ref, declared, exported, diagnostics);
|
12253 | const scope = {
|
12254 | ngModule: ngModule.ref.node,
|
12255 | compilation: {
|
12256 | directives: Array.from(compilationDirectives.values()),
|
12257 | pipes: Array.from(compilationPipes.values()),
|
12258 | ngModules: Array.from(compilationModules),
|
12259 | isPoisoned
|
12260 | },
|
12261 | exported,
|
12262 | reexports,
|
12263 | schemas: ngModule.schemas
|
12264 | };
|
12265 | if (diagnostics.length > 0) {
|
12266 | this.scopeErrors.set(ref.node, diagnostics);
|
12267 | this.modulesWithStructuralErrors.add(ref.node);
|
12268 | }
|
12269 | this.cache.set(ref.node, scope);
|
12270 | return scope;
|
12271 | }
|
12272 | getRemoteScope(node) {
|
12273 | return this.remoteScoping.has(node) ? this.remoteScoping.get(node) : null;
|
12274 | }
|
12275 | setComponentRemoteScope(node, directives, pipes) {
|
12276 | this.remoteScoping.set(node, { directives, pipes });
|
12277 | }
|
12278 | getExportedScope(ref, diagnostics, ownerForErrors, type) {
|
12279 | if (ref.node.getSourceFile().isDeclarationFile) {
|
12280 | if (!ts49.isClassDeclaration(ref.node)) {
|
12281 | const code = type === "import" ? ErrorCode.NGMODULE_INVALID_IMPORT : ErrorCode.NGMODULE_INVALID_EXPORT;
|
12282 | 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`));
|
12283 | return "invalid";
|
12284 | }
|
12285 | return this.dependencyScopeReader.resolve(ref);
|
12286 | } else {
|
12287 | return this.getScopeOfModuleReference(ref);
|
12288 | }
|
12289 | }
|
12290 | getReexports(ngModule, ref, declared, exported, diagnostics) {
|
12291 | let reexports = null;
|
12292 | const sourceFile = ref.node.getSourceFile();
|
12293 | if (this.aliasingHost === null) {
|
12294 | return null;
|
12295 | }
|
12296 | reexports = [];
|
12297 | const reexportMap = new Map();
|
12298 | const ngModuleRef = ref;
|
12299 | const addReexport = (exportRef) => {
|
12300 | if (exportRef.node.getSourceFile() === sourceFile) {
|
12301 | return;
|
12302 | }
|
12303 | const isReExport = !declared.has(exportRef.node);
|
12304 | const exportName = this.aliasingHost.maybeAliasSymbolAs(exportRef, sourceFile, ngModule.ref.node.name.text, isReExport);
|
12305 | if (exportName === null) {
|
12306 | return;
|
12307 | }
|
12308 | if (!reexportMap.has(exportName)) {
|
12309 | if (exportRef.alias && exportRef.alias instanceof ExternalExpr8) {
|
12310 | reexports.push({
|
12311 | fromModule: exportRef.alias.value.moduleName,
|
12312 | symbolName: exportRef.alias.value.name,
|
12313 | asAlias: exportName
|
12314 | });
|
12315 | } else {
|
12316 | const expr = this.refEmitter.emit(exportRef.cloneWithNoIdentifiers(), sourceFile).expression;
|
12317 | if (!(expr instanceof ExternalExpr8) || expr.value.moduleName === null || expr.value.name === null) {
|
12318 | throw new Error("Expected ExternalExpr");
|
12319 | }
|
12320 | reexports.push({
|
12321 | fromModule: expr.value.moduleName,
|
12322 | symbolName: expr.value.name,
|
12323 | asAlias: exportName
|
12324 | });
|
12325 | }
|
12326 | reexportMap.set(exportName, exportRef);
|
12327 | } else {
|
12328 | const prevRef = reexportMap.get(exportName);
|
12329 | diagnostics.push(reexportCollision(ngModuleRef.node, prevRef, exportRef));
|
12330 | }
|
12331 | };
|
12332 | for (const { ref: ref2 } of exported.directives) {
|
12333 | addReexport(ref2);
|
12334 | }
|
12335 | for (const { ref: ref2 } of exported.pipes) {
|
12336 | addReexport(ref2);
|
12337 | }
|
12338 | return reexports;
|
12339 | }
|
12340 | assertCollecting() {
|
12341 | if (this.sealed) {
|
12342 | throw new Error(`Assertion: LocalModuleScopeRegistry is not COLLECTING`);
|
12343 | }
|
12344 | }
|
12345 | };
|
12346 | function invalidRef(clazz, decl, type) {
|
12347 | const code = type === "import" ? ErrorCode.NGMODULE_INVALID_IMPORT : ErrorCode.NGMODULE_INVALID_EXPORT;
|
12348 | const resolveTarget = type === "import" ? "NgModule" : "NgModule, Component, Directive, or Pipe";
|
12349 | let message = `Appears in the NgModule.${type}s of ${nodeNameForError(clazz)}, but could not be resolved to an ${resolveTarget} class.
|
12350 |
|
12351 | `;
|
12352 | const library = decl.ownedByModuleGuess !== null ? ` (${decl.ownedByModuleGuess})` : "";
|
12353 | const sf = decl.node.getSourceFile();
|
12354 | if (!sf.isDeclarationFile) {
|
12355 | const annotationType = type === "import" ? "@NgModule" : "Angular";
|
12356 | message += `Is it missing an ${annotationType} annotation?`;
|
12357 | } else if (sf.fileName.indexOf("node_modules") !== -1) {
|
12358 | message += `This likely means that the library${library} which declares ${decl.debugName} has not been processed correctly by ngcc, or 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.`;
|
12359 | } else {
|
12360 | message += `This likely means that the dependency${library} which declares ${decl.debugName} has not been processed correctly by ngcc.`;
|
12361 | }
|
12362 | return makeDiagnostic(code, identifierOfNode(decl.node) || decl.node, message);
|
12363 | }
|
12364 | function invalidTransitiveNgModuleRef(clazz, decl, type) {
|
12365 | const code = type === "import" ? ErrorCode.NGMODULE_INVALID_IMPORT : ErrorCode.NGMODULE_INVALID_EXPORT;
|
12366 | return makeDiagnostic(code, identifierOfNode(decl.node) || decl.node, `Appears in the NgModule.${type}s of ${nodeNameForError(clazz)}, but itself has errors`);
|
12367 | }
|
12368 | function invalidReexport(clazz, decl) {
|
12369 | return makeDiagnostic(ErrorCode.NGMODULE_INVALID_REEXPORT, identifierOfNode(decl.node) || decl.node, `Present in the NgModule.exports of ${nodeNameForError(clazz)} but neither declared nor imported`);
|
12370 | }
|
12371 | function reexportCollision(module7, refA, refB) {
|
12372 | const childMessageText = `This directive/pipe is part of the exports of '${module7.name.text}' and shares the same name as another exported directive/pipe.`;
|
12373 | return makeDiagnostic(ErrorCode.NGMODULE_REEXPORT_NAME_COLLISION, module7.name, `
|
12374 | There was a name collision between two classes named '${refA.node.name.text}', which are both part of the exports of '${module7.name.text}'.
|
12375 |
|
12376 | 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.
|
12377 |
|
12378 | To fix this problem please re-export one or both classes directly from this file.
|
12379 | `.trim(), [
|
12380 | makeRelatedInformation(refA.node.name, childMessageText),
|
12381 | makeRelatedInformation(refB.node.name, childMessageText)
|
12382 | ]);
|
12383 | }
|
12384 |
|
12385 |
|
12386 | import { CssSelector as CssSelector2, SelectorMatcher as SelectorMatcher2 } from "@angular/compiler";
|
12387 | import ts50 from "typescript";
|
12388 | var TypeCheckScopeRegistry = class {
|
12389 | constructor(scopeReader, metaReader) {
|
12390 | this.scopeReader = scopeReader;
|
12391 | this.metaReader = metaReader;
|
12392 | this.flattenedDirectiveMetaCache = new Map();
|
12393 | this.scopeCache = new Map();
|
12394 | }
|
12395 | getTypeCheckScope(node) {
|
12396 | const matcher = new SelectorMatcher2();
|
12397 | const directives = [];
|
12398 | const pipes = new Map();
|
12399 | const scope = this.scopeReader.getScopeForComponent(node);
|
12400 | if (scope === null) {
|
12401 | return {
|
12402 | matcher,
|
12403 | directives,
|
12404 | pipes,
|
12405 | schemas: [],
|
12406 | isPoisoned: false
|
12407 | };
|
12408 | }
|
12409 | if (this.scopeCache.has(scope.ngModule)) {
|
12410 | return this.scopeCache.get(scope.ngModule);
|
12411 | }
|
12412 | for (const meta of scope.compilation.directives) {
|
12413 | if (meta.selector !== null) {
|
12414 | const extMeta = this.getTypeCheckDirectiveMetadata(meta.ref);
|
12415 | matcher.addSelectables(CssSelector2.parse(meta.selector), extMeta);
|
12416 | directives.push(extMeta);
|
12417 | }
|
12418 | }
|
12419 | for (const { name, ref } of scope.compilation.pipes) {
|
12420 | if (!ts50.isClassDeclaration(ref.node)) {
|
12421 | throw new Error(`Unexpected non-class declaration ${ts50.SyntaxKind[ref.node.kind]} for pipe ${ref.debugName}`);
|
12422 | }
|
12423 | pipes.set(name, ref);
|
12424 | }
|
12425 | const typeCheckScope = {
|
12426 | matcher,
|
12427 | directives,
|
12428 | pipes,
|
12429 | schemas: scope.schemas,
|
12430 | isPoisoned: scope.compilation.isPoisoned || scope.exported.isPoisoned
|
12431 | };
|
12432 | this.scopeCache.set(scope.ngModule, typeCheckScope);
|
12433 | return typeCheckScope;
|
12434 | }
|
12435 | getTypeCheckDirectiveMetadata(ref) {
|
12436 | const clazz = ref.node;
|
12437 | if (this.flattenedDirectiveMetaCache.has(clazz)) {
|
12438 | return this.flattenedDirectiveMetaCache.get(clazz);
|
12439 | }
|
12440 | const meta = flattenInheritedDirectiveMetadata(this.metaReader, ref);
|
12441 | this.flattenedDirectiveMetaCache.set(clazz, meta);
|
12442 | return meta;
|
12443 | }
|
12444 | };
|
12445 |
|
12446 |
|
12447 | import ts51 from "typescript";
|
12448 | function isClassDeclaration(clazz) {
|
12449 | return isNamedClassDeclaration(clazz) || isNamedFunctionDeclaration(clazz) || isNamedVariableDeclaration(clazz);
|
12450 | }
|
12451 | function hasDirectiveDecorator(host, clazz) {
|
12452 | const ref = new Reference(clazz);
|
12453 | return host.metadata.getDirectiveMetadata(ref) !== null;
|
12454 | }
|
12455 | function hasPipeDecorator(host, clazz) {
|
12456 | const ref = new Reference(clazz);
|
12457 | return host.metadata.getPipeMetadata(ref) !== null;
|
12458 | }
|
12459 | function hasConstructor(host, clazz) {
|
12460 | return host.reflectionHost.getConstructorParameters(clazz) !== null;
|
12461 | }
|
12462 | function createDirectiveDecorator(clazz, metadata) {
|
12463 | const args = [];
|
12464 | if (metadata !== void 0) {
|
12465 | const metaArgs = [];
|
12466 | if (metadata.selector !== null) {
|
12467 | metaArgs.push(property("selector", metadata.selector));
|
12468 | }
|
12469 | if (metadata.exportAs !== null) {
|
12470 | metaArgs.push(property("exportAs", metadata.exportAs.join(", ")));
|
12471 | }
|
12472 | args.push(reifySourceFile(ts51.createObjectLiteral(metaArgs)));
|
12473 | }
|
12474 | return {
|
12475 | name: "Directive",
|
12476 | identifier: null,
|
12477 | import: { name: "Directive", from: "@angular/core" },
|
12478 | node: null,
|
12479 | synthesizedFor: clazz.name,
|
12480 | args
|
12481 | };
|
12482 | }
|
12483 | function createComponentDecorator(clazz, metadata) {
|
12484 | const metaArgs = [
|
12485 | property("template", "")
|
12486 | ];
|
12487 | if (metadata.selector !== null) {
|
12488 | metaArgs.push(property("selector", metadata.selector));
|
12489 | }
|
12490 | if (metadata.exportAs !== null) {
|
12491 | metaArgs.push(property("exportAs", metadata.exportAs.join(", ")));
|
12492 | }
|
12493 | return {
|
12494 | name: "Component",
|
12495 | identifier: null,
|
12496 | import: { name: "Component", from: "@angular/core" },
|
12497 | node: null,
|
12498 | synthesizedFor: clazz.name,
|
12499 | args: [
|
12500 | reifySourceFile(ts51.createObjectLiteral(metaArgs))
|
12501 | ]
|
12502 | };
|
12503 | }
|
12504 | function createInjectableDecorator(clazz) {
|
12505 | return {
|
12506 | name: "Injectable",
|
12507 | identifier: null,
|
12508 | import: { name: "Injectable", from: "@angular/core" },
|
12509 | node: null,
|
12510 | synthesizedFor: clazz.name,
|
12511 | args: []
|
12512 | };
|
12513 | }
|
12514 | function property(name, value) {
|
12515 | return ts51.createPropertyAssignment(name, ts51.createStringLiteral(value));
|
12516 | }
|
12517 | var EMPTY_SF = ts51.createSourceFile("(empty)", "", ts51.ScriptTarget.Latest);
|
12518 | function reifySourceFile(expr) {
|
12519 | const printer = ts51.createPrinter();
|
12520 | const exprText = printer.printNode(ts51.EmitHint.Unspecified, expr, EMPTY_SF);
|
12521 | const sf = ts51.createSourceFile("(synthetic)", `const expr = ${exprText};`, ts51.ScriptTarget.Latest, true, ts51.ScriptKind.JS);
|
12522 | const stmt = sf.statements[0];
|
12523 | if (!ts51.isVariableStatement(stmt)) {
|
12524 | throw new Error(`Expected VariableStatement, got ${ts51.SyntaxKind[stmt.kind]}`);
|
12525 | }
|
12526 | return stmt.declarationList.declarations[0].initializer;
|
12527 | }
|
12528 |
|
12529 |
|
12530 | var MissingInjectableMigration = class {
|
12531 | apply(clazz, host) {
|
12532 | const decorators = host.reflectionHost.getDecoratorsOfDeclaration(clazz);
|
12533 | if (decorators === null) {
|
12534 | return null;
|
12535 | }
|
12536 | for (const decorator of decorators) {
|
12537 | const name = getAngularCoreDecoratorName(decorator);
|
12538 | if (name === "NgModule") {
|
12539 | migrateNgModuleProviders(decorator, host);
|
12540 | } else if (name === "Directive") {
|
12541 | migrateDirectiveProviders(decorator, host, false);
|
12542 | } else if (name === "Component") {
|
12543 | migrateDirectiveProviders(decorator, host, true);
|
12544 | }
|
12545 | }
|
12546 | return null;
|
12547 | }
|
12548 | };
|
12549 | function migrateNgModuleProviders(decorator, host) {
|
12550 | if (decorator.args === null || decorator.args.length !== 1) {
|
12551 | return;
|
12552 | }
|
12553 | const metadata = host.evaluator.evaluate(decorator.args[0], forwardRefResolver);
|
12554 | if (!(metadata instanceof Map)) {
|
12555 | return;
|
12556 | }
|
12557 | migrateProviders(metadata, "providers", host);
|
12558 | }
|
12559 | function migrateDirectiveProviders(decorator, host, isComponent) {
|
12560 | if (decorator.args === null || decorator.args.length !== 1) {
|
12561 | return;
|
12562 | }
|
12563 | const metadata = host.evaluator.evaluate(decorator.args[0], forwardRefResolver);
|
12564 | if (!(metadata instanceof Map)) {
|
12565 | return;
|
12566 | }
|
12567 | migrateProviders(metadata, "providers", host);
|
12568 | if (isComponent) {
|
12569 | migrateProviders(metadata, "viewProviders", host);
|
12570 | }
|
12571 | }
|
12572 | function migrateProviders(metadata, field, host) {
|
12573 | if (!metadata.has(field)) {
|
12574 | return;
|
12575 | }
|
12576 | const providers = metadata.get(field);
|
12577 | if (!Array.isArray(providers)) {
|
12578 | return;
|
12579 | }
|
12580 | for (const provider of providers) {
|
12581 | migrateProvider(provider, host);
|
12582 | }
|
12583 | }
|
12584 | function migrateProvider(provider, host) {
|
12585 | if (provider instanceof Map) {
|
12586 | if (!provider.has("provide") || provider.has("useValue") || provider.has("useFactory") || provider.has("useExisting")) {
|
12587 | return;
|
12588 | }
|
12589 | if (provider.has("useClass")) {
|
12590 | if (!provider.has("deps")) {
|
12591 | migrateProviderClass(provider.get("useClass"), host);
|
12592 | }
|
12593 | } else {
|
12594 | migrateProviderClass(provider.get("provide"), host);
|
12595 | }
|
12596 | } else if (Array.isArray(provider)) {
|
12597 | for (const v of provider) {
|
12598 | migrateProvider(v, host);
|
12599 | }
|
12600 | } else {
|
12601 | migrateProviderClass(provider, host);
|
12602 | }
|
12603 | }
|
12604 | function migrateProviderClass(provider, host) {
|
12605 | if (!(provider instanceof Reference)) {
|
12606 | return;
|
12607 | }
|
12608 | const clazz = provider.node;
|
12609 | if (isClassDeclaration(clazz) && host.isInScope(clazz) && needsInjectableDecorator(clazz, host)) {
|
12610 | host.injectSyntheticDecorator(clazz, createInjectableDecorator(clazz));
|
12611 | }
|
12612 | }
|
12613 | var NO_MIGRATE_DECORATORS = new Set(["Injectable", "Directive", "Component", "Pipe"]);
|
12614 | function needsInjectableDecorator(clazz, host) {
|
12615 | const decorators = host.getAllDecorators(clazz);
|
12616 | if (decorators === null) {
|
12617 | return true;
|
12618 | }
|
12619 | for (const decorator of decorators) {
|
12620 | const name = getAngularCoreDecoratorName(decorator);
|
12621 | if (name !== null && NO_MIGRATE_DECORATORS.has(name)) {
|
12622 | return false;
|
12623 | }
|
12624 | }
|
12625 | return true;
|
12626 | }
|
12627 | function getAngularCoreDecoratorName(decorator) {
|
12628 | if (decorator.import === null || decorator.import.from !== "@angular/core") {
|
12629 | return null;
|
12630 | }
|
12631 | return decorator.import.name;
|
12632 | }
|
12633 |
|
12634 |
|
12635 | var UndecoratedChildMigration = class {
|
12636 | apply(clazz, host) {
|
12637 | const moduleMeta = host.metadata.getNgModuleMetadata(new Reference(clazz));
|
12638 | if (moduleMeta === null) {
|
12639 | return null;
|
12640 | }
|
12641 | for (const decl of moduleMeta.declarations) {
|
12642 | this.maybeMigrate(decl, host);
|
12643 | }
|
12644 | return null;
|
12645 | }
|
12646 | maybeMigrate(ref, host) {
|
12647 | if (hasDirectiveDecorator(host, ref.node) || hasPipeDecorator(host, ref.node)) {
|
12648 | return;
|
12649 | }
|
12650 | const baseRef = readBaseClass2(ref.node, host.reflectionHost, host.evaluator);
|
12651 | if (baseRef === null) {
|
12652 | return;
|
12653 | } else if (baseRef === "dynamic") {
|
12654 | return;
|
12655 | }
|
12656 | this.maybeMigrate(baseRef, host);
|
12657 | const baseMeta = host.metadata.getDirectiveMetadata(baseRef);
|
12658 | if (baseMeta === null) {
|
12659 | return;
|
12660 | }
|
12661 | if (baseMeta.isComponent) {
|
12662 | host.injectSyntheticDecorator(ref.node, createComponentDecorator(ref.node, baseMeta), HandlerFlags.FULL_INHERITANCE);
|
12663 | } else {
|
12664 | host.injectSyntheticDecorator(ref.node, createDirectiveDecorator(ref.node, baseMeta), HandlerFlags.FULL_INHERITANCE);
|
12665 | }
|
12666 | }
|
12667 | };
|
12668 |
|
12669 |
|
12670 | var UndecoratedParentMigration = class {
|
12671 | apply(clazz, host) {
|
12672 | if (!hasDirectiveDecorator(host, clazz) || hasConstructor(host, clazz)) {
|
12673 | return null;
|
12674 | }
|
12675 | let baseClazzRef = determineBaseClass(clazz, host);
|
12676 | while (baseClazzRef !== null) {
|
12677 | const baseClazz = baseClazzRef.node;
|
12678 | if (hasDirectiveDecorator(host, baseClazz) || !host.isInScope(baseClazz)) {
|
12679 | break;
|
12680 | }
|
12681 | host.injectSyntheticDecorator(baseClazz, createDirectiveDecorator(baseClazz));
|
12682 | if (hasConstructor(host, baseClazz)) {
|
12683 | break;
|
12684 | }
|
12685 | baseClazzRef = determineBaseClass(baseClazz, host);
|
12686 | }
|
12687 | return null;
|
12688 | }
|
12689 | };
|
12690 | function determineBaseClass(clazz, host) {
|
12691 | const baseClassExpr = host.reflectionHost.getBaseClassExpression(clazz);
|
12692 | if (baseClassExpr === null) {
|
12693 | return null;
|
12694 | }
|
12695 | const baseClass = host.evaluator.evaluate(baseClassExpr);
|
12696 | if (!(baseClass instanceof Reference) || !isClassDeclaration(baseClass.node)) {
|
12697 | return null;
|
12698 | }
|
12699 | return baseClass;
|
12700 | }
|
12701 |
|
12702 |
|
12703 | import ts52 from "typescript";
|
12704 | var DefaultMigrationHost = class {
|
12705 | constructor(reflectionHost, metadata, evaluator, compiler, entryPointPath) {
|
12706 | this.reflectionHost = reflectionHost;
|
12707 | this.metadata = metadata;
|
12708 | this.evaluator = evaluator;
|
12709 | this.compiler = compiler;
|
12710 | this.entryPointPath = entryPointPath;
|
12711 | }
|
12712 | injectSyntheticDecorator(clazz, decorator, flags) {
|
12713 | const migratedTraits = this.compiler.injectSyntheticDecorator(clazz, decorator, flags);
|
12714 | for (const trait of migratedTraits) {
|
12715 | if ((trait.state === TraitState.Analyzed || trait.state === TraitState.Resolved) && trait.analysisDiagnostics !== null) {
|
12716 | trait.analysisDiagnostics = trait.analysisDiagnostics.map((diag) => createMigrationDiagnostic(diag, clazz, decorator));
|
12717 | }
|
12718 | if (trait.state === TraitState.Resolved && trait.resolveDiagnostics !== null) {
|
12719 | trait.resolveDiagnostics = trait.resolveDiagnostics.map((diag) => createMigrationDiagnostic(diag, clazz, decorator));
|
12720 | }
|
12721 | }
|
12722 | }
|
12723 | getAllDecorators(clazz) {
|
12724 | return this.compiler.getAllDecorators(clazz);
|
12725 | }
|
12726 | isInScope(clazz) {
|
12727 | return isWithinPackage(this.entryPointPath, absoluteFromSourceFile(clazz.getSourceFile()));
|
12728 | }
|
12729 | };
|
12730 | function createMigrationDiagnostic(diagnostic, source, decorator) {
|
12731 | const clone = __spreadValues({}, diagnostic);
|
12732 | const chain = [{
|
12733 | messageText: `Occurs for @${decorator.name} decorator inserted by an automatic migration`,
|
12734 | category: ts52.DiagnosticCategory.Message,
|
12735 | code: 0
|
12736 | }];
|
12737 | if (decorator.args !== null) {
|
12738 | const args = decorator.args.map((arg) => arg.getText()).join(", ");
|
12739 | chain.push({
|
12740 | messageText: `@${decorator.name}(${args})`,
|
12741 | category: ts52.DiagnosticCategory.Message,
|
12742 | code: 0
|
12743 | });
|
12744 | }
|
12745 | if (typeof clone.messageText === "string") {
|
12746 | clone.messageText = {
|
12747 | messageText: clone.messageText,
|
12748 | category: diagnostic.category,
|
12749 | code: diagnostic.code,
|
12750 | next: chain
|
12751 | };
|
12752 | } else {
|
12753 | if (clone.messageText.next === void 0) {
|
12754 | clone.messageText.next = chain;
|
12755 | } else {
|
12756 | clone.messageText.next.push(...chain);
|
12757 | }
|
12758 | }
|
12759 | return clone;
|
12760 | }
|
12761 |
|
12762 |
|
12763 | var NgccTraitCompiler = class extends TraitCompiler {
|
12764 | constructor(handlers, ngccReflector) {
|
12765 | super(handlers, ngccReflector, NOOP_PERF_RECORDER, new NoIncrementalBuild(), true, CompilationMode.FULL, new DtsTransformRegistry(), null);
|
12766 | this.ngccReflector = ngccReflector;
|
12767 | }
|
12768 | get analyzedFiles() {
|
12769 | return Array.from(this.fileToClasses.keys());
|
12770 | }
|
12771 | analyzeFile(sf) {
|
12772 | const ngccClassSymbols = this.ngccReflector.findClassSymbols(sf);
|
12773 | for (const classSymbol of ngccClassSymbols) {
|
12774 | this.analyzeClass(classSymbol.declaration.valueDeclaration, null);
|
12775 | }
|
12776 | return void 0;
|
12777 | }
|
12778 | injectSyntheticDecorator(clazz, decorator, flags) {
|
12779 | const migratedTraits = this.detectTraits(clazz, [decorator]);
|
12780 | if (migratedTraits === null) {
|
12781 | return [];
|
12782 | }
|
12783 | for (const trait of migratedTraits) {
|
12784 | this.analyzeTrait(clazz, trait, flags);
|
12785 | }
|
12786 | return migratedTraits;
|
12787 | }
|
12788 | getAllDecorators(clazz) {
|
12789 | const record = this.recordFor(clazz);
|
12790 | if (record === null) {
|
12791 | return null;
|
12792 | }
|
12793 | return record.traits.map((trait) => trait.detected.decorator).filter(isDefined);
|
12794 | }
|
12795 | };
|
12796 | var NoIncrementalBuild = class {
|
12797 | priorAnalysisFor(sf) {
|
12798 | return null;
|
12799 | }
|
12800 | priorTypeCheckingResultsFor() {
|
12801 | return null;
|
12802 | }
|
12803 | recordSuccessfulTypeCheck() {
|
12804 | }
|
12805 | };
|
12806 |
|
12807 |
|
12808 | var DecorationAnalyses = Map;
|
12809 |
|
12810 |
|
12811 | var NgccResourceLoader = class {
|
12812 | constructor(fs5) {
|
12813 | this.fs = fs5;
|
12814 | this.canPreload = false;
|
12815 | this.canPreprocess = false;
|
12816 | }
|
12817 | preload() {
|
12818 | throw new Error("Not implemented.");
|
12819 | }
|
12820 | preprocessInline() {
|
12821 | throw new Error("Not implemented.");
|
12822 | }
|
12823 | load(url) {
|
12824 | return this.fs.readFile(this.fs.resolve(url));
|
12825 | }
|
12826 | resolve(url, containingFile) {
|
12827 | return this.fs.resolve(this.fs.dirname(containingFile), url);
|
12828 | }
|
12829 | };
|
12830 | var DecorationAnalyzer = class {
|
12831 | constructor(fs5, bundle, reflectionHost, referencesRegistry, diagnosticHandler = () => {
|
12832 | }, tsConfig = null) {
|
12833 | this.fs = fs5;
|
12834 | this.bundle = bundle;
|
12835 | this.reflectionHost = reflectionHost;
|
12836 | this.referencesRegistry = referencesRegistry;
|
12837 | this.diagnosticHandler = diagnosticHandler;
|
12838 | this.tsConfig = tsConfig;
|
12839 | this.program = this.bundle.src.program;
|
12840 | this.options = this.bundle.src.options;
|
12841 | this.host = this.bundle.src.host;
|
12842 | this.typeChecker = this.bundle.src.program.getTypeChecker();
|
12843 | this.rootDirs = this.bundle.rootDirs;
|
12844 | this.packagePath = this.bundle.entryPoint.packagePath;
|
12845 | this.isCore = this.bundle.isCore;
|
12846 | this.compilerOptions = this.tsConfig !== null ? this.tsConfig.options : {};
|
12847 | this.moduleResolver = new ModuleResolver2(this.program, this.options, this.host, null);
|
12848 | this.resourceManager = new NgccResourceLoader(this.fs);
|
12849 | this.metaRegistry = new LocalMetadataRegistry();
|
12850 | this.dtsMetaReader = new DtsMetadataReader(this.typeChecker, this.reflectionHost);
|
12851 | this.fullMetaReader = new CompoundMetadataReader([this.metaRegistry, this.dtsMetaReader]);
|
12852 | this.refEmitter = new ReferenceEmitter([
|
12853 | new LocalIdentifierStrategy(),
|
12854 | new AbsoluteModuleStrategy(this.program, this.typeChecker, this.moduleResolver, this.reflectionHost),
|
12855 | new LogicalProjectStrategy(this.reflectionHost, new LogicalFileSystem(this.rootDirs, this.host))
|
12856 | ]);
|
12857 | this.aliasingHost = this.bundle.entryPoint.generateDeepReexports ? new PrivateExportAliasingHost(this.reflectionHost) : null;
|
12858 | this.dtsModuleScopeResolver = new MetadataDtsModuleScopeResolver(this.dtsMetaReader, this.aliasingHost);
|
12859 | this.scopeRegistry = new LocalModuleScopeRegistry(this.metaRegistry, this.dtsModuleScopeResolver, this.refEmitter, this.aliasingHost);
|
12860 | this.fullRegistry = new CompoundMetadataRegistry([this.metaRegistry, this.scopeRegistry]);
|
12861 | this.evaluator = new PartialEvaluator(this.reflectionHost, this.typeChecker, null);
|
12862 | this.importGraph = new ImportGraph(this.typeChecker, NOOP_PERF_RECORDER);
|
12863 | this.cycleAnalyzer = new CycleAnalyzer(this.importGraph);
|
12864 | this.injectableRegistry = new InjectableClassRegistry(this.reflectionHost);
|
12865 | this.typeCheckScopeRegistry = new TypeCheckScopeRegistry(this.scopeRegistry, this.fullMetaReader);
|
12866 | this.handlers = [
|
12867 | new ComponentDecoratorHandler(this.reflectionHost, this.evaluator, this.fullRegistry, this.fullMetaReader, this.scopeRegistry, this.scopeRegistry, this.typeCheckScopeRegistry, new ResourceRegistry(), this.isCore, this.resourceManager, this.rootDirs, !!this.compilerOptions.preserveWhitespaces, true, this.bundle.enableI18nLegacyMessageIdFormat, false, false, this.moduleResolver, this.cycleAnalyzer, 0, this.refEmitter, NOOP_DEPENDENCY_TRACKER, this.injectableRegistry, null, !!this.compilerOptions.annotateForClosureCompiler, NOOP_PERF_RECORDER),
|
12868 | new DirectiveDecoratorHandler(this.reflectionHost, this.evaluator, this.fullRegistry, this.scopeRegistry, this.fullMetaReader, this.injectableRegistry, this.isCore, null, !!this.compilerOptions.annotateForClosureCompiler, true, NOOP_PERF_RECORDER),
|
12869 | new PipeDecoratorHandler(this.reflectionHost, this.evaluator, this.metaRegistry, this.scopeRegistry, this.injectableRegistry, this.isCore, NOOP_PERF_RECORDER),
|
12870 | new InjectableDecoratorHandler(this.reflectionHost, this.isCore, false, this.injectableRegistry, NOOP_PERF_RECORDER, false),
|
12871 | new NgModuleDecoratorHandler(this.reflectionHost, this.evaluator, this.fullMetaReader, this.fullRegistry, this.scopeRegistry, this.referencesRegistry, this.isCore, this.refEmitter, null, !!this.compilerOptions.annotateForClosureCompiler, this.injectableRegistry, NOOP_PERF_RECORDER)
|
12872 | ];
|
12873 | this.compiler = new NgccTraitCompiler(this.handlers, this.reflectionHost);
|
12874 | this.migrations = [
|
12875 | new UndecoratedParentMigration(),
|
12876 | new UndecoratedChildMigration(),
|
12877 | new MissingInjectableMigration()
|
12878 | ];
|
12879 | }
|
12880 | analyzeProgram() {
|
12881 | for (const sourceFile of this.program.getSourceFiles()) {
|
12882 | if (!sourceFile.isDeclarationFile && isWithinPackage(this.packagePath, absoluteFromSourceFile(sourceFile))) {
|
12883 | this.compiler.analyzeFile(sourceFile);
|
12884 | }
|
12885 | }
|
12886 | this.applyMigrations();
|
12887 | this.compiler.resolve();
|
12888 | this.reportDiagnostics();
|
12889 | const decorationAnalyses = new DecorationAnalyses();
|
12890 | for (const analyzedFile of this.compiler.analyzedFiles) {
|
12891 | const compiledFile = this.compileFile(analyzedFile);
|
12892 | decorationAnalyses.set(compiledFile.sourceFile, compiledFile);
|
12893 | }
|
12894 | return decorationAnalyses;
|
12895 | }
|
12896 | applyMigrations() {
|
12897 | const migrationHost = new DefaultMigrationHost(this.reflectionHost, this.fullMetaReader, this.evaluator, this.compiler, this.bundle.entryPoint.path);
|
12898 | this.migrations.forEach((migration) => {
|
12899 | this.compiler.analyzedFiles.forEach((analyzedFile) => {
|
12900 | const records = this.compiler.recordsFor(analyzedFile);
|
12901 | if (records === null) {
|
12902 | throw new Error("Assertion error: file to migrate must have records.");
|
12903 | }
|
12904 | records.forEach((record) => {
|
12905 | const addDiagnostic = (diagnostic) => {
|
12906 | if (record.metaDiagnostics === null) {
|
12907 | record.metaDiagnostics = [];
|
12908 | }
|
12909 | record.metaDiagnostics.push(diagnostic);
|
12910 | };
|
12911 | try {
|
12912 | const result = migration.apply(record.node, migrationHost);
|
12913 | if (result !== null) {
|
12914 | addDiagnostic(result);
|
12915 | }
|
12916 | } catch (e) {
|
12917 | if (isFatalDiagnosticError(e)) {
|
12918 | addDiagnostic(e.toDiagnostic());
|
12919 | } else {
|
12920 | throw e;
|
12921 | }
|
12922 | }
|
12923 | });
|
12924 | });
|
12925 | });
|
12926 | }
|
12927 | reportDiagnostics() {
|
12928 | this.compiler.diagnostics.forEach(this.diagnosticHandler);
|
12929 | }
|
12930 | compileFile(sourceFile) {
|
12931 | const constantPool = new ConstantPool2();
|
12932 | const records = this.compiler.recordsFor(sourceFile);
|
12933 | if (records === null) {
|
12934 | throw new Error("Assertion error: file to compile must have records.");
|
12935 | }
|
12936 | const compiledClasses = [];
|
12937 | for (const record of records) {
|
12938 | const compilation = this.compiler.compile(record.node, constantPool);
|
12939 | if (compilation === null) {
|
12940 | continue;
|
12941 | }
|
12942 | compiledClasses.push({
|
12943 | name: record.node.name.text,
|
12944 | decorators: this.compiler.getAllDecorators(record.node),
|
12945 | declaration: record.node,
|
12946 | compilation
|
12947 | });
|
12948 | }
|
12949 | const reexports = this.getReexportsForSourceFile(sourceFile);
|
12950 | return { constantPool, sourceFile, compiledClasses, reexports };
|
12951 | }
|
12952 | getReexportsForSourceFile(sf) {
|
12953 | const exportStatements = this.compiler.exportStatements;
|
12954 | if (!exportStatements.has(sf.fileName)) {
|
12955 | return [];
|
12956 | }
|
12957 | const exports = exportStatements.get(sf.fileName);
|
12958 | const reexports = [];
|
12959 | exports.forEach(([fromModule, symbolName], asAlias) => {
|
12960 | reexports.push({ asAlias, fromModule, symbolName });
|
12961 | });
|
12962 | return reexports;
|
12963 | }
|
12964 | };
|
12965 |
|
12966 |
|
12967 | import ts53 from "typescript";
|
12968 | var ModuleWithProvidersAnalyses = Map;
|
12969 | var ModuleWithProvidersAnalyzer = class {
|
12970 | constructor(host, typeChecker, referencesRegistry, processDts) {
|
12971 | this.host = host;
|
12972 | this.typeChecker = typeChecker;
|
12973 | this.referencesRegistry = referencesRegistry;
|
12974 | this.processDts = processDts;
|
12975 | this.evaluator = new PartialEvaluator(this.host, this.typeChecker, null);
|
12976 | }
|
12977 | analyzeProgram(program) {
|
12978 | const analyses = new ModuleWithProvidersAnalyses();
|
12979 | const rootFiles = this.getRootFiles(program);
|
12980 | rootFiles.forEach((f) => {
|
12981 | const fns = this.getModuleWithProvidersFunctions(f);
|
12982 | fns && fns.forEach((fn) => {
|
12983 | if (fn.ngModule.bestGuessOwningModule === null) {
|
12984 | this.referencesRegistry.add(fn.ngModule.node, new Reference(fn.ngModule.node));
|
12985 | }
|
12986 | if (this.processDts) {
|
12987 | const dtsFn = this.getDtsModuleWithProvidersFunction(fn);
|
12988 | const dtsFnType = dtsFn.declaration.type;
|
12989 | const typeParam = dtsFnType && ts53.isTypeReferenceNode(dtsFnType) && dtsFnType.typeArguments && dtsFnType.typeArguments[0] || null;
|
12990 | if (!typeParam || isAnyKeyword(typeParam)) {
|
12991 | const dtsFile = dtsFn.declaration.getSourceFile();
|
12992 | const analysis = analyses.has(dtsFile) ? analyses.get(dtsFile) : [];
|
12993 | analysis.push(dtsFn);
|
12994 | analyses.set(dtsFile, analysis);
|
12995 | }
|
12996 | }
|
12997 | });
|
12998 | });
|
12999 | return analyses;
|
13000 | }
|
13001 | getRootFiles(program) {
|
13002 | return program.getRootFileNames().map((f) => program.getSourceFile(f)).filter(isDefined);
|
13003 | }
|
13004 | getModuleWithProvidersFunctions(f) {
|
13005 | const exports = this.host.getExportsOfModule(f);
|
13006 | if (!exports)
|
13007 | return [];
|
13008 | const infos = [];
|
13009 | exports.forEach((declaration) => {
|
13010 | if (declaration.node === null) {
|
13011 | return;
|
13012 | }
|
13013 | if (this.host.isClass(declaration.node)) {
|
13014 | this.host.getMembersOfClass(declaration.node).forEach((member) => {
|
13015 | if (member.isStatic) {
|
13016 | const info = this.parseForModuleWithProviders(member.name, member.node, member.implementation, declaration.node);
|
13017 | if (info) {
|
13018 | infos.push(info);
|
13019 | }
|
13020 | }
|
13021 | });
|
13022 | } else {
|
13023 | if (hasNameIdentifier(declaration.node)) {
|
13024 | const info = this.parseForModuleWithProviders(declaration.node.name.text, declaration.node);
|
13025 | if (info) {
|
13026 | infos.push(info);
|
13027 | }
|
13028 | }
|
13029 | }
|
13030 | });
|
13031 | return infos;
|
13032 | }
|
13033 | parseForModuleWithProviders(name, node, implementation = node, container = null) {
|
13034 | if (implementation === null || !ts53.isFunctionDeclaration(implementation) && !ts53.isMethodDeclaration(implementation) && !ts53.isFunctionExpression(implementation)) {
|
13035 | return null;
|
13036 | }
|
13037 | const declaration = implementation;
|
13038 | const definition = this.host.getDefinitionOfFunction(declaration);
|
13039 | if (definition === null) {
|
13040 | return null;
|
13041 | }
|
13042 | const body = definition.body;
|
13043 | if (body === null || body.length === 0) {
|
13044 | return null;
|
13045 | }
|
13046 | const lastStatement = body[body.length - 1];
|
13047 | if (!ts53.isReturnStatement(lastStatement) || lastStatement.expression === void 0) {
|
13048 | return null;
|
13049 | }
|
13050 | const result = this.evaluator.evaluate(lastStatement.expression);
|
13051 | if (!(result instanceof Map) || !result.has("ngModule")) {
|
13052 | return null;
|
13053 | }
|
13054 | const ngModuleRef = result.get("ngModule");
|
13055 | if (!(ngModuleRef instanceof Reference)) {
|
13056 | return null;
|
13057 | }
|
13058 | if (!isNamedClassDeclaration(ngModuleRef.node) && !isNamedVariableDeclaration(ngModuleRef.node)) {
|
13059 | throw new Error(`The identity given by ${ngModuleRef.debugName} referenced in "${declaration.getText()}" doesn't appear to be a "class" declaration.`);
|
13060 | }
|
13061 | const ngModule = ngModuleRef;
|
13062 | return { name, ngModule, declaration, container };
|
13063 | }
|
13064 | getDtsModuleWithProvidersFunction(fn) {
|
13065 | let dtsFn = null;
|
13066 | const containerClass = fn.container && this.host.getClassSymbol(fn.container);
|
13067 | if (containerClass) {
|
13068 | const dtsClass = this.host.getDtsDeclaration(containerClass.declaration.valueDeclaration);
|
13069 | dtsFn = dtsClass && ts53.isClassDeclaration(dtsClass) ? dtsClass.members.find((member) => ts53.isMethodDeclaration(member) && ts53.isIdentifier(member.name) && member.name.text === fn.name) : null;
|
13070 | } else {
|
13071 | dtsFn = this.host.getDtsDeclaration(fn.declaration);
|
13072 | }
|
13073 | if (!dtsFn) {
|
13074 | throw new Error(`Matching type declaration for ${fn.declaration.getText()} is missing`);
|
13075 | }
|
13076 | if (!isFunctionOrMethod(dtsFn)) {
|
13077 | throw new Error(`Matching type declaration for ${fn.declaration.getText()} is not a function: ${dtsFn.getText()}`);
|
13078 | }
|
13079 | const container = containerClass ? containerClass.declaration.valueDeclaration : null;
|
13080 | const ngModule = this.resolveNgModuleReference(fn);
|
13081 | return { name: fn.name, container, declaration: dtsFn, ngModule };
|
13082 | }
|
13083 | resolveNgModuleReference(fn) {
|
13084 | const ngModule = fn.ngModule;
|
13085 | if (ngModule.bestGuessOwningModule !== null) {
|
13086 | return ngModule;
|
13087 | }
|
13088 | const dtsNgModule = this.host.getDtsDeclaration(ngModule.node);
|
13089 | if (!dtsNgModule) {
|
13090 | throw new Error(`No typings declaration can be found for the referenced NgModule class in ${fn.declaration.getText()}.`);
|
13091 | }
|
13092 | if (!isNamedClassDeclaration(dtsNgModule)) {
|
13093 | throw new Error(`The referenced NgModule in ${fn.declaration.getText()} is not a named class declaration in the typings program; instead we get ${dtsNgModule.getText()}`);
|
13094 | }
|
13095 | return new Reference(dtsNgModule, null);
|
13096 | }
|
13097 | };
|
13098 | function isFunctionOrMethod(declaration) {
|
13099 | return ts53.isFunctionDeclaration(declaration) || ts53.isMethodDeclaration(declaration);
|
13100 | }
|
13101 | function isAnyKeyword(typeParam) {
|
13102 | return typeParam.kind === ts53.SyntaxKind.AnyKeyword;
|
13103 | }
|
13104 |
|
13105 |
|
13106 | var NgccReferencesRegistry = class {
|
13107 | constructor(host) {
|
13108 | this.host = host;
|
13109 | this.map = new Map();
|
13110 | }
|
13111 | add(source, ...references) {
|
13112 | references.forEach((ref) => {
|
13113 | if (ref.bestGuessOwningModule === null && hasNameIdentifier(ref.node)) {
|
13114 | const declaration = this.host.getDeclarationOfIdentifier(ref.node.name);
|
13115 | if (declaration && hasNameIdentifier(declaration.node)) {
|
13116 | this.map.set(declaration.node.name, declaration);
|
13117 | }
|
13118 | }
|
13119 | });
|
13120 | }
|
13121 | getDeclarationMap() {
|
13122 | return this.map;
|
13123 | }
|
13124 | };
|
13125 |
|
13126 |
|
13127 | var PrivateDeclarationsAnalyzer = class {
|
13128 | constructor(host, referencesRegistry) {
|
13129 | this.host = host;
|
13130 | this.referencesRegistry = referencesRegistry;
|
13131 | }
|
13132 | analyzeProgram(program) {
|
13133 | const rootFiles = this.getRootFiles(program);
|
13134 | return this.getPrivateDeclarations(rootFiles, this.referencesRegistry.getDeclarationMap());
|
13135 | }
|
13136 | getRootFiles(program) {
|
13137 | return program.getRootFileNames().map((f) => program.getSourceFile(f)).filter(isDefined);
|
13138 | }
|
13139 | getPrivateDeclarations(rootFiles, declarations) {
|
13140 | const privateDeclarations = new Map(declarations);
|
13141 | rootFiles.forEach((f) => {
|
13142 | const exports = this.host.getExportsOfModule(f);
|
13143 | if (exports) {
|
13144 | exports.forEach((declaration, exportedName) => {
|
13145 | if (declaration.node !== null && hasNameIdentifier(declaration.node)) {
|
13146 | if (privateDeclarations.has(declaration.node.name)) {
|
13147 | const privateDeclaration = privateDeclarations.get(declaration.node.name);
|
13148 | if (privateDeclaration.node !== declaration.node) {
|
13149 | throw new Error(`${declaration.node.name.text} is declared multiple times.`);
|
13150 | }
|
13151 | privateDeclarations.delete(declaration.node.name);
|
13152 | }
|
13153 | }
|
13154 | });
|
13155 | }
|
13156 | });
|
13157 | return Array.from(privateDeclarations.keys()).map((id) => {
|
13158 | const from = absoluteFromSourceFile(id.getSourceFile());
|
13159 | const declaration = privateDeclarations.get(id);
|
13160 | const dtsDeclaration = this.host.getDtsDeclaration(declaration.node);
|
13161 | const dtsFrom = dtsDeclaration && absoluteFromSourceFile(dtsDeclaration.getSourceFile());
|
13162 | return { identifier: id.text, from, dtsFrom };
|
13163 | });
|
13164 | }
|
13165 | };
|
13166 |
|
13167 |
|
13168 | import ts54 from "typescript";
|
13169 | var CommonJsReflectionHost = class extends Esm5ReflectionHost {
|
13170 | constructor(logger, isCore, src, dts = null) {
|
13171 | super(logger, isCore, src, dts);
|
13172 | this.commonJsExports = new FactoryMap((sf) => this.computeExportsOfCommonJsModule(sf));
|
13173 | this.topLevelHelperCalls = new FactoryMap((helperName) => new FactoryMap((sf) => sf.statements.map((stmt) => this.getHelperCall(stmt, [helperName])).filter(isDefined)));
|
13174 | this.program = src.program;
|
13175 | this.compilerHost = src.host;
|
13176 | }
|
13177 | getImportOfIdentifier(id) {
|
13178 | const requireCall = this.findCommonJsImport(id);
|
13179 | if (requireCall === null) {
|
13180 | return null;
|
13181 | }
|
13182 | return { from: requireCall.arguments[0].text, name: id.text };
|
13183 | }
|
13184 | getDeclarationOfIdentifier(id) {
|
13185 | return this.getCommonJsModuleDeclaration(id) || super.getDeclarationOfIdentifier(id);
|
13186 | }
|
13187 | getExportsOfModule(module7) {
|
13188 | return super.getExportsOfModule(module7) || this.commonJsExports.get(module7.getSourceFile());
|
13189 | }
|
13190 | getHelperCallsForClass(classSymbol, helperNames) {
|
13191 | const esm5HelperCalls = super.getHelperCallsForClass(classSymbol, helperNames);
|
13192 | if (esm5HelperCalls.length > 0) {
|
13193 | return esm5HelperCalls;
|
13194 | } else {
|
13195 | const sourceFile = classSymbol.declaration.valueDeclaration.getSourceFile();
|
13196 | return this.getTopLevelHelperCalls(sourceFile, helperNames);
|
13197 | }
|
13198 | }
|
13199 | getTopLevelHelperCalls(sourceFile, helperNames) {
|
13200 | const calls = [];
|
13201 | helperNames.forEach((helperName) => {
|
13202 | const helperCallsMap = this.topLevelHelperCalls.get(helperName);
|
13203 | calls.push(...helperCallsMap.get(sourceFile));
|
13204 | });
|
13205 | return calls;
|
13206 | }
|
13207 | computeExportsOfCommonJsModule(sourceFile) {
|
13208 | const moduleMap = new Map();
|
13209 | for (const statement of this.getModuleStatements(sourceFile)) {
|
13210 | if (isExportsStatement(statement)) {
|
13211 | const exportDeclaration = this.extractBasicCommonJsExportDeclaration(statement);
|
13212 | moduleMap.set(exportDeclaration.name, exportDeclaration.declaration);
|
13213 | } else if (isWildcardReexportStatement(statement)) {
|
13214 | const reexports = this.extractCommonJsWildcardReexports(statement, sourceFile);
|
13215 | for (const reexport of reexports) {
|
13216 | moduleMap.set(reexport.name, reexport.declaration);
|
13217 | }
|
13218 | } else if (isDefinePropertyReexportStatement(statement)) {
|
13219 | const exportDeclaration = this.extractCommonJsDefinePropertyExportDeclaration(statement);
|
13220 | if (exportDeclaration !== null) {
|
13221 | moduleMap.set(exportDeclaration.name, exportDeclaration.declaration);
|
13222 | }
|
13223 | }
|
13224 | }
|
13225 | return moduleMap;
|
13226 | }
|
13227 | extractBasicCommonJsExportDeclaration(statement) {
|
13228 | var _a;
|
13229 | const exportExpression = skipAliases(statement.expression.right);
|
13230 | const node = statement.expression.left;
|
13231 | const declaration = (_a = this.getDeclarationOfExpression(exportExpression)) != null ? _a : {
|
13232 | kind: 1,
|
13233 | node,
|
13234 | implementation: exportExpression,
|
13235 | known: null,
|
13236 | viaModule: null
|
13237 | };
|
13238 | return { name: node.name.text, declaration };
|
13239 | }
|
13240 | extractCommonJsWildcardReexports(statement, containingFile) {
|
13241 | const reexportArg = statement.expression.arguments[0];
|
13242 | const requireCall = isRequireCall(reexportArg) ? reexportArg : ts54.isIdentifier(reexportArg) ? findRequireCallReference(reexportArg, this.checker) : null;
|
13243 | if (requireCall === null) {
|
13244 | return [];
|
13245 | }
|
13246 | const importPath = requireCall.arguments[0].text;
|
13247 | const importedFile = this.resolveModuleName(importPath, containingFile);
|
13248 | if (importedFile === void 0) {
|
13249 | return [];
|
13250 | }
|
13251 | const importedExports = this.getExportsOfModule(importedFile);
|
13252 | if (importedExports === null) {
|
13253 | return [];
|
13254 | }
|
13255 | const viaModule = isExternalImport(importPath) ? importPath : null;
|
13256 | const reexports = [];
|
13257 | importedExports.forEach((declaration, name) => {
|
13258 | if (viaModule !== null && declaration.viaModule === null) {
|
13259 | declaration = __spreadProps(__spreadValues({}, declaration), { viaModule });
|
13260 | }
|
13261 | reexports.push({ name, declaration });
|
13262 | });
|
13263 | return reexports;
|
13264 | }
|
13265 | extractCommonJsDefinePropertyExportDeclaration(statement) {
|
13266 | const args = statement.expression.arguments;
|
13267 | const name = args[1].text;
|
13268 | const getterFnExpression = extractGetterFnExpression(statement);
|
13269 | if (getterFnExpression === null) {
|
13270 | return null;
|
13271 | }
|
13272 | const declaration = this.getDeclarationOfExpression(getterFnExpression);
|
13273 | if (declaration !== null) {
|
13274 | return { name, declaration };
|
13275 | }
|
13276 | return {
|
13277 | name,
|
13278 | declaration: {
|
13279 | kind: 1,
|
13280 | node: args[1],
|
13281 | implementation: getterFnExpression,
|
13282 | known: null,
|
13283 | viaModule: null
|
13284 | }
|
13285 | };
|
13286 | }
|
13287 | findCommonJsImport(id) {
|
13288 | const nsIdentifier = findNamespaceOfIdentifier(id);
|
13289 | return nsIdentifier && findRequireCallReference(nsIdentifier, this.checker);
|
13290 | }
|
13291 | getCommonJsModuleDeclaration(id) {
|
13292 | const requireCall = findRequireCallReference(id, this.checker);
|
13293 | if (requireCall === null) {
|
13294 | return null;
|
13295 | }
|
13296 | const importPath = requireCall.arguments[0].text;
|
13297 | const module7 = this.resolveModuleName(importPath, id.getSourceFile());
|
13298 | if (module7 === void 0) {
|
13299 | return null;
|
13300 | }
|
13301 | const viaModule = isExternalImport(importPath) ? importPath : null;
|
13302 | return { node: module7, known: null, viaModule, identity: null, kind: 0 };
|
13303 | }
|
13304 | getDeclarationOfExpression(expression) {
|
13305 | const inner = getInnerClassDeclaration(expression);
|
13306 | if (inner !== null) {
|
13307 | const outer = getOuterNodeFromInnerDeclaration(inner);
|
13308 | if (outer !== null && isExportsAssignment(outer)) {
|
13309 | return {
|
13310 | kind: 1,
|
13311 | node: outer.left,
|
13312 | implementation: inner,
|
13313 | known: null,
|
13314 | viaModule: null
|
13315 | };
|
13316 | }
|
13317 | }
|
13318 | return super.getDeclarationOfExpression(expression);
|
13319 | }
|
13320 | resolveModuleName(moduleName, containingFile) {
|
13321 | if (this.compilerHost.resolveModuleNames) {
|
13322 | const moduleInfo = this.compilerHost.resolveModuleNames([moduleName], containingFile.fileName, void 0, void 0, this.program.getCompilerOptions())[0];
|
13323 | return moduleInfo && this.program.getSourceFile(absoluteFrom(moduleInfo.resolvedFileName));
|
13324 | } else {
|
13325 | const moduleInfo = ts54.resolveModuleName(moduleName, containingFile.fileName, this.program.getCompilerOptions(), this.compilerHost);
|
13326 | return moduleInfo.resolvedModule && this.program.getSourceFile(absoluteFrom(moduleInfo.resolvedModule.resolvedFileName));
|
13327 | }
|
13328 | }
|
13329 | };
|
13330 |
|
13331 |
|
13332 | var DelegatingReflectionHost = class {
|
13333 | constructor(tsHost, ngccHost) {
|
13334 | this.tsHost = tsHost;
|
13335 | this.ngccHost = ngccHost;
|
13336 | }
|
13337 | getConstructorParameters(clazz) {
|
13338 | if (isFromDtsFile(clazz)) {
|
13339 | return this.tsHost.getConstructorParameters(clazz);
|
13340 | }
|
13341 | return this.ngccHost.getConstructorParameters(clazz);
|
13342 | }
|
13343 | getDeclarationOfIdentifier(id) {
|
13344 | if (isFromDtsFile(id)) {
|
13345 | const declaration = this.tsHost.getDeclarationOfIdentifier(id);
|
13346 | return declaration !== null ? this.detectKnownDeclaration(declaration) : null;
|
13347 | }
|
13348 | return this.ngccHost.getDeclarationOfIdentifier(id);
|
13349 | }
|
13350 | getDecoratorsOfDeclaration(declaration) {
|
13351 | if (isFromDtsFile(declaration)) {
|
13352 | return this.tsHost.getDecoratorsOfDeclaration(declaration);
|
13353 | }
|
13354 | return this.ngccHost.getDecoratorsOfDeclaration(declaration);
|
13355 | }
|
13356 | getDefinitionOfFunction(fn) {
|
13357 | if (isFromDtsFile(fn)) {
|
13358 | return this.tsHost.getDefinitionOfFunction(fn);
|
13359 | }
|
13360 | return this.ngccHost.getDefinitionOfFunction(fn);
|
13361 | }
|
13362 | getDtsDeclaration(declaration) {
|
13363 | if (isFromDtsFile(declaration)) {
|
13364 | return this.tsHost.getDtsDeclaration(declaration);
|
13365 | }
|
13366 | return this.ngccHost.getDtsDeclaration(declaration);
|
13367 | }
|
13368 | getExportsOfModule(module7) {
|
13369 | if (isFromDtsFile(module7)) {
|
13370 | const exportMap = this.tsHost.getExportsOfModule(module7);
|
13371 | if (exportMap !== null) {
|
13372 | exportMap.forEach((decl) => this.detectKnownDeclaration(decl));
|
13373 | }
|
13374 | return exportMap;
|
13375 | }
|
13376 | return this.ngccHost.getExportsOfModule(module7);
|
13377 | }
|
13378 | getGenericArityOfClass(clazz) {
|
13379 | if (isFromDtsFile(clazz)) {
|
13380 | return this.tsHost.getGenericArityOfClass(clazz);
|
13381 | }
|
13382 | return this.ngccHost.getGenericArityOfClass(clazz);
|
13383 | }
|
13384 | getImportOfIdentifier(id) {
|
13385 | if (isFromDtsFile(id)) {
|
13386 | return this.tsHost.getImportOfIdentifier(id);
|
13387 | }
|
13388 | return this.ngccHost.getImportOfIdentifier(id);
|
13389 | }
|
13390 | getInternalNameOfClass(clazz) {
|
13391 | if (isFromDtsFile(clazz)) {
|
13392 | return this.tsHost.getInternalNameOfClass(clazz);
|
13393 | }
|
13394 | return this.ngccHost.getInternalNameOfClass(clazz);
|
13395 | }
|
13396 | getAdjacentNameOfClass(clazz) {
|
13397 | if (isFromDtsFile(clazz)) {
|
13398 | return this.tsHost.getAdjacentNameOfClass(clazz);
|
13399 | }
|
13400 | return this.ngccHost.getAdjacentNameOfClass(clazz);
|
13401 | }
|
13402 | getMembersOfClass(clazz) {
|
13403 | if (isFromDtsFile(clazz)) {
|
13404 | return this.tsHost.getMembersOfClass(clazz);
|
13405 | }
|
13406 | return this.ngccHost.getMembersOfClass(clazz);
|
13407 | }
|
13408 | getVariableValue(declaration) {
|
13409 | if (isFromDtsFile(declaration)) {
|
13410 | return this.tsHost.getVariableValue(declaration);
|
13411 | }
|
13412 | return this.ngccHost.getVariableValue(declaration);
|
13413 | }
|
13414 | hasBaseClass(clazz) {
|
13415 | if (isFromDtsFile(clazz)) {
|
13416 | return this.tsHost.hasBaseClass(clazz);
|
13417 | }
|
13418 | return this.ngccHost.hasBaseClass(clazz);
|
13419 | }
|
13420 | getBaseClassExpression(clazz) {
|
13421 | if (isFromDtsFile(clazz)) {
|
13422 | return this.tsHost.getBaseClassExpression(clazz);
|
13423 | }
|
13424 | return this.ngccHost.getBaseClassExpression(clazz);
|
13425 | }
|
13426 | isClass(node) {
|
13427 | if (isFromDtsFile(node)) {
|
13428 | return this.tsHost.isClass(node);
|
13429 | }
|
13430 | return this.ngccHost.isClass(node);
|
13431 | }
|
13432 | findClassSymbols(sourceFile) {
|
13433 | return this.ngccHost.findClassSymbols(sourceFile);
|
13434 | }
|
13435 | getClassSymbol(node) {
|
13436 | return this.ngccHost.getClassSymbol(node);
|
13437 | }
|
13438 | getDecoratorsOfSymbol(symbol) {
|
13439 | return this.ngccHost.getDecoratorsOfSymbol(symbol);
|
13440 | }
|
13441 | getEndOfClass(classSymbol) {
|
13442 | return this.ngccHost.getEndOfClass(classSymbol);
|
13443 | }
|
13444 | detectKnownDeclaration(decl) {
|
13445 | return this.ngccHost.detectKnownDeclaration(decl);
|
13446 | }
|
13447 | isStaticallyExported(decl) {
|
13448 | return this.ngccHost.isStaticallyExported(decl);
|
13449 | }
|
13450 | };
|
13451 |
|
13452 |
|
13453 | import ts57 from "typescript";
|
13454 |
|
13455 |
|
13456 | import ts56 from "typescript";
|
13457 |
|
13458 |
|
13459 | import ts55 from "typescript";
|
13460 |
|
13461 |
|
13462 | var NgccFlatImportRewriter = class {
|
13463 | shouldImportSymbol(symbol, specifier) {
|
13464 | if (specifier === "@angular/core") {
|
13465 | return false;
|
13466 | } else {
|
13467 | return true;
|
13468 | }
|
13469 | }
|
13470 | rewriteSymbol(symbol, specifier) {
|
13471 | if (specifier === "@angular/core") {
|
13472 | return validateAndRewriteCoreSymbol(symbol);
|
13473 | } else {
|
13474 | return symbol;
|
13475 | }
|
13476 | }
|
13477 | rewriteSpecifier(originalModulePath, inContextOfFile) {
|
13478 | return originalModulePath;
|
13479 | }
|
13480 | };
|
13481 |
|
13482 |
|
13483 | function getImportRewriter(r3SymbolsFile, isCore, isFlat) {
|
13484 | if (isCore && isFlat) {
|
13485 | return new NgccFlatImportRewriter();
|
13486 | } else if (isCore) {
|
13487 | return new R3SymbolsImportRewriter(r3SymbolsFile.fileName);
|
13488 | } else {
|
13489 | return new NoopImportRewriter();
|
13490 | }
|
13491 | }
|
13492 | function stripExtension3(filePath) {
|
13493 | return filePath.replace(/\.(js|d\.ts)$/, "");
|
13494 | }
|
13495 |
|
13496 |
|
13497 | var EsmRenderingFormatter = class {
|
13498 | constructor(fs5, host, isCore) {
|
13499 | this.fs = fs5;
|
13500 | this.host = host;
|
13501 | this.isCore = isCore;
|
13502 | this.printer = ts55.createPrinter({ newLine: ts55.NewLineKind.LineFeed });
|
13503 | }
|
13504 | addImports(output, imports, sf) {
|
13505 | if (imports.length === 0) {
|
13506 | return;
|
13507 | }
|
13508 | const insertionPoint = this.findEndOfImports(sf);
|
13509 | const renderedImports = imports.map((i) => `import * as ${i.qualifier.text} from '${i.specifier}';
|
13510 | `).join("");
|
13511 | output.appendLeft(insertionPoint, renderedImports);
|
13512 | }
|
13513 | addExports(output, entryPointBasePath, exports, importManager, file) {
|
13514 | exports.forEach((e) => {
|
13515 | let exportFrom = "";
|
13516 | const isDtsFile = isDtsPath(entryPointBasePath);
|
13517 | const from = isDtsFile ? e.dtsFrom : e.from;
|
13518 | if (from) {
|
13519 | const basePath = stripExtension3(from);
|
13520 | const relativePath = this.fs.relative(this.fs.dirname(entryPointBasePath), basePath);
|
13521 | const relativeImport = toRelativeImport(relativePath);
|
13522 | exportFrom = entryPointBasePath !== basePath ? ` from '${relativeImport}'` : "";
|
13523 | }
|
13524 | const exportStr = `
|
13525 | export {${e.identifier}}${exportFrom};`;
|
13526 | output.append(exportStr);
|
13527 | });
|
13528 | }
|
13529 | addDirectExports(output, exports, importManager, file) {
|
13530 | for (const e of exports) {
|
13531 | const exportStatement = `
|
13532 | export {${e.symbolName} as ${e.asAlias}} from '${e.fromModule}';`;
|
13533 | output.append(exportStatement);
|
13534 | }
|
13535 | }
|
13536 | addConstants(output, constants, file) {
|
13537 | if (constants === "") {
|
13538 | return;
|
13539 | }
|
13540 | const insertionPoint = this.findEndOfImports(file);
|
13541 | output.appendRight(insertionPoint, "\n" + constants + "\n");
|
13542 | }
|
13543 | addDefinitions(output, compiledClass, definitions) {
|
13544 | const classSymbol = this.host.getClassSymbol(compiledClass.declaration);
|
13545 | if (!classSymbol) {
|
13546 | throw new Error(`Compiled class does not have a valid symbol: ${compiledClass.name}`);
|
13547 | }
|
13548 | const declarationStatement = getContainingStatement(classSymbol.implementation.valueDeclaration);
|
13549 | const insertionPoint = declarationStatement.getEnd();
|
13550 | output.appendLeft(insertionPoint, "\n" + definitions);
|
13551 | }
|
13552 | addAdjacentStatements(output, compiledClass, statements) {
|
13553 | const classSymbol = this.host.getClassSymbol(compiledClass.declaration);
|
13554 | if (!classSymbol) {
|
13555 | throw new Error(`Compiled class does not have a valid symbol: ${compiledClass.name}`);
|
13556 | }
|
13557 | const endOfClass = this.host.getEndOfClass(classSymbol);
|
13558 | output.appendLeft(endOfClass.getEnd(), "\n" + statements);
|
13559 | }
|
13560 | removeDecorators(output, decoratorsToRemove) {
|
13561 | decoratorsToRemove.forEach((nodesToRemove, containerNode) => {
|
13562 | if (ts55.isArrayLiteralExpression(containerNode)) {
|
13563 | const items = containerNode.elements;
|
13564 | if (items.length === nodesToRemove.length) {
|
13565 | const statement = findStatement(containerNode);
|
13566 | if (statement) {
|
13567 | if (ts55.isExpressionStatement(statement)) {
|
13568 | output.remove(statement.getFullStart(), statement.getEnd());
|
13569 | } else if (ts55.isReturnStatement(statement) && statement.expression && isAssignment2(statement.expression)) {
|
13570 | const startOfRemoval = statement.expression.left.getEnd();
|
13571 | const endOfRemoval = getEndExceptSemicolon(statement);
|
13572 | output.remove(startOfRemoval, endOfRemoval);
|
13573 | }
|
13574 | }
|
13575 | } else {
|
13576 | nodesToRemove.forEach((node) => {
|
13577 | const nextSibling = getNextSiblingInArray(node, items);
|
13578 | let end;
|
13579 | if (nextSibling !== null && output.slice(nextSibling.getFullStart() - 1, nextSibling.getFullStart()) === ",") {
|
13580 | end = nextSibling.getFullStart() - 1 + nextSibling.getLeadingTriviaWidth();
|
13581 | } else if (output.slice(node.getEnd(), node.getEnd() + 1) === ",") {
|
13582 | end = node.getEnd() + 1;
|
13583 | } else {
|
13584 | end = node.getEnd();
|
13585 | }
|
13586 | output.remove(node.getFullStart(), end);
|
13587 | });
|
13588 | }
|
13589 | }
|
13590 | });
|
13591 | }
|
13592 | addModuleWithProvidersParams(outputText, moduleWithProviders, importManager) {
|
13593 | moduleWithProviders.forEach((info) => {
|
13594 | const ngModuleName = info.ngModule.node.name.text;
|
13595 | const declarationFile = absoluteFromSourceFile(info.declaration.getSourceFile());
|
13596 | const ngModuleFile = absoluteFromSourceFile(info.ngModule.node.getSourceFile());
|
13597 | const relativePath = this.fs.relative(this.fs.dirname(declarationFile), ngModuleFile);
|
13598 | const relativeImport = toRelativeImport(relativePath);
|
13599 | const importPath = info.ngModule.ownedByModuleGuess || (declarationFile !== ngModuleFile ? stripExtension3(relativeImport) : null);
|
13600 | const ngModule = generateImportString(importManager, importPath, ngModuleName);
|
13601 | if (info.declaration.type) {
|
13602 | const typeName = info.declaration.type && ts55.isTypeReferenceNode(info.declaration.type) ? info.declaration.type.typeName : null;
|
13603 | if (this.isCoreModuleWithProvidersType(typeName)) {
|
13604 | outputText.overwrite(info.declaration.type.getStart(), info.declaration.type.getEnd(), `ModuleWithProviders<${ngModule}>`);
|
13605 | } else {
|
13606 | const originalTypeString = info.declaration.type.getText();
|
13607 | outputText.overwrite(info.declaration.type.getStart(), info.declaration.type.getEnd(), `(${originalTypeString})&{ngModule:${ngModule}}`);
|
13608 | }
|
13609 | } else {
|
13610 | const lastToken = info.declaration.getLastToken();
|
13611 | const insertPoint = lastToken && lastToken.kind === ts55.SyntaxKind.SemicolonToken ? lastToken.getStart() : info.declaration.getEnd();
|
13612 | outputText.appendLeft(insertPoint, `: ${generateImportString(importManager, "@angular/core", "ModuleWithProviders")}<${ngModule}>`);
|
13613 | }
|
13614 | });
|
13615 | }
|
13616 | printStatement(stmt, sourceFile, importManager) {
|
13617 | const node = translateStatement(stmt, importManager);
|
13618 | const code = this.printer.printNode(ts55.EmitHint.Unspecified, node, sourceFile);
|
13619 | return code;
|
13620 | }
|
13621 | findEndOfImports(sf) {
|
13622 | for (const stmt of sf.statements) {
|
13623 | if (!ts55.isImportDeclaration(stmt) && !ts55.isImportEqualsDeclaration(stmt) && !ts55.isNamespaceImport(stmt)) {
|
13624 | return stmt.getStart();
|
13625 | }
|
13626 | }
|
13627 | return 0;
|
13628 | }
|
13629 | isCoreModuleWithProvidersType(typeName) {
|
13630 | const id = typeName && ts55.isIdentifier(typeName) ? this.host.getImportOfIdentifier(typeName) : null;
|
13631 | return id && id.name === "ModuleWithProviders" && (this.isCore || id.from === "@angular/core");
|
13632 | }
|
13633 | };
|
13634 | function findStatement(node) {
|
13635 | while (node) {
|
13636 | if (ts55.isExpressionStatement(node) || ts55.isReturnStatement(node)) {
|
13637 | return node;
|
13638 | }
|
13639 | node = node.parent;
|
13640 | }
|
13641 | return void 0;
|
13642 | }
|
13643 | function generateImportString(importManager, importPath, importName) {
|
13644 | const importAs = importPath ? importManager.generateNamedImport(importPath, importName) : null;
|
13645 | return importAs && importAs.moduleImport ? `${importAs.moduleImport.text}.${importAs.symbol}` : `${importName}`;
|
13646 | }
|
13647 | function getNextSiblingInArray(node, array) {
|
13648 | const index = array.indexOf(node);
|
13649 | return index !== -1 && array.length > index + 1 ? array[index + 1] : null;
|
13650 | }
|
13651 | function getEndExceptSemicolon(statement) {
|
13652 | const lastToken = statement.getLastToken();
|
13653 | return lastToken && lastToken.kind === ts55.SyntaxKind.SemicolonToken ? statement.getEnd() - 1 : statement.getEnd();
|
13654 | }
|
13655 |
|
13656 |
|
13657 | var Esm5RenderingFormatter = class extends EsmRenderingFormatter {
|
13658 | addDefinitions(output, compiledClass, definitions) {
|
13659 | const classSymbol = this.host.getClassSymbol(compiledClass.declaration);
|
13660 | if (!classSymbol) {
|
13661 | throw new Error(`Compiled class "${compiledClass.name}" in "${compiledClass.declaration.getSourceFile().fileName}" does not have a valid syntax.
|
13662 | Expected an ES5 IIFE wrapped function. But got:
|
13663 | ` + compiledClass.declaration.getText());
|
13664 | }
|
13665 | const declarationStatement = getContainingStatement(classSymbol.implementation.valueDeclaration);
|
13666 | const iifeBody = declarationStatement.parent;
|
13667 | if (!iifeBody || !ts56.isBlock(iifeBody)) {
|
13668 | throw new Error(`Compiled class declaration is not inside an IIFE: ${compiledClass.name} in ${compiledClass.declaration.getSourceFile().fileName}`);
|
13669 | }
|
13670 | const returnStatement = iifeBody.statements.find(ts56.isReturnStatement);
|
13671 | if (!returnStatement) {
|
13672 | throw new Error(`Compiled class wrapper IIFE does not have a return statement: ${compiledClass.name} in ${compiledClass.declaration.getSourceFile().fileName}`);
|
13673 | }
|
13674 | const insertionPoint = returnStatement.getFullStart();
|
13675 | output.appendLeft(insertionPoint, "\n" + definitions);
|
13676 | }
|
13677 | printStatement(stmt, sourceFile, importManager) {
|
13678 | const node = translateStatement(stmt, importManager, { downlevelTaggedTemplates: true, downlevelVariableDeclarations: true });
|
13679 | const code = this.printer.printNode(ts56.EmitHint.Unspecified, node, sourceFile);
|
13680 | return code;
|
13681 | }
|
13682 | };
|
13683 |
|
13684 |
|
13685 | var CommonJsRenderingFormatter = class extends Esm5RenderingFormatter {
|
13686 | constructor(fs5, commonJsHost, isCore) {
|
13687 | super(fs5, commonJsHost, isCore);
|
13688 | this.commonJsHost = commonJsHost;
|
13689 | }
|
13690 | addImports(output, imports, file) {
|
13691 | if (imports.length === 0) {
|
13692 | return;
|
13693 | }
|
13694 | const insertionPoint = this.findEndOfImports(file);
|
13695 | const renderedImports = imports.map((i) => `var ${i.qualifier.text} = require('${i.specifier}');
|
13696 | `).join("");
|
13697 | output.appendLeft(insertionPoint, renderedImports);
|
13698 | }
|
13699 | addExports(output, entryPointBasePath, exports, importManager, file) {
|
13700 | exports.forEach((e) => {
|
13701 | const basePath = stripExtension3(e.from);
|
13702 | const relativePath = "./" + this.fs.relative(this.fs.dirname(entryPointBasePath), basePath);
|
13703 | const namedImport = entryPointBasePath !== basePath ? importManager.generateNamedImport(relativePath, e.identifier) : { symbol: e.identifier, moduleImport: null };
|
13704 | const importNamespace = namedImport.moduleImport ? `${namedImport.moduleImport.text}.` : "";
|
13705 | const exportStr = `
|
13706 | exports.${e.identifier} = ${importNamespace}${namedImport.symbol};`;
|
13707 | output.append(exportStr);
|
13708 | });
|
13709 | }
|
13710 | addDirectExports(output, exports, importManager, file) {
|
13711 | for (const e of exports) {
|
13712 | const namedImport = importManager.generateNamedImport(e.fromModule, e.symbolName);
|
13713 | const importNamespace = namedImport.moduleImport ? `${namedImport.moduleImport.text}.` : "";
|
13714 | const exportStr = `
|
13715 | exports.${e.asAlias} = ${importNamespace}${namedImport.symbol};`;
|
13716 | output.append(exportStr);
|
13717 | }
|
13718 | }
|
13719 | findEndOfImports(sf) {
|
13720 | for (const statement of sf.statements) {
|
13721 | if (ts57.isExpressionStatement(statement) && isRequireCall(statement.expression)) {
|
13722 | continue;
|
13723 | }
|
13724 | const declarations = ts57.isVariableStatement(statement) ? Array.from(statement.declarationList.declarations) : [];
|
13725 | if (declarations.some((d) => !d.initializer || !isRequireCall(d.initializer))) {
|
13726 | return statement.getStart();
|
13727 | }
|
13728 | }
|
13729 | return 0;
|
13730 | }
|
13731 | };
|
13732 |
|
13733 |
|
13734 | import MagicString from "magic-string";
|
13735 | import ts58 from "typescript";
|
13736 |
|
13737 |
|
13738 | var IMPORT_PREFIX = "\u0275ngcc";
|
13739 | var NGCC_TIMED_OUT_EXIT_CODE = 177;
|
13740 |
|
13741 |
|
13742 | import mapHelpers3 from "convert-source-map";
|
13743 |
|
13744 |
|
13745 | var ContentOrigin;
|
13746 | (function(ContentOrigin2) {
|
13747 | ContentOrigin2[ContentOrigin2["Provided"] = 0] = "Provided";
|
13748 | ContentOrigin2[ContentOrigin2["Inline"] = 1] = "Inline";
|
13749 | ContentOrigin2[ContentOrigin2["FileSystem"] = 2] = "FileSystem";
|
13750 | })(ContentOrigin || (ContentOrigin = {}));
|
13751 |
|
13752 |
|
13753 | import mapHelpers from "convert-source-map";
|
13754 | import { decode, encode } from "sourcemap-codec";
|
13755 |
|
13756 |
|
13757 | function compareSegments(a, b) {
|
13758 | return a.position - b.position;
|
13759 | }
|
13760 | function offsetSegment(startOfLinePositions, marker, offset) {
|
13761 | if (offset === 0) {
|
13762 | return marker;
|
13763 | }
|
13764 | let line = marker.line;
|
13765 | const position = marker.position + offset;
|
13766 | while (line < startOfLinePositions.length - 1 && startOfLinePositions[line + 1] <= position) {
|
13767 | line++;
|
13768 | }
|
13769 | while (line > 0 && startOfLinePositions[line] > position) {
|
13770 | line--;
|
13771 | }
|
13772 | const column = position - startOfLinePositions[line];
|
13773 | return { line, column, position, next: void 0 };
|
13774 | }
|
13775 |
|
13776 |
|
13777 | function removeSourceMapComments(contents) {
|
13778 | return mapHelpers.removeMapFileComments(mapHelpers.removeComments(contents)).replace(/\n\n$/, "\n");
|
13779 | }
|
13780 | var SourceFile = class {
|
13781 | constructor(sourcePath, contents, rawMap, sources, fs5) {
|
13782 | this.sourcePath = sourcePath;
|
13783 | this.contents = contents;
|
13784 | this.rawMap = rawMap;
|
13785 | this.sources = sources;
|
13786 | this.fs = fs5;
|
13787 | this.contents = removeSourceMapComments(contents);
|
13788 | this.startOfLinePositions = computeStartOfLinePositions(this.contents);
|
13789 | this.flattenedMappings = this.flattenMappings();
|
13790 | }
|
13791 | renderFlattenedSourceMap() {
|
13792 | const sources = new IndexedMap();
|
13793 | const names = new IndexedSet();
|
13794 | const mappings = [];
|
13795 | const sourcePathDir = this.fs.dirname(this.sourcePath);
|
13796 | const relativeSourcePathCache = new Cache((input) => this.fs.relative(sourcePathDir, input));
|
13797 | for (const mapping of this.flattenedMappings) {
|
13798 | const sourceIndex = sources.set(relativeSourcePathCache.get(mapping.originalSource.sourcePath), mapping.originalSource.contents);
|
13799 | const mappingArray = [
|
13800 | mapping.generatedSegment.column,
|
13801 | sourceIndex,
|
13802 | mapping.originalSegment.line,
|
13803 | mapping.originalSegment.column
|
13804 | ];
|
13805 | if (mapping.name !== void 0) {
|
13806 | const nameIndex = names.add(mapping.name);
|
13807 | mappingArray.push(nameIndex);
|
13808 | }
|
13809 | const line = mapping.generatedSegment.line;
|
13810 | while (line >= mappings.length) {
|
13811 | mappings.push([]);
|
13812 | }
|
13813 | mappings[line].push(mappingArray);
|
13814 | }
|
13815 | const sourceMap = {
|
13816 | version: 3,
|
13817 | file: this.fs.relative(sourcePathDir, this.sourcePath),
|
13818 | sources: sources.keys,
|
13819 | names: names.values,
|
13820 | mappings: encode(mappings),
|
13821 | sourcesContent: sources.values
|
13822 | };
|
13823 | return sourceMap;
|
13824 | }
|
13825 | getOriginalLocation(line, column) {
|
13826 | if (this.flattenedMappings.length === 0) {
|
13827 | return null;
|
13828 | }
|
13829 | let position;
|
13830 | if (line < this.startOfLinePositions.length) {
|
13831 | position = this.startOfLinePositions[line] + column;
|
13832 | } else {
|
13833 | position = this.contents.length;
|
13834 | }
|
13835 | const locationSegment = { line, column, position, next: void 0 };
|
13836 | let mappingIndex = findLastMappingIndexBefore(this.flattenedMappings, locationSegment, false, 0);
|
13837 | if (mappingIndex < 0) {
|
13838 | mappingIndex = 0;
|
13839 | }
|
13840 | const { originalSegment, originalSource, generatedSegment } = this.flattenedMappings[mappingIndex];
|
13841 | const offset = locationSegment.position - generatedSegment.position;
|
13842 | const offsetOriginalSegment = offsetSegment(originalSource.startOfLinePositions, originalSegment, offset);
|
13843 | return {
|
13844 | file: originalSource.sourcePath,
|
13845 | line: offsetOriginalSegment.line,
|
13846 | column: offsetOriginalSegment.column
|
13847 | };
|
13848 | }
|
13849 | flattenMappings() {
|
13850 | const mappings = parseMappings(this.rawMap && this.rawMap.map, this.sources, this.startOfLinePositions);
|
13851 | ensureOriginalSegmentLinks(mappings);
|
13852 | const flattenedMappings = [];
|
13853 | for (let mappingIndex = 0; mappingIndex < mappings.length; mappingIndex++) {
|
13854 | const aToBmapping = mappings[mappingIndex];
|
13855 | const bSource = aToBmapping.originalSource;
|
13856 | if (bSource.flattenedMappings.length === 0) {
|
13857 | flattenedMappings.push(aToBmapping);
|
13858 | continue;
|
13859 | }
|
13860 | const incomingStart = aToBmapping.originalSegment;
|
13861 | const incomingEnd = incomingStart.next;
|
13862 | let outgoingStartIndex = findLastMappingIndexBefore(bSource.flattenedMappings, incomingStart, false, 0);
|
13863 | if (outgoingStartIndex < 0) {
|
13864 | outgoingStartIndex = 0;
|
13865 | }
|
13866 | const outgoingEndIndex = incomingEnd !== void 0 ? findLastMappingIndexBefore(bSource.flattenedMappings, incomingEnd, true, outgoingStartIndex) : bSource.flattenedMappings.length - 1;
|
13867 | for (let bToCmappingIndex = outgoingStartIndex; bToCmappingIndex <= outgoingEndIndex; bToCmappingIndex++) {
|
13868 | const bToCmapping = bSource.flattenedMappings[bToCmappingIndex];
|
13869 | flattenedMappings.push(mergeMappings(this, aToBmapping, bToCmapping));
|
13870 | }
|
13871 | }
|
13872 | return flattenedMappings;
|
13873 | }
|
13874 | };
|
13875 | function findLastMappingIndexBefore(mappings, marker, exclusive, lowerIndex) {
|
13876 | let upperIndex = mappings.length - 1;
|
13877 | const test = exclusive ? -1 : 0;
|
13878 | if (compareSegments(mappings[lowerIndex].generatedSegment, marker) > test) {
|
13879 | return -1;
|
13880 | }
|
13881 | let matchingIndex = -1;
|
13882 | while (lowerIndex <= upperIndex) {
|
13883 | const index = upperIndex + lowerIndex >> 1;
|
13884 | if (compareSegments(mappings[index].generatedSegment, marker) <= test) {
|
13885 | matchingIndex = index;
|
13886 | lowerIndex = index + 1;
|
13887 | } else {
|
13888 | upperIndex = index - 1;
|
13889 | }
|
13890 | }
|
13891 | return matchingIndex;
|
13892 | }
|
13893 | function mergeMappings(generatedSource, ab, bc) {
|
13894 | const name = bc.name || ab.name;
|
13895 | const diff = compareSegments(bc.generatedSegment, ab.originalSegment);
|
13896 | if (diff > 0) {
|
13897 | return {
|
13898 | name,
|
13899 | generatedSegment: offsetSegment(generatedSource.startOfLinePositions, ab.generatedSegment, diff),
|
13900 | originalSource: bc.originalSource,
|
13901 | originalSegment: bc.originalSegment
|
13902 | };
|
13903 | } else {
|
13904 | return {
|
13905 | name,
|
13906 | generatedSegment: ab.generatedSegment,
|
13907 | originalSource: bc.originalSource,
|
13908 | originalSegment: offsetSegment(bc.originalSource.startOfLinePositions, bc.originalSegment, -diff)
|
13909 | };
|
13910 | }
|
13911 | }
|
13912 | function parseMappings(rawMap, sources, generatedSourceStartOfLinePositions) {
|
13913 | if (rawMap === null) {
|
13914 | return [];
|
13915 | }
|
13916 | const rawMappings = decode(rawMap.mappings);
|
13917 | if (rawMappings === null) {
|
13918 | return [];
|
13919 | }
|
13920 | const mappings = [];
|
13921 | for (let generatedLine = 0; generatedLine < rawMappings.length; generatedLine++) {
|
13922 | const generatedLineMappings = rawMappings[generatedLine];
|
13923 | for (const rawMapping of generatedLineMappings) {
|
13924 | if (rawMapping.length >= 4) {
|
13925 | const originalSource = sources[rawMapping[1]];
|
13926 | if (originalSource === null || originalSource === void 0) {
|
13927 | continue;
|
13928 | }
|
13929 | const generatedColumn = rawMapping[0];
|
13930 | const name = rawMapping.length === 5 ? rawMap.names[rawMapping[4]] : void 0;
|
13931 | const line = rawMapping[2];
|
13932 | const column = rawMapping[3];
|
13933 | const generatedSegment = {
|
13934 | line: generatedLine,
|
13935 | column: generatedColumn,
|
13936 | position: generatedSourceStartOfLinePositions[generatedLine] + generatedColumn,
|
13937 | next: void 0
|
13938 | };
|
13939 | const originalSegment = {
|
13940 | line,
|
13941 | column,
|
13942 | position: originalSource.startOfLinePositions[line] + column,
|
13943 | next: void 0
|
13944 | };
|
13945 | mappings.push({ name, generatedSegment, originalSegment, originalSource });
|
13946 | }
|
13947 | }
|
13948 | }
|
13949 | return mappings;
|
13950 | }
|
13951 | function extractOriginalSegments(mappings) {
|
13952 | const originalSegments = new Map();
|
13953 | for (const mapping of mappings) {
|
13954 | const originalSource = mapping.originalSource;
|
13955 | if (!originalSegments.has(originalSource)) {
|
13956 | originalSegments.set(originalSource, []);
|
13957 | }
|
13958 | const segments = originalSegments.get(originalSource);
|
13959 | segments.push(mapping.originalSegment);
|
13960 | }
|
13961 | originalSegments.forEach((segmentMarkers) => segmentMarkers.sort(compareSegments));
|
13962 | return originalSegments;
|
13963 | }
|
13964 | function ensureOriginalSegmentLinks(mappings) {
|
13965 | const segmentsBySource = extractOriginalSegments(mappings);
|
13966 | segmentsBySource.forEach((markers) => {
|
13967 | for (let i = 0; i < markers.length - 1; i++) {
|
13968 | markers[i].next = markers[i + 1];
|
13969 | }
|
13970 | });
|
13971 | }
|
13972 | function computeStartOfLinePositions(str) {
|
13973 | const NEWLINE_MARKER_OFFSET = 1;
|
13974 | const lineLengths = computeLineLengths(str);
|
13975 | const startPositions = [0];
|
13976 | for (let i = 0; i < lineLengths.length - 1; i++) {
|
13977 | startPositions.push(startPositions[i] + lineLengths[i] + NEWLINE_MARKER_OFFSET);
|
13978 | }
|
13979 | return startPositions;
|
13980 | }
|
13981 | function computeLineLengths(str) {
|
13982 | return str.split(/\n/).map((s) => s.length);
|
13983 | }
|
13984 | var IndexedMap = class {
|
13985 | constructor() {
|
13986 | this.map = new Map();
|
13987 | this.keys = [];
|
13988 | this.values = [];
|
13989 | }
|
13990 | set(key, value) {
|
13991 | if (this.map.has(key)) {
|
13992 | return this.map.get(key);
|
13993 | }
|
13994 | const index = this.values.push(value) - 1;
|
13995 | this.keys.push(key);
|
13996 | this.map.set(key, index);
|
13997 | return index;
|
13998 | }
|
13999 | };
|
14000 | var IndexedSet = class {
|
14001 | constructor() {
|
14002 | this.map = new Map();
|
14003 | this.values = [];
|
14004 | }
|
14005 | add(value) {
|
14006 | if (this.map.has(value)) {
|
14007 | return this.map.get(value);
|
14008 | }
|
14009 | const index = this.values.push(value) - 1;
|
14010 | this.map.set(value, index);
|
14011 | return index;
|
14012 | }
|
14013 | };
|
14014 | var Cache = class {
|
14015 | constructor(computeFn) {
|
14016 | this.computeFn = computeFn;
|
14017 | this.map = new Map();
|
14018 | }
|
14019 | get(input) {
|
14020 | if (!this.map.has(input)) {
|
14021 | this.map.set(input, this.computeFn(input));
|
14022 | }
|
14023 | return this.map.get(input);
|
14024 | }
|
14025 | };
|
14026 |
|
14027 |
|
14028 | import mapHelpers2 from "convert-source-map";
|
14029 | var SCHEME_MATCHER = /^([a-z][a-z0-9.-]*):\/\//i;
|
14030 | var SourceFileLoader = class {
|
14031 | constructor(fs5, logger, schemeMap) {
|
14032 | this.fs = fs5;
|
14033 | this.logger = logger;
|
14034 | this.schemeMap = schemeMap;
|
14035 | this.currentPaths = [];
|
14036 | }
|
14037 | loadSourceFile(sourcePath, contents = null, mapAndPath = null) {
|
14038 | const contentsOrigin = contents !== null ? ContentOrigin.Provided : ContentOrigin.FileSystem;
|
14039 | const sourceMapInfo = mapAndPath && __spreadValues({ origin: ContentOrigin.Provided }, mapAndPath);
|
14040 | return this.loadSourceFileInternal(sourcePath, contents, contentsOrigin, sourceMapInfo);
|
14041 | }
|
14042 | loadSourceFileInternal(sourcePath, contents, sourceOrigin, sourceMapInfo) {
|
14043 | const previousPaths = this.currentPaths.slice();
|
14044 | try {
|
14045 | if (contents === null) {
|
14046 | if (!this.fs.exists(sourcePath)) {
|
14047 | return null;
|
14048 | }
|
14049 | contents = this.readSourceFile(sourcePath);
|
14050 | }
|
14051 | if (sourceMapInfo === null) {
|
14052 | sourceMapInfo = this.loadSourceMap(sourcePath, contents, sourceOrigin);
|
14053 | }
|
14054 | let sources = [];
|
14055 | if (sourceMapInfo !== null) {
|
14056 | const basePath = sourceMapInfo.mapPath || sourcePath;
|
14057 | sources = this.processSources(basePath, sourceMapInfo);
|
14058 | }
|
14059 | return new SourceFile(sourcePath, contents, sourceMapInfo, sources, this.fs);
|
14060 | } catch (e) {
|
14061 | this.logger.warn(`Unable to fully load ${sourcePath} for source-map flattening: ${e.message}`);
|
14062 | return null;
|
14063 | } finally {
|
14064 | this.currentPaths = previousPaths;
|
14065 | }
|
14066 | }
|
14067 | loadSourceMap(sourcePath, sourceContents, sourceOrigin) {
|
14068 | const lastLine = this.getLastNonEmptyLine(sourceContents);
|
14069 | const inline = mapHelpers2.commentRegex.exec(lastLine);
|
14070 | if (inline !== null) {
|
14071 | return {
|
14072 | map: mapHelpers2.fromComment(inline.pop()).sourcemap,
|
14073 | mapPath: null,
|
14074 | origin: ContentOrigin.Inline
|
14075 | };
|
14076 | }
|
14077 | if (sourceOrigin === ContentOrigin.Inline) {
|
14078 | return null;
|
14079 | }
|
14080 | const external = mapHelpers2.mapFileCommentRegex.exec(lastLine);
|
14081 | if (external) {
|
14082 | try {
|
14083 | const fileName = external[1] || external[2];
|
14084 | const externalMapPath = this.fs.resolve(this.fs.dirname(sourcePath), fileName);
|
14085 | return {
|
14086 | map: this.readRawSourceMap(externalMapPath),
|
14087 | mapPath: externalMapPath,
|
14088 | origin: ContentOrigin.FileSystem
|
14089 | };
|
14090 | } catch (e) {
|
14091 | this.logger.warn(`Unable to fully load ${sourcePath} for source-map flattening: ${e.message}`);
|
14092 | return null;
|
14093 | }
|
14094 | }
|
14095 | const impliedMapPath = this.fs.resolve(sourcePath + ".map");
|
14096 | if (this.fs.exists(impliedMapPath)) {
|
14097 | return {
|
14098 | map: this.readRawSourceMap(impliedMapPath),
|
14099 | mapPath: impliedMapPath,
|
14100 | origin: ContentOrigin.FileSystem
|
14101 | };
|
14102 | }
|
14103 | return null;
|
14104 | }
|
14105 | processSources(basePath, { map, origin: sourceMapOrigin }) {
|
14106 | const sourceRoot = this.fs.resolve(this.fs.dirname(basePath), this.replaceSchemeWithPath(map.sourceRoot || ""));
|
14107 | return map.sources.map((source, index) => {
|
14108 | const path7 = this.fs.resolve(sourceRoot, this.replaceSchemeWithPath(source));
|
14109 | const content = map.sourcesContent && map.sourcesContent[index] || null;
|
14110 | const sourceOrigin = content !== null && sourceMapOrigin !== ContentOrigin.Provided ? ContentOrigin.Inline : ContentOrigin.FileSystem;
|
14111 | return this.loadSourceFileInternal(path7, content, sourceOrigin, null);
|
14112 | });
|
14113 | }
|
14114 | readSourceFile(sourcePath) {
|
14115 | this.trackPath(sourcePath);
|
14116 | return this.fs.readFile(sourcePath);
|
14117 | }
|
14118 | readRawSourceMap(mapPath) {
|
14119 | this.trackPath(mapPath);
|
14120 | return JSON.parse(this.fs.readFile(mapPath));
|
14121 | }
|
14122 | trackPath(path7) {
|
14123 | if (this.currentPaths.includes(path7)) {
|
14124 | throw new Error(`Circular source file mapping dependency: ${this.currentPaths.join(" -> ")} -> ${path7}`);
|
14125 | }
|
14126 | this.currentPaths.push(path7);
|
14127 | }
|
14128 | getLastNonEmptyLine(contents) {
|
14129 | let trailingWhitespaceIndex = contents.length - 1;
|
14130 | while (trailingWhitespaceIndex > 0 && (contents[trailingWhitespaceIndex] === "\n" || contents[trailingWhitespaceIndex] === "\r")) {
|
14131 | trailingWhitespaceIndex--;
|
14132 | }
|
14133 | let lastRealLineIndex = contents.lastIndexOf("\n", trailingWhitespaceIndex - 1);
|
14134 | if (lastRealLineIndex === -1) {
|
14135 | lastRealLineIndex = 0;
|
14136 | }
|
14137 | return contents.substr(lastRealLineIndex + 1);
|
14138 | }
|
14139 | replaceSchemeWithPath(path7) {
|
14140 | return path7.replace(SCHEME_MATCHER, (_, scheme) => this.schemeMap[scheme.toLowerCase()] || "");
|
14141 | }
|
14142 | };
|
14143 |
|
14144 |
|
14145 | function renderSourceAndMap(logger, fs5, sourceFile, generatedMagicString) {
|
14146 | var _a;
|
14147 | const sourceFilePath = absoluteFromSourceFile(sourceFile);
|
14148 | const sourceMapPath = absoluteFrom(`${sourceFilePath}.map`);
|
14149 | const generatedContent = generatedMagicString.toString();
|
14150 | const generatedMap = generatedMagicString.generateMap({ file: sourceFilePath, source: sourceFilePath, includeContent: true });
|
14151 | try {
|
14152 | const loader = new SourceFileLoader(fs5, logger, {});
|
14153 | const generatedFile = loader.loadSourceFile(sourceFilePath, generatedContent, { map: generatedMap, mapPath: sourceMapPath });
|
14154 | const rawMergedMap = generatedFile.renderFlattenedSourceMap();
|
14155 | const mergedMap = mapHelpers3.fromObject(rawMergedMap);
|
14156 | const originalFile = loader.loadSourceFile(sourceFilePath, generatedMagicString.original);
|
14157 | if (originalFile.rawMap === null && !sourceFile.isDeclarationFile || ((_a = originalFile.rawMap) == null ? void 0 : _a.origin) === ContentOrigin.Inline) {
|
14158 | return [
|
14159 | { path: sourceFilePath, contents: `${generatedFile.contents}
|
14160 | ${mergedMap.toComment()}` }
|
14161 | ];
|
14162 | }
|
14163 | const sourceMapComment = mapHelpers3.generateMapFileComment(`${fs5.basename(sourceFilePath)}.map`);
|
14164 | return [
|
14165 | { path: sourceFilePath, contents: `${generatedFile.contents}
|
14166 | ${sourceMapComment}` },
|
14167 | { path: sourceMapPath, contents: mergedMap.toJSON() }
|
14168 | ];
|
14169 | } catch (e) {
|
14170 | logger.error(`Error when flattening the source-map "${sourceMapPath}" for "${sourceFilePath}": ${e.toString()}`);
|
14171 | return [
|
14172 | { path: sourceFilePath, contents: generatedContent },
|
14173 | { path: sourceMapPath, contents: mapHelpers3.fromObject(generatedMap).toJSON() }
|
14174 | ];
|
14175 | }
|
14176 | }
|
14177 |
|
14178 |
|
14179 | var DtsRenderInfo = class {
|
14180 | constructor() {
|
14181 | this.classInfo = [];
|
14182 | this.moduleWithProviders = [];
|
14183 | this.privateExports = [];
|
14184 | this.reexports = [];
|
14185 | }
|
14186 | };
|
14187 | var DtsRenderer = class {
|
14188 | constructor(dtsFormatter, fs5, logger, host, bundle) {
|
14189 | this.dtsFormatter = dtsFormatter;
|
14190 | this.fs = fs5;
|
14191 | this.logger = logger;
|
14192 | this.host = host;
|
14193 | this.bundle = bundle;
|
14194 | }
|
14195 | renderProgram(decorationAnalyses, privateDeclarationsAnalyses, moduleWithProvidersAnalyses) {
|
14196 | const renderedFiles = [];
|
14197 | if (this.bundle.dts) {
|
14198 | const dtsFiles = this.getTypingsFilesToRender(decorationAnalyses, privateDeclarationsAnalyses, moduleWithProvidersAnalyses);
|
14199 | if (!dtsFiles.has(this.bundle.dts.file)) {
|
14200 | dtsFiles.set(this.bundle.dts.file, new DtsRenderInfo());
|
14201 | }
|
14202 | dtsFiles.forEach((renderInfo, file) => renderedFiles.push(...this.renderDtsFile(file, renderInfo)));
|
14203 | }
|
14204 | return renderedFiles;
|
14205 | }
|
14206 | renderDtsFile(dtsFile, renderInfo) {
|
14207 | const outputText = new MagicString(dtsFile.text);
|
14208 | const printer = ts58.createPrinter();
|
14209 | const importManager = new ImportManager(getImportRewriter(this.bundle.dts.r3SymbolsFile, this.bundle.isCore, false), IMPORT_PREFIX);
|
14210 | renderInfo.classInfo.forEach((dtsClass) => {
|
14211 | const endOfClass = dtsClass.dtsDeclaration.getEnd();
|
14212 | dtsClass.compilation.forEach((declaration) => {
|
14213 | const type = translateType(declaration.type, importManager);
|
14214 | markForEmitAsSingleLine2(type);
|
14215 | const typeStr = printer.printNode(ts58.EmitHint.Unspecified, type, dtsFile);
|
14216 | const newStatement = ` static ${declaration.name}: ${typeStr};
|
14217 | `;
|
14218 | outputText.appendRight(endOfClass - 1, newStatement);
|
14219 | });
|
14220 | });
|
14221 | if (renderInfo.reexports.length > 0) {
|
14222 | for (const e of renderInfo.reexports) {
|
14223 | const newStatement = `
|
14224 | export {${e.symbolName} as ${e.asAlias}} from '${e.fromModule}';`;
|
14225 | outputText.append(newStatement);
|
14226 | }
|
14227 | }
|
14228 | this.dtsFormatter.addModuleWithProvidersParams(outputText, renderInfo.moduleWithProviders, importManager);
|
14229 | this.dtsFormatter.addExports(outputText, dtsFile.fileName, renderInfo.privateExports, importManager, dtsFile);
|
14230 | this.dtsFormatter.addImports(outputText, importManager.getAllImports(dtsFile.fileName), dtsFile);
|
14231 | return renderSourceAndMap(this.logger, this.fs, dtsFile, outputText);
|
14232 | }
|
14233 | getTypingsFilesToRender(decorationAnalyses, privateDeclarationsAnalyses, moduleWithProvidersAnalyses) {
|
14234 | const dtsMap = new Map();
|
14235 | decorationAnalyses.forEach((compiledFile) => {
|
14236 | let appliedReexports = false;
|
14237 | compiledFile.compiledClasses.forEach((compiledClass) => {
|
14238 | const dtsDeclaration = this.host.getDtsDeclaration(compiledClass.declaration);
|
14239 | if (dtsDeclaration) {
|
14240 | const dtsFile = dtsDeclaration.getSourceFile();
|
14241 | const renderInfo = dtsMap.has(dtsFile) ? dtsMap.get(dtsFile) : new DtsRenderInfo();
|
14242 | renderInfo.classInfo.push({ dtsDeclaration, compilation: compiledClass.compilation });
|
14243 | if (!appliedReexports && compiledClass.declaration.getSourceFile().fileName === dtsFile.fileName.replace(/\.d\.ts$/, ".js")) {
|
14244 | renderInfo.reexports.push(...compiledFile.reexports);
|
14245 | appliedReexports = true;
|
14246 | }
|
14247 | dtsMap.set(dtsFile, renderInfo);
|
14248 | }
|
14249 | });
|
14250 | });
|
14251 | if (moduleWithProvidersAnalyses !== null) {
|
14252 | moduleWithProvidersAnalyses.forEach((moduleWithProvidersToFix, dtsFile) => {
|
14253 | const renderInfo = dtsMap.has(dtsFile) ? dtsMap.get(dtsFile) : new DtsRenderInfo();
|
14254 | renderInfo.moduleWithProviders = moduleWithProvidersToFix;
|
14255 | dtsMap.set(dtsFile, renderInfo);
|
14256 | });
|
14257 | }
|
14258 | if (privateDeclarationsAnalyses.length) {
|
14259 | privateDeclarationsAnalyses.forEach((e) => {
|
14260 | if (!e.dtsFrom) {
|
14261 | throw new Error(`There is no typings path for ${e.identifier} in ${e.from}.
|
14262 | We need to add an export for this class to a .d.ts typings file because Angular compiler needs to be able to reference this class in compiled code, such as templates.
|
14263 | The simplest fix for this is to ensure that this class is exported from the package's entry-point.`);
|
14264 | }
|
14265 | });
|
14266 | const dtsEntryPoint = this.bundle.dts.file;
|
14267 | const renderInfo = dtsMap.has(dtsEntryPoint) ? dtsMap.get(dtsEntryPoint) : new DtsRenderInfo();
|
14268 | renderInfo.privateExports = privateDeclarationsAnalyses;
|
14269 | dtsMap.set(dtsEntryPoint, renderInfo);
|
14270 | }
|
14271 | return dtsMap;
|
14272 | }
|
14273 | };
|
14274 | function markForEmitAsSingleLine2(node) {
|
14275 | ts58.setEmitFlags(node, ts58.EmitFlags.SingleLine);
|
14276 | ts58.forEachChild(node, markForEmitAsSingleLine2);
|
14277 | }
|
14278 |
|
14279 |
|
14280 | import { jsDocComment, WrappedNodeExpr as WrappedNodeExpr9, WritePropExpr } from "@angular/compiler";
|
14281 | import MagicString2 from "magic-string";
|
14282 |
|
14283 |
|
14284 | var RedundantDecoratorMap = Map;
|
14285 |
|
14286 |
|
14287 | var Renderer = class {
|
14288 | constructor(host, srcFormatter, fs5, logger, bundle, tsConfig = null) {
|
14289 | this.host = host;
|
14290 | this.srcFormatter = srcFormatter;
|
14291 | this.fs = fs5;
|
14292 | this.logger = logger;
|
14293 | this.bundle = bundle;
|
14294 | this.tsConfig = tsConfig;
|
14295 | }
|
14296 | renderProgram(decorationAnalyses, privateDeclarationsAnalyses) {
|
14297 | const renderedFiles = [];
|
14298 | this.bundle.src.program.getSourceFiles().forEach((sourceFile) => {
|
14299 | if (decorationAnalyses.has(sourceFile) || sourceFile === this.bundle.src.file) {
|
14300 | const compiledFile = decorationAnalyses.get(sourceFile);
|
14301 | renderedFiles.push(...this.renderFile(sourceFile, compiledFile, privateDeclarationsAnalyses));
|
14302 | }
|
14303 | });
|
14304 | return renderedFiles;
|
14305 | }
|
14306 | renderFile(sourceFile, compiledFile, privateDeclarationsAnalyses) {
|
14307 | const isEntryPoint2 = sourceFile === this.bundle.src.file;
|
14308 | const outputText = new MagicString2(sourceFile.text);
|
14309 | const importManager = new ImportManager(getImportRewriter(this.bundle.src.r3SymbolsFile, this.bundle.isCore, this.bundle.isFlatCore), IMPORT_PREFIX);
|
14310 | if (compiledFile) {
|
14311 | const decoratorsToRemove = this.computeDecoratorsToRemove(compiledFile.compiledClasses);
|
14312 | this.srcFormatter.removeDecorators(outputText, decoratorsToRemove);
|
14313 | compiledFile.compiledClasses.forEach((clazz) => {
|
14314 | var _a;
|
14315 | const renderedDefinition = this.renderDefinitions(compiledFile.sourceFile, clazz, importManager, !!((_a = this.tsConfig) == null ? void 0 : _a.options.annotateForClosureCompiler));
|
14316 | this.srcFormatter.addDefinitions(outputText, clazz, renderedDefinition);
|
14317 | const renderedStatements = this.renderAdjacentStatements(compiledFile.sourceFile, clazz, importManager);
|
14318 | this.srcFormatter.addAdjacentStatements(outputText, clazz, renderedStatements);
|
14319 | });
|
14320 | if (!isEntryPoint2 && compiledFile.reexports.length > 0) {
|
14321 | this.srcFormatter.addDirectExports(outputText, compiledFile.reexports, importManager, compiledFile.sourceFile);
|
14322 | }
|
14323 | this.srcFormatter.addConstants(outputText, renderConstantPool(this.srcFormatter, compiledFile.sourceFile, compiledFile.constantPool, importManager), compiledFile.sourceFile);
|
14324 | }
|
14325 | if (isEntryPoint2) {
|
14326 | const entryPointBasePath = stripExtension3(this.bundle.src.path);
|
14327 | this.srcFormatter.addExports(outputText, entryPointBasePath, privateDeclarationsAnalyses, importManager, sourceFile);
|
14328 | }
|
14329 | if (isEntryPoint2 || compiledFile) {
|
14330 | this.srcFormatter.addImports(outputText, importManager.getAllImports(sourceFile.fileName), sourceFile);
|
14331 | }
|
14332 | if (compiledFile || isEntryPoint2) {
|
14333 | return renderSourceAndMap(this.logger, this.fs, sourceFile, outputText);
|
14334 | } else {
|
14335 | return [];
|
14336 | }
|
14337 | }
|
14338 | computeDecoratorsToRemove(classes) {
|
14339 | const decoratorsToRemove = new RedundantDecoratorMap();
|
14340 | classes.forEach((clazz) => {
|
14341 | if (clazz.decorators === null) {
|
14342 | return;
|
14343 | }
|
14344 | clazz.decorators.forEach((dec) => {
|
14345 | if (dec.node === null) {
|
14346 | return;
|
14347 | }
|
14348 | const decoratorArray = dec.node.parent;
|
14349 | if (!decoratorsToRemove.has(decoratorArray)) {
|
14350 | decoratorsToRemove.set(decoratorArray, [dec.node]);
|
14351 | } else {
|
14352 | decoratorsToRemove.get(decoratorArray).push(dec.node);
|
14353 | }
|
14354 | });
|
14355 | });
|
14356 | return decoratorsToRemove;
|
14357 | }
|
14358 | renderDefinitions(sourceFile, compiledClass, imports, annotateForClosureCompiler) {
|
14359 | const name = this.host.getInternalNameOfClass(compiledClass.declaration);
|
14360 | const leadingComment = annotateForClosureCompiler ? jsDocComment([{ tagName: "nocollapse" }]) : void 0;
|
14361 | const statements = compiledClass.compilation.map((c) => createAssignmentStatement(name, c.name, c.initializer, leadingComment));
|
14362 | return this.renderStatements(sourceFile, statements, imports);
|
14363 | }
|
14364 | renderAdjacentStatements(sourceFile, compiledClass, imports) {
|
14365 | const statements = [];
|
14366 | for (const c of compiledClass.compilation) {
|
14367 | statements.push(...c.statements);
|
14368 | }
|
14369 | return this.renderStatements(sourceFile, statements, imports);
|
14370 | }
|
14371 | renderStatements(sourceFile, statements, imports) {
|
14372 | const printStatement = (stmt) => this.srcFormatter.printStatement(stmt, sourceFile, imports);
|
14373 | return statements.map(printStatement).join("\n");
|
14374 | }
|
14375 | };
|
14376 | function renderConstantPool(formatter, sourceFile, constantPool, imports) {
|
14377 | const printStatement = (stmt) => formatter.printStatement(stmt, sourceFile, imports);
|
14378 | return constantPool.statements.map(printStatement).join("\n");
|
14379 | }
|
14380 | function createAssignmentStatement(receiverName, propName, initializer, leadingComment) {
|
14381 | const receiver = new WrappedNodeExpr9(receiverName);
|
14382 | const statement = new WritePropExpr(receiver, propName, initializer, void 0, void 0).toStmt();
|
14383 | if (leadingComment !== void 0) {
|
14384 | statement.addLeadingComment(leadingComment);
|
14385 | }
|
14386 | return statement;
|
14387 | }
|
14388 |
|
14389 |
|
14390 | import ts59 from "typescript";
|
14391 | var UmdRenderingFormatter = class extends Esm5RenderingFormatter {
|
14392 | constructor(fs5, umdHost, isCore) {
|
14393 | super(fs5, umdHost, isCore);
|
14394 | this.umdHost = umdHost;
|
14395 | }
|
14396 | addImports(output, imports, file) {
|
14397 | if (imports.length === 0) {
|
14398 | return;
|
14399 | }
|
14400 | const umdModule = this.umdHost.getUmdModule(file);
|
14401 | if (!umdModule) {
|
14402 | return;
|
14403 | }
|
14404 | const { factoryFn, factoryCalls } = umdModule;
|
14405 | renderCommonJsDependencies(output, factoryCalls.commonJs, imports);
|
14406 | renderCommonJsDependencies(output, factoryCalls.commonJs2, imports);
|
14407 | renderAmdDependencies(output, factoryCalls.amdDefine, imports);
|
14408 | renderGlobalDependencies(output, factoryCalls.global, imports);
|
14409 | renderFactoryParameters(output, factoryFn, imports);
|
14410 | }
|
14411 | addExports(output, entryPointBasePath, exports, importManager, file) {
|
14412 | const umdModule = this.umdHost.getUmdModule(file);
|
14413 | if (!umdModule) {
|
14414 | return;
|
14415 | }
|
14416 | const factoryFunction = umdModule.factoryFn;
|
14417 | const lastStatement = factoryFunction.body.statements[factoryFunction.body.statements.length - 1];
|
14418 | const insertionPoint = lastStatement ? lastStatement.getEnd() : factoryFunction.body.getEnd() - 1;
|
14419 | exports.forEach((e) => {
|
14420 | const basePath = stripExtension3(e.from);
|
14421 | const relativePath = "./" + this.fs.relative(this.fs.dirname(entryPointBasePath), basePath);
|
14422 | const namedImport = entryPointBasePath !== basePath ? importManager.generateNamedImport(relativePath, e.identifier) : { symbol: e.identifier, moduleImport: null };
|
14423 | const importNamespace = namedImport.moduleImport ? `${namedImport.moduleImport.text}.` : "";
|
14424 | const exportStr = `
|
14425 | exports.${e.identifier} = ${importNamespace}${namedImport.symbol};`;
|
14426 | output.appendRight(insertionPoint, exportStr);
|
14427 | });
|
14428 | }
|
14429 | addDirectExports(output, exports, importManager, file) {
|
14430 | const umdModule = this.umdHost.getUmdModule(file);
|
14431 | if (!umdModule) {
|
14432 | return;
|
14433 | }
|
14434 | const factoryFunction = umdModule.factoryFn;
|
14435 | const lastStatement = factoryFunction.body.statements[factoryFunction.body.statements.length - 1];
|
14436 | const insertionPoint = lastStatement ? lastStatement.getEnd() : factoryFunction.body.getEnd() - 1;
|
14437 | for (const e of exports) {
|
14438 | const namedImport = importManager.generateNamedImport(e.fromModule, e.symbolName);
|
14439 | const importNamespace = namedImport.moduleImport ? `${namedImport.moduleImport.text}.` : "";
|
14440 | const exportStr = `
|
14441 | exports.${e.asAlias} = ${importNamespace}${namedImport.symbol};`;
|
14442 | output.appendRight(insertionPoint, exportStr);
|
14443 | }
|
14444 | }
|
14445 | addConstants(output, constants, file) {
|
14446 | if (constants === "") {
|
14447 | return;
|
14448 | }
|
14449 | const umdModule = this.umdHost.getUmdModule(file);
|
14450 | if (!umdModule) {
|
14451 | return;
|
14452 | }
|
14453 | const factoryFunction = umdModule.factoryFn;
|
14454 | const firstStatement = factoryFunction.body.statements[0];
|
14455 | const insertionPoint = firstStatement ? firstStatement.getStart() : factoryFunction.body.getStart() + 1;
|
14456 | output.appendLeft(insertionPoint, "\n" + constants + "\n");
|
14457 | }
|
14458 | };
|
14459 | function renderCommonJsDependencies(output, factoryCall, imports) {
|
14460 | if (factoryCall === null) {
|
14461 | return;
|
14462 | }
|
14463 | const injectionPoint = factoryCall.arguments.length > 0 ? factoryCall.arguments[0].getFullStart() : factoryCall.getEnd() - 1;
|
14464 | const importString = imports.map((i) => `require('${i.specifier}')`).join(",");
|
14465 | output.appendLeft(injectionPoint, importString + (factoryCall.arguments.length > 0 ? "," : ""));
|
14466 | }
|
14467 | function renderAmdDependencies(output, amdDefineCall, imports) {
|
14468 | if (amdDefineCall === null) {
|
14469 | return;
|
14470 | }
|
14471 | const importString = imports.map((i) => `'${i.specifier}'`).join(",");
|
14472 | const factoryIndex = amdDefineCall.arguments.length - 1;
|
14473 | const dependencyArray = amdDefineCall.arguments[factoryIndex - 1];
|
14474 | if (dependencyArray === void 0 || !ts59.isArrayLiteralExpression(dependencyArray)) {
|
14475 | const injectionPoint = amdDefineCall.arguments[factoryIndex].getFullStart();
|
14476 | output.appendLeft(injectionPoint, `[${importString}],`);
|
14477 | } else {
|
14478 | const injectionPoint = dependencyArray.elements.length > 0 ? dependencyArray.elements[0].getFullStart() : dependencyArray.getEnd() - 1;
|
14479 | output.appendLeft(injectionPoint, importString + (dependencyArray.elements.length > 0 ? "," : ""));
|
14480 | }
|
14481 | }
|
14482 | function renderGlobalDependencies(output, factoryCall, imports) {
|
14483 | if (factoryCall === null) {
|
14484 | return;
|
14485 | }
|
14486 | const injectionPoint = factoryCall.arguments.length > 0 ? factoryCall.arguments[0].getFullStart() : factoryCall.getEnd() - 1;
|
14487 | const importString = imports.map((i) => `global.${getGlobalIdentifier(i)}`).join(",");
|
14488 | output.appendLeft(injectionPoint, importString + (factoryCall.arguments.length > 0 ? "," : ""));
|
14489 | }
|
14490 | function renderFactoryParameters(output, factoryFunction, imports) {
|
14491 | const parameters = factoryFunction.parameters;
|
14492 | const parameterString = imports.map((i) => i.qualifier.text).join(",");
|
14493 | if (parameters.length > 0) {
|
14494 | const injectionPoint = parameters[0].getFullStart();
|
14495 | output.appendLeft(injectionPoint, parameterString + ",");
|
14496 | } else {
|
14497 | const injectionPoint = factoryFunction.getStart() + factoryFunction.getText().indexOf("()") + 1;
|
14498 | output.appendLeft(injectionPoint, parameterString);
|
14499 | }
|
14500 | }
|
14501 | function getGlobalIdentifier(i) {
|
14502 | return i.specifier.replace(/^@angular\//, "ng.").replace(/^@/, "").replace(/\//g, ".").replace(/[-_]+(.?)/g, (_, c) => c.toUpperCase()).replace(/^./, (c) => c.toLowerCase());
|
14503 | }
|
14504 |
|
14505 |
|
14506 | var Transformer = class {
|
14507 | constructor(fs5, logger, tsConfig = null) {
|
14508 | this.fs = fs5;
|
14509 | this.logger = logger;
|
14510 | this.tsConfig = tsConfig;
|
14511 | }
|
14512 | transform(bundle) {
|
14513 | const ngccReflectionHost = this.getHost(bundle);
|
14514 | const tsReflectionHost = new TypeScriptReflectionHost(bundle.src.program.getTypeChecker());
|
14515 | const reflectionHost = new DelegatingReflectionHost(tsReflectionHost, ngccReflectionHost);
|
14516 | const { decorationAnalyses, privateDeclarationsAnalyses, moduleWithProvidersAnalyses, diagnostics } = this.analyzeProgram(reflectionHost, bundle);
|
14517 | if (hasErrors(diagnostics)) {
|
14518 | return { success: false, diagnostics };
|
14519 | }
|
14520 | let renderedFiles = [];
|
14521 | if (bundle.dtsProcessing !== DtsProcessing.Only) {
|
14522 | const srcFormatter = this.getRenderingFormatter(ngccReflectionHost, bundle);
|
14523 | const renderer = new Renderer(reflectionHost, srcFormatter, this.fs, this.logger, bundle, this.tsConfig);
|
14524 | renderedFiles = renderer.renderProgram(decorationAnalyses, privateDeclarationsAnalyses);
|
14525 | }
|
14526 | if (bundle.dts) {
|
14527 | const dtsFormatter = new EsmRenderingFormatter(this.fs, reflectionHost, bundle.isCore);
|
14528 | const dtsRenderer = new DtsRenderer(dtsFormatter, this.fs, this.logger, reflectionHost, bundle);
|
14529 | const renderedDtsFiles = dtsRenderer.renderProgram(decorationAnalyses, privateDeclarationsAnalyses, moduleWithProvidersAnalyses);
|
14530 | renderedFiles = renderedFiles.concat(renderedDtsFiles);
|
14531 | }
|
14532 | return { success: true, diagnostics, transformedFiles: renderedFiles };
|
14533 | }
|
14534 | getHost(bundle) {
|
14535 | switch (bundle.format) {
|
14536 | case "esm2015":
|
14537 | return new Esm2015ReflectionHost(this.logger, bundle.isCore, bundle.src, bundle.dts);
|
14538 | case "esm5":
|
14539 | return new Esm5ReflectionHost(this.logger, bundle.isCore, bundle.src, bundle.dts);
|
14540 | case "umd":
|
14541 | return new UmdReflectionHost(this.logger, bundle.isCore, bundle.src, bundle.dts);
|
14542 | case "commonjs":
|
14543 | return new CommonJsReflectionHost(this.logger, bundle.isCore, bundle.src, bundle.dts);
|
14544 | default:
|
14545 | throw new Error(`Reflection host for "${bundle.format}" not yet implemented.`);
|
14546 | }
|
14547 | }
|
14548 | getRenderingFormatter(host, bundle) {
|
14549 | switch (bundle.format) {
|
14550 | case "esm2015":
|
14551 | return new EsmRenderingFormatter(this.fs, host, bundle.isCore);
|
14552 | case "esm5":
|
14553 | return new Esm5RenderingFormatter(this.fs, host, bundle.isCore);
|
14554 | case "umd":
|
14555 | if (!(host instanceof UmdReflectionHost)) {
|
14556 | throw new Error("UmdRenderer requires a UmdReflectionHost");
|
14557 | }
|
14558 | return new UmdRenderingFormatter(this.fs, host, bundle.isCore);
|
14559 | case "commonjs":
|
14560 | return new CommonJsRenderingFormatter(this.fs, host, bundle.isCore);
|
14561 | default:
|
14562 | throw new Error(`Renderer for "${bundle.format}" not yet implemented.`);
|
14563 | }
|
14564 | }
|
14565 | analyzeProgram(reflectionHost, bundle) {
|
14566 | const referencesRegistry = new NgccReferencesRegistry(reflectionHost);
|
14567 | const diagnostics = [];
|
14568 | const decorationAnalyzer = new DecorationAnalyzer(this.fs, bundle, reflectionHost, referencesRegistry, (diagnostic) => diagnostics.push(diagnostic), this.tsConfig);
|
14569 | const decorationAnalyses = decorationAnalyzer.analyzeProgram();
|
14570 | const moduleWithProvidersAnalyzer = new ModuleWithProvidersAnalyzer(reflectionHost, bundle.src.program.getTypeChecker(), referencesRegistry, bundle.dts !== null);
|
14571 | const moduleWithProvidersAnalyses = moduleWithProvidersAnalyzer && moduleWithProvidersAnalyzer.analyzeProgram(bundle.src.program);
|
14572 | const privateDeclarationsAnalyzer = new PrivateDeclarationsAnalyzer(reflectionHost, referencesRegistry);
|
14573 | const privateDeclarationsAnalyses = privateDeclarationsAnalyzer.analyzeProgram(bundle.src.program);
|
14574 | return {
|
14575 | decorationAnalyses,
|
14576 | privateDeclarationsAnalyses,
|
14577 | moduleWithProvidersAnalyses,
|
14578 | diagnostics
|
14579 | };
|
14580 | }
|
14581 | };
|
14582 | function hasErrors(diagnostics) {
|
14583 | return diagnostics.some((d) => d.category === ts60.DiagnosticCategory.Error);
|
14584 | }
|
14585 |
|
14586 |
|
14587 | function getCreateCompileFn(fileSystem, logger, fileWriter, enableI18nLegacyMessageIdFormat, tsConfig, pathMappings) {
|
14588 | return (beforeWritingFiles, onTaskCompleted) => {
|
14589 | const transformer = new Transformer(fileSystem, logger, tsConfig);
|
14590 | const sharedFileCache = new SharedFileCache(fileSystem);
|
14591 | const moduleResolutionCache = createModuleResolutionCache(fileSystem);
|
14592 | return (task) => {
|
14593 | const { entryPoint, formatProperty, formatPropertiesToMarkAsProcessed, processDts } = task;
|
14594 | const isCore = entryPoint.name === "@angular/core";
|
14595 | const packageJson = entryPoint.packageJson;
|
14596 | const formatPath = packageJson[formatProperty];
|
14597 | const format = getEntryPointFormat(fileSystem, entryPoint, formatProperty);
|
14598 | if (!formatPath || !format) {
|
14599 | onTaskCompleted(task, 1, `property \`${formatProperty}\` pointing to a missing or empty file: ${formatPath}`);
|
14600 | return;
|
14601 | }
|
14602 | logger.info(`- ${entryPoint.name} [${formatProperty}/${format}] (${entryPoint.repositoryUrl})`);
|
14603 | const bundle = makeEntryPointBundle(fileSystem, entryPoint, sharedFileCache, moduleResolutionCache, formatPath, isCore, format, processDts, pathMappings, true, enableI18nLegacyMessageIdFormat);
|
14604 | const result = transformer.transform(bundle);
|
14605 | if (result.success) {
|
14606 | if (result.diagnostics.length > 0) {
|
14607 | logger.warn(replaceTsWithNgInErrors(ts61.formatDiagnosticsWithColorAndContext(result.diagnostics, bundle.src.host)));
|
14608 | }
|
14609 | const writeBundle = () => {
|
14610 | fileWriter.writeBundle(bundle, result.transformedFiles, formatPropertiesToMarkAsProcessed);
|
14611 | logger.debug(` Successfully compiled ${entryPoint.name} : ${formatProperty}`);
|
14612 | onTaskCompleted(task, 0, null);
|
14613 | };
|
14614 | const beforeWritingResult = beforeWritingFiles(result.transformedFiles);
|
14615 | return beforeWritingResult instanceof Promise ? beforeWritingResult.then(writeBundle) : writeBundle();
|
14616 | } else {
|
14617 | const errors = replaceTsWithNgInErrors(ts61.formatDiagnosticsWithColorAndContext(result.diagnostics, bundle.src.host));
|
14618 | onTaskCompleted(task, 1, `compilation errors:
|
14619 | ${errors}`);
|
14620 | }
|
14621 | };
|
14622 | };
|
14623 | }
|
14624 |
|
14625 |
|
14626 | var SingleProcessorExecutorBase = class {
|
14627 | constructor(logger, createTaskCompletedCallback) {
|
14628 | this.logger = logger;
|
14629 | this.createTaskCompletedCallback = createTaskCompletedCallback;
|
14630 | }
|
14631 | doExecute(analyzeEntryPoints, createCompileFn) {
|
14632 | this.logger.debug(`Running ngcc on ${this.constructor.name}.`);
|
14633 | const taskQueue = analyzeEntryPoints();
|
14634 | const onTaskCompleted = this.createTaskCompletedCallback(taskQueue);
|
14635 | const compile = createCompileFn(() => {
|
14636 | }, onTaskCompleted);
|
14637 | this.logger.debug("Processing tasks...");
|
14638 | const startTime = Date.now();
|
14639 | while (!taskQueue.allTasksCompleted) {
|
14640 | const task = taskQueue.getNextTask();
|
14641 | compile(task);
|
14642 | taskQueue.markAsCompleted(task);
|
14643 | }
|
14644 | const duration = Math.round((Date.now() - startTime) / 1e3);
|
14645 | this.logger.debug(`Processed tasks in ${duration}s.`);
|
14646 | }
|
14647 | };
|
14648 | var SingleProcessExecutorSync = class extends SingleProcessorExecutorBase {
|
14649 | constructor(logger, lockFile, createTaskCompletedCallback) {
|
14650 | super(logger, createTaskCompletedCallback);
|
14651 | this.lockFile = lockFile;
|
14652 | }
|
14653 | execute(analyzeEntryPoints, createCompileFn) {
|
14654 | this.lockFile.lock(() => this.doExecute(analyzeEntryPoints, createCompileFn));
|
14655 | }
|
14656 | };
|
14657 | var SingleProcessExecutorAsync = class extends SingleProcessorExecutorBase {
|
14658 | constructor(logger, lockFile, createTaskCompletedCallback) {
|
14659 | super(logger, createTaskCompletedCallback);
|
14660 | this.lockFile = lockFile;
|
14661 | }
|
14662 | async execute(analyzeEntryPoints, createCompileFn) {
|
14663 | await this.lockFile.lock(async () => this.doExecute(analyzeEntryPoints, createCompileFn));
|
14664 | }
|
14665 | };
|
14666 |
|
14667 |
|
14668 | function composeTaskCompletedCallbacks(callbacks) {
|
14669 | return (task, outcome, message) => {
|
14670 | const callback = callbacks[outcome];
|
14671 | if (callback === void 0) {
|
14672 | throw new Error(`Unknown task outcome: "${outcome}" - supported outcomes: ${JSON.stringify(Object.keys(callbacks))}`);
|
14673 | }
|
14674 | callback(task, message);
|
14675 | };
|
14676 | }
|
14677 | function createMarkAsProcessedHandler(fs5, pkgJsonUpdater) {
|
14678 | return (task) => {
|
14679 | const { entryPoint, formatPropertiesToMarkAsProcessed, processDts } = task;
|
14680 | const packageJsonPath = fs5.resolve(entryPoint.path, "package.json");
|
14681 | const propsToMarkAsProcessed = [...formatPropertiesToMarkAsProcessed];
|
14682 | if (processDts !== DtsProcessing.No) {
|
14683 | propsToMarkAsProcessed.push("typings");
|
14684 | }
|
14685 | markAsProcessed(pkgJsonUpdater, entryPoint.packageJson, packageJsonPath, propsToMarkAsProcessed);
|
14686 | };
|
14687 | }
|
14688 | function createThrowErrorHandler(fs5) {
|
14689 | return (task, message) => {
|
14690 | throw new Error(createErrorMessage(fs5, task, message));
|
14691 | };
|
14692 | }
|
14693 | function createLogErrorHandler(logger, fs5, taskQueue) {
|
14694 | return (task, message) => {
|
14695 | taskQueue.markAsFailed(task);
|
14696 | logger.error(createErrorMessage(fs5, task, message));
|
14697 | };
|
14698 | }
|
14699 | function createErrorMessage(fs5, task, message) {
|
14700 | var _a;
|
14701 | const jsFormat = `\`${task.formatProperty}\` as ${(_a = getEntryPointFormat(fs5, task.entryPoint, task.formatProperty)) != null ? _a : "unknown format"}`;
|
14702 | const format = task.typingsOnly ? `typings only using ${jsFormat}` : jsFormat;
|
14703 | message = message !== null ? ` due to ${message}` : "";
|
14704 | return `Failed to compile entry-point ${task.entryPoint.name} (${format})` + message;
|
14705 | }
|
14706 |
|
14707 |
|
14708 | var TimeoutError = class extends Error {
|
14709 | constructor() {
|
14710 | super(...arguments);
|
14711 | this.code = NGCC_TIMED_OUT_EXIT_CODE;
|
14712 | }
|
14713 | };
|
14714 | var AsyncLocker = class {
|
14715 | constructor(lockFile, logger, retryDelay, retryAttempts) {
|
14716 | this.lockFile = lockFile;
|
14717 | this.logger = logger;
|
14718 | this.retryDelay = retryDelay;
|
14719 | this.retryAttempts = retryAttempts;
|
14720 | }
|
14721 | async lock(fn) {
|
14722 | await this.create();
|
14723 | try {
|
14724 | return await fn();
|
14725 | } finally {
|
14726 | this.lockFile.remove();
|
14727 | }
|
14728 | }
|
14729 | async create() {
|
14730 | let pid = "";
|
14731 | for (let attempts = 0; attempts < this.retryAttempts; attempts++) {
|
14732 | try {
|
14733 | return this.lockFile.write();
|
14734 | } catch (e) {
|
14735 | if (e.code !== "EEXIST") {
|
14736 | throw e;
|
14737 | }
|
14738 | const newPid = this.lockFile.read();
|
14739 | if (newPid !== pid) {
|
14740 | attempts = 0;
|
14741 | pid = newPid;
|
14742 | }
|
14743 | if (attempts === 0) {
|
14744 | this.logger.info(`Another process, with id ${pid}, is currently running ngcc.
|
14745 | Waiting up to ${this.retryDelay * this.retryAttempts / 1e3}s for it to finish.
|
14746 | (If you are sure no ngcc process is running then you should delete the lock-file at ${this.lockFile.path}.)`);
|
14747 | }
|
14748 | await new Promise((resolve5) => setTimeout(resolve5, this.retryDelay));
|
14749 | }
|
14750 | }
|
14751 | throw new TimeoutError(`Timed out waiting ${this.retryAttempts * this.retryDelay / 1e3}s for another ngcc process, with id ${pid}, to complete.
|
14752 | (If you are sure no ngcc process is running then you should delete the lock-file at ${this.lockFile.path}.)`);
|
14753 | }
|
14754 | };
|
14755 |
|
14756 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/ngcc/src/locking/lock_file_with_child_process/index.mjs
|
14757 | import { fork } from "child_process";
|
14758 | import module5 from "module";
|
14759 |
|
14760 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/logging/src/logger.mjs
|
14761 | var LogLevel;
|
14762 | (function(LogLevel2) {
|
14763 | LogLevel2[LogLevel2["debug"] = 0] = "debug";
|
14764 | LogLevel2[LogLevel2["info"] = 1] = "info";
|
14765 | LogLevel2[LogLevel2["warn"] = 2] = "warn";
|
14766 | LogLevel2[LogLevel2["error"] = 3] = "error";
|
14767 | })(LogLevel || (LogLevel = {}));
|
14768 |
|
14769 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/logging/src/console_logger.mjs
|
14770 | var RESET = "[0m";
|
14771 | var RED = "[31m";
|
14772 | var YELLOW = "[33m";
|
14773 | var BLUE = "[36m";
|
14774 | var DEBUG = `${BLUE}Debug:${RESET}`;
|
14775 | var WARN = `${YELLOW}Warning:${RESET}`;
|
14776 | var ERROR = `${RED}Error:${RESET}`;
|
14777 | var ConsoleLogger = class {
|
14778 | constructor(level) {
|
14779 | this.level = level;
|
14780 | }
|
14781 | debug(...args) {
|
14782 | if (this.level <= LogLevel.debug)
|
14783 | console.debug(DEBUG, ...args);
|
14784 | }
|
14785 | info(...args) {
|
14786 | if (this.level <= LogLevel.info)
|
14787 | console.info(...args);
|
14788 | }
|
14789 | warn(...args) {
|
14790 | if (this.level <= LogLevel.warn)
|
14791 | console.warn(WARN, ...args);
|
14792 | }
|
14793 | error(...args) {
|
14794 | if (this.level <= LogLevel.error)
|
14795 | console.error(ERROR, ...args);
|
14796 | }
|
14797 | };
|
14798 |
|
14799 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/ngcc/src/locking/lock_file.mjs
|
14800 | import module4 from "module";
|
14801 | function getLockFilePath(fs5) {
|
14802 | const requireFn = typeof __require !== "undefined" ? __require : module4.createRequire(__ESM_IMPORT_META_URL__);
|
14803 | const ngccEntryPointFile = requireFn.resolve("@angular/compiler-cli/package.json");
|
14804 | return fs5.resolve(ngccEntryPointFile, "../../../.ngcc_lock_file");
|
14805 | }
|
14806 |
|
14807 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/ngcc/src/locking/lock_file_with_child_process/util.mjs
|
14808 | function removeLockFile(fs5, logger, lockFilePath, pid) {
|
14809 | try {
|
14810 | logger.debug(`Attempting to remove lock-file at ${lockFilePath}.`);
|
14811 | const lockFilePid = fs5.readFile(lockFilePath);
|
14812 | if (lockFilePid === pid) {
|
14813 | logger.debug(`PIDs match (${pid}), so removing ${lockFilePath}.`);
|
14814 | fs5.removeFile(lockFilePath);
|
14815 | } else {
|
14816 | logger.debug(`PIDs do not match (${pid} and ${lockFilePid}), so not removing ${lockFilePath}.`);
|
14817 | }
|
14818 | } catch (e) {
|
14819 | if (e.code === "ENOENT") {
|
14820 | logger.debug(`The lock-file at ${lockFilePath} was already removed.`);
|
14821 | } else {
|
14822 | throw e;
|
14823 | }
|
14824 | }
|
14825 | }
|
14826 |
|
14827 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/ngcc/src/locking/lock_file_with_child_process/index.mjs
|
14828 | var LockFileWithChildProcess = class {
|
14829 | constructor(fs5, logger) {
|
14830 | this.fs = fs5;
|
14831 | this.logger = logger;
|
14832 | this.path = getLockFilePath(fs5);
|
14833 | this.unlocker = this.createUnlocker(this.path);
|
14834 | }
|
14835 | write() {
|
14836 | if (this.unlocker === null) {
|
14837 | this.unlocker = this.createUnlocker(this.path);
|
14838 | }
|
14839 | this.logger.debug(`Attemping to write lock-file at ${this.path} with PID ${process.pid}`);
|
14840 | this.fs.writeFile(this.path, process.pid.toString(), true);
|
14841 | this.logger.debug(`Written lock-file at ${this.path} with PID ${process.pid}`);
|
14842 | }
|
14843 | read() {
|
14844 | try {
|
14845 | return this.fs.readFile(this.path);
|
14846 | } catch {
|
14847 | return "{unknown}";
|
14848 | }
|
14849 | }
|
14850 | remove() {
|
14851 | removeLockFile(this.fs, this.logger, this.path, process.pid.toString());
|
14852 | if (this.unlocker !== null) {
|
14853 | this.unlocker.disconnect();
|
14854 | this.unlocker = null;
|
14855 | }
|
14856 | }
|
14857 | createUnlocker(path7) {
|
14858 | var _a, _b;
|
14859 | this.logger.debug("Forking unlocker child-process");
|
14860 | const logLevel = this.logger.level !== void 0 ? this.logger.level.toString() : LogLevel.info.toString();
|
14861 | const isWindows = process.platform === "win32";
|
14862 | const unlocker = fork(getLockFileUnlockerScriptPath(this.fs), [path7, logLevel], { detached: true, stdio: isWindows ? "pipe" : "inherit" });
|
14863 | if (isWindows) {
|
14864 | (_a = unlocker.stdout) == null ? void 0 : _a.on("data", process.stdout.write.bind(process.stdout));
|
14865 | (_b = unlocker.stderr) == null ? void 0 : _b.on("data", process.stderr.write.bind(process.stderr));
|
14866 | }
|
14867 | return unlocker;
|
14868 | }
|
14869 | };
|
14870 | function getLockFileUnlockerScriptPath(fileSystem) {
|
14871 | const requireFn = typeof __require !== "undefined" ? __require : module5.createRequire(__ESM_IMPORT_META_URL__);
|
14872 | const unlockerScriptPath = requireFn.resolve("@angular/compiler-cli/ngcc/src/locking/lock_file_with_child_process/ngcc_lock_unlocker");
|
14873 | return fileSystem.resolve(unlockerScriptPath);
|
14874 | }
|
14875 |
|
14876 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/ngcc/src/locking/sync_locker.mjs
|
14877 | var SyncLocker = class {
|
14878 | constructor(lockFile) {
|
14879 | this.lockFile = lockFile;
|
14880 | }
|
14881 | lock(fn) {
|
14882 | this.create();
|
14883 | try {
|
14884 | return fn();
|
14885 | } finally {
|
14886 | this.lockFile.remove();
|
14887 | }
|
14888 | }
|
14889 | create() {
|
14890 | try {
|
14891 | this.lockFile.write();
|
14892 | } catch (e) {
|
14893 | if (e.code !== "EEXIST") {
|
14894 | throw e;
|
14895 | }
|
14896 | this.handleExistingLockFile();
|
14897 | }
|
14898 | }
|
14899 | handleExistingLockFile() {
|
14900 | const pid = this.lockFile.read();
|
14901 | throw new Error(`ngcc is already running at process with id ${pid}.
|
14902 | If you are running multiple builds in parallel then you might try pre-processing your node_modules via the command line ngcc tool before starting the builds.
|
14903 | (If you are sure no ngcc process is running then you should delete the lock-file at ${this.lockFile.path}.)`);
|
14904 | }
|
14905 | };
|
14906 |
|
14907 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/ngcc/src/ngcc_options.mjs
|
14908 | import {
|
14909 | cpus
|
14910 | } from "os";
|
14911 |
|
14912 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/perform_compile.mjs
|
14913 | import { isSyntaxError as isSyntaxError2 } from "@angular/compiler";
|
14914 | import ts110 from "typescript";
|
14915 |
|
14916 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/transformers/api.mjs
|
14917 | var UNKNOWN_ERROR_CODE = 500;
|
14918 | var EmitFlags;
|
14919 | (function(EmitFlags2) {
|
14920 | EmitFlags2[EmitFlags2["DTS"] = 1] = "DTS";
|
14921 | EmitFlags2[EmitFlags2["JS"] = 2] = "JS";
|
14922 | EmitFlags2[EmitFlags2["Metadata"] = 4] = "Metadata";
|
14923 | EmitFlags2[EmitFlags2["I18nBundle"] = 8] = "I18nBundle";
|
14924 | EmitFlags2[EmitFlags2["Codegen"] = 16] = "Codegen";
|
14925 | EmitFlags2[EmitFlags2["Default"] = 19] = "Default";
|
14926 | EmitFlags2[EmitFlags2["All"] = 31] = "All";
|
14927 | })(EmitFlags || (EmitFlags = {}));
|
14928 |
|
14929 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/transformers/compiler_host.mjs
|
14930 | import { collectExternalReferences, syntaxError as syntaxError2, TypeScriptEmitter } from "@angular/compiler";
|
14931 | import fs3 from "fs";
|
14932 | import {
|
14933 | basename as basename5,
|
14934 | dirname as dirname5,
|
14935 | join as join5,
|
14936 | normalize as normalize3,
|
14937 | relative as relative4,
|
14938 | resolve as resolve3
|
14939 | } from "path";
|
14940 | import ts68 from "typescript";
|
14941 |
|
14942 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/metadata/collector.mjs
|
14943 | import ts64 from "typescript";
|
14944 |
|
14945 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/metadata/evaluator.mjs
|
14946 | import ts62 from "typescript";
|
14947 | var spreadElementSyntaxKind = ts62.SyntaxKind.SpreadElement || ts62.SyntaxKind.SpreadElementExpression;
|
14948 | var empty = ts62.createNodeArray();
|
14949 |
|
14950 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/metadata/symbols.mjs
|
14951 | import ts63 from "typescript";
|
14952 |
|
14953 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/metadata/bundle_index_host.mjs
|
14954 | import {
|
14955 | basename as basename4,
|
14956 | dirname as dirname4,
|
14957 | join as join4,
|
14958 | normalize as normalize2
|
14959 | } from "path";
|
14960 | import ts66 from "typescript";
|
14961 |
|
14962 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/metadata/bundler.mjs
|
14963 | import {
|
14964 | basename as basename3,
|
14965 | dirname as dirname3,
|
14966 | join as join3,
|
14967 | normalize,
|
14968 | sep
|
14969 | } from "path";
|
14970 | import ts65 from "typescript";
|
14971 |
|
14972 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/transformers/util.mjs
|
14973 | import { syntaxError } from "@angular/compiler";
|
14974 | import {
|
14975 | relative as relative3
|
14976 | } from "path";
|
14977 | import ts67 from "typescript";
|
14978 |
|
14979 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/transformers/program.mjs
|
14980 | import { core, createAotCompiler, getMissingNgModuleMetadataErrorData, getParseErrors, isFormattedError, isSyntaxError } from "@angular/compiler";
|
14981 | import {
|
14982 | readFileSync as readFileSync2
|
14983 | } from "fs";
|
14984 | import * as path6 from "path";
|
14985 | import ts109 from "typescript";
|
14986 |
|
14987 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/diagnostics/translate_diagnostics.mjs
|
14988 | import ts69 from "typescript";
|
14989 |
|
14990 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/core/src/compiler.mjs
|
14991 | import ts97 from "typescript";
|
14992 |
|
14993 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/entry_point/src/generator.mjs
|
14994 | import ts70 from "typescript";
|
14995 |
|
14996 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/entry_point/src/private_export_checker.mjs
|
14997 | import ts71 from "typescript";
|
14998 |
|
14999 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/program_driver/src/api.mjs
|
15000 | var NgOriginalFile = Symbol("NgOriginalFile");
|
15001 | var UpdateMode;
|
15002 | (function(UpdateMode2) {
|
15003 | UpdateMode2[UpdateMode2["Complete"] = 0] = "Complete";
|
15004 | UpdateMode2[UpdateMode2["Incremental"] = 1] = "Incremental";
|
15005 | })(UpdateMode || (UpdateMode = {}));
|
15006 |
|
15007 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/program_driver/src/ts_create_program_driver.mjs
|
15008 | import ts75 from "typescript";
|
15009 |
|
15010 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/shims/src/adapter.mjs
|
15011 | import ts72 from "typescript";
|
15012 |
|
15013 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/shims/src/expando.mjs
|
15014 | var NgExtension = Symbol("NgExtension");
|
15015 |
|
15016 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/shims/src/factory_generator.mjs
|
15017 | import ts73 from "typescript";
|
15018 |
|
15019 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/shims/src/summary_generator.mjs
|
15020 | import ts74 from "typescript";
|
15021 |
|
15022 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/incremental/src/state.mjs
|
15023 | var IncrementalStateKind;
|
15024 | (function(IncrementalStateKind2) {
|
15025 | IncrementalStateKind2[IncrementalStateKind2["Fresh"] = 0] = "Fresh";
|
15026 | IncrementalStateKind2[IncrementalStateKind2["Delta"] = 1] = "Delta";
|
15027 | IncrementalStateKind2[IncrementalStateKind2["Analyzed"] = 2] = "Analyzed";
|
15028 | })(IncrementalStateKind || (IncrementalStateKind = {}));
|
15029 |
|
15030 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/incremental/src/incremental.mjs
|
15031 | var PhaseKind;
|
15032 | (function(PhaseKind2) {
|
15033 | PhaseKind2[PhaseKind2["Analysis"] = 0] = "Analysis";
|
15034 | PhaseKind2[PhaseKind2["TypeCheckAndEmit"] = 1] = "TypeCheckAndEmit";
|
15035 | })(PhaseKind || (PhaseKind = {}));
|
15036 |
|
15037 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/incremental/src/strategy.mjs
|
15038 | var SYM_INCREMENTAL_STATE = Symbol("NgIncrementalState");
|
15039 |
|
15040 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/indexer/src/api.mjs
|
15041 | var IdentifierKind;
|
15042 | (function(IdentifierKind2) {
|
15043 | IdentifierKind2[IdentifierKind2["Property"] = 0] = "Property";
|
15044 | IdentifierKind2[IdentifierKind2["Method"] = 1] = "Method";
|
15045 | IdentifierKind2[IdentifierKind2["Element"] = 2] = "Element";
|
15046 | IdentifierKind2[IdentifierKind2["Template"] = 3] = "Template";
|
15047 | IdentifierKind2[IdentifierKind2["Attribute"] = 4] = "Attribute";
|
15048 | IdentifierKind2[IdentifierKind2["Reference"] = 5] = "Reference";
|
15049 | IdentifierKind2[IdentifierKind2["Variable"] = 6] = "Variable";
|
15050 | })(IdentifierKind || (IdentifierKind = {}));
|
15051 |
|
15052 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/indexer/src/transform.mjs
|
15053 | import { ParseSourceFile as ParseSourceFile3 } from "@angular/compiler";
|
15054 |
|
15055 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/indexer/src/template.mjs
|
15056 | import { ASTWithSource, ImplicitReceiver, RecursiveAstVisitor, TmplAstElement, TmplAstRecursiveVisitor, TmplAstReference, TmplAstTemplate } from "@angular/compiler";
|
15057 |
|
15058 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/resource/src/loader.mjs
|
15059 | import ts76 from "typescript";
|
15060 | var RESOURCE_MARKER = ".$ngresource$";
|
15061 | var RESOURCE_MARKER_TS = RESOURCE_MARKER + ".ts";
|
15062 |
|
15063 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/checker.mjs
|
15064 | import { CssSelector as CssSelector3, DomElementSchemaRegistry as DomElementSchemaRegistry3 } from "@angular/compiler";
|
15065 |
|
15066 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/api/checker.mjs
|
15067 | var OptimizeFor;
|
15068 | (function(OptimizeFor2) {
|
15069 | OptimizeFor2[OptimizeFor2["SingleFile"] = 0] = "SingleFile";
|
15070 | OptimizeFor2[OptimizeFor2["WholeProgram"] = 1] = "WholeProgram";
|
15071 | })(OptimizeFor || (OptimizeFor = {}));
|
15072 |
|
15073 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/api/completion.mjs
|
15074 | var CompletionKind;
|
15075 | (function(CompletionKind2) {
|
15076 | CompletionKind2[CompletionKind2["Reference"] = 0] = "Reference";
|
15077 | CompletionKind2[CompletionKind2["Variable"] = 1] = "Variable";
|
15078 | })(CompletionKind || (CompletionKind = {}));
|
15079 |
|
15080 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/api/symbols.mjs
|
15081 | var SymbolKind;
|
15082 | (function(SymbolKind2) {
|
15083 | SymbolKind2[SymbolKind2["Input"] = 0] = "Input";
|
15084 | SymbolKind2[SymbolKind2["Output"] = 1] = "Output";
|
15085 | SymbolKind2[SymbolKind2["Binding"] = 2] = "Binding";
|
15086 | SymbolKind2[SymbolKind2["Reference"] = 3] = "Reference";
|
15087 | SymbolKind2[SymbolKind2["Variable"] = 4] = "Variable";
|
15088 | SymbolKind2[SymbolKind2["Directive"] = 5] = "Directive";
|
15089 | SymbolKind2[SymbolKind2["Element"] = 6] = "Element";
|
15090 | SymbolKind2[SymbolKind2["Template"] = 7] = "Template";
|
15091 | SymbolKind2[SymbolKind2["Expression"] = 8] = "Expression";
|
15092 | SymbolKind2[SymbolKind2["DomBinding"] = 9] = "DomBinding";
|
15093 | SymbolKind2[SymbolKind2["Pipe"] = 10] = "Pipe";
|
15094 | })(SymbolKind || (SymbolKind = {}));
|
15095 |
|
15096 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/diagnostics/src/diagnostic.mjs
|
15097 | import ts77 from "typescript";
|
15098 |
|
15099 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/diagnostics/src/id.mjs
|
15100 | var TEMPLATE_ID = Symbol("ngTemplateId");
|
15101 | var NEXT_TEMPLATE_ID = Symbol("ngNextTemplateId");
|
15102 |
|
15103 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/completion.mjs
|
15104 | import { EmptyExpr, ImplicitReceiver as ImplicitReceiver2, PropertyRead, PropertyWrite, SafePropertyRead, TmplAstReference as TmplAstReference2, TmplAstTextAttribute } from "@angular/compiler";
|
15105 | import ts79 from "typescript";
|
15106 |
|
15107 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/comments.mjs
|
15108 | import { AbsoluteSourceSpan as AbsoluteSourceSpan2 } from "@angular/compiler";
|
15109 | import ts78 from "typescript";
|
15110 | var CommentTriviaType;
|
15111 | (function(CommentTriviaType2) {
|
15112 | CommentTriviaType2["DIAGNOSTIC"] = "D";
|
15113 | CommentTriviaType2["EXPRESSION_TYPE_IDENTIFIER"] = "T";
|
15114 | })(CommentTriviaType || (CommentTriviaType = {}));
|
15115 | var ExpressionIdentifier;
|
15116 | (function(ExpressionIdentifier2) {
|
15117 | ExpressionIdentifier2["DIRECTIVE"] = "DIR";
|
15118 | ExpressionIdentifier2["COMPONENT_COMPLETION"] = "COMPCOMP";
|
15119 | ExpressionIdentifier2["EVENT_PARAMETER"] = "EP";
|
15120 | })(ExpressionIdentifier || (ExpressionIdentifier = {}));
|
15121 | var IGNORE_FOR_DIAGNOSTICS_MARKER = `${CommentTriviaType.DIAGNOSTIC}:ignore`;
|
15122 |
|
15123 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/context.mjs
|
15124 | import ts93 from "typescript";
|
15125 |
|
15126 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/dom.mjs
|
15127 | import { DomElementSchemaRegistry as DomElementSchemaRegistry2 } from "@angular/compiler";
|
15128 | import ts80 from "typescript";
|
15129 | var REGISTRY = new DomElementSchemaRegistry2();
|
15130 |
|
15131 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/environment.mjs
|
15132 | import { ExpressionType, ExternalExpr as ExternalExpr9 } from "@angular/compiler";
|
15133 | import ts86 from "typescript";
|
15134 |
|
15135 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/ts_util.mjs
|
15136 | import ts81 from "typescript";
|
15137 | var SAFE_TO_CAST_WITHOUT_PARENS = new Set([
|
15138 | ts81.SyntaxKind.ParenthesizedExpression,
|
15139 | ts81.SyntaxKind.Identifier,
|
15140 | ts81.SyntaxKind.CallExpression,
|
15141 | ts81.SyntaxKind.NonNullExpression,
|
15142 | ts81.SyntaxKind.ElementAccessExpression,
|
15143 | ts81.SyntaxKind.PropertyAccessExpression,
|
15144 | ts81.SyntaxKind.ArrayLiteralExpression,
|
15145 | ts81.SyntaxKind.ObjectLiteralExpression,
|
15146 | ts81.SyntaxKind.StringLiteral,
|
15147 | ts81.SyntaxKind.NumericLiteral,
|
15148 | ts81.SyntaxKind.TrueKeyword,
|
15149 | ts81.SyntaxKind.FalseKeyword,
|
15150 | ts81.SyntaxKind.NullKeyword,
|
15151 | ts81.SyntaxKind.UndefinedKeyword
|
15152 | ]);
|
15153 |
|
15154 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/type_constructor.mjs
|
15155 | import ts85 from "typescript";
|
15156 |
|
15157 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/tcb_util.mjs
|
15158 | import ts84 from "typescript";
|
15159 |
|
15160 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/type_parameter_emitter.mjs
|
15161 | import ts83 from "typescript";
|
15162 |
|
15163 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/type_emitter.mjs
|
15164 | import ts82 from "typescript";
|
15165 |
|
15166 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/tcb_util.mjs
|
15167 | var TcbInliningRequirement;
|
15168 | (function(TcbInliningRequirement2) {
|
15169 | TcbInliningRequirement2[TcbInliningRequirement2["MustInline"] = 0] = "MustInline";
|
15170 | TcbInliningRequirement2[TcbInliningRequirement2["ShouldInlineForGenericBounds"] = 1] = "ShouldInlineForGenericBounds";
|
15171 | TcbInliningRequirement2[TcbInliningRequirement2["None"] = 2] = "None";
|
15172 | })(TcbInliningRequirement || (TcbInliningRequirement = {}));
|
15173 |
|
15174 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/oob.mjs
|
15175 | import { TmplAstElement as TmplAstElement2 } from "@angular/compiler";
|
15176 | import ts87 from "typescript";
|
15177 |
|
15178 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/shim.mjs
|
15179 | import ts88 from "typescript";
|
15180 |
|
15181 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.mjs
|
15182 | import { BindingPipe, Call as Call2, DYNAMIC_TYPE, ImplicitReceiver as ImplicitReceiver4, PropertyRead as PropertyRead2, PropertyWrite as PropertyWrite2, SafePropertyRead as SafePropertyRead3, ThisReceiver, TmplAstBoundAttribute, TmplAstBoundText, TmplAstElement as TmplAstElement3, TmplAstIcu, TmplAstReference as TmplAstReference3, TmplAstTemplate as TmplAstTemplate2, TmplAstTextAttribute as TmplAstTextAttribute2, TmplAstVariable as TmplAstVariable2 } from "@angular/compiler";
|
15183 | import ts91 from "typescript";
|
15184 |
|
15185 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/diagnostics.mjs
|
15186 | import { AbsoluteSourceSpan as AbsoluteSourceSpan3 } from "@angular/compiler";
|
15187 | import ts89 from "typescript";
|
15188 |
|
15189 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/expression.mjs
|
15190 | import { ASTWithSource as ASTWithSource2, Call, EmptyExpr as EmptyExpr2, SafeKeyedRead, SafePropertyRead as SafePropertyRead2 } from "@angular/compiler";
|
15191 | import ts90 from "typescript";
|
15192 | var NULL_AS_ANY = ts90.createAsExpression(ts90.createNull(), ts90.createKeywordTypeNode(ts90.SyntaxKind.AnyKeyword));
|
15193 | var UNDEFINED = ts90.createIdentifier("undefined");
|
15194 | var UNARY_OPS = new Map([
|
15195 | ["+", ts90.SyntaxKind.PlusToken],
|
15196 | ["-", ts90.SyntaxKind.MinusToken]
|
15197 | ]);
|
15198 | var BINARY_OPS = new Map([
|
15199 | ["+", ts90.SyntaxKind.PlusToken],
|
15200 | ["-", ts90.SyntaxKind.MinusToken],
|
15201 | ["<", ts90.SyntaxKind.LessThanToken],
|
15202 | [">", ts90.SyntaxKind.GreaterThanToken],
|
15203 | ["<=", ts90.SyntaxKind.LessThanEqualsToken],
|
15204 | [">=", ts90.SyntaxKind.GreaterThanEqualsToken],
|
15205 | ["==", ts90.SyntaxKind.EqualsEqualsToken],
|
15206 | ["===", ts90.SyntaxKind.EqualsEqualsEqualsToken],
|
15207 | ["*", ts90.SyntaxKind.AsteriskToken],
|
15208 | ["/", ts90.SyntaxKind.SlashToken],
|
15209 | ["%", ts90.SyntaxKind.PercentToken],
|
15210 | ["!=", ts90.SyntaxKind.ExclamationEqualsToken],
|
15211 | ["!==", ts90.SyntaxKind.ExclamationEqualsEqualsToken],
|
15212 | ["||", ts90.SyntaxKind.BarBarToken],
|
15213 | ["&&", ts90.SyntaxKind.AmpersandAmpersandToken],
|
15214 | ["&", ts90.SyntaxKind.AmpersandToken],
|
15215 | ["|", ts90.SyntaxKind.BarToken],
|
15216 | ["??", ts90.SyntaxKind.QuestionQuestionToken]
|
15217 | ]);
|
15218 | var VeSafeLhsInferenceBugDetector = class {
|
15219 | static veWillInferAnyFor(ast) {
|
15220 | const visitor = VeSafeLhsInferenceBugDetector.SINGLETON;
|
15221 | return ast instanceof Call ? ast.visit(visitor) : ast.receiver.visit(visitor);
|
15222 | }
|
15223 | visitUnary(ast) {
|
15224 | return ast.expr.visit(this);
|
15225 | }
|
15226 | visitBinary(ast) {
|
15227 | return ast.left.visit(this) || ast.right.visit(this);
|
15228 | }
|
15229 | visitChain(ast) {
|
15230 | return false;
|
15231 | }
|
15232 | visitConditional(ast) {
|
15233 | return ast.condition.visit(this) || ast.trueExp.visit(this) || ast.falseExp.visit(this);
|
15234 | }
|
15235 | visitCall(ast) {
|
15236 | return true;
|
15237 | }
|
15238 | visitImplicitReceiver(ast) {
|
15239 | return false;
|
15240 | }
|
15241 | visitThisReceiver(ast) {
|
15242 | return false;
|
15243 | }
|
15244 | visitInterpolation(ast) {
|
15245 | return ast.expressions.some((exp) => exp.visit(this));
|
15246 | }
|
15247 | visitKeyedRead(ast) {
|
15248 | return false;
|
15249 | }
|
15250 | visitKeyedWrite(ast) {
|
15251 | return false;
|
15252 | }
|
15253 | visitLiteralArray(ast) {
|
15254 | return true;
|
15255 | }
|
15256 | visitLiteralMap(ast) {
|
15257 | return true;
|
15258 | }
|
15259 | visitLiteralPrimitive(ast) {
|
15260 | return false;
|
15261 | }
|
15262 | visitPipe(ast) {
|
15263 | return true;
|
15264 | }
|
15265 | visitPrefixNot(ast) {
|
15266 | return ast.expression.visit(this);
|
15267 | }
|
15268 | visitNonNullAssert(ast) {
|
15269 | return ast.expression.visit(this);
|
15270 | }
|
15271 | visitPropertyRead(ast) {
|
15272 | return false;
|
15273 | }
|
15274 | visitPropertyWrite(ast) {
|
15275 | return false;
|
15276 | }
|
15277 | visitQuote(ast) {
|
15278 | return false;
|
15279 | }
|
15280 | visitSafePropertyRead(ast) {
|
15281 | return false;
|
15282 | }
|
15283 | visitSafeKeyedRead(ast) {
|
15284 | return false;
|
15285 | }
|
15286 | };
|
15287 | VeSafeLhsInferenceBugDetector.SINGLETON = new VeSafeLhsInferenceBugDetector();
|
15288 |
|
15289 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/template_semantics.mjs
|
15290 | import { ImplicitReceiver as ImplicitReceiver3, RecursiveAstVisitor as RecursiveAstVisitor2, TmplAstVariable } from "@angular/compiler";
|
15291 |
|
15292 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.mjs
|
15293 | var TcbGenericContextBehavior;
|
15294 | (function(TcbGenericContextBehavior2) {
|
15295 | TcbGenericContextBehavior2[TcbGenericContextBehavior2["UseEmitter"] = 0] = "UseEmitter";
|
15296 | TcbGenericContextBehavior2[TcbGenericContextBehavior2["CopyClassNodes"] = 1] = "CopyClassNodes";
|
15297 | TcbGenericContextBehavior2[TcbGenericContextBehavior2["FallbackToAny"] = 2] = "FallbackToAny";
|
15298 | })(TcbGenericContextBehavior || (TcbGenericContextBehavior = {}));
|
15299 | var INFER_TYPE_FOR_CIRCULAR_OP_EXPR = ts91.createNonNullExpression(ts91.createNull());
|
15300 |
|
15301 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/type_check_file.mjs
|
15302 | import ts92 from "typescript";
|
15303 |
|
15304 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/context.mjs
|
15305 | var InliningMode;
|
15306 | (function(InliningMode2) {
|
15307 | InliningMode2[InliningMode2["InlineOps"] = 0] = "InlineOps";
|
15308 | InliningMode2[InliningMode2["Error"] = 1] = "Error";
|
15309 | })(InliningMode || (InliningMode = {}));
|
15310 |
|
15311 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/source.mjs
|
15312 | import { ParseLocation as ParseLocation2, ParseSourceSpan as ParseSourceSpan2 } from "@angular/compiler";
|
15313 |
|
15314 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/template_symbol_builder.mjs
|
15315 | import { AST, ASTWithSource as ASTWithSource3, BindingPipe as BindingPipe2, PropertyRead as PropertyRead3, PropertyWrite as PropertyWrite3, SafePropertyRead as SafePropertyRead4, TmplAstBoundAttribute as TmplAstBoundAttribute2, TmplAstBoundEvent, TmplAstElement as TmplAstElement4, TmplAstReference as TmplAstReference4, TmplAstTemplate as TmplAstTemplate3, TmplAstTextAttribute as TmplAstTextAttribute3, TmplAstVariable as TmplAstVariable3 } from "@angular/compiler";
|
15316 | import ts94 from "typescript";
|
15317 |
|
15318 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/src/checker.mjs
|
15319 | var REGISTRY2 = new DomElementSchemaRegistry3();
|
15320 |
|
15321 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/invalid_banana_in_box/index.mjs
|
15322 | import { TmplAstBoundEvent as TmplAstBoundEvent2 } from "@angular/compiler";
|
15323 | import ts95 from "typescript";
|
15324 |
|
15325 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/extended/api/api.mjs
|
15326 | import { ASTWithSource as ASTWithSource4, RecursiveAstVisitor as RecursiveAstVisitor3 } from "@angular/compiler";
|
15327 |
|
15328 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/nullish_coalescing_not_nullable/index.mjs
|
15329 | import { Binary } from "@angular/compiler";
|
15330 | import ts96 from "typescript";
|
15331 |
|
15332 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/core/src/compiler.mjs
|
15333 | var CompilationTicketKind;
|
15334 | (function(CompilationTicketKind2) {
|
15335 | CompilationTicketKind2[CompilationTicketKind2["Fresh"] = 0] = "Fresh";
|
15336 | CompilationTicketKind2[CompilationTicketKind2["IncrementalTypeScript"] = 1] = "IncrementalTypeScript";
|
15337 | CompilationTicketKind2[CompilationTicketKind2["IncrementalResource"] = 2] = "IncrementalResource";
|
15338 | })(CompilationTicketKind || (CompilationTicketKind = {}));
|
15339 |
|
15340 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/program.mjs
|
15341 | import { HtmlParser, MessageBundle } from "@angular/compiler";
|
15342 | import ts100 from "typescript";
|
15343 |
|
15344 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/transformers/i18n.mjs
|
15345 | import { Xliff, Xliff2, Xmb } from "@angular/compiler";
|
15346 | import {
|
15347 | relative as relative5,
|
15348 | resolve as resolve4,
|
15349 | sep as sep2
|
15350 | } from "path";
|
15351 |
|
15352 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/typescript_support.mjs
|
15353 | import ts98 from "typescript";
|
15354 | var tsVersion = ts98.version;
|
15355 |
|
15356 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/core/src/host.mjs
|
15357 | import ts99 from "typescript";
|
15358 |
|
15359 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/transformers/downlevel_decorators_transform/downlevel_decorators_transform.mjs
|
15360 | import ts102 from "typescript";
|
15361 |
|
15362 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/transformers/downlevel_decorators_transform/patch_alias_reference_resolution.mjs
|
15363 | import ts101 from "typescript";
|
15364 | var patchedReferencedAliasesSymbol = Symbol("patchedReferencedAliases");
|
15365 |
|
15366 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/transformers/inline_resources.mjs
|
15367 | import ts103 from "typescript";
|
15368 |
|
15369 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/transformers/lower_expressions.mjs
|
15370 | import { createLoweredSymbol, isLoweredSymbol } from "@angular/compiler";
|
15371 | import ts104 from "typescript";
|
15372 |
|
15373 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/transformers/metadata_cache.mjs
|
15374 | import ts105 from "typescript";
|
15375 |
|
15376 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/transformers/node_emitter_transform.mjs
|
15377 | import ts107 from "typescript";
|
15378 |
|
15379 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/transformers/node_emitter.mjs
|
15380 | import { BinaryOperator as BinaryOperator2, BuiltinMethod, BuiltinVar, ClassStmt, ExternalExpr as ExternalExpr10, Statement, StmtModifier as StmtModifier2, UnaryOperator as UnaryOperator2 } from "@angular/compiler";
|
15381 | import ts106 from "typescript";
|
15382 |
|
15383 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/transformers/r3_metadata_transform.mjs
|
15384 | import { ClassStmt as ClassStmt2, StmtModifier as StmtModifier3 } from "@angular/compiler";
|
15385 | import ts108 from "typescript";
|
15386 |
|
15387 | // bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/transformers/program.mjs
|
15388 | var VE_DISABLED_MESSAGE = `
|
15389 | This compilation is using the View Engine compiler which is no longer supported by the Angular team
|
15390 | and is being removed. Please upgrade to the Ivy compiler by switching to \`NgtscProgram\`. See
|
15391 | https://angular.io/guide/ivy for more information.
|
15392 | `.trim().split("\n").join(" ");
|
15393 | var LOWER_FIELDS = ["useValue", "useFactory", "data", "id", "loadChildren"];
|
15394 | var R3_LOWER_FIELDS = [...LOWER_FIELDS, "providers", "imports", "exports"];
|
15395 | var emptyModules = {
|
15396 | ngModules: [],
|
15397 | ngModuleByPipeOrDirective: new Map(),
|
15398 | files: []
|
15399 | };
|
15400 |
|
15401 |
|
15402 | function calcProjectFileAndBasePath(project, host = getFileSystem()) {
|
15403 | const absProject = host.resolve(project);
|
15404 | const projectIsDir = host.lstat(absProject).isDirectory();
|
15405 | const projectFile = projectIsDir ? host.join(absProject, "tsconfig.json") : absProject;
|
15406 | const projectDir = projectIsDir ? absProject : host.dirname(absProject);
|
15407 | const basePath = host.resolve(projectDir);
|
15408 | return { projectFile, basePath };
|
15409 | }
|
15410 | function readConfiguration(project, existingOptions, host = getFileSystem()) {
|
15411 | var _a;
|
15412 | try {
|
15413 | const fs5 = getFileSystem();
|
15414 | const readConfigFile = (configFile) => ts110.readConfigFile(configFile, (file) => host.readFile(host.resolve(file)));
|
15415 | const readAngularCompilerOptions = (configFile, parentOptions = {}) => {
|
15416 | const { config: config2, error: error3 } = readConfigFile(configFile);
|
15417 | if (error3) {
|
15418 | return parentOptions;
|
15419 | }
|
15420 | const existingNgCompilerOptions = __spreadValues(__spreadValues({}, config2.angularCompilerOptions), parentOptions);
|
15421 | if (config2.extends && typeof config2.extends === "string") {
|
15422 | const extendedConfigPath = getExtendedConfigPath(configFile, config2.extends, host, fs5);
|
15423 | if (extendedConfigPath !== null) {
|
15424 | return readAngularCompilerOptions(extendedConfigPath, existingNgCompilerOptions);
|
15425 | }
|
15426 | }
|
15427 | return existingNgCompilerOptions;
|
15428 | };
|
15429 | const { projectFile, basePath } = calcProjectFileAndBasePath(project, host);
|
15430 | const configFileName = host.resolve(host.pwd(), projectFile);
|
15431 | const { config, error: error2 } = readConfigFile(projectFile);
|
15432 | if (error2) {
|
15433 | return {
|
15434 | project,
|
15435 | errors: [error2],
|
15436 | rootNames: [],
|
15437 | options: {},
|
15438 | emitFlags: EmitFlags.Default
|
15439 | };
|
15440 | }
|
15441 | const existingCompilerOptions = __spreadValues(__spreadValues({
|
15442 | genDir: basePath,
|
15443 | basePath
|
15444 | }, readAngularCompilerOptions(configFileName)), existingOptions);
|
15445 | const parseConfigHost = createParseConfigHost(host, fs5);
|
15446 | const { options, errors, fileNames: rootNames, projectReferences } = ts110.parseJsonConfigFileContent(config, parseConfigHost, basePath, existingCompilerOptions, configFileName);
|
15447 | options.enableIvy = !!((_a = options.enableIvy) != null ? _a : true);
|
15448 | let emitFlags = EmitFlags.Default;
|
15449 | if (!(options.skipMetadataEmit || options.flatModuleOutFile)) {
|
15450 | emitFlags |= EmitFlags.Metadata;
|
15451 | }
|
15452 | if (options.skipTemplateCodegen) {
|
15453 | emitFlags = emitFlags & ~EmitFlags.Codegen;
|
15454 | }
|
15455 | return { project: projectFile, rootNames, projectReferences, options, errors, emitFlags };
|
15456 | } catch (e) {
|
15457 | const errors = [{
|
15458 | category: ts110.DiagnosticCategory.Error,
|
15459 | messageText: e.stack,
|
15460 | file: void 0,
|
15461 | start: void 0,
|
15462 | length: void 0,
|
15463 | source: "angular",
|
15464 | code: UNKNOWN_ERROR_CODE
|
15465 | }];
|
15466 | return { project: "", errors, rootNames: [], options: {}, emitFlags: EmitFlags.Default };
|
15467 | }
|
15468 | }
|
15469 | function createParseConfigHost(host, fs5 = getFileSystem()) {
|
15470 | return {
|
15471 | fileExists: host.exists.bind(host),
|
15472 | readDirectory: ts110.sys.readDirectory,
|
15473 | readFile: host.readFile.bind(host),
|
15474 | useCaseSensitiveFileNames: fs5.isCaseSensitive()
|
15475 | };
|
15476 | }
|
15477 | function getExtendedConfigPath(configFile, extendsValue, host, fs5) {
|
15478 | const result = getExtendedConfigPathWorker(configFile, extendsValue, host, fs5);
|
15479 | if (result !== null) {
|
15480 | return result;
|
15481 | }
|
15482 | return getExtendedConfigPathWorker(configFile, `${extendsValue}.json`, host, fs5);
|
15483 | }
|
15484 | function getExtendedConfigPathWorker(configFile, extendsValue, host, fs5) {
|
15485 | if (extendsValue.startsWith(".") || fs5.isRooted(extendsValue)) {
|
15486 | const extendedConfigPath = host.resolve(host.dirname(configFile), extendsValue);
|
15487 | if (host.exists(extendedConfigPath)) {
|
15488 | return extendedConfigPath;
|
15489 | }
|
15490 | } else {
|
15491 | const parseConfigHost = createParseConfigHost(host, fs5);
|
15492 | const { resolvedModule } = ts110.nodeModuleNameResolver(extendsValue, configFile, { moduleResolution: ts110.ModuleResolutionKind.NodeJs, resolveJsonModule: true }, parseConfigHost);
|
15493 | if (resolvedModule) {
|
15494 | return absoluteFrom(resolvedModule.resolvedFileName);
|
15495 | }
|
15496 | }
|
15497 | return null;
|
15498 | }
|
15499 |
|
15500 |
|
15501 | function getSharedSetup(options) {
|
15502 | const fileSystem = getFileSystem();
|
15503 | const absBasePath = absoluteFrom(options.basePath);
|
15504 | const projectPath = fileSystem.dirname(absBasePath);
|
15505 | const tsConfig = options.tsConfigPath !== null ? getTsConfig(options.tsConfigPath || projectPath) : null;
|
15506 | let { basePath, targetEntryPointPath, propertiesToConsider = SUPPORTED_FORMAT_PROPERTIES, typingsOnly = false, compileAllFormats = true, createNewEntryPointFormats = false, logger = new ConsoleLogger(LogLevel.info), pathMappings = getPathMappingsFromTsConfig(fileSystem, tsConfig, projectPath), async = false, errorOnFailedEntryPoint = false, enableI18nLegacyMessageIdFormat = true, invalidateEntryPointManifest = false, tsConfigPath } = options;
|
15507 | if (!!targetEntryPointPath) {
|
15508 | errorOnFailedEntryPoint = true;
|
15509 | }
|
15510 | if (typingsOnly) {
|
15511 | compileAllFormats = false;
|
15512 | }
|
15513 | checkForSolutionStyleTsConfig(fileSystem, logger, projectPath, options.tsConfigPath, tsConfig);
|
15514 | return {
|
15515 | basePath,
|
15516 | targetEntryPointPath,
|
15517 | propertiesToConsider,
|
15518 | typingsOnly,
|
15519 | compileAllFormats,
|
15520 | createNewEntryPointFormats,
|
15521 | logger,
|
15522 | pathMappings,
|
15523 | async,
|
15524 | errorOnFailedEntryPoint,
|
15525 | enableI18nLegacyMessageIdFormat,
|
15526 | invalidateEntryPointManifest,
|
15527 | tsConfigPath,
|
15528 | fileSystem,
|
15529 | absBasePath,
|
15530 | projectPath,
|
15531 | tsConfig,
|
15532 | getFileWriter: (pkgJsonUpdater) => createNewEntryPointFormats ? new NewEntryPointFileWriter(fileSystem, logger, errorOnFailedEntryPoint, pkgJsonUpdater) : new InPlaceFileWriter(fileSystem, logger, errorOnFailedEntryPoint)
|
15533 | };
|
15534 | }
|
15535 | var tsConfigCache = null;
|
15536 | var tsConfigPathCache = null;
|
15537 | function getTsConfig(tsConfigPath) {
|
15538 | if (tsConfigPath !== tsConfigPathCache) {
|
15539 | tsConfigPathCache = tsConfigPath;
|
15540 | tsConfigCache = readConfiguration(tsConfigPath);
|
15541 | }
|
15542 | return tsConfigCache;
|
15543 | }
|
15544 | function clearTsConfigCache() {
|
15545 | tsConfigPathCache = null;
|
15546 | tsConfigCache = null;
|
15547 | }
|
15548 | function checkForSolutionStyleTsConfig(fileSystem, logger, projectPath, tsConfigPath, tsConfig) {
|
15549 | if (tsConfigPath !== null && !tsConfigPath && tsConfig !== null && tsConfig.rootNames.length === 0 && tsConfig.projectReferences !== void 0 && tsConfig.projectReferences.length > 0) {
|
15550 | logger.warn(`The inferred tsconfig file "${tsConfig.project}" appears to be "solution-style" since it contains no root files but does contain project references.
|
15551 | This is probably not wanted, since ngcc is unable to infer settings like "paths" mappings from such a file.
|
15552 | Perhaps you should have explicitly specified one of the referenced projects using the --tsconfig option. For example:
|
15553 |
|
15554 | ` + tsConfig.projectReferences.map((ref) => ` ngcc ... --tsconfig "${ref.originalPath}"
|
15555 | `).join("") + `
|
15556 | Find out more about solution-style tsconfig at https://devblogs.microsoft.com/typescript/announcing-typescript-3-9/#solution-style-tsconfig.
|
15557 | If you did intend to use this file, then you can hide this warning by providing it explicitly:
|
15558 |
|
15559 | ngcc ... --tsconfig "${fileSystem.relative(projectPath, tsConfig.project)}"`);
|
15560 | }
|
15561 | }
|
15562 | function getMaxNumberOfWorkers() {
|
15563 | const maxWorkers = process.env.NGCC_MAX_WORKERS;
|
15564 | if (maxWorkers === void 0) {
|
15565 | return Math.max(1, Math.min(4, cpus().length - 1));
|
15566 | }
|
15567 | const numericMaxWorkers = +maxWorkers.trim();
|
15568 | if (!Number.isInteger(numericMaxWorkers)) {
|
15569 | throw new Error("NGCC_MAX_WORKERS should be an integer.");
|
15570 | } else if (numericMaxWorkers < 1) {
|
15571 | throw new Error("NGCC_MAX_WORKERS should be at least 1.");
|
15572 | }
|
15573 | return numericMaxWorkers;
|
15574 | }
|
15575 |
|
15576 |
|
15577 | import { createHash } from "crypto";
|
15578 | import module6 from "module";
|
15579 | import semver from "semver";
|
15580 | import {
|
15581 | runInNewContext
|
15582 | } from "vm";
|
15583 | var PartiallyProcessedConfig = class {
|
15584 | constructor(projectConfig) {
|
15585 | this.packages = new Map();
|
15586 | this.locking = {};
|
15587 | this.hashAlgorithm = "sha256";
|
15588 | if (projectConfig.locking !== void 0) {
|
15589 | this.locking = projectConfig.locking;
|
15590 | }
|
15591 | for (const packageNameAndVersion in projectConfig.packages) {
|
15592 | const packageConfig = projectConfig.packages[packageNameAndVersion];
|
15593 | if (packageConfig) {
|
15594 | const [packageName, versionRange = "*"] = this.splitNameAndVersion(packageNameAndVersion);
|
15595 | this.addPackageConfig(packageName, __spreadProps(__spreadValues({}, packageConfig), { versionRange }));
|
15596 | }
|
15597 | }
|
15598 | if (projectConfig.hashAlgorithm !== void 0) {
|
15599 | this.hashAlgorithm = projectConfig.hashAlgorithm;
|
15600 | }
|
15601 | }
|
15602 | splitNameAndVersion(packageNameAndVersion) {
|
15603 | const versionIndex = packageNameAndVersion.lastIndexOf("@");
|
15604 | return versionIndex > 0 ? [
|
15605 | packageNameAndVersion.substring(0, versionIndex),
|
15606 | packageNameAndVersion.substring(versionIndex + 1)
|
15607 | ] : [packageNameAndVersion, void 0];
|
15608 | }
|
15609 | addPackageConfig(packageName, config) {
|
15610 | if (!this.packages.has(packageName)) {
|
15611 | this.packages.set(packageName, []);
|
15612 | }
|
15613 | this.packages.get(packageName).push(config);
|
15614 | }
|
15615 | findPackageConfig(packageName, version) {
|
15616 | var _a;
|
15617 | if (!this.packages.has(packageName)) {
|
15618 | return null;
|
15619 | }
|
15620 | const configs = this.packages.get(packageName);
|
15621 | if (version === null) {
|
15622 | return configs[0];
|
15623 | }
|
15624 | return (_a = configs.find((config) => semver.satisfies(version, config.versionRange, { includePrerelease: true }))) != null ? _a : null;
|
15625 | }
|
15626 | toJson() {
|
15627 | return JSON.stringify(this, (key, value) => {
|
15628 | if (value instanceof Map) {
|
15629 | const res = {};
|
15630 | for (const [k, v] of value) {
|
15631 | res[k] = v;
|
15632 | }
|
15633 | return res;
|
15634 | } else {
|
15635 | return value;
|
15636 | }
|
15637 | });
|
15638 | }
|
15639 | };
|
15640 | var DEFAULT_NGCC_CONFIG = {
|
15641 | packages: {
|
15642 | "angular2-highcharts": {
|
15643 | entryPoints: {
|
15644 | ".": {
|
15645 | override: {
|
15646 | main: "./index.js"
|
15647 | }
|
15648 | }
|
15649 | }
|
15650 | },
|
15651 | "ng2-dragula": {
|
15652 | entryPoints: {
|
15653 | "./dist": { ignore: true }
|
15654 | }
|
15655 | }
|
15656 | },
|
15657 | locking: {
|
15658 | retryDelay: 500,
|
15659 | retryAttempts: 500
|
15660 | }
|
15661 | };
|
15662 | var NGCC_CONFIG_FILENAME = "ngcc.config.js";
|
15663 | var isCommonJS2 = typeof __require !== "undefined";
|
15664 | var currentFileUrl2 = isCommonJS2 ? null : __ESM_IMPORT_META_URL__;
|
15665 | var ProcessedNgccPackageConfig = class {
|
15666 | constructor(fs5, packagePath, { entryPoints = {}, ignorableDeepImportMatchers = [] }) {
|
15667 | const absolutePathEntries = Object.entries(entryPoints).map(([relativePath, config]) => [fs5.resolve(packagePath, relativePath), config]);
|
15668 | this.packagePath = packagePath;
|
15669 | this.entryPoints = new Map(absolutePathEntries);
|
15670 | this.ignorableDeepImportMatchers = ignorableDeepImportMatchers;
|
15671 | }
|
15672 | };
|
15673 | var NgccConfiguration = class {
|
15674 | constructor(fs5, baseDir) {
|
15675 | this.fs = fs5;
|
15676 | this.cache = new Map();
|
15677 | this.defaultConfig = new PartiallyProcessedConfig(DEFAULT_NGCC_CONFIG);
|
15678 | this.projectConfig = new PartiallyProcessedConfig(this.loadProjectConfig(baseDir));
|
15679 | this.hashAlgorithm = this.projectConfig.hashAlgorithm;
|
15680 | this.hash = this.computeHash();
|
15681 | }
|
15682 | getLockingConfig() {
|
15683 | let { retryAttempts, retryDelay } = this.projectConfig.locking;
|
15684 | if (retryAttempts === void 0) {
|
15685 | retryAttempts = this.defaultConfig.locking.retryAttempts;
|
15686 | }
|
15687 | if (retryDelay === void 0) {
|
15688 | retryDelay = this.defaultConfig.locking.retryDelay;
|
15689 | }
|
15690 | return { retryAttempts, retryDelay };
|
15691 | }
|
15692 | getPackageConfig(packageName, packagePath, version) {
|
15693 | const rawPackageConfig = this.getRawPackageConfig(packageName, packagePath, version);
|
15694 | return new ProcessedNgccPackageConfig(this.fs, packagePath, rawPackageConfig);
|
15695 | }
|
15696 | getRawPackageConfig(packageName, packagePath, version) {
|
15697 | const cacheKey = packageName + (version !== null ? `@${version}` : "");
|
15698 | if (this.cache.has(cacheKey)) {
|
15699 | return this.cache.get(cacheKey);
|
15700 | }
|
15701 | const projectLevelConfig = this.projectConfig.findPackageConfig(packageName, version);
|
15702 | if (projectLevelConfig !== null) {
|
15703 | this.cache.set(cacheKey, projectLevelConfig);
|
15704 | return projectLevelConfig;
|
15705 | }
|
15706 | const packageLevelConfig = this.loadPackageConfig(packagePath, version);
|
15707 | if (packageLevelConfig !== null) {
|
15708 | this.cache.set(cacheKey, packageLevelConfig);
|
15709 | return packageLevelConfig;
|
15710 | }
|
15711 | const defaultLevelConfig = this.defaultConfig.findPackageConfig(packageName, version);
|
15712 | if (defaultLevelConfig !== null) {
|
15713 | this.cache.set(cacheKey, defaultLevelConfig);
|
15714 | return defaultLevelConfig;
|
15715 | }
|
15716 | return { versionRange: "*" };
|
15717 | }
|
15718 | loadProjectConfig(baseDir) {
|
15719 | const configFilePath = this.fs.join(baseDir, NGCC_CONFIG_FILENAME);
|
15720 | if (this.fs.exists(configFilePath)) {
|
15721 | try {
|
15722 | return this.evalSrcFile(configFilePath);
|
15723 | } catch (e) {
|
15724 | throw new Error(`Invalid project configuration file at "${configFilePath}": ` + e.message);
|
15725 | }
|
15726 | } else {
|
15727 | return { packages: {} };
|
15728 | }
|
15729 | }
|
15730 | loadPackageConfig(packagePath, version) {
|
15731 | const configFilePath = this.fs.join(packagePath, NGCC_CONFIG_FILENAME);
|
15732 | if (this.fs.exists(configFilePath)) {
|
15733 | try {
|
15734 | const packageConfig = this.evalSrcFile(configFilePath);
|
15735 | return __spreadProps(__spreadValues({}, packageConfig), {
|
15736 | versionRange: version || "*"
|
15737 | });
|
15738 | } catch (e) {
|
15739 | throw new Error(`Invalid package configuration file at "${configFilePath}": ` + e.message);
|
15740 | }
|
15741 | } else {
|
15742 | return null;
|
15743 | }
|
15744 | }
|
15745 | evalSrcFile(srcPath) {
|
15746 | const requireFn = isCommonJS2 ? __require : module6.createRequire(currentFileUrl2);
|
15747 | const src = this.fs.readFile(srcPath);
|
15748 | const theExports = {};
|
15749 | const sandbox = {
|
15750 | module: { exports: theExports },
|
15751 | exports: theExports,
|
15752 | require: requireFn,
|
15753 | __dirname: this.fs.dirname(srcPath),
|
15754 | __filename: srcPath
|
15755 | };
|
15756 | runInNewContext(src, sandbox, { filename: srcPath });
|
15757 | return sandbox.module.exports;
|
15758 | }
|
15759 | computeHash() {
|
15760 | return createHash(this.hashAlgorithm).update(this.projectConfig.toJson()).digest("hex");
|
15761 | }
|
15762 | };
|
15763 |
|
15764 |
|
15765 | import { createHash as createHash2 } from "crypto";
|
15766 | var EntryPointManifest = class {
|
15767 | constructor(fs5, config, logger) {
|
15768 | this.fs = fs5;
|
15769 | this.config = config;
|
15770 | this.logger = logger;
|
15771 | }
|
15772 | readEntryPointsUsingManifest(basePath) {
|
15773 | try {
|
15774 | if (this.fs.basename(basePath) !== "node_modules") {
|
15775 | return null;
|
15776 | }
|
15777 | const manifestPath = this.getEntryPointManifestPath(basePath);
|
15778 | if (!this.fs.exists(manifestPath)) {
|
15779 | return null;
|
15780 | }
|
15781 | const computedLockFileHash = this.computeLockFileHash(basePath);
|
15782 | if (computedLockFileHash === null) {
|
15783 | return null;
|
15784 | }
|
15785 | const { ngccVersion, configFileHash, lockFileHash, entryPointPaths } = JSON.parse(this.fs.readFile(manifestPath));
|
15786 | if (ngccVersion !== NGCC_VERSION || configFileHash !== this.config.hash || lockFileHash !== computedLockFileHash) {
|
15787 | return null;
|
15788 | }
|
15789 | this.logger.debug(`Entry-point manifest found for ${basePath} so loading entry-point information directly.`);
|
15790 | const startTime = Date.now();
|
15791 | const entryPoints = [];
|
15792 | for (const [packagePath, entryPointPath, dependencyPaths = [], missingPaths = [], deepImportPaths = []] of entryPointPaths) {
|
15793 | const result = getEntryPointInfo(this.fs, this.config, this.logger, this.fs.resolve(basePath, packagePath), this.fs.resolve(basePath, entryPointPath));
|
15794 | if (!isEntryPoint(result)) {
|
15795 | throw new Error(`The entry-point manifest at ${manifestPath} contained an invalid pair of package paths: [${packagePath}, ${entryPointPath}]`);
|
15796 | } else {
|
15797 | entryPoints.push({
|
15798 | entryPoint: result,
|
15799 | depInfo: {
|
15800 | dependencies: new Set(dependencyPaths),
|
15801 | missing: new Set(missingPaths),
|
15802 | deepImports: new Set(deepImportPaths)
|
15803 | }
|
15804 | });
|
15805 | }
|
15806 | }
|
15807 | const duration = Math.round((Date.now() - startTime) / 100) / 10;
|
15808 | this.logger.debug(`Reading entry-points using the manifest entries took ${duration}s.`);
|
15809 | return entryPoints;
|
15810 | } catch (e) {
|
15811 | this.logger.warn(`Unable to read the entry-point manifest for ${basePath}:
|
15812 | `, e.stack || e.toString());
|
15813 | return null;
|
15814 | }
|
15815 | }
|
15816 | writeEntryPointManifest(basePath, entryPoints) {
|
15817 | if (this.fs.basename(basePath) !== "node_modules") {
|
15818 | return;
|
15819 | }
|
15820 | const lockFileHash = this.computeLockFileHash(basePath);
|
15821 | if (lockFileHash === null) {
|
15822 | return;
|
15823 | }
|
15824 | const manifest = {
|
15825 | ngccVersion: NGCC_VERSION,
|
15826 | configFileHash: this.config.hash,
|
15827 | lockFileHash,
|
15828 | entryPointPaths: entryPoints.map((e) => {
|
15829 | const entryPointPaths = [
|
15830 | this.fs.relative(basePath, e.entryPoint.packagePath),
|
15831 | this.fs.relative(basePath, e.entryPoint.path)
|
15832 | ];
|
15833 | if (e.depInfo.dependencies.size > 0) {
|
15834 | entryPointPaths[2] = Array.from(e.depInfo.dependencies);
|
15835 | } else if (e.depInfo.missing.size > 0 || e.depInfo.deepImports.size > 0) {
|
15836 | entryPointPaths[2] = [];
|
15837 | }
|
15838 | if (e.depInfo.missing.size > 0) {
|
15839 | entryPointPaths[3] = Array.from(e.depInfo.missing);
|
15840 | } else if (e.depInfo.deepImports.size > 0) {
|
15841 | entryPointPaths[3] = [];
|
15842 | }
|
15843 | if (e.depInfo.deepImports.size > 0) {
|
15844 | entryPointPaths[4] = Array.from(e.depInfo.deepImports);
|
15845 | }
|
15846 | return entryPointPaths;
|
15847 | })
|
15848 | };
|
15849 | this.fs.writeFile(this.getEntryPointManifestPath(basePath), JSON.stringify(manifest));
|
15850 | }
|
15851 | getEntryPointManifestPath(basePath) {
|
15852 | return this.fs.resolve(basePath, "__ngcc_entry_points__.json");
|
15853 | }
|
15854 | computeLockFileHash(basePath) {
|
15855 | const directory = this.fs.dirname(basePath);
|
15856 | for (const lockFileName of ["yarn.lock", "package-lock.json"]) {
|
15857 | const lockFilePath = this.fs.resolve(directory, lockFileName);
|
15858 | if (this.fs.exists(lockFilePath)) {
|
15859 | const lockFileContents = this.fs.readFile(lockFilePath);
|
15860 | return createHash2(this.config.hashAlgorithm).update(lockFileContents).digest("hex");
|
15861 | }
|
15862 | }
|
15863 | return null;
|
15864 | }
|
15865 | };
|
15866 | var InvalidatingEntryPointManifest = class extends EntryPointManifest {
|
15867 | readEntryPointsUsingManifest(_basePath) {
|
15868 | return null;
|
15869 | }
|
15870 | };
|
15871 |
|
15872 |
|
15873 | var PackageJsonUpdate = class {
|
15874 | constructor(writeChangesImpl) {
|
15875 | this.writeChangesImpl = writeChangesImpl;
|
15876 | this.changes = [];
|
15877 | this.applied = false;
|
15878 | }
|
15879 | addChange(propertyPath, value, positioning = "unimportant") {
|
15880 | this.ensureNotApplied();
|
15881 | this.changes.push([propertyPath, value, positioning]);
|
15882 | return this;
|
15883 | }
|
15884 | writeChanges(packageJsonPath, parsedJson) {
|
15885 | this.ensureNotApplied();
|
15886 | this.writeChangesImpl(this.changes, packageJsonPath, parsedJson);
|
15887 | this.applied = true;
|
15888 | }
|
15889 | ensureNotApplied() {
|
15890 | if (this.applied) {
|
15891 | throw new Error("Trying to apply a `PackageJsonUpdate` that has already been applied.");
|
15892 | }
|
15893 | }
|
15894 | };
|
15895 | var DirectPackageJsonUpdater = class {
|
15896 | constructor(fs5) {
|
15897 | this.fs = fs5;
|
15898 | }
|
15899 | createUpdate() {
|
15900 | return new PackageJsonUpdate((...args) => this.writeChanges(...args));
|
15901 | }
|
15902 | writeChanges(changes, packageJsonPath, preExistingParsedJson) {
|
15903 | if (changes.length === 0) {
|
15904 | throw new Error(`No changes to write to '${packageJsonPath}'.`);
|
15905 | }
|
15906 | const parsedJson = this.fs.exists(packageJsonPath) ? JSON.parse(this.fs.readFile(packageJsonPath)) : {};
|
15907 | for (const [propPath, value, positioning] of changes) {
|
15908 | if (propPath.length === 0) {
|
15909 | throw new Error(`Missing property path for writing value to '${packageJsonPath}'.`);
|
15910 | }
|
15911 | applyChange(parsedJson, propPath, value, positioning);
|
15912 | if (preExistingParsedJson) {
|
15913 | applyChange(preExistingParsedJson, propPath, value, "unimportant");
|
15914 | }
|
15915 | }
|
15916 | this.fs.ensureDir(dirname(packageJsonPath));
|
15917 | this.fs.writeFile(packageJsonPath, `${JSON.stringify(parsedJson, null, 2)}
|
15918 | `);
|
15919 | }
|
15920 | };
|
15921 | function applyChange(ctx, propPath, value, positioning) {
|
15922 | const lastPropIdx = propPath.length - 1;
|
15923 | const lastProp = propPath[lastPropIdx];
|
15924 | for (let i = 0; i < lastPropIdx; i++) {
|
15925 | const key = propPath[i];
|
15926 | const newCtx = ctx.hasOwnProperty(key) ? ctx[key] : ctx[key] = {};
|
15927 | if (typeof newCtx !== "object" || newCtx === null || Array.isArray(newCtx)) {
|
15928 | throw new Error(`Property path '${propPath.join(".")}' does not point to an object.`);
|
15929 | }
|
15930 | ctx = newCtx;
|
15931 | }
|
15932 | ctx[lastProp] = value;
|
15933 | positionProperty(ctx, lastProp, positioning);
|
15934 | }
|
15935 | function movePropBefore(ctx, prop, isNextProp) {
|
15936 | const allProps = Object.keys(ctx);
|
15937 | const otherProps = allProps.filter((p2) => p2 !== prop);
|
15938 | const nextPropIdx = otherProps.findIndex(isNextProp);
|
15939 | const propsToShift = nextPropIdx === -1 ? [] : otherProps.slice(nextPropIdx);
|
15940 | movePropToEnd(ctx, prop);
|
15941 | propsToShift.forEach((p2) => movePropToEnd(ctx, p2));
|
15942 | }
|
15943 | function movePropToEnd(ctx, prop) {
|
15944 | const value = ctx[prop];
|
15945 | delete ctx[prop];
|
15946 | ctx[prop] = value;
|
15947 | }
|
15948 | function positionProperty(ctx, prop, positioning) {
|
15949 | switch (positioning) {
|
15950 | case "alphabetic":
|
15951 | movePropBefore(ctx, prop, (p2) => p2 > prop);
|
15952 | break;
|
15953 | case "unimportant":
|
15954 | break;
|
15955 | default:
|
15956 | if (typeof positioning !== "object" || positioning.before === void 0) {
|
15957 | throw new Error(`Unknown positioning (${JSON.stringify(positioning)}) for property '${prop}'.`);
|
15958 | }
|
15959 | movePropBefore(ctx, prop, (p2) => p2 === positioning.before);
|
15960 | break;
|
15961 | }
|
15962 | }
|
15963 |
|
15964 |
|
15965 | function mainNgcc(options) {
|
15966 | const { basePath, targetEntryPointPath, propertiesToConsider, typingsOnly, compileAllFormats, logger, pathMappings, async, errorOnFailedEntryPoint, enableI18nLegacyMessageIdFormat, invalidateEntryPointManifest, fileSystem, absBasePath, projectPath, tsConfig, getFileWriter } = getSharedSetup(options);
|
15967 | const config = new NgccConfiguration(fileSystem, projectPath);
|
15968 | const dependencyResolver = getDependencyResolver(fileSystem, logger, config, pathMappings);
|
15969 | const entryPointManifest = invalidateEntryPointManifest ? new InvalidatingEntryPointManifest(fileSystem, config, logger) : new EntryPointManifest(fileSystem, config, logger);
|
15970 | const supportedPropertiesToConsider = ensureSupportedProperties(propertiesToConsider);
|
15971 | const absoluteTargetEntryPointPath = targetEntryPointPath !== void 0 ? fileSystem.resolve(basePath, targetEntryPointPath) : null;
|
15972 | const finder = getEntryPointFinder(fileSystem, logger, dependencyResolver, config, entryPointManifest, absBasePath, absoluteTargetEntryPointPath, pathMappings, options.findEntryPointsFromTsConfigProgram ? tsConfig : null, projectPath);
|
15973 | if (finder instanceof TargetedEntryPointFinder && !finder.targetNeedsProcessingOrCleaning(supportedPropertiesToConsider, compileAllFormats)) {
|
15974 | logger.debug("The target entry-point has already been processed");
|
15975 | return;
|
15976 | }
|
15977 | const workerCount = async ? getMaxNumberOfWorkers() : 1;
|
15978 | const inParallel = workerCount > 1;
|
15979 | const analyzeEntryPoints = getAnalyzeEntryPointsFn(logger, finder, fileSystem, supportedPropertiesToConsider, typingsOnly, compileAllFormats, propertiesToConsider, inParallel);
|
15980 | const pkgJsonUpdater = new DirectPackageJsonUpdater(fileSystem);
|
15981 | const fileWriter = getFileWriter(pkgJsonUpdater);
|
15982 | const createCompileFn = getCreateCompileFn(fileSystem, logger, fileWriter, enableI18nLegacyMessageIdFormat, tsConfig, pathMappings);
|
15983 | const createTaskCompletedCallback = getCreateTaskCompletedCallback(pkgJsonUpdater, errorOnFailedEntryPoint, logger, fileSystem);
|
15984 | const executor = getExecutor(async, workerCount, logger, fileWriter, pkgJsonUpdater, fileSystem, config, createTaskCompletedCallback);
|
15985 | return executor.execute(analyzeEntryPoints, createCompileFn);
|
15986 | }
|
15987 | function ensureSupportedProperties(properties) {
|
15988 | if (properties === SUPPORTED_FORMAT_PROPERTIES)
|
15989 | return SUPPORTED_FORMAT_PROPERTIES;
|
15990 | const supportedProperties = [];
|
15991 | for (const prop of properties) {
|
15992 | if (SUPPORTED_FORMAT_PROPERTIES.indexOf(prop) !== -1) {
|
15993 | supportedProperties.push(prop);
|
15994 | }
|
15995 | }
|
15996 | if (supportedProperties.length === 0) {
|
15997 | throw new Error(`No supported format property to consider among [${properties.join(", ")}]. Supported properties: ${SUPPORTED_FORMAT_PROPERTIES.join(", ")}`);
|
15998 | }
|
15999 | return supportedProperties;
|
16000 | }
|
16001 | function getCreateTaskCompletedCallback(pkgJsonUpdater, errorOnFailedEntryPoint, logger, fileSystem) {
|
16002 | return (taskQueue) => composeTaskCompletedCallbacks({
|
16003 | [0]: createMarkAsProcessedHandler(fileSystem, pkgJsonUpdater),
|
16004 | [1]: errorOnFailedEntryPoint ? createThrowErrorHandler(fileSystem) : createLogErrorHandler(logger, fileSystem, taskQueue)
|
16005 | });
|
16006 | }
|
16007 | function getExecutor(async, workerCount, logger, fileWriter, pkgJsonUpdater, fileSystem, config, createTaskCompletedCallback) {
|
16008 | const lockFile = new LockFileWithChildProcess(fileSystem, logger);
|
16009 | if (async) {
|
16010 | const { retryAttempts, retryDelay } = config.getLockingConfig();
|
16011 | const locker = new AsyncLocker(lockFile, logger, retryDelay, retryAttempts);
|
16012 | if (workerCount > 1) {
|
16013 | return new ClusterExecutor(workerCount, fileSystem, logger, fileWriter, pkgJsonUpdater, locker, createTaskCompletedCallback);
|
16014 | } else {
|
16015 | return new SingleProcessExecutorAsync(logger, locker, createTaskCompletedCallback);
|
16016 | }
|
16017 | } else {
|
16018 | return new SingleProcessExecutorSync(logger, new SyncLocker(lockFile), createTaskCompletedCallback);
|
16019 | }
|
16020 | }
|
16021 | function getDependencyResolver(fileSystem, logger, config, pathMappings) {
|
16022 | const moduleResolver = new ModuleResolver(fileSystem, pathMappings);
|
16023 | const esmDependencyHost = new EsmDependencyHost(fileSystem, moduleResolver);
|
16024 | const umdDependencyHost = new UmdDependencyHost(fileSystem, moduleResolver);
|
16025 | const commonJsDependencyHost = new CommonJsDependencyHost(fileSystem, moduleResolver);
|
16026 | const dtsDependencyHost = new DtsDependencyHost(fileSystem, pathMappings);
|
16027 | return new DependencyResolver(fileSystem, logger, config, {
|
16028 | esm5: esmDependencyHost,
|
16029 | esm2015: esmDependencyHost,
|
16030 | umd: umdDependencyHost,
|
16031 | commonjs: commonJsDependencyHost
|
16032 | }, dtsDependencyHost);
|
16033 | }
|
16034 | function getEntryPointFinder(fs5, logger, resolver, config, entryPointManifest, basePath, absoluteTargetEntryPointPath, pathMappings, tsConfig, projectPath) {
|
16035 | if (absoluteTargetEntryPointPath !== null) {
|
16036 | return new TargetedEntryPointFinder(fs5, config, logger, resolver, basePath, pathMappings, absoluteTargetEntryPointPath);
|
16037 | } else {
|
16038 | const entryPointCollector = new EntryPointCollector(fs5, config, logger, resolver);
|
16039 | if (tsConfig !== null) {
|
16040 | return new ProgramBasedEntryPointFinder(fs5, config, logger, resolver, entryPointCollector, entryPointManifest, basePath, tsConfig, projectPath);
|
16041 | } else {
|
16042 | return new DirectoryWalkerEntryPointFinder(logger, resolver, entryPointCollector, entryPointManifest, basePath, pathMappings);
|
16043 | }
|
16044 | }
|
16045 | }
|
16046 |
|
16047 |
|
16048 | function process2(options) {
|
16049 | setFileSystem(new NodeJSFileSystem());
|
16050 | return mainNgcc(options);
|
16051 | }
|
16052 | var containingDirPath = typeof __dirname !== "undefined" ? __dirname : dirname6(fileURLToPath2(__ESM_IMPORT_META_URL__));
|
16053 | var ngccMainFilePath = join6(containingDirPath, "./main-ngcc.js");
|
16054 | export {
|
16055 | ConsoleLogger,
|
16056 | LogLevel,
|
16057 | clearTsConfigCache,
|
16058 | containingDirPath,
|
16059 | ngccMainFilePath,
|
16060 | process2 as process
|
16061 | };
|
16062 |
|
16063 |
|
16064 |
|
16065 |
|
16066 |
|
16067 |
|
16068 |
|
16069 |
|