projecte_ionic/node_modules/@ngtools/webpack/src/resource_loader.js
2022-02-09 18:30:03 +01:00

288 lines
14 KiB
JavaScript
Executable file

"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;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (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.WebpackResourceLoader = void 0;
const crypto_1 = require("crypto");
const path = __importStar(require("path"));
const vm = __importStar(require("vm"));
const inline_data_loader_1 = require("./inline-data-loader");
const paths_1 = require("./ivy/paths");
class WebpackResourceLoader {
constructor(shouldCache) {
this._fileDependencies = new Map();
this._reverseDependencies = new Map();
this.modifiedResources = new Set();
this.outputPathCounter = 1;
this.inlineDataLoaderPath = require.resolve('./inline-data-loader');
if (shouldCache) {
this.fileCache = new Map();
this.assetCache = new Map();
}
}
update(parentCompilation, changedFiles) {
var _a, _b, _c, _d, _e;
this._parentCompilation = parentCompilation;
// Update resource cache and modified resources
this.modifiedResources.clear();
if (changedFiles) {
for (const changedFile of changedFiles) {
const changedFileNormalized = paths_1.normalizePath(changedFile);
(_a = this.assetCache) === null || _a === void 0 ? void 0 : _a.delete(changedFileNormalized);
for (const affectedResource of this.getAffectedResources(changedFile)) {
const affectedResourceNormalized = paths_1.normalizePath(affectedResource);
(_b = this.fileCache) === null || _b === void 0 ? void 0 : _b.delete(affectedResourceNormalized);
this.modifiedResources.add(affectedResource);
for (const effectedDependencies of this.getResourceDependencies(affectedResourceNormalized)) {
(_c = this.assetCache) === null || _c === void 0 ? void 0 : _c.delete(paths_1.normalizePath(effectedDependencies));
}
}
}
}
else {
(_d = this.fileCache) === null || _d === void 0 ? void 0 : _d.clear();
(_e = this.assetCache) === null || _e === void 0 ? void 0 : _e.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));
}
async _compile(filePath, data, mimeType, fileExtension, resourceType, containingFile) {
if (!this._parentCompilation) {
throw new Error('WebpackResourceLoader cannot be used without parentCompilation');
}
// Create a special URL for reading the resource from memory
const entry = filePath ||
(resourceType
? `${containingFile}-${this.outputPathCounter}.${fileExtension}!=!${this.inlineDataLoaderPath}!${containingFile}`
: // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
`angular-resource:${resourceType},${crypto_1.createHash('md5').update(data).digest('hex')}`);
if (!entry) {
throw new Error(`"filePath" or "data" must be specified.`);
}
// Simple sanity check.
if (filePath === null || filePath === void 0 ? void 0 : 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 { context, webpack } = this._parentCompilation.compiler;
const { EntryPlugin, NormalModule, library, node, sources } = webpack;
const childCompiler = this._parentCompilation.createChildCompiler('angular-compiler:resource', outputOptions, [
new node.NodeTemplatePlugin(outputOptions),
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;
}
if (mimeType) {
resourceData.data.mimetype = mimeType;
}
return true;
});
NormalModule.getCompilationHooks(compilation)
.readResourceForScheme.for('angular-resource')
.tap('angular-compiler', () => data);
compilation[inline_data_loader_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) {
// Use compilation errors, as otherwise webpack will choke
compilation.errors.push(error);
}
});
});
let finalContent;
let finalMap;
childCompiler.hooks.compilation.tap('angular-compiler', (childCompilation) => {
childCompilation.hooks.processAssets.tap({ name: 'angular-compiler', stage: webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT }, () => {
var _a, _b;
finalContent = (_a = childCompilation.assets[outputFilePath]) === null || _a === void 0 ? void 0 : _a.source().toString();
finalMap = (_b = childCompilation.assets[outputFilePath + '.map']) === null || _b === void 0 ? void 0 : _b.source().toString();
delete childCompilation.assets[outputFilePath];
delete childCompilation.assets[outputFilePath + '.map'];
});
});
return new Promise((resolve, reject) => {
childCompiler.runAsChild((error, _, childCompilation) => {
var _a, _b;
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 = 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 = (_a = info.sourceFilename) !== null && _a !== void 0 ? _a : `!![GENERATED]:${name}`;
this.assetCache.set(cacheKey, { info, name, source });
}
}
}
resolve({
content: finalContent !== null && finalContent !== void 0 ? finalContent : '',
success: ((_b = childCompilation.errors) === null || _b === void 0 ? void 0 : _b.length) === 0,
});
});
});
}
_evaluate(filename, source) {
var _a;
// Evaluate code
const context = {};
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 ((_a = context.resource) === null || _a === void 0 ? void 0 : _a.default) === 'string') {
return context.resource.default;
}
throw new Error(`The loader "${filename}" didn't return a string.`);
}
async get(filePath) {
var _a;
const normalizedFile = paths_1.normalizePath(filePath);
let compilationResult = (_a = this.fileCache) === null || _a === void 0 ? void 0 : _a.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, mimeType, fileExtension, resourceType, containingFile) {
if (data.trim().length === 0) {
return '';
}
const compilationResult = await this._compile(undefined, data, mimeType, fileExtension, resourceType, containingFile);
return compilationResult.content;
}
}
exports.WebpackResourceLoader = WebpackResourceLoader;