Updated the files.

This commit is contained in:
Batuhan Berk Başoğlu 2024-02-08 19:38:41 -05:00
parent 1553e6b971
commit 753967d4f5
23418 changed files with 3784666 additions and 0 deletions

21
my-app/node_modules/@ngtools/webpack/LICENSE generated vendored Executable file
View file

@ -0,0 +1,21 @@
The MIT License
Copyright (c) 2017 Google, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

80
my-app/node_modules/@ngtools/webpack/README.md generated vendored Executable file
View file

@ -0,0 +1,80 @@
# Angular Compiler Webpack Plugin
Webpack 5.x plugin for the Angular Ahead-of-Time compiler. The plugin also supports Angular JIT mode.
When this plugin is used outside of the Angular CLI, the Ivy linker will also be needed to support
the usage of Angular libraries. An example configuration of the Babel-based Ivy linker is provided
in the linker section. For additional information regarding the linker, please see: https://v13.angular.io/guide/creating-libraries#consuming-partial-ivy-code-outside-the-angular-cli
## Usage
In your webpack config, add the following plugin and loader.
```typescript
import { AngularWebpackPlugin } from '@ngtools/webpack';
exports = {
/* ... */
module: {
rules: [
/* ... */
{
test: /\.[jt]sx?$/,
loader: '@ngtools/webpack',
},
],
},
plugins: [
new AngularWebpackPlugin({
tsconfig: 'path/to/tsconfig.json',
// ... other options as needed
}),
],
};
```
The loader works with webpack plugin to compile the application's TypeScript. It is important to include both, and to not include any other TypeScript loader.
## Options
- `tsconfig` [default: `tsconfig.json`] - The path to the application's TypeScript Configuration file. In the `tsconfig.json`, you can pass options to the Angular Compiler with `angularCompilerOptions`. Relative paths will be resolved from the Webpack compilation's context.
- `compilerOptions` [default: none] - Overrides options in the application's TypeScript Configuration file (`tsconfig.json`).
- `jitMode` [default: `false`] - Enables JIT compilation and do not refactor the code to bootstrap. This replaces `templateUrl: "string"` with `template: require("string")` (and similar for styles) to allow for webpack to properly link the resources.
- `directTemplateLoading` [default: `true`] - Causes the plugin to load component templates (HTML) directly from the filesystem. This is more efficient if only using the `raw-loader` to load component templates. Do not enable this option if additional loaders are configured for component templates.
- `fileReplacements` [default: none] - Allows replacing TypeScript files with other TypeScript files in the build. This option acts on fully resolved file paths.
- `inlineStyleFileExtension` [default: none] - When set inline component styles will be processed by Webpack as files with the provided extension.
## Ivy Linker
The Ivy linker can be setup by using the Webpack `babel-loader` package.
If not already installed, add the `babel-loader` package using your project's package manager.
Then in your webpack config, add the `babel-loader` with the following configuration.
If the `babel-loader` is already present in your configuration, the linker plugin can be added to
the existing loader configuration as well.
Enabling caching for the `babel-loader` is recommended to avoid reprocessing libraries on
every build.
For additional information regarding the `babel-loader` package, please see: https://github.com/babel/babel-loader/tree/main#readme
```typescript
import linkerPlugin from '@angular/compiler-cli/linker/babel';
exports = {
/* ... */
module: {
rules: [
/* ... */
{
test: /\.[cm]?js$/,
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
compact: false,
plugins: [linkerPlugin],
},
},
},
],
},
};
```

38
my-app/node_modules/@ngtools/webpack/package.json generated vendored Executable file
View file

@ -0,0 +1,38 @@
{
"name": "@ngtools/webpack",
"version": "17.1.3",
"description": "Webpack plugin that AoT compiles your Angular components and modules.",
"main": "./src/index.js",
"typings": "src/index.d.ts",
"license": "MIT",
"keywords": [
"Angular CLI",
"Angular DevKit",
"angular",
"aot",
"devkit",
"plugin",
"sdk",
"webpack"
],
"repository": {
"type": "git",
"url": "https://github.com/angular/angular-cli.git"
},
"author": "Angular Authors",
"bugs": {
"url": "https://github.com/angular/angular-cli/issues"
},
"homepage": "https://github.com/angular/angular-cli",
"dependencies": {},
"peerDependencies": {
"@angular/compiler-cli": "^17.0.0",
"typescript": ">=5.2 <5.4",
"webpack": "^5.54.0"
},
"engines": {
"node": "^18.13.0 || >=20.9.0",
"npm": "^6.11.0 || ^7.5.6 || >=8.0.0",
"yarn": ">= 1.13.0"
}
}

9
my-app/node_modules/@ngtools/webpack/src/benchmark.d.ts generated vendored Executable file
View file

@ -0,0 +1,9 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export declare function time(label: string): void;
export declare function timeEnd(label: string): void;

27
my-app/node_modules/@ngtools/webpack/src/benchmark.js generated vendored Executable file
View file

@ -0,0 +1,27 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.timeEnd = exports.time = void 0;
// Internal benchmark reporting flag.
// Use with CLI --no-progress flag for best results.
// This should be false for commited code.
const _benchmark = false;
/* eslint-disable no-console */
function time(label) {
if (_benchmark) {
console.time(label);
}
}
exports.time = time;
function timeEnd(label) {
if (_benchmark) {
console.timeEnd(label);
}
}
exports.timeEnd = timeEnd;

8
my-app/node_modules/@ngtools/webpack/src/index.d.ts generated vendored Executable file
View file

@ -0,0 +1,8 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export { AngularWebpackLoaderPath, AngularWebpackPlugin, AngularWebpackPluginOptions, imageDomains, default, } from './ivy';

18
my-app/node_modules/@ngtools/webpack/src/index.js generated vendored Executable file
View file

@ -0,0 +1,18 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = exports.imageDomains = exports.AngularWebpackPlugin = exports.AngularWebpackLoaderPath = void 0;
var ivy_1 = require("./ivy");
Object.defineProperty(exports, "AngularWebpackLoaderPath", { enumerable: true, get: function () { return ivy_1.AngularWebpackLoaderPath; } });
Object.defineProperty(exports, "AngularWebpackPlugin", { enumerable: true, get: function () { return ivy_1.AngularWebpackPlugin; } });
Object.defineProperty(exports, "imageDomains", { enumerable: true, get: function () { return ivy_1.imageDomains; } });
Object.defineProperty(exports, "default", { enumerable: true, get: function () { return __importDefault(ivy_1).default; } });

14
my-app/node_modules/@ngtools/webpack/src/ivy/cache.d.ts generated vendored Executable file
View file

@ -0,0 +1,14 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
export declare class SourceFileCache extends Map<string, ts.SourceFile> {
private readonly angularDiagnostics;
invalidate(file: string): void;
updateAngularDiagnostics(sourceFile: ts.SourceFile, diagnostics: ts.Diagnostic[]): void;
getAngularDiagnostics(sourceFile: ts.SourceFile): ts.Diagnostic[] | undefined;
}

32
my-app/node_modules/@ngtools/webpack/src/ivy/cache.js generated vendored Executable file
View file

@ -0,0 +1,32 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.SourceFileCache = void 0;
class SourceFileCache extends Map {
angularDiagnostics = new Map();
invalidate(file) {
const sourceFile = this.get(file);
if (sourceFile) {
this.delete(file);
this.angularDiagnostics.delete(sourceFile);
}
}
updateAngularDiagnostics(sourceFile, diagnostics) {
if (diagnostics.length > 0) {
this.angularDiagnostics.set(sourceFile, diagnostics);
}
else {
this.angularDiagnostics.delete(sourceFile);
}
}
getAngularDiagnostics(sourceFile) {
return this.angularDiagnostics.get(sourceFile);
}
}
exports.SourceFileCache = SourceFileCache;

View file

@ -0,0 +1,13 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { Diagnostic } from 'typescript';
import type { Compilation } from 'webpack';
export type DiagnosticsReporter = (diagnostics: readonly Diagnostic[]) => void;
export declare function createDiagnosticsReporter(compilation: Compilation, formatter: (diagnostic: Diagnostic) => string): DiagnosticsReporter;
export declare function addWarning(compilation: Compilation, message: string): void;
export declare function addError(compilation: Compilation, message: string): void;

33
my-app/node_modules/@ngtools/webpack/src/ivy/diagnostics.js generated vendored Executable file
View file

@ -0,0 +1,33 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.addError = exports.addWarning = exports.createDiagnosticsReporter = void 0;
const typescript_1 = require("typescript");
function createDiagnosticsReporter(compilation, formatter) {
return (diagnostics) => {
for (const diagnostic of diagnostics) {
const text = formatter(diagnostic);
if (diagnostic.category === typescript_1.DiagnosticCategory.Error) {
addError(compilation, text);
}
else {
addWarning(compilation, text);
}
}
};
}
exports.createDiagnosticsReporter = createDiagnosticsReporter;
function addWarning(compilation, message) {
compilation.warnings.push(new compilation.compiler.webpack.WebpackError(message));
}
exports.addWarning = addWarning;
function addError(compilation, message) {
compilation.errors.push(new compilation.compiler.webpack.WebpackError(message));
}
exports.addError = addError;

33
my-app/node_modules/@ngtools/webpack/src/ivy/host.d.ts generated vendored Executable file
View file

@ -0,0 +1,33 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
import { WebpackResourceLoader } from '../resource_loader';
export declare function augmentHostWithResources(host: ts.CompilerHost, resourceLoader: WebpackResourceLoader, options?: {
directTemplateLoading?: boolean;
inlineStyleFileExtension?: string;
}): void;
/**
* Augments a TypeScript Compiler Host's resolveModuleNames function to collect dependencies
* of the containing file passed to the resolveModuleNames function. This process assumes
* that consumers of the Compiler Host will only call resolveModuleNames with modules that are
* actually present in a containing file.
* This process is a workaround for gathering a TypeScript SourceFile's dependencies as there
* is no currently exposed public method to do so. A BuilderProgram does have a `getAllDependencies`
* function. However, that function returns all transitive dependencies as well which can cause
* excessive Webpack rebuilds.
*
* @param host The CompilerHost to augment.
* @param dependencies A Map which will be used to store file dependencies.
* @param moduleResolutionCache An optional resolution cache to use when the host resolves a module.
*/
export declare function augmentHostWithDependencyCollection(host: ts.CompilerHost, dependencies: Map<string, Set<string>>, moduleResolutionCache?: ts.ModuleResolutionCache): void;
export declare function augmentHostWithReplacements(host: ts.CompilerHost, replacements: Record<string, string>, moduleResolutionCache?: ts.ModuleResolutionCache): void;
export declare function augmentHostWithSubstitutions(host: ts.CompilerHost, substitutions: Record<string, string>): void;
export declare function augmentHostWithVersioning(host: ts.CompilerHost): void;
export declare function augmentProgramWithVersioning(program: ts.Program): void;
export declare function augmentHostWithCaching(host: ts.CompilerHost, cache: Map<string, ts.SourceFile>): void;

227
my-app/node_modules/@ngtools/webpack/src/ivy/host.js generated vendored Executable file
View file

@ -0,0 +1,227 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.augmentHostWithCaching = exports.augmentProgramWithVersioning = exports.augmentHostWithVersioning = exports.augmentHostWithSubstitutions = exports.augmentHostWithReplacements = exports.augmentHostWithDependencyCollection = exports.augmentHostWithResources = void 0;
const crypto_1 = require("crypto");
const path = __importStar(require("path"));
const ts = __importStar(require("typescript"));
const paths_1 = require("./paths");
function augmentHostWithResources(host, resourceLoader, options = {}) {
const resourceHost = host;
resourceHost.readResource = function (fileName) {
const filePath = (0, paths_1.normalizePath)(fileName);
if (options.directTemplateLoading &&
(filePath.endsWith('.html') || filePath.endsWith('.svg'))) {
const content = this.readFile(filePath);
if (content === undefined) {
throw new Error('Unable to locate component resource: ' + fileName);
}
resourceLoader.setAffectedResources(filePath, [filePath]);
return content;
}
else {
return resourceLoader.get(filePath);
}
};
resourceHost.resourceNameToFileName = function (resourceName, containingFile) {
return path.join(path.dirname(containingFile), resourceName);
};
resourceHost.getModifiedResourceFiles = function () {
return resourceLoader.getModifiedResourceFiles();
};
resourceHost.transformResource = async function (data, context) {
// Only inline style resources are supported currently
if (context.resourceFile || context.type !== 'style') {
return null;
}
if (options.inlineStyleFileExtension) {
const content = await resourceLoader.process(data, options.inlineStyleFileExtension, context.type, context.containingFile);
return { content };
}
return null;
};
}
exports.augmentHostWithResources = augmentHostWithResources;
function augmentResolveModuleNames(host, resolvedModuleModifier, moduleResolutionCache) {
if (host.resolveModuleNames) {
const baseResolveModuleNames = host.resolveModuleNames;
host.resolveModuleNames = function (moduleNames, ...parameters) {
return moduleNames.map((name) => {
const result = baseResolveModuleNames.call(host, [name], ...parameters);
return resolvedModuleModifier(result[0], name);
});
};
}
else {
host.resolveModuleNames = function (moduleNames, containingFile, _reusedNames, redirectedReference, options) {
return moduleNames.map((name) => {
const result = ts.resolveModuleName(name, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule;
return resolvedModuleModifier(result, name);
});
};
}
}
/**
* Augments a TypeScript Compiler Host's resolveModuleNames function to collect dependencies
* of the containing file passed to the resolveModuleNames function. This process assumes
* that consumers of the Compiler Host will only call resolveModuleNames with modules that are
* actually present in a containing file.
* This process is a workaround for gathering a TypeScript SourceFile's dependencies as there
* is no currently exposed public method to do so. A BuilderProgram does have a `getAllDependencies`
* function. However, that function returns all transitive dependencies as well which can cause
* excessive Webpack rebuilds.
*
* @param host The CompilerHost to augment.
* @param dependencies A Map which will be used to store file dependencies.
* @param moduleResolutionCache An optional resolution cache to use when the host resolves a module.
*/
function augmentHostWithDependencyCollection(host, dependencies, moduleResolutionCache) {
if (host.resolveModuleNames) {
const baseResolveModuleNames = host.resolveModuleNames;
host.resolveModuleNames = function (moduleNames, containingFile, ...parameters) {
const results = baseResolveModuleNames.call(host, moduleNames, containingFile, ...parameters);
const containingFilePath = (0, paths_1.normalizePath)(containingFile);
for (const result of results) {
if (result) {
const containingFileDependencies = dependencies.get(containingFilePath);
if (containingFileDependencies) {
containingFileDependencies.add(result.resolvedFileName);
}
else {
dependencies.set(containingFilePath, new Set([result.resolvedFileName]));
}
}
}
return results;
};
}
else {
host.resolveModuleNames = function (moduleNames, containingFile, _reusedNames, redirectedReference, options) {
return moduleNames.map((name) => {
const result = ts.resolveModuleName(name, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule;
if (result) {
const containingFilePath = (0, paths_1.normalizePath)(containingFile);
const containingFileDependencies = dependencies.get(containingFilePath);
if (containingFileDependencies) {
containingFileDependencies.add(result.resolvedFileName);
}
else {
dependencies.set(containingFilePath, new Set([result.resolvedFileName]));
}
}
return result;
});
};
}
}
exports.augmentHostWithDependencyCollection = augmentHostWithDependencyCollection;
function augmentHostWithReplacements(host, replacements, moduleResolutionCache) {
if (Object.keys(replacements).length === 0) {
return;
}
const normalizedReplacements = {};
for (const [key, value] of Object.entries(replacements)) {
normalizedReplacements[(0, paths_1.normalizePath)(key)] = (0, paths_1.normalizePath)(value);
}
const tryReplace = (resolvedModule) => {
const replacement = resolvedModule && normalizedReplacements[resolvedModule.resolvedFileName];
if (replacement) {
return {
resolvedFileName: replacement,
isExternalLibraryImport: /[/\\]node_modules[/\\]/.test(replacement),
};
}
else {
return resolvedModule;
}
};
augmentResolveModuleNames(host, tryReplace, moduleResolutionCache);
}
exports.augmentHostWithReplacements = augmentHostWithReplacements;
function augmentHostWithSubstitutions(host, substitutions) {
const regexSubstitutions = [];
for (const [key, value] of Object.entries(substitutions)) {
regexSubstitutions.push([new RegExp(`\\b${key}\\b`, 'g'), value]);
}
if (regexSubstitutions.length === 0) {
return;
}
const baseReadFile = host.readFile;
host.readFile = function (...parameters) {
let file = baseReadFile.call(host, ...parameters);
if (file) {
for (const entry of regexSubstitutions) {
file = file.replace(entry[0], entry[1]);
}
}
return file;
};
}
exports.augmentHostWithSubstitutions = augmentHostWithSubstitutions;
function augmentHostWithVersioning(host) {
const baseGetSourceFile = host.getSourceFile;
host.getSourceFile = function (...parameters) {
const file = baseGetSourceFile.call(host, ...parameters);
if (file && file.version === undefined) {
file.version = (0, crypto_1.createHash)('sha256').update(file.text).digest('hex');
}
return file;
};
}
exports.augmentHostWithVersioning = augmentHostWithVersioning;
function augmentProgramWithVersioning(program) {
const baseGetSourceFiles = program.getSourceFiles;
program.getSourceFiles = function (...parameters) {
const files = baseGetSourceFiles(...parameters);
for (const file of files) {
if (file.version === undefined) {
file.version = (0, crypto_1.createHash)('sha256').update(file.text).digest('hex');
}
}
return files;
};
}
exports.augmentProgramWithVersioning = augmentProgramWithVersioning;
function augmentHostWithCaching(host, cache) {
const baseGetSourceFile = host.getSourceFile;
host.getSourceFile = function (fileName, languageVersion, onError, shouldCreateNewSourceFile, ...parameters) {
if (!shouldCreateNewSourceFile && cache.has(fileName)) {
return cache.get(fileName);
}
const file = baseGetSourceFile.call(host, fileName, languageVersion, onError, true, ...parameters);
if (file) {
cache.set(fileName, file);
}
return file;
};
}
exports.augmentHostWithCaching = augmentHostWithCaching;

10
my-app/node_modules/@ngtools/webpack/src/ivy/index.d.ts generated vendored Executable file
View file

@ -0,0 +1,10 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export { angularWebpackLoader as default } from './loader';
export { AngularWebpackPluginOptions, AngularWebpackPlugin, imageDomains } from './plugin';
export declare const AngularWebpackLoaderPath: string;

16
my-app/node_modules/@ngtools/webpack/src/ivy/index.js generated vendored Executable file
View file

@ -0,0 +1,16 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.AngularWebpackLoaderPath = exports.imageDomains = exports.AngularWebpackPlugin = exports.default = void 0;
var loader_1 = require("./loader");
Object.defineProperty(exports, "default", { enumerable: true, get: function () { return loader_1.angularWebpackLoader; } });
var plugin_1 = require("./plugin");
Object.defineProperty(exports, "AngularWebpackPlugin", { enumerable: true, get: function () { return plugin_1.AngularWebpackPlugin; } });
Object.defineProperty(exports, "imageDomains", { enumerable: true, get: function () { return plugin_1.imageDomains; } });
exports.AngularWebpackLoaderPath = __filename;

10
my-app/node_modules/@ngtools/webpack/src/ivy/loader.d.ts generated vendored Executable file
View file

@ -0,0 +1,10 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import type { LoaderContext } from 'webpack';
export declare function angularWebpackLoader(this: LoaderContext<unknown>, content: string, map: string): void;
export { angularWebpackLoader as default };

85
my-app/node_modules/@ngtools/webpack/src/ivy/loader.js generated vendored Executable file
View file

@ -0,0 +1,85 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = exports.angularWebpackLoader = void 0;
const path = __importStar(require("path"));
const symbol_1 = require("./symbol");
const JS_FILE_REGEXP = /\.[cm]?js$/;
function angularWebpackLoader(content, map) {
const callback = this.async();
if (!callback) {
throw new Error('Invalid webpack version');
}
const fileEmitter = this[symbol_1.AngularPluginSymbol];
if (!fileEmitter || typeof fileEmitter !== 'object') {
if (JS_FILE_REGEXP.test(this.resourcePath)) {
// Passthrough for JS files when no plugin is used
this.callback(undefined, content, map);
return;
}
callback(new Error('The Angular Webpack loader requires the AngularWebpackPlugin.'));
return;
}
fileEmitter
.emit(this.resourcePath)
.then((result) => {
if (!result) {
if (JS_FILE_REGEXP.test(this.resourcePath)) {
// Return original content for JS files if not compiled by TypeScript ("allowJs")
this.callback(undefined, content, map);
}
else {
// File is not part of the compilation
const message = `${this.resourcePath} is missing from the TypeScript compilation. ` +
`Please make sure it is in your tsconfig via the 'files' or 'include' property.`;
callback(new Error(message));
}
return;
}
result.dependencies.forEach((dependency) => this.addDependency(dependency));
let resultContent = result.content || '';
let resultMap;
if (result.map) {
resultContent = resultContent.replace(/^\/\/# sourceMappingURL=[^\r\n]*/gm, '');
resultMap = JSON.parse(result.map);
resultMap.sources = resultMap.sources.map((source) => path.join(path.dirname(this.resourcePath), source));
}
callback(undefined, resultContent, resultMap);
})
.catch((err) => {
// The below is needed to hide stacktraces from users.
const message = err instanceof Error ? err.message : err;
callback(new Error(message));
});
}
exports.angularWebpackLoader = angularWebpackLoader;
exports.default = angularWebpackLoader;

9
my-app/node_modules/@ngtools/webpack/src/ivy/paths.d.ts generated vendored Executable file
View file

@ -0,0 +1,9 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export declare function normalizePath(path: string): string;
export declare const externalizePath: (path: string) => string;

59
my-app/node_modules/@ngtools/webpack/src/ivy/paths.js generated vendored Executable file
View file

@ -0,0 +1,59 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.externalizePath = exports.normalizePath = void 0;
const nodePath = __importStar(require("path"));
const normalizationCache = new Map();
function normalizePath(path) {
let result = normalizationCache.get(path);
if (result === undefined) {
result = nodePath.win32.normalize(path).replace(/\\/g, nodePath.posix.sep);
normalizationCache.set(path, result);
}
return result;
}
exports.normalizePath = normalizePath;
const externalizationCache = new Map();
function externalizeForWindows(path) {
let result = externalizationCache.get(path);
if (result === undefined) {
result = nodePath.win32.normalize(path);
externalizationCache.set(path, result);
}
return result;
}
exports.externalizePath = (() => {
if (process.platform !== 'win32') {
return (path) => path;
}
return externalizeForWindows;
})();

51
my-app/node_modules/@ngtools/webpack/src/ivy/plugin.d.ts generated vendored Executable file
View file

@ -0,0 +1,51 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import type { CompilerOptions } from '@angular/compiler-cli';
import type { Compiler } from 'webpack';
export declare const imageDomains: Set<string>;
export interface AngularWebpackPluginOptions {
tsconfig: string;
compilerOptions?: CompilerOptions;
fileReplacements: Record<string, string>;
substitutions: Record<string, string>;
directTemplateLoading: boolean;
emitClassMetadata: boolean;
emitNgModuleScope: boolean;
emitSetClassDebugInfo?: boolean;
jitMode: boolean;
inlineStyleFileExtension?: string;
}
export declare class AngularWebpackPlugin {
private readonly pluginOptions;
private compilerCliModule?;
private watchMode?;
private ngtscNextProgram?;
private builder?;
private sourceFileCache?;
private webpackCache?;
private webpackCreateHash?;
private readonly fileDependencies;
private readonly requiredFilesToEmit;
private readonly requiredFilesToEmitCache;
private readonly fileEmitHistory;
constructor(options?: Partial<AngularWebpackPluginOptions>);
private get compilerCli();
get options(): AngularWebpackPluginOptions;
apply(compiler: Compiler): void;
private setupCompilation;
private registerWithCompilation;
private markResourceUsed;
private rebuildRequiredFiles;
private loadConfiguration;
private updateAotProgram;
private updateJitProgram;
private createFileEmitter;
private initializeCompilerCli;
private addFileEmitHistory;
private getFileEmitHistory;
}

537
my-app/node_modules/@ngtools/webpack/src/ivy/plugin.js generated vendored Executable file
View file

@ -0,0 +1,537 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AngularWebpackPlugin = exports.imageDomains = void 0;
const assert_1 = require("assert");
const ts = __importStar(require("typescript"));
const paths_plugin_1 = require("../paths-plugin");
const resource_loader_1 = require("../resource_loader");
const cache_1 = require("./cache");
const diagnostics_1 = require("./diagnostics");
const host_1 = require("./host");
const paths_1 = require("./paths");
const symbol_1 = require("./symbol");
const system_1 = require("./system");
const transformation_1 = require("./transformation");
/**
* The threshold used to determine whether Angular file diagnostics should optimize for full programs
* or single files. If the number of affected files for a build is more than the threshold, full
* program optimization will be used.
*/
const DIAGNOSTICS_AFFECTED_THRESHOLD = 1;
exports.imageDomains = new Set();
const PLUGIN_NAME = 'angular-compiler';
const compilationFileEmitters = new WeakMap();
class AngularWebpackPlugin {
pluginOptions;
compilerCliModule;
watchMode;
ngtscNextProgram;
builder;
sourceFileCache;
webpackCache;
webpackCreateHash;
fileDependencies = new Map();
requiredFilesToEmit = new Set();
requiredFilesToEmitCache = new Map();
fileEmitHistory = new Map();
constructor(options = {}) {
this.pluginOptions = {
emitClassMetadata: false,
emitNgModuleScope: false,
jitMode: false,
fileReplacements: {},
substitutions: {},
directTemplateLoading: true,
tsconfig: 'tsconfig.json',
...options,
};
}
get compilerCli() {
// The compilerCliModule field is guaranteed to be defined during a compilation
// due to the `beforeCompile` hook. Usage of this property accessor prior to the
// hook execution is an implementation error.
assert_1.strict.ok(this.compilerCliModule, `'@angular/compiler-cli' used prior to Webpack compilation.`);
return this.compilerCliModule;
}
get options() {
return this.pluginOptions;
}
apply(compiler) {
const { NormalModuleReplacementPlugin, WebpackError, util } = compiler.webpack;
this.webpackCreateHash = util.createHash;
// Setup file replacements with webpack
for (const [key, value] of Object.entries(this.pluginOptions.fileReplacements)) {
new NormalModuleReplacementPlugin(new RegExp('^' + key.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&') + '$'), value).apply(compiler);
}
// Set resolver options
const pathsPlugin = new paths_plugin_1.TypeScriptPathsPlugin();
compiler.hooks.afterResolvers.tap(PLUGIN_NAME, (compiler) => {
compiler.resolverFactory.hooks.resolveOptions
.for('normal')
.tap(PLUGIN_NAME, (resolveOptions) => {
resolveOptions.plugins ??= [];
resolveOptions.plugins.push(pathsPlugin);
return resolveOptions;
});
});
// Load the compiler-cli if not already available
compiler.hooks.beforeCompile.tapPromise(PLUGIN_NAME, () => this.initializeCompilerCli());
const compilationState = { pathsPlugin };
compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
try {
this.setupCompilation(compilation, compilationState);
}
catch (error) {
(0, diagnostics_1.addError)(compilation, `Failed to initialize Angular compilation - ${error instanceof Error ? error.message : error}`);
}
});
}
setupCompilation(compilation, state) {
const compiler = compilation.compiler;
// Register plugin to ensure deterministic emit order in multi-plugin usage
const emitRegistration = this.registerWithCompilation(compilation);
this.watchMode = compiler.watchMode;
// Initialize webpack cache
if (!this.webpackCache && compilation.options.cache) {
this.webpackCache = compilation.getCache(PLUGIN_NAME);
}
// Initialize the resource loader if not already setup
if (!state.resourceLoader) {
state.resourceLoader = new resource_loader_1.WebpackResourceLoader(this.watchMode);
}
// Setup and read TypeScript and Angular compiler configuration
const { compilerOptions, rootNames, errors } = this.loadConfiguration();
// Create diagnostics reporter and report configuration file errors
const diagnosticsReporter = (0, diagnostics_1.createDiagnosticsReporter)(compilation, (diagnostic) => this.compilerCli.formatDiagnostics([diagnostic]));
diagnosticsReporter(errors);
// Update TypeScript path mapping plugin with new configuration
state.pathsPlugin.update(compilerOptions);
// Create a Webpack-based TypeScript compiler host
const system = (0, system_1.createWebpackSystem)(
// Webpack lacks an InputFileSytem type definition with sync functions
compiler.inputFileSystem, (0, paths_1.normalizePath)(compiler.context));
const host = ts.createIncrementalCompilerHost(compilerOptions, system);
// Setup source file caching and reuse cache from previous compilation if present
let cache = this.sourceFileCache;
let changedFiles;
if (cache) {
changedFiles = new Set();
for (const changedFile of [
...(compiler.modifiedFiles ?? []),
...(compiler.removedFiles ?? []),
]) {
const normalizedChangedFile = (0, paths_1.normalizePath)(changedFile);
// Invalidate file dependencies
this.fileDependencies.delete(normalizedChangedFile);
// Invalidate existing cache
cache.invalidate(normalizedChangedFile);
changedFiles.add(normalizedChangedFile);
}
}
else {
// Initialize a new cache
cache = new cache_1.SourceFileCache();
// Only store cache if in watch mode
if (this.watchMode) {
this.sourceFileCache = cache;
}
}
(0, host_1.augmentHostWithCaching)(host, cache);
const moduleResolutionCache = ts.createModuleResolutionCache(host.getCurrentDirectory(), host.getCanonicalFileName.bind(host), compilerOptions);
// Setup source file dependency collection
(0, host_1.augmentHostWithDependencyCollection)(host, this.fileDependencies, moduleResolutionCache);
// Setup resource loading
state.resourceLoader.update(compilation, changedFiles);
(0, host_1.augmentHostWithResources)(host, state.resourceLoader, {
directTemplateLoading: this.pluginOptions.directTemplateLoading,
inlineStyleFileExtension: this.pluginOptions.inlineStyleFileExtension,
});
// Setup source file adjustment options
(0, host_1.augmentHostWithReplacements)(host, this.pluginOptions.fileReplacements, moduleResolutionCache);
(0, host_1.augmentHostWithSubstitutions)(host, this.pluginOptions.substitutions);
// Create the file emitter used by the webpack loader
const { fileEmitter, builder, internalFiles } = this.pluginOptions.jitMode
? this.updateJitProgram(compilerOptions, rootNames, host, diagnosticsReporter)
: this.updateAotProgram(compilerOptions, rootNames, host, diagnosticsReporter, state.resourceLoader);
// Set of files used during the unused TypeScript file analysis
const currentUnused = new Set();
for (const sourceFile of builder.getSourceFiles()) {
if (internalFiles?.has(sourceFile)) {
continue;
}
// Ensure all program files are considered part of the compilation and will be watched.
// Webpack does not normalize paths. Therefore, we need to normalize the path with FS seperators.
compilation.fileDependencies.add((0, paths_1.externalizePath)(sourceFile.fileName));
// Add all non-declaration files to the initial set of unused files. The set will be
// analyzed and pruned after all Webpack modules are finished building.
if (!sourceFile.isDeclarationFile) {
currentUnused.add((0, paths_1.normalizePath)(sourceFile.fileName));
}
}
compilation.hooks.finishModules.tapPromise(PLUGIN_NAME, async (modules) => {
// Rebuild any remaining AOT required modules
await this.rebuildRequiredFiles(modules, compilation, fileEmitter);
// Clear out the Webpack compilation to avoid an extra retaining reference
state.resourceLoader?.clearParentCompilation();
// Analyze program for unused files
if (compilation.errors.length > 0) {
return;
}
for (const webpackModule of modules) {
const resource = webpackModule.resource;
if (resource) {
this.markResourceUsed((0, paths_1.normalizePath)(resource), currentUnused);
}
}
for (const unused of currentUnused) {
if (state.previousUnused?.has(unused)) {
continue;
}
(0, diagnostics_1.addWarning)(compilation, `${unused} is part of the TypeScript compilation but it's unused.\n` +
`Add only entry points to the 'files' or 'include' properties in your tsconfig.`);
}
state.previousUnused = currentUnused;
});
// Store file emitter for loader usage
emitRegistration.update(fileEmitter);
}
registerWithCompilation(compilation) {
let fileEmitters = compilationFileEmitters.get(compilation);
if (!fileEmitters) {
fileEmitters = new symbol_1.FileEmitterCollection();
compilationFileEmitters.set(compilation, fileEmitters);
compilation.compiler.webpack.NormalModule.getCompilationHooks(compilation).loader.tap(PLUGIN_NAME, (loaderContext) => {
loaderContext[symbol_1.AngularPluginSymbol] = fileEmitters;
});
}
const emitRegistration = fileEmitters.register();
return emitRegistration;
}
markResourceUsed(normalizedResourcePath, currentUnused) {
if (!currentUnused.has(normalizedResourcePath)) {
return;
}
currentUnused.delete(normalizedResourcePath);
const dependencies = this.fileDependencies.get(normalizedResourcePath);
if (!dependencies) {
return;
}
for (const dependency of dependencies) {
this.markResourceUsed((0, paths_1.normalizePath)(dependency), currentUnused);
}
}
async rebuildRequiredFiles(modules, compilation, fileEmitter) {
if (this.requiredFilesToEmit.size === 0) {
return;
}
const filesToRebuild = new Set();
for (const requiredFile of this.requiredFilesToEmit) {
const history = await this.getFileEmitHistory(requiredFile);
if (history) {
const emitResult = await fileEmitter(requiredFile);
if (emitResult?.content === undefined ||
history.length !== emitResult.content.length ||
emitResult.hash === undefined ||
Buffer.compare(history.hash, emitResult.hash) !== 0) {
// New emit result is different so rebuild using new emit result
this.requiredFilesToEmitCache.set(requiredFile, emitResult);
filesToRebuild.add(requiredFile);
}
}
else {
// No emit history so rebuild
filesToRebuild.add(requiredFile);
}
}
if (filesToRebuild.size > 0) {
const rebuild = (webpackModule) => new Promise((resolve) => compilation.rebuildModule(webpackModule, () => resolve()));
const modulesToRebuild = [];
for (const webpackModule of modules) {
const resource = webpackModule.resource;
if (resource && filesToRebuild.has((0, paths_1.normalizePath)(resource))) {
modulesToRebuild.push(webpackModule);
}
}
await Promise.all(modulesToRebuild.map((webpackModule) => rebuild(webpackModule)));
}
this.requiredFilesToEmit.clear();
this.requiredFilesToEmitCache.clear();
}
loadConfiguration() {
const { options: compilerOptions, rootNames, errors, } = this.compilerCli.readConfiguration(this.pluginOptions.tsconfig, this.pluginOptions.compilerOptions);
compilerOptions.noEmitOnError = false;
compilerOptions.suppressOutputPathCheck = true;
compilerOptions.outDir = undefined;
compilerOptions.inlineSources = compilerOptions.sourceMap;
compilerOptions.inlineSourceMap = false;
compilerOptions.mapRoot = undefined;
compilerOptions.sourceRoot = undefined;
compilerOptions.allowEmptyCodegenFiles = false;
compilerOptions.annotationsAs = 'decorators';
compilerOptions.enableResourceInlining = false;
return { compilerOptions, rootNames, errors };
}
updateAotProgram(compilerOptions, rootNames, host, diagnosticsReporter, resourceLoader) {
// Create the Angular specific program that contains the Angular compiler
const angularProgram = new this.compilerCli.NgtscProgram(rootNames, compilerOptions, host, this.ngtscNextProgram);
const angularCompiler = angularProgram.compiler;
// The `ignoreForEmit` return value can be safely ignored when emitting. Only files
// that will be bundled (requested by Webpack) will be emitted. Combined with TypeScript's
// eliding of type only imports, this will cause type only files to be automatically ignored.
// Internal Angular type check files are also not resolvable by the bundler. Even if they
// were somehow errantly imported, the bundler would error before an emit was attempted.
// Diagnostics are still collected for all files which requires using `ignoreForDiagnostics`.
const { ignoreForDiagnostics, ignoreForEmit } = angularCompiler;
// SourceFile versions are required for builder programs.
// The wrapped host inside NgtscProgram adds additional files that will not have versions.
const typeScriptProgram = angularProgram.getTsProgram();
(0, host_1.augmentProgramWithVersioning)(typeScriptProgram);
let builder;
if (this.watchMode) {
builder = this.builder = ts.createEmitAndSemanticDiagnosticsBuilderProgram(typeScriptProgram, host, this.builder);
this.ngtscNextProgram = angularProgram;
}
else {
// When not in watch mode, the startup cost of the incremental analysis can be avoided by
// using an abstract builder that only wraps a TypeScript program.
builder = ts.createAbstractBuilder(typeScriptProgram, host);
}
// Update semantic diagnostics cache
const affectedFiles = new Set();
// Analyze affected files when in watch mode for incremental type checking
if ('getSemanticDiagnosticsOfNextAffectedFile' in builder) {
// eslint-disable-next-line no-constant-condition
while (true) {
const result = builder.getSemanticDiagnosticsOfNextAffectedFile(undefined, (sourceFile) => {
// If the affected file is a TTC shim, add the shim's original source file.
// This ensures that changes that affect TTC are typechecked even when the changes
// are otherwise unrelated from a TS perspective and do not result in Ivy codegen changes.
// For example, changing @Input property types of a directive used in another component's
// template.
if (ignoreForDiagnostics.has(sourceFile) &&
sourceFile.fileName.endsWith('.ngtypecheck.ts')) {
// This file name conversion relies on internal compiler logic and should be converted
// to an official method when available. 15 is length of `.ngtypecheck.ts`
const originalFilename = sourceFile.fileName.slice(0, -15) + '.ts';
const originalSourceFile = builder.getSourceFile(originalFilename);
if (originalSourceFile) {
affectedFiles.add(originalSourceFile);
}
return true;
}
return false;
});
if (!result) {
break;
}
affectedFiles.add(result.affected);
}
}
// Collect program level diagnostics
const diagnostics = [
...angularCompiler.getOptionDiagnostics(),
...builder.getOptionsDiagnostics(),
...builder.getGlobalDiagnostics(),
];
diagnosticsReporter(diagnostics);
// Collect source file specific diagnostics
for (const sourceFile of builder.getSourceFiles()) {
if (!ignoreForDiagnostics.has(sourceFile)) {
diagnosticsReporter(builder.getSyntacticDiagnostics(sourceFile));
diagnosticsReporter(builder.getSemanticDiagnostics(sourceFile));
}
}
const transformers = (0, transformation_1.createAotTransformers)(builder, this.pluginOptions, exports.imageDomains);
const getDependencies = (sourceFile) => {
const dependencies = [];
for (const resourcePath of angularCompiler.getResourceDependencies(sourceFile)) {
dependencies.push(resourcePath,
// Retrieve all dependencies of the resource (stylesheet imports, etc.)
...resourceLoader.getResourceDependencies(resourcePath));
}
return dependencies;
};
// Required to support asynchronous resource loading
// Must be done before creating transformers or getting template diagnostics
const pendingAnalysis = angularCompiler
.analyzeAsync()
.then(() => {
this.requiredFilesToEmit.clear();
for (const sourceFile of builder.getSourceFiles()) {
if (sourceFile.isDeclarationFile) {
continue;
}
// Collect sources that are required to be emitted
if (!ignoreForEmit.has(sourceFile) &&
!angularCompiler.incrementalCompilation.safeToSkipEmit(sourceFile)) {
this.requiredFilesToEmit.add((0, paths_1.normalizePath)(sourceFile.fileName));
// If required to emit, diagnostics may have also changed
if (!ignoreForDiagnostics.has(sourceFile)) {
affectedFiles.add(sourceFile);
}
}
else if (this.sourceFileCache &&
!affectedFiles.has(sourceFile) &&
!ignoreForDiagnostics.has(sourceFile)) {
// Use cached Angular diagnostics for unchanged and unaffected files
const angularDiagnostics = this.sourceFileCache.getAngularDiagnostics(sourceFile);
if (angularDiagnostics) {
diagnosticsReporter(angularDiagnostics);
}
}
}
// Collect new Angular diagnostics for files affected by changes
const OptimizeFor = this.compilerCli.OptimizeFor;
const optimizeDiagnosticsFor = affectedFiles.size <= DIAGNOSTICS_AFFECTED_THRESHOLD
? OptimizeFor.SingleFile
: OptimizeFor.WholeProgram;
for (const affectedFile of affectedFiles) {
const angularDiagnostics = angularCompiler.getDiagnosticsForFile(affectedFile, optimizeDiagnosticsFor);
diagnosticsReporter(angularDiagnostics);
this.sourceFileCache?.updateAngularDiagnostics(affectedFile, angularDiagnostics);
}
return {
emitter: this.createFileEmitter(builder, (0, transformation_1.mergeTransformers)(angularCompiler.prepareEmit().transformers, transformers), getDependencies, (sourceFile) => {
this.requiredFilesToEmit.delete((0, paths_1.normalizePath)(sourceFile.fileName));
angularCompiler.incrementalCompilation.recordSuccessfulEmit(sourceFile);
}),
};
})
.catch((err) => ({ errorMessage: err instanceof Error ? err.message : `${err}` }));
const analyzingFileEmitter = async (file) => {
const analysis = await pendingAnalysis;
if ('errorMessage' in analysis) {
throw new Error(analysis.errorMessage);
}
return analysis.emitter(file);
};
return {
fileEmitter: analyzingFileEmitter,
builder,
internalFiles: ignoreForEmit,
};
}
updateJitProgram(compilerOptions, rootNames, host, diagnosticsReporter) {
let builder;
if (this.watchMode) {
builder = this.builder = ts.createEmitAndSemanticDiagnosticsBuilderProgram(rootNames, compilerOptions, host, this.builder);
}
else {
// When not in watch mode, the startup cost of the incremental analysis can be avoided by
// using an abstract builder that only wraps a TypeScript program.
builder = ts.createAbstractBuilder(rootNames, compilerOptions, host);
}
const diagnostics = [
...builder.getOptionsDiagnostics(),
...builder.getGlobalDiagnostics(),
...builder.getSyntacticDiagnostics(),
// Gather incremental semantic diagnostics
...builder.getSemanticDiagnostics(),
];
diagnosticsReporter(diagnostics);
const transformers = (0, transformation_1.createJitTransformers)(builder, this.compilerCli, this.pluginOptions);
return {
fileEmitter: this.createFileEmitter(builder, transformers, () => []),
builder,
internalFiles: undefined,
};
}
createFileEmitter(program, transformers = {}, getExtraDependencies, onAfterEmit) {
return async (file) => {
const filePath = (0, paths_1.normalizePath)(file);
if (this.requiredFilesToEmitCache.has(filePath)) {
return this.requiredFilesToEmitCache.get(filePath);
}
const sourceFile = program.getSourceFile(filePath);
if (!sourceFile) {
return undefined;
}
let content;
let map;
program.emit(sourceFile, (filename, data) => {
if (filename.endsWith('.map')) {
map = data;
}
else if (filename.endsWith('.js')) {
content = data;
}
}, undefined, undefined, transformers);
onAfterEmit?.(sourceFile);
// Capture emit history info for Angular rebuild analysis
const hash = content ? (await this.addFileEmitHistory(filePath, content)).hash : undefined;
const dependencies = [
...(this.fileDependencies.get(filePath) || []),
...getExtraDependencies(sourceFile),
].map(paths_1.externalizePath);
return { content, map, dependencies, hash };
};
}
async initializeCompilerCli() {
if (this.compilerCliModule) {
return;
}
// This uses a dynamic import to load `@angular/compiler-cli` which may be ESM.
// CommonJS code can load ESM code via a dynamic import. Unfortunately, TypeScript
// will currently, unconditionally downlevel dynamic import into a require call.
// require calls cannot load ESM code and will result in a runtime error. To workaround
// this, a Function constructor is used to prevent TypeScript from changing the dynamic import.
// Once TypeScript provides support for keeping the dynamic import this workaround can
// be dropped.
this.compilerCliModule = await new Function(`return import('@angular/compiler-cli');`)();
}
async addFileEmitHistory(filePath, content) {
assert_1.strict.ok(this.webpackCreateHash, 'File emitter is used prior to Webpack compilation');
const historyData = {
length: content.length,
hash: this.webpackCreateHash('xxhash64').update(content).digest(),
};
if (this.webpackCache) {
const history = await this.getFileEmitHistory(filePath);
if (!history || Buffer.compare(history.hash, historyData.hash) !== 0) {
// Hash doesn't match or item doesn't exist.
await this.webpackCache.storePromise(filePath, null, historyData);
}
}
else if (this.watchMode) {
// The in memory file emit history is only required during watch mode.
this.fileEmitHistory.set(filePath, historyData);
}
return historyData;
}
async getFileEmitHistory(filePath) {
return this.webpackCache
? this.webpackCache.getPromise(filePath, null)
: this.fileEmitHistory.get(filePath);
}
}
exports.AngularWebpackPlugin = AngularWebpackPlugin;

25
my-app/node_modules/@ngtools/webpack/src/ivy/symbol.d.ts generated vendored Executable file
View file

@ -0,0 +1,25 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export declare const AngularPluginSymbol: unique symbol;
export interface EmitFileResult {
content?: string;
map?: string;
dependencies: readonly string[];
hash?: Uint8Array;
}
export type FileEmitter = (file: string) => Promise<EmitFileResult | undefined>;
export declare class FileEmitterRegistration {
#private;
update(emitter: FileEmitter): void;
emit(file: string): Promise<EmitFileResult | undefined>;
}
export declare class FileEmitterCollection {
#private;
register(): FileEmitterRegistration;
emit(file: string): Promise<EmitFileResult | undefined>;
}

44
my-app/node_modules/@ngtools/webpack/src/ivy/symbol.js generated vendored Executable file
View file

@ -0,0 +1,44 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.FileEmitterCollection = exports.FileEmitterRegistration = exports.AngularPluginSymbol = void 0;
exports.AngularPluginSymbol = Symbol.for('@ngtools/webpack[angular-compiler]');
class FileEmitterRegistration {
#fileEmitter;
update(emitter) {
this.#fileEmitter = emitter;
}
emit(file) {
if (!this.#fileEmitter) {
throw new Error('Emit attempted before Angular Webpack plugin initialization.');
}
return this.#fileEmitter(file);
}
}
exports.FileEmitterRegistration = FileEmitterRegistration;
class FileEmitterCollection {
#registrations = [];
register() {
const registration = new FileEmitterRegistration();
this.#registrations.push(registration);
return registration;
}
async emit(file) {
if (this.#registrations.length === 1) {
return this.#registrations[0].emit(file);
}
for (const registration of this.#registrations) {
const result = await registration.emit(file);
if (result) {
return result;
}
}
}
}
exports.FileEmitterCollection = FileEmitterCollection;

20
my-app/node_modules/@ngtools/webpack/src/ivy/system.d.ts generated vendored Executable file
View file

@ -0,0 +1,20 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
import { Compiler } from 'webpack';
export type InputFileSystem = Compiler['inputFileSystem'];
export interface InputFileSystemSync extends InputFileSystem {
readFileSync(path: string): Buffer;
statSync(path: string): {
size: number;
mtime: Date;
isDirectory(): boolean;
isFile(): boolean;
};
}
export declare function createWebpackSystem(input: InputFileSystemSync, currentDirectory: string): ts.System;

105
my-app/node_modules/@ngtools/webpack/src/ivy/system.js generated vendored Executable file
View file

@ -0,0 +1,105 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createWebpackSystem = void 0;
const ts = __importStar(require("typescript"));
const paths_1 = require("./paths");
function shouldNotWrite() {
throw new Error('Webpack TypeScript System should not write.');
}
function createWebpackSystem(input, currentDirectory) {
// Webpack's CachedInputFileSystem uses the default directory separator in the paths it uses
// for keys to its cache. If the keys do not match then the file watcher will not purge outdated
// files and cause stale data to be used in the next rebuild. TypeScript always uses a `/` (POSIX)
// directory separator internally which is also supported with Windows system APIs. However,
// if file operations are performed with the non-default directory separator, the Webpack cache
// will contain a key that will not be purged. `externalizePath` ensures the paths are as expected.
const system = {
...ts.sys,
readFile(path) {
let data;
try {
data = input.readFileSync((0, paths_1.externalizePath)(path));
}
catch {
return undefined;
}
// Strip BOM if present
let start = 0;
if (data.length > 3 && data[0] === 0xef && data[1] === 0xbb && data[2] === 0xbf) {
start = 3;
}
return data.toString('utf8', start);
},
getFileSize(path) {
try {
return input.statSync((0, paths_1.externalizePath)(path)).size;
}
catch {
return 0;
}
},
fileExists(path) {
try {
return input.statSync((0, paths_1.externalizePath)(path)).isFile();
}
catch {
return false;
}
},
directoryExists(path) {
try {
return input.statSync((0, paths_1.externalizePath)(path)).isDirectory();
}
catch {
return false;
}
},
getModifiedTime(path) {
try {
return input.statSync((0, paths_1.externalizePath)(path)).mtime;
}
catch {
return undefined;
}
},
getCurrentDirectory() {
return currentDirectory;
},
writeFile: shouldNotWrite,
createDirectory: shouldNotWrite,
deleteFile: shouldNotWrite,
setModifiedTime: shouldNotWrite,
};
return system;
}
exports.createWebpackSystem = createWebpackSystem;

View file

@ -0,0 +1,18 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
export declare function createAotTransformers(builder: ts.BuilderProgram, options: {
emitClassMetadata?: boolean;
emitNgModuleScope?: boolean;
emitSetClassDebugInfo?: boolean;
}, imageDomains: Set<string>): ts.CustomTransformers;
export declare function createJitTransformers(builder: ts.BuilderProgram, compilerCli: typeof import('@angular/compiler-cli'), options: {
inlineStyleFileExtension?: string;
}): ts.CustomTransformers;
export declare function mergeTransformers(first: ts.CustomTransformers, second: ts.CustomTransformers): ts.CustomTransformers;
export declare function replaceBootstrap(getTypeChecker: () => ts.TypeChecker): ts.TransformerFactory<ts.SourceFile>;

View file

@ -0,0 +1,127 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.replaceBootstrap = exports.mergeTransformers = exports.createJitTransformers = exports.createAotTransformers = void 0;
const ts = __importStar(require("typescript"));
const elide_imports_1 = require("../transformers/elide_imports");
const find_image_domains_1 = require("../transformers/find_image_domains");
const remove_ivy_jit_support_calls_1 = require("../transformers/remove-ivy-jit-support-calls");
const replace_resources_1 = require("../transformers/replace_resources");
function createAotTransformers(builder, options, imageDomains) {
const getTypeChecker = () => builder.getProgram().getTypeChecker();
const transformers = {
before: [(0, find_image_domains_1.findImageDomains)(imageDomains), replaceBootstrap(getTypeChecker)],
after: [],
};
const removeClassMetadata = !options.emitClassMetadata;
const removeNgModuleScope = !options.emitNgModuleScope;
const removeSetClassDebugInfo = !options.emitSetClassDebugInfo;
if (removeClassMetadata || removeNgModuleScope || removeSetClassDebugInfo) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
transformers.before.push((0, remove_ivy_jit_support_calls_1.removeIvyJitSupportCalls)(removeClassMetadata, removeNgModuleScope, removeSetClassDebugInfo, getTypeChecker));
}
return transformers;
}
exports.createAotTransformers = createAotTransformers;
function createJitTransformers(builder, compilerCli, options) {
const getTypeChecker = () => builder.getProgram().getTypeChecker();
return {
before: [
(0, replace_resources_1.replaceResources)(() => true, getTypeChecker, options.inlineStyleFileExtension),
compilerCli.constructorParametersDownlevelTransform(builder.getProgram()),
],
};
}
exports.createJitTransformers = createJitTransformers;
function mergeTransformers(first, second) {
const result = {};
if (first.before || second.before) {
result.before = [...(first.before || []), ...(second.before || [])];
}
if (first.after || second.after) {
result.after = [...(first.after || []), ...(second.after || [])];
}
if (first.afterDeclarations || second.afterDeclarations) {
result.afterDeclarations = [
...(first.afterDeclarations || []),
...(second.afterDeclarations || []),
];
}
return result;
}
exports.mergeTransformers = mergeTransformers;
/**
* The name of the Angular platform that should be replaced within
* bootstrap call expressions to support AOT.
*/
const PLATFORM_BROWSER_DYNAMIC_NAME = 'platformBrowserDynamic';
function replaceBootstrap(getTypeChecker) {
return (context) => {
let bootstrapImport;
let bootstrapNamespace;
const replacedNodes = [];
const nodeFactory = context.factory;
const visitNode = (node) => {
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {
const target = node.expression;
if (target.text === PLATFORM_BROWSER_DYNAMIC_NAME) {
if (!bootstrapNamespace) {
bootstrapNamespace = nodeFactory.createUniqueName('__NgCli_bootstrap_');
bootstrapImport = nodeFactory.createImportDeclaration(undefined, nodeFactory.createImportClause(false, undefined, nodeFactory.createNamespaceImport(bootstrapNamespace)), nodeFactory.createStringLiteral('@angular/platform-browser'));
}
replacedNodes.push(target);
return nodeFactory.updateCallExpression(node, nodeFactory.createPropertyAccessExpression(bootstrapNamespace, 'platformBrowser'), node.typeArguments, node.arguments);
}
}
return ts.visitEachChild(node, visitNode, context);
};
return (sourceFile) => {
if (!sourceFile.text.includes(PLATFORM_BROWSER_DYNAMIC_NAME)) {
return sourceFile;
}
let updatedSourceFile = ts.visitEachChild(sourceFile, visitNode, context);
if (bootstrapImport) {
// Remove any unused platform browser dynamic imports
const removals = (0, elide_imports_1.elideImports)(updatedSourceFile, replacedNodes, getTypeChecker, context.getCompilerOptions());
if (removals.size > 0) {
updatedSourceFile = ts.visitEachChild(updatedSourceFile, (node) => (removals.has(node) ? undefined : node), context);
}
// Add new platform browser import
return nodeFactory.updateSourceFile(updatedSourceFile, ts.setTextRange(nodeFactory.createNodeArray([bootstrapImport, ...updatedSourceFile.statements]), sourceFile.statements));
}
else {
return updatedSourceFile;
}
};
};
}
exports.replaceBootstrap = replaceBootstrap;

View file

@ -0,0 +1,16 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import type { Compilation, LoaderContext } from 'webpack';
export declare const InlineAngularResourceLoaderPath: string;
export declare const InlineAngularResourceSymbol: unique symbol;
export interface CompilationWithInlineAngularResource extends Compilation {
[InlineAngularResourceSymbol]: string;
}
export default function (this: LoaderContext<{
data?: string;
}>): void;

View file

@ -0,0 +1,24 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.InlineAngularResourceSymbol = exports.InlineAngularResourceLoaderPath = void 0;
exports.InlineAngularResourceLoaderPath = __filename;
exports.InlineAngularResourceSymbol = Symbol('@ngtools/webpack[angular-resource]');
function default_1() {
const callback = this.async();
const { data } = this.getOptions();
if (data) {
callback(undefined, Buffer.from(data, 'base64').toString());
}
else {
const content = this._compilation[exports.InlineAngularResourceSymbol];
callback(undefined, content);
}
}
exports.default = default_1;

35
my-app/node_modules/@ngtools/webpack/src/paths-plugin.d.ts generated vendored Executable file
View file

@ -0,0 +1,35 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { CompilerOptions } from 'typescript';
import type { Resolver } from 'webpack';
export interface TypeScriptPathsPluginOptions extends Pick<CompilerOptions, 'paths' | 'baseUrl'> {
}
type ResolverRequest = NonNullable<Parameters<Parameters<Resolver['resolve']>[4]>[2]>;
interface PathPluginResolverRequest extends ResolverRequest {
context?: {
issuer?: string;
};
typescriptPathMapped?: boolean;
}
export declare class TypeScriptPathsPlugin {
private baseUrl?;
private patterns?;
constructor(options?: TypeScriptPathsPluginOptions);
/**
* Update the plugin with new path mapping option values.
* The options will also be preprocessed to reduce the overhead of individual resolve actions
* during a build.
*
* @param options The `paths` and `baseUrl` options from TypeScript's `CompilerOptions`.
*/
update(options: TypeScriptPathsPluginOptions): void;
apply(resolver: Resolver): void;
findReplacements(originalRequest: string): IterableIterator<string>;
createReplacementRequests(request: PathPluginResolverRequest, originalRequest: string): IterableIterator<PathPluginResolverRequest>;
}
export {};

244
my-app/node_modules/@ngtools/webpack/src/paths-plugin.js generated vendored Executable file
View file

@ -0,0 +1,244 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TypeScriptPathsPlugin = void 0;
const path = __importStar(require("path"));
class TypeScriptPathsPlugin {
baseUrl;
patterns;
constructor(options) {
if (options) {
this.update(options);
}
}
/**
* Update the plugin with new path mapping option values.
* The options will also be preprocessed to reduce the overhead of individual resolve actions
* during a build.
*
* @param options The `paths` and `baseUrl` options from TypeScript's `CompilerOptions`.
*/
update(options) {
this.baseUrl = options.baseUrl;
this.patterns = undefined;
if (options.paths) {
for (const [pattern, potentials] of Object.entries(options.paths)) {
// Ignore any entries that would not result in a new mapping
if (potentials.length === 0 || potentials.every((potential) => potential === '*')) {
continue;
}
const starIndex = pattern.indexOf('*');
let prefix = pattern;
let suffix;
if (starIndex > -1) {
prefix = pattern.slice(0, starIndex);
if (starIndex < pattern.length - 1) {
suffix = pattern.slice(starIndex + 1);
}
}
this.patterns ??= [];
this.patterns.push({
starIndex,
prefix,
suffix,
potentials: potentials.map((potential) => {
const potentialStarIndex = potential.indexOf('*');
if (potentialStarIndex === -1) {
return { hasStar: false, prefix: potential };
}
return {
hasStar: true,
prefix: potential.slice(0, potentialStarIndex),
suffix: potentialStarIndex < potential.length - 1
? potential.slice(potentialStarIndex + 1)
: undefined,
};
}),
});
}
// Sort patterns so that exact matches take priority then largest prefix match
this.patterns?.sort((a, b) => {
if (a.starIndex === -1) {
return -1;
}
else if (b.starIndex === -1) {
return 1;
}
else {
return b.starIndex - a.starIndex;
}
});
}
}
apply(resolver) {
const target = resolver.ensureHook('resolve');
// To support synchronous resolvers this hook cannot be promise based.
// Webpack supports synchronous resolution with `tap` and `tapAsync` hooks.
resolver
.getHook('described-resolve')
.tapAsync('TypeScriptPathsPlugin', (request, resolveContext, callback) => {
// Preprocessing of the options will ensure that `patterns` is either undefined or has elements to check
if (!this.patterns) {
callback();
return;
}
if (!request || request.typescriptPathMapped) {
callback();
return;
}
const originalRequest = request.request || request.path;
if (!originalRequest) {
callback();
return;
}
// Only work on Javascript/TypeScript issuers.
if (!request?.context?.issuer?.match(/\.[cm]?[jt]sx?$/)) {
callback();
return;
}
// Absolute requests are not mapped
if (path.isAbsolute(originalRequest)) {
callback();
return;
}
switch (originalRequest[0]) {
case '.':
// Relative requests are not mapped
callback();
return;
case '!':
// Ignore all webpack special requests
if (originalRequest.length > 1 && originalRequest[1] === '!') {
callback();
return;
}
break;
}
// A generator is used to limit the amount of replacements requests that need to be created.
// For example, if the first one resolves, any others are not needed and do not need
// to be created.
const requests = this.createReplacementRequests(request, originalRequest);
const tryResolve = () => {
const next = requests.next();
if (next.done) {
callback();
return;
}
resolver.doResolve(target, next.value, '', resolveContext, (error, result) => {
if (error) {
callback(error);
}
else if (result) {
callback(undefined, result);
}
else {
tryResolve();
}
});
};
tryResolve();
});
}
*findReplacements(originalRequest) {
if (!this.patterns) {
return;
}
// check if any path mapping rules are relevant
for (const { starIndex, prefix, suffix, potentials } of this.patterns) {
let partial;
if (starIndex === -1) {
// No star means an exact match is required
if (prefix === originalRequest) {
partial = '';
}
}
else if (starIndex === 0 && !suffix) {
// Everything matches a single wildcard pattern ("*")
partial = originalRequest;
}
else if (!suffix) {
// No suffix means the star is at the end of the pattern
if (originalRequest.startsWith(prefix)) {
partial = originalRequest.slice(prefix.length);
}
}
else {
// Star was in the middle of the pattern
if (originalRequest.startsWith(prefix) && originalRequest.endsWith(suffix)) {
partial = originalRequest.substring(prefix.length, originalRequest.length - suffix.length);
}
}
// If request was not matched, move on to the next pattern
if (partial === undefined) {
continue;
}
// Create the full replacement values based on the original request and the potentials
// for the successfully matched pattern.
for (const { hasStar, prefix, suffix } of potentials) {
let replacement = prefix;
if (hasStar) {
replacement += partial;
if (suffix) {
replacement += suffix;
}
}
yield replacement;
}
}
}
*createReplacementRequests(request, originalRequest) {
for (const replacement of this.findReplacements(originalRequest)) {
const targetPath = path.resolve(this.baseUrl ?? '', replacement);
// Resolution in the original callee location, but with the updated request
// to point to the mapped target location.
yield {
...request,
request: targetPath,
typescriptPathMapped: true,
};
// If there is no extension. i.e. the target does not refer to an explicit
// file, then this is a candidate for module/package resolution.
const canBeModule = path.extname(targetPath) === '';
if (canBeModule) {
// Resolution in the target location, preserving the original request.
// This will work with the `resolve-in-package` resolution hook, supporting
// package exports for e.g. locally-built APF libraries.
yield {
...request,
path: targetPath,
typescriptPathMapped: true,
};
}
}
}
}
exports.TypeScriptPathsPlugin = TypeScriptPathsPlugin;

View file

@ -0,0 +1,29 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import type { Compilation } from 'webpack';
export declare class WebpackResourceLoader {
private _parentCompilation?;
private _fileDependencies;
private _reverseDependencies;
private fileCache?;
private assetCache?;
private modifiedResources;
private outputPathCounter;
private readonly inlineDataLoaderPath;
constructor(shouldCache: boolean);
update(parentCompilation: Compilation, changedFiles?: Iterable<string>): void;
clearParentCompilation(): void;
getModifiedResourceFiles(): Set<string>;
getResourceDependencies(filePath: string): never[] | Set<string>;
getAffectedResources(file: string): never[] | Set<string>;
setAffectedResources(file: string, resources: Iterable<string>): void;
private _compile;
private _evaluate;
get(filePath: string): Promise<string>;
process(data: string, fileExtension: string | undefined, resourceType: 'template' | 'style', containingFile?: string): Promise<string>;
}

310
my-app/node_modules/@ngtools/webpack/src/resource_loader.js generated vendored Executable file
View file

@ -0,0 +1,310 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebpackResourceLoader = void 0;
const node_assert_1 = __importDefault(require("node:assert"));
const node_buffer_1 = require("node:buffer");
const path = __importStar(require("node:path"));
const vm = __importStar(require("node:vm"));
const diagnostics_1 = require("./ivy/diagnostics");
const paths_1 = require("./ivy/paths");
const inline_resource_1 = require("./loaders/inline-resource");
const replace_resources_1 = require("./transformers/replace_resources");
class WebpackResourceLoader {
_parentCompilation;
_fileDependencies = new Map();
_reverseDependencies = new Map();
fileCache;
assetCache;
modifiedResources = new Set();
outputPathCounter = 1;
inlineDataLoaderPath = inline_resource_1.InlineAngularResourceLoaderPath;
constructor(shouldCache) {
if (shouldCache) {
this.fileCache = new Map();
this.assetCache = new Map();
}
}
update(parentCompilation, changedFiles) {
this._parentCompilation = parentCompilation;
// Update resource cache and modified resources
this.modifiedResources.clear();
if (changedFiles) {
for (const changedFile of changedFiles) {
const changedFileNormalized = (0, paths_1.normalizePath)(changedFile);
this.assetCache?.delete(changedFileNormalized);
for (const affectedResource of this.getAffectedResources(changedFile)) {
const affectedResourceNormalized = (0, paths_1.normalizePath)(affectedResource);
this.fileCache?.delete(affectedResourceNormalized);
this.modifiedResources.add(affectedResource);
for (const effectedDependencies of this.getResourceDependencies(affectedResourceNormalized)) {
this.assetCache?.delete((0, paths_1.normalizePath)(effectedDependencies));
}
}
}
}
else {
this.fileCache?.clear();
this.assetCache?.clear();
}
// Re-emit all assets for un-effected files
if (this.assetCache) {
for (const [, { name, source, info }] of this.assetCache) {
this._parentCompilation.emitAsset(name, source, info);
}
}
}
clearParentCompilation() {
this._parentCompilation = undefined;
}
getModifiedResourceFiles() {
return this.modifiedResources;
}
getResourceDependencies(filePath) {
return this._fileDependencies.get(filePath) || [];
}
getAffectedResources(file) {
return this._reverseDependencies.get(file) || [];
}
setAffectedResources(file, resources) {
this._reverseDependencies.set(file, new Set(resources));
}
// eslint-disable-next-line max-lines-per-function
async _compile(filePath, data, fileExtension, resourceType, containingFile) {
if (!this._parentCompilation) {
throw new Error('WebpackResourceLoader cannot be used without parentCompilation');
}
const { context, webpack } = this._parentCompilation.compiler;
const { EntryPlugin, NormalModule, library, node, sources, util: { createHash }, } = webpack;
const getEntry = () => {
if (filePath) {
return `${filePath}?${replace_resources_1.NG_COMPONENT_RESOURCE_QUERY}`;
}
else if (resourceType) {
return (
// app.component.ts-2.css?ngResource!=!@ngtools/webpack/src/loaders/inline-resource.js!app.component.ts
`${containingFile}-${this.outputPathCounter}.${fileExtension}` +
`?${replace_resources_1.NG_COMPONENT_RESOURCE_QUERY}!=!${this.inlineDataLoaderPath}!${containingFile}`);
}
else if (data) {
// Create a special URL for reading the resource from memory
return `angular-resource:${resourceType},${createHash('xxhash64')
.update(data)
.digest('hex')}`;
}
throw new Error(`"filePath", "resourceType" or "data" must be specified.`);
};
const entry = getEntry();
// Simple sanity check.
if (filePath?.match(/\.[jt]s$/)) {
throw new Error(`Cannot use a JavaScript or TypeScript file (${filePath}) in a component's styleUrls or templateUrl.`);
}
const outputFilePath = filePath ||
`${containingFile}-angular-inline--${this.outputPathCounter++}.${resourceType === 'template' ? 'html' : 'css'}`;
const outputOptions = {
filename: outputFilePath,
library: {
type: 'var',
name: 'resource',
},
};
const childCompiler = this._parentCompilation.createChildCompiler('angular-compiler:resource', outputOptions, [
new node.NodeTemplatePlugin(),
new node.NodeTargetPlugin(),
new EntryPlugin(context, entry, { name: 'resource' }),
new library.EnableLibraryPlugin('var'),
]);
childCompiler.hooks.thisCompilation.tap('angular-compiler', (compilation, { normalModuleFactory }) => {
// If no data is provided, the resource will be read from the filesystem
if (data !== undefined) {
normalModuleFactory.hooks.resolveForScheme
.for('angular-resource')
.tap('angular-compiler', (resourceData) => {
if (filePath) {
resourceData.path = filePath;
resourceData.resource = filePath;
}
return true;
});
NormalModule.getCompilationHooks(compilation)
.readResourceForScheme.for('angular-resource')
.tap('angular-compiler', () => data);
compilation[inline_resource_1.InlineAngularResourceSymbol] = data;
}
compilation.hooks.additionalAssets.tap('angular-compiler', () => {
const asset = compilation.assets[outputFilePath];
if (!asset) {
return;
}
try {
const output = this._evaluate(outputFilePath, asset.source().toString());
if (typeof output === 'string') {
compilation.assets[outputFilePath] = new sources.RawSource(output);
}
}
catch (error) {
(0, node_assert_1.default)(error instanceof Error, 'catch clause variable is not an Error instance');
// Use compilation errors, as otherwise webpack will choke
(0, diagnostics_1.addError)(compilation, error.message);
}
});
});
let finalContent;
childCompiler.hooks.compilation.tap('angular-compiler', (childCompilation) => {
childCompilation.hooks.processAssets.tap({ name: 'angular-compiler', stage: webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT }, () => {
finalContent = childCompilation.assets[outputFilePath]?.source().toString();
for (const { files } of childCompilation.chunks) {
for (const file of files) {
childCompilation.deleteAsset(file);
}
}
});
});
return new Promise((resolve, reject) => {
childCompiler.runAsChild((error, _, childCompilation) => {
if (error) {
reject(error);
return;
}
else if (!childCompilation) {
reject(new Error('Unknown child compilation error'));
return;
}
// Workaround to attempt to reduce memory usage of child compilations.
// This removes the child compilation from the main compilation and manually propagates
// all dependencies, warnings, and errors.
const parent = childCompiler.parentCompilation;
if (parent) {
parent.children = parent.children.filter((child) => child !== childCompilation);
let fileDependencies;
for (const dependency of childCompilation.fileDependencies) {
// Skip paths that do not appear to be files (have no extension).
// `fileDependencies` can contain directories and not just files which can
// cause incorrect cache invalidation on rebuilds.
if (!path.extname(dependency)) {
continue;
}
if (data && containingFile && dependency.endsWith(entry)) {
// use containing file if the resource was inline
parent.fileDependencies.add(containingFile);
}
else {
parent.fileDependencies.add(dependency);
}
// Save the dependencies for this resource.
if (filePath) {
const resolvedFile = (0, paths_1.normalizePath)(dependency);
const entry = this._reverseDependencies.get(resolvedFile);
if (entry) {
entry.add(filePath);
}
else {
this._reverseDependencies.set(resolvedFile, new Set([filePath]));
}
if (fileDependencies) {
fileDependencies.add(dependency);
}
else {
fileDependencies = new Set([dependency]);
this._fileDependencies.set(filePath, fileDependencies);
}
}
}
parent.contextDependencies.addAll(childCompilation.contextDependencies);
parent.missingDependencies.addAll(childCompilation.missingDependencies);
parent.buildDependencies.addAll(childCompilation.buildDependencies);
parent.warnings.push(...childCompilation.warnings);
parent.errors.push(...childCompilation.errors);
if (this.assetCache) {
for (const { info, name, source } of childCompilation.getAssets()) {
// Use the originating file as the cache key if present
// Otherwise, generate a cache key based on the generated name
const cacheKey = info.sourceFilename ?? `!![GENERATED]:${name}`;
this.assetCache.set(cacheKey, { info, name, source });
}
}
}
resolve({
content: finalContent ?? '',
success: childCompilation.errors?.length === 0,
});
});
});
}
_evaluate(filename, source) {
// Evaluate code
// css-loader requires the btoa function to exist to correctly generate inline sourcemaps
const context = {
btoa(input) {
return node_buffer_1.Buffer.from(input).toString('base64');
},
};
try {
vm.runInNewContext(source, context, { filename });
}
catch {
// Error are propagated through the child compilation.
return null;
}
if (typeof context.resource === 'string') {
return context.resource;
}
else if (typeof context.resource?.default === 'string') {
return context.resource.default;
}
throw new Error(`The loader "${filename}" didn't return a string.`);
}
async get(filePath) {
const normalizedFile = (0, paths_1.normalizePath)(filePath);
let compilationResult = this.fileCache?.get(normalizedFile);
if (compilationResult === undefined) {
// cache miss so compile resource
compilationResult = await this._compile(filePath);
// Only cache if compilation was successful
if (this.fileCache && compilationResult.success) {
this.fileCache.set(normalizedFile, compilationResult);
}
}
return compilationResult.content;
}
async process(data, fileExtension, resourceType, containingFile) {
if (data.trim().length === 0) {
return '';
}
const compilationResult = await this._compile(undefined, data, fileExtension, resourceType, containingFile);
return compilationResult.content;
}
}
exports.WebpackResourceLoader = WebpackResourceLoader;

View file

@ -0,0 +1,9 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
export declare function elideImports(sourceFile: ts.SourceFile, removedNodes: ts.Node[], getTypeChecker: () => ts.TypeChecker, compilerOptions: ts.CompilerOptions): Set<ts.Node>;

View file

@ -0,0 +1,156 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.elideImports = void 0;
const ts = __importStar(require("typescript"));
// Remove imports for which all identifiers have been removed.
// Needs type checker, and works even if it's not the first transformer.
// Works by removing imports for symbols whose identifiers have all been removed.
// Doesn't use the `symbol.declarations` because that previous transforms might have removed nodes
// but the type checker doesn't know.
// See https://github.com/Microsoft/TypeScript/issues/17552 for more information.
function elideImports(sourceFile, removedNodes, getTypeChecker, compilerOptions) {
const importNodeRemovals = new Set();
if (removedNodes.length === 0) {
return importNodeRemovals;
}
const typeChecker = getTypeChecker();
// Collect all imports and used identifiers
const usedSymbols = new Set();
const imports = [];
ts.forEachChild(sourceFile, function visit(node) {
// Skip removed nodes.
if (removedNodes.includes(node)) {
return;
}
// Consider types for 'implements' as unused.
// A HeritageClause token can also be an 'AbstractKeyword'
// which in that case we should not elide the import.
if (ts.isHeritageClause(node) && node.token === ts.SyntaxKind.ImplementsKeyword) {
return;
}
// Record import and skip
if (ts.isImportDeclaration(node)) {
if (!node.importClause?.isTypeOnly) {
imports.push(node);
}
return;
}
// Type reference imports do not need to be emitted when emitDecoratorMetadata is disabled.
if (ts.isTypeReferenceNode(node) && !compilerOptions.emitDecoratorMetadata) {
return;
}
let symbol;
switch (node.kind) {
case ts.SyntaxKind.Identifier:
const parent = node.parent;
if (parent && ts.isShorthandPropertyAssignment(parent)) {
const shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(parent);
if (shorthandSymbol) {
symbol = shorthandSymbol;
}
}
else {
symbol = typeChecker.getSymbolAtLocation(node);
}
break;
case ts.SyntaxKind.ExportSpecifier:
symbol = typeChecker.getExportSpecifierLocalTargetSymbol(node);
break;
case ts.SyntaxKind.ShorthandPropertyAssignment:
symbol = typeChecker.getShorthandAssignmentValueSymbol(node);
break;
}
if (symbol) {
usedSymbols.add(symbol);
}
ts.forEachChild(node, visit);
});
if (imports.length === 0) {
return importNodeRemovals;
}
const isUnused = (node) => {
// Do not remove JSX factory imports
if (node.text === compilerOptions.jsxFactory) {
return false;
}
const symbol = typeChecker.getSymbolAtLocation(node);
return symbol && !usedSymbols.has(symbol);
};
for (const node of imports) {
if (!node.importClause) {
// "import 'abc';"
continue;
}
const namedBindings = node.importClause.namedBindings;
if (namedBindings && ts.isNamespaceImport(namedBindings)) {
// "import * as XYZ from 'abc';"
if (isUnused(namedBindings.name)) {
importNodeRemovals.add(node);
}
}
else {
const specifierNodeRemovals = [];
let clausesCount = 0;
// "import { XYZ, ... } from 'abc';"
if (namedBindings && ts.isNamedImports(namedBindings)) {
let removedClausesCount = 0;
clausesCount += namedBindings.elements.length;
for (const specifier of namedBindings.elements) {
if (specifier.isTypeOnly || isUnused(specifier.name)) {
removedClausesCount++;
// in case we don't have any more namedImports we should remove the parent ie the {}
const nodeToRemove = clausesCount === removedClausesCount ? specifier.parent : specifier;
specifierNodeRemovals.push(nodeToRemove);
}
}
}
// "import XYZ from 'abc';"
if (node.importClause.name) {
clausesCount++;
if (node.importClause.isTypeOnly || isUnused(node.importClause.name)) {
specifierNodeRemovals.push(node.importClause.name);
}
}
if (specifierNodeRemovals.length === clausesCount) {
importNodeRemovals.add(node);
}
else {
for (const specifierNodeRemoval of specifierNodeRemovals) {
importNodeRemovals.add(specifierNodeRemoval);
}
}
}
}
return importNodeRemovals;
}
exports.elideImports = elideImports;

View file

@ -0,0 +1,9 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
export declare function findImageDomains(imageDomains: Set<string>): ts.TransformerFactory<ts.SourceFile>;

View file

@ -0,0 +1,153 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.findImageDomains = void 0;
const ts = __importStar(require("typescript"));
const TARGET_TEXT = '@NgModule';
const BUILTIN_LOADERS = new Set([
'provideCloudflareLoader',
'provideCloudinaryLoader',
'provideImageKitLoader',
'provideImgixLoader',
]);
const URL_REGEX = /(https?:\/\/[^/]*)\//g;
function findImageDomains(imageDomains) {
return (context) => {
return (sourceFile) => {
const isBuiltinImageLoader = (node) => {
return BUILTIN_LOADERS.has(node.expression.getText());
};
const findDomainString = (node) => {
if (ts.isStringLiteral(node) ||
ts.isTemplateHead(node) ||
ts.isTemplateMiddle(node) ||
ts.isTemplateTail(node)) {
const domain = node.text.match(URL_REGEX);
if (domain && domain[0]) {
imageDomains.add(domain[0]);
return node;
}
}
ts.visitEachChild(node, findDomainString, context);
return node;
};
function isImageProviderKey(property) {
return (ts.isPropertyAssignment(property) &&
property.name.getText() === 'provide' &&
property.initializer.getText() === 'IMAGE_LOADER');
}
function isImageProviderValue(property) {
return ts.isPropertyAssignment(property) && property.name.getText() === 'useValue';
}
function checkForDomain(node) {
if (node.properties.find(isImageProviderKey)) {
const value = node.properties.find(isImageProviderValue);
if (value && ts.isPropertyAssignment(value)) {
if (ts.isArrowFunction(value.initializer) ||
ts.isFunctionExpression(value.initializer)) {
ts.visitEachChild(node, findDomainString, context);
}
}
}
}
function findImageLoaders(node) {
if (ts.isCallExpression(node)) {
if (isBuiltinImageLoader(node)) {
const firstArg = node.arguments[0];
if (ts.isStringLiteralLike(firstArg)) {
imageDomains.add(firstArg.text);
}
}
}
else if (ts.isObjectLiteralExpression(node)) {
checkForDomain(node);
}
return node;
}
function findProvidersAssignment(node) {
if (ts.isPropertyAssignment(node)) {
if (ts.isIdentifier(node.name) && node.name.escapedText === 'providers') {
ts.visitEachChild(node.initializer, findImageLoaders, context);
}
}
return node;
}
function findFeaturesAssignment(node) {
if (ts.isPropertyAssignment(node)) {
if (ts.isIdentifier(node.name) &&
node.name.escapedText === 'features' &&
ts.isArrayLiteralExpression(node.initializer)) {
const providerElement = node.initializer.elements.find(isProvidersFeatureElement);
if (providerElement &&
ts.isCallExpression(providerElement) &&
providerElement.arguments[0]) {
ts.visitEachChild(providerElement.arguments[0], findImageLoaders, context);
}
}
}
return node;
}
function isProvidersFeatureElement(node) {
return (ts.isCallExpression(node) &&
ts.isPropertyAccessExpression(node.expression) &&
ts.isIdentifier(node.expression.expression) &&
node.expression.expression.escapedText === 'i0' &&
ts.isIdentifier(node.expression.name) &&
node.expression.name.escapedText === 'ɵɵProvidersFeature');
}
function findPropertyDeclaration(node) {
if (ts.isPropertyDeclaration(node) &&
ts.isIdentifier(node.name) &&
node.initializer &&
ts.isCallExpression(node.initializer) &&
node.initializer.arguments[0]) {
if (node.name.escapedText === 'ɵinj') {
ts.visitEachChild(node.initializer.arguments[0], findProvidersAssignment, context);
}
else if (node.name.escapedText === 'ɵcmp') {
ts.visitEachChild(node.initializer.arguments[0], findFeaturesAssignment, context);
}
}
return node;
}
function findClassDeclaration(node) {
if (ts.isClassDeclaration(node)) {
ts.visitEachChild(node, findPropertyDeclaration, context);
}
return node;
}
ts.visitEachChild(sourceFile, findClassDeclaration, context);
return sourceFile;
};
};
}
exports.findImageDomains = findImageDomains;

View file

@ -0,0 +1,9 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export * from './elide_imports';
export * from './replace_resources';

View file

@ -0,0 +1,25 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./elide_imports"), exports);
__exportStar(require("./replace_resources"), exports);

View file

@ -0,0 +1,9 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
export declare function removeIvyJitSupportCalls(classMetadata: boolean, ngModuleScope: boolean, debugInfo: boolean, getTypeChecker: () => ts.TypeChecker): ts.TransformerFactory<ts.SourceFile>;

View file

@ -0,0 +1,126 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.removeIvyJitSupportCalls = void 0;
const ts = __importStar(require("typescript"));
const elide_imports_1 = require("./elide_imports");
function removeIvyJitSupportCalls(classMetadata, ngModuleScope, debugInfo, getTypeChecker) {
return (context) => {
const removedNodes = [];
const visitNode = (node) => {
const innerExpression = ts.isExpressionStatement(node) ? getIifeExpression(node) : null;
if (innerExpression) {
if (ngModuleScope &&
ts.isBinaryExpression(innerExpression) &&
isIvyPrivateCallExpression(innerExpression.right, 'ɵɵsetNgModuleScope')) {
removedNodes.push(innerExpression);
return undefined;
}
if (classMetadata) {
const expression = ts.isBinaryExpression(innerExpression)
? innerExpression.right
: innerExpression;
if (isIvyPrivateCallExpression(expression, 'ɵsetClassMetadata') ||
isIvyPrivateCallExpression(expression, 'ɵsetClassMetadataAsync')) {
removedNodes.push(innerExpression);
return undefined;
}
}
if (debugInfo &&
ts.isBinaryExpression(innerExpression) &&
isIvyPrivateCallExpression(innerExpression.right, 'ɵsetClassDebugInfo')) {
removedNodes.push(innerExpression);
return undefined;
}
}
return ts.visitEachChild(node, visitNode, context);
};
return (sourceFile) => {
let updatedSourceFile = ts.visitEachChild(sourceFile, visitNode, context);
if (removedNodes.length > 0) {
// Remove any unused imports
const importRemovals = (0, elide_imports_1.elideImports)(updatedSourceFile, removedNodes, getTypeChecker, context.getCompilerOptions());
if (importRemovals.size > 0) {
updatedSourceFile = ts.visitEachChild(updatedSourceFile, function visitForRemoval(node) {
return importRemovals.has(node)
? undefined
: ts.visitEachChild(node, visitForRemoval, context);
}, context);
}
}
return updatedSourceFile;
};
};
}
exports.removeIvyJitSupportCalls = removeIvyJitSupportCalls;
// Each Ivy private call expression is inside an IIFE
function getIifeExpression(exprStmt) {
const expression = exprStmt.expression;
if (!expression || !ts.isCallExpression(expression) || expression.arguments.length !== 0) {
return null;
}
const parenExpr = expression;
if (!ts.isParenthesizedExpression(parenExpr.expression)) {
return null;
}
const funExpr = parenExpr.expression.expression;
if (!ts.isFunctionExpression(funExpr) && !ts.isArrowFunction(funExpr)) {
return null;
}
if (!ts.isBlock(funExpr.body)) {
return funExpr.body;
}
const innerStmts = funExpr.body.statements;
if (innerStmts.length !== 1) {
return null;
}
const innerExprStmt = innerStmts[0];
if (!ts.isExpressionStatement(innerExprStmt)) {
return null;
}
return innerExprStmt.expression;
}
function isIvyPrivateCallExpression(expression, name) {
// Now we're in the IIFE and have the inner expression statement. We can check if it matches
// a private Ivy call.
if (!ts.isCallExpression(expression)) {
return false;
}
const propAccExpr = expression.expression;
if (!ts.isPropertyAccessExpression(propAccExpr)) {
return false;
}
if (propAccExpr.name.text !== name) {
return false;
}
return true;
}

View file

@ -0,0 +1,11 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
export declare const NG_COMPONENT_RESOURCE_QUERY = "ngResource";
export declare function replaceResources(shouldTransform: (fileName: string) => boolean, getTypeChecker: () => ts.TypeChecker, inlineStyleFileExtension?: string): ts.TransformerFactory<ts.SourceFile>;
export declare function getResourceUrl(node: ts.Node): string | null;

View file

@ -0,0 +1,237 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getResourceUrl = exports.replaceResources = exports.NG_COMPONENT_RESOURCE_QUERY = void 0;
const ts = __importStar(require("typescript"));
const inline_resource_1 = require("../loaders/inline-resource");
exports.NG_COMPONENT_RESOURCE_QUERY = 'ngResource';
function replaceResources(shouldTransform, getTypeChecker, inlineStyleFileExtension) {
return (context) => {
const typeChecker = getTypeChecker();
const resourceImportDeclarations = [];
const moduleKind = context.getCompilerOptions().module;
const nodeFactory = context.factory;
const visitNode = (node) => {
if (ts.isClassDeclaration(node)) {
const decorators = ts.getDecorators(node);
if (!decorators || decorators.length === 0) {
return node;
}
return nodeFactory.updateClassDeclaration(node, [
...decorators.map((current) => visitDecorator(nodeFactory, current, typeChecker, resourceImportDeclarations, moduleKind, inlineStyleFileExtension)),
...(ts.getModifiers(node) ?? []),
], node.name, node.typeParameters, node.heritageClauses, node.members);
}
return ts.visitEachChild(node, visitNode, context);
};
return (sourceFile) => {
if (!shouldTransform(sourceFile.fileName)) {
return sourceFile;
}
const updatedSourceFile = ts.visitNode(sourceFile, visitNode);
if (resourceImportDeclarations.length) {
// Add resource imports
return context.factory.updateSourceFile(updatedSourceFile, ts.setTextRange(context.factory.createNodeArray([
...resourceImportDeclarations,
...updatedSourceFile.statements,
]), updatedSourceFile.statements));
}
return updatedSourceFile;
};
};
}
exports.replaceResources = replaceResources;
function visitDecorator(nodeFactory, node, typeChecker, resourceImportDeclarations, moduleKind, inlineStyleFileExtension) {
if (!isComponentDecorator(node, typeChecker)) {
return node;
}
if (!ts.isCallExpression(node.expression)) {
return node;
}
const decoratorFactory = node.expression;
const args = decoratorFactory.arguments;
if (args.length !== 1 || !ts.isObjectLiteralExpression(args[0])) {
// Unsupported component metadata
return node;
}
const objectExpression = args[0];
const styleReplacements = [];
// visit all properties
let properties = ts.visitNodes(objectExpression.properties, (node) => ts.isObjectLiteralElementLike(node)
? visitComponentMetadata(nodeFactory, node, styleReplacements, resourceImportDeclarations, moduleKind, inlineStyleFileExtension)
: node);
// replace properties with updated properties
if (styleReplacements.length > 0) {
const styleProperty = nodeFactory.createPropertyAssignment(nodeFactory.createIdentifier('styles'), nodeFactory.createArrayLiteralExpression(styleReplacements));
properties = nodeFactory.createNodeArray([...properties, styleProperty]);
}
return nodeFactory.updateDecorator(node, nodeFactory.updateCallExpression(decoratorFactory, decoratorFactory.expression, decoratorFactory.typeArguments, [nodeFactory.updateObjectLiteralExpression(objectExpression, properties)]));
}
function visitComponentMetadata(nodeFactory, node, styleReplacements, resourceImportDeclarations, moduleKind = ts.ModuleKind.ES2015, inlineStyleFileExtension) {
if (!ts.isPropertyAssignment(node) || ts.isComputedPropertyName(node.name)) {
return node;
}
const name = node.name.text;
switch (name) {
case 'moduleId':
return undefined;
case 'templateUrl':
const url = getResourceUrl(node.initializer);
if (!url) {
return node;
}
const importName = createResourceImport(nodeFactory, url, resourceImportDeclarations, moduleKind);
if (!importName) {
return node;
}
return nodeFactory.updatePropertyAssignment(node, nodeFactory.createIdentifier('template'), importName);
case 'styles':
case 'styleUrl':
case 'styleUrls':
const isInlineStyle = name === 'styles';
let styles;
if (ts.isStringLiteralLike(node.initializer)) {
styles = [
transformInlineStyleLiteral(node.initializer, nodeFactory, isInlineStyle, inlineStyleFileExtension, resourceImportDeclarations, moduleKind),
];
}
else if (ts.isArrayLiteralExpression(node.initializer)) {
styles = ts.visitNodes(node.initializer.elements, (node) => transformInlineStyleLiteral(node, nodeFactory, isInlineStyle, inlineStyleFileExtension, resourceImportDeclarations, moduleKind));
}
else {
return node;
}
// Styles should be placed first
if (isInlineStyle) {
styleReplacements.unshift(...styles);
}
else {
styleReplacements.push(...styles);
}
return undefined;
default:
return node;
}
}
function transformInlineStyleLiteral(node, nodeFactory, isInlineStyle, inlineStyleFileExtension, resourceImportDeclarations, moduleKind) {
if (!ts.isStringLiteralLike(node)) {
return node;
}
// Don't transform empty strings as PostCSS will choke on them. No work to do anyways.
if (node.text === '') {
return node;
}
if (!isInlineStyle) {
const url = getResourceUrl(node);
return url
? createResourceImport(nodeFactory, url, resourceImportDeclarations, moduleKind)
: node;
}
if (!inlineStyleFileExtension) {
return nodeFactory.createStringLiteral(node.text);
}
const data = Buffer.from(node.text).toString('base64');
const containingFile = node.getSourceFile().fileName;
// app.component.ts.css?ngResource!=!@ngtools/webpack/src/loaders/inline-resource.js?data=...!app.component.ts
const url = `${containingFile}.${inlineStyleFileExtension}?${exports.NG_COMPONENT_RESOURCE_QUERY}` +
`!=!${inline_resource_1.InlineAngularResourceLoaderPath}?data=${encodeURIComponent(data)}!${containingFile}`;
return createResourceImport(nodeFactory, url, resourceImportDeclarations, moduleKind);
}
function getResourceUrl(node) {
// only analyze strings
if (!ts.isStringLiteralLike(node)) {
return null;
}
return `${/^\.?\.\//.test(node.text) ? '' : './'}${node.text}?${exports.NG_COMPONENT_RESOURCE_QUERY}`;
}
exports.getResourceUrl = getResourceUrl;
function isComponentDecorator(node, typeChecker) {
if (!ts.isDecorator(node)) {
return false;
}
const origin = getDecoratorOrigin(node, typeChecker);
if (origin && origin.module === '@angular/core' && origin.name === 'Component') {
return true;
}
return false;
}
function createResourceImport(nodeFactory, url, resourceImportDeclarations, moduleKind) {
const urlLiteral = nodeFactory.createStringLiteral(url);
if (moduleKind < ts.ModuleKind.ES2015) {
return nodeFactory.createCallExpression(nodeFactory.createIdentifier('require'), [], [urlLiteral]);
}
else {
const importName = nodeFactory.createIdentifier(`__NG_CLI_RESOURCE__${resourceImportDeclarations.length}`);
resourceImportDeclarations.push(nodeFactory.createImportDeclaration(undefined, nodeFactory.createImportClause(false, importName, undefined), urlLiteral));
return importName;
}
}
function getDecoratorOrigin(decorator, typeChecker) {
if (!ts.isCallExpression(decorator.expression)) {
return null;
}
let identifier;
let name = '';
if (ts.isPropertyAccessExpression(decorator.expression.expression)) {
identifier = decorator.expression.expression.expression;
name = decorator.expression.expression.name.text;
}
else if (ts.isIdentifier(decorator.expression.expression)) {
identifier = decorator.expression.expression;
}
else {
return null;
}
// NOTE: resolver.getReferencedImportDeclaration would work as well but is internal
const symbol = typeChecker.getSymbolAtLocation(identifier);
if (symbol && symbol.declarations && symbol.declarations.length > 0) {
const declaration = symbol.declarations[0];
let module;
if (ts.isImportSpecifier(declaration)) {
name = (declaration.propertyName || declaration.name).text;
module = declaration.parent.parent.parent.moduleSpecifier.text;
}
else if (ts.isNamespaceImport(declaration)) {
// Use the name from the decorator namespace property access
module = declaration.parent.parent.moduleSpecifier.text;
}
else if (ts.isImportClause(declaration)) {
name = declaration.name.text;
module = declaration.parent.moduleSpecifier.text;
}
else {
return null;
}
return { name, module };
}
return null;
}

View file

@ -0,0 +1,13 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
export declare function createTypescriptContext(content: string, additionalFiles?: Record<string, string>, useLibs?: boolean, extraCompilerOptions?: ts.CompilerOptions, jsxFile?: boolean): {
compilerHost: ts.CompilerHost;
program: ts.Program;
};
export declare function transformTypescript(content: string | undefined, transformers: ts.TransformerFactory<ts.SourceFile>[], program?: ts.Program, compilerHost?: ts.CompilerHost): string | undefined;

View file

@ -0,0 +1,109 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformTypescript = exports.createTypescriptContext = void 0;
const path_1 = require("path");
const ts = __importStar(require("typescript"));
// Test transform helpers.
const basefileName = 'test-file.ts';
function createTypescriptContext(content, additionalFiles, useLibs = false, extraCompilerOptions = {}, jsxFile = false) {
const fileName = basefileName + (jsxFile ? 'x' : '');
// Set compiler options.
const compilerOptions = {
noEmitOnError: useLibs,
allowJs: true,
newLine: ts.NewLineKind.LineFeed,
moduleResolution: ts.ModuleResolutionKind.Node10,
module: ts.ModuleKind.ES2020,
target: ts.ScriptTarget.ES2020,
skipLibCheck: true,
sourceMap: false,
importHelpers: true,
experimentalDecorators: true,
types: [],
...extraCompilerOptions,
};
// Create compiler host.
const compilerHost = ts.createCompilerHost(compilerOptions, true);
const baseFileExists = compilerHost.fileExists;
compilerHost.fileExists = function (compilerFileName) {
return (compilerFileName === fileName ||
!!additionalFiles?.[(0, path_1.basename)(compilerFileName)] ||
baseFileExists(compilerFileName));
};
const baseReadFile = compilerHost.readFile;
compilerHost.readFile = function (compilerFileName) {
if (compilerFileName === fileName) {
return content;
}
else if (additionalFiles?.[(0, path_1.basename)(compilerFileName)]) {
return additionalFiles[(0, path_1.basename)(compilerFileName)];
}
else {
return baseReadFile(compilerFileName);
}
};
// Create the TypeScript program.
const program = ts.createProgram([fileName], compilerOptions, compilerHost);
return { compilerHost, program };
}
exports.createTypescriptContext = createTypescriptContext;
function transformTypescript(content, transformers, program, compilerHost) {
// Use given context or create a new one.
if (content !== undefined) {
const typescriptContext = createTypescriptContext(content);
if (!program) {
program = typescriptContext.program;
}
if (!compilerHost) {
compilerHost = typescriptContext.compilerHost;
}
}
else if (!program || !compilerHost) {
throw new Error('transformTypescript needs either `content` or a `program` and `compilerHost');
}
const outputFileName = basefileName.replace(/\.tsx?$/, '.js');
let outputContent;
// Emit.
const { emitSkipped, diagnostics } = program.emit(undefined, (filename, data) => {
if (filename === outputFileName) {
outputContent = data;
}
}, undefined, undefined, { before: transformers });
// Throw error with diagnostics if emit wasn't successfull.
if (emitSkipped) {
throw new Error(ts.formatDiagnostics(diagnostics, compilerHost));
}
// Return the transpiled js.
return outputContent;
}
exports.transformTypescript = transformTypescript;