source: trip-planner-front/node_modules/@ngtools/webpack/src/resource_loader.js@ 6fe77af

Last change on this file since 6fe77af was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 13.6 KB
Line 
1"use strict";
2/**
3 * @license
4 * Copyright Google LLC All Rights Reserved.
5 *
6 * Use of this source code is governed by an MIT-style license that can be
7 * found in the LICENSE file at https://angular.io/license
8 */
9var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10 if (k2 === undefined) k2 = k;
11 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
12}) : (function(o, m, k, k2) {
13 if (k2 === undefined) k2 = k;
14 o[k2] = m[k];
15}));
16var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
17 Object.defineProperty(o, "default", { enumerable: true, value: v });
18}) : function(o, v) {
19 o["default"] = v;
20});
21var __importStar = (this && this.__importStar) || function (mod) {
22 if (mod && mod.__esModule) return mod;
23 var result = {};
24 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
25 __setModuleDefault(result, mod);
26 return result;
27};
28Object.defineProperty(exports, "__esModule", { value: true });
29exports.WebpackResourceLoader = void 0;
30const crypto_1 = require("crypto");
31const path = __importStar(require("path"));
32const vm = __importStar(require("vm"));
33const paths_1 = require("./ivy/paths");
34const inline_resource_1 = require("./loaders/inline-resource");
35class WebpackResourceLoader {
36 constructor(shouldCache) {
37 this._fileDependencies = new Map();
38 this._reverseDependencies = new Map();
39 this.modifiedResources = new Set();
40 this.outputPathCounter = 1;
41 this.inlineDataLoaderPath = inline_resource_1.InlineAngularResourceLoaderPath;
42 if (shouldCache) {
43 this.fileCache = new Map();
44 this.assetCache = new Map();
45 }
46 }
47 update(parentCompilation, changedFiles) {
48 var _a, _b, _c, _d, _e;
49 this._parentCompilation = parentCompilation;
50 // Update resource cache and modified resources
51 this.modifiedResources.clear();
52 if (changedFiles) {
53 for (const changedFile of changedFiles) {
54 const changedFileNormalized = paths_1.normalizePath(changedFile);
55 (_a = this.assetCache) === null || _a === void 0 ? void 0 : _a.delete(changedFileNormalized);
56 for (const affectedResource of this.getAffectedResources(changedFile)) {
57 const affectedResourceNormalized = paths_1.normalizePath(affectedResource);
58 (_b = this.fileCache) === null || _b === void 0 ? void 0 : _b.delete(affectedResourceNormalized);
59 this.modifiedResources.add(affectedResource);
60 for (const effectedDependencies of this.getResourceDependencies(affectedResourceNormalized)) {
61 (_c = this.assetCache) === null || _c === void 0 ? void 0 : _c.delete(paths_1.normalizePath(effectedDependencies));
62 }
63 }
64 }
65 }
66 else {
67 (_d = this.fileCache) === null || _d === void 0 ? void 0 : _d.clear();
68 (_e = this.assetCache) === null || _e === void 0 ? void 0 : _e.clear();
69 }
70 // Re-emit all assets for un-effected files
71 if (this.assetCache) {
72 for (const [, { name, source, info }] of this.assetCache) {
73 this._parentCompilation.emitAsset(name, source, info);
74 }
75 }
76 }
77 clearParentCompilation() {
78 this._parentCompilation = undefined;
79 }
80 getModifiedResourceFiles() {
81 return this.modifiedResources;
82 }
83 getResourceDependencies(filePath) {
84 return this._fileDependencies.get(filePath) || [];
85 }
86 getAffectedResources(file) {
87 return this._reverseDependencies.get(file) || [];
88 }
89 setAffectedResources(file, resources) {
90 this._reverseDependencies.set(file, new Set(resources));
91 }
92 async _compile(filePath, data, mimeType, fileExtension, resourceType, containingFile) {
93 if (!this._parentCompilation) {
94 throw new Error('WebpackResourceLoader cannot be used without parentCompilation');
95 }
96 // Create a special URL for reading the resource from memory
97 const entry = filePath ||
98 (resourceType
99 ? `${containingFile}-${this.outputPathCounter}.${fileExtension}!=!${this.inlineDataLoaderPath}!${containingFile}`
100 : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
101 `angular-resource:${resourceType},${crypto_1.createHash('md5').update(data).digest('hex')}`);
102 if (!entry) {
103 throw new Error(`"filePath" or "data" must be specified.`);
104 }
105 // Simple sanity check.
106 if (filePath === null || filePath === void 0 ? void 0 : filePath.match(/\.[jt]s$/)) {
107 throw new Error(`Cannot use a JavaScript or TypeScript file (${filePath}) in a component's styleUrls or templateUrl.`);
108 }
109 const outputFilePath = filePath ||
110 `${containingFile}-angular-inline--${this.outputPathCounter++}.${resourceType === 'template' ? 'html' : 'css'}`;
111 const outputOptions = {
112 filename: outputFilePath,
113 library: {
114 type: 'var',
115 name: 'resource',
116 },
117 };
118 const { context, webpack } = this._parentCompilation.compiler;
119 const { EntryPlugin, NormalModule, library, node, sources } = webpack;
120 const childCompiler = this._parentCompilation.createChildCompiler('angular-compiler:resource', outputOptions, [
121 new node.NodeTemplatePlugin(outputOptions),
122 new node.NodeTargetPlugin(),
123 new EntryPlugin(context, entry, { name: 'resource' }),
124 new library.EnableLibraryPlugin('var'),
125 ]);
126 childCompiler.hooks.thisCompilation.tap('angular-compiler', (compilation, { normalModuleFactory }) => {
127 // If no data is provided, the resource will be read from the filesystem
128 if (data !== undefined) {
129 normalModuleFactory.hooks.resolveForScheme
130 .for('angular-resource')
131 .tap('angular-compiler', (resourceData) => {
132 if (filePath) {
133 resourceData.path = filePath;
134 resourceData.resource = filePath;
135 }
136 if (mimeType) {
137 resourceData.data.mimetype = mimeType;
138 }
139 return true;
140 });
141 NormalModule.getCompilationHooks(compilation)
142 .readResourceForScheme.for('angular-resource')
143 .tap('angular-compiler', () => data);
144 compilation[inline_resource_1.InlineAngularResourceSymbol] = data;
145 }
146 compilation.hooks.additionalAssets.tap('angular-compiler', () => {
147 const asset = compilation.assets[outputFilePath];
148 if (!asset) {
149 return;
150 }
151 try {
152 const output = this._evaluate(outputFilePath, asset.source().toString());
153 if (typeof output === 'string') {
154 compilation.assets[outputFilePath] = new sources.RawSource(output);
155 }
156 }
157 catch (error) {
158 // Use compilation errors, as otherwise webpack will choke
159 compilation.errors.push(error);
160 }
161 });
162 });
163 let finalContent;
164 childCompiler.hooks.compilation.tap('angular-compiler', (childCompilation) => {
165 childCompilation.hooks.processAssets.tap({ name: 'angular-compiler', stage: webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT }, () => {
166 var _a;
167 finalContent = (_a = childCompilation.assets[outputFilePath]) === null || _a === void 0 ? void 0 : _a.source().toString();
168 delete childCompilation.assets[outputFilePath];
169 delete childCompilation.assets[outputFilePath + '.map'];
170 });
171 });
172 return new Promise((resolve, reject) => {
173 childCompiler.runAsChild((error, _, childCompilation) => {
174 var _a, _b;
175 if (error) {
176 reject(error);
177 return;
178 }
179 else if (!childCompilation) {
180 reject(new Error('Unknown child compilation error'));
181 return;
182 }
183 // Workaround to attempt to reduce memory usage of child compilations.
184 // This removes the child compilation from the main compilation and manually propagates
185 // all dependencies, warnings, and errors.
186 const parent = childCompiler.parentCompilation;
187 if (parent) {
188 parent.children = parent.children.filter((child) => child !== childCompilation);
189 let fileDependencies;
190 for (const dependency of childCompilation.fileDependencies) {
191 // Skip paths that do not appear to be files (have no extension).
192 // `fileDependencies` can contain directories and not just files which can
193 // cause incorrect cache invalidation on rebuilds.
194 if (!path.extname(dependency)) {
195 continue;
196 }
197 if (data && containingFile && dependency.endsWith(entry)) {
198 // use containing file if the resource was inline
199 parent.fileDependencies.add(containingFile);
200 }
201 else {
202 parent.fileDependencies.add(dependency);
203 }
204 // Save the dependencies for this resource.
205 if (filePath) {
206 const resolvedFile = paths_1.normalizePath(dependency);
207 const entry = this._reverseDependencies.get(resolvedFile);
208 if (entry) {
209 entry.add(filePath);
210 }
211 else {
212 this._reverseDependencies.set(resolvedFile, new Set([filePath]));
213 }
214 if (fileDependencies) {
215 fileDependencies.add(dependency);
216 }
217 else {
218 fileDependencies = new Set([dependency]);
219 this._fileDependencies.set(filePath, fileDependencies);
220 }
221 }
222 }
223 parent.contextDependencies.addAll(childCompilation.contextDependencies);
224 parent.missingDependencies.addAll(childCompilation.missingDependencies);
225 parent.buildDependencies.addAll(childCompilation.buildDependencies);
226 parent.warnings.push(...childCompilation.warnings);
227 parent.errors.push(...childCompilation.errors);
228 if (this.assetCache) {
229 for (const { info, name, source } of childCompilation.getAssets()) {
230 // Use the originating file as the cache key if present
231 // Otherwise, generate a cache key based on the generated name
232 const cacheKey = (_a = info.sourceFilename) !== null && _a !== void 0 ? _a : `!![GENERATED]:${name}`;
233 this.assetCache.set(cacheKey, { info, name, source });
234 }
235 }
236 }
237 resolve({
238 content: finalContent !== null && finalContent !== void 0 ? finalContent : '',
239 success: ((_b = childCompilation.errors) === null || _b === void 0 ? void 0 : _b.length) === 0,
240 });
241 });
242 });
243 }
244 _evaluate(filename, source) {
245 var _a;
246 // Evaluate code
247 const context = {};
248 try {
249 vm.runInNewContext(source, context, { filename });
250 }
251 catch {
252 // Error are propagated through the child compilation.
253 return null;
254 }
255 if (typeof context.resource === 'string') {
256 return context.resource;
257 }
258 else if (typeof ((_a = context.resource) === null || _a === void 0 ? void 0 : _a.default) === 'string') {
259 return context.resource.default;
260 }
261 throw new Error(`The loader "${filename}" didn't return a string.`);
262 }
263 async get(filePath) {
264 var _a;
265 const normalizedFile = paths_1.normalizePath(filePath);
266 let compilationResult = (_a = this.fileCache) === null || _a === void 0 ? void 0 : _a.get(normalizedFile);
267 if (compilationResult === undefined) {
268 // cache miss so compile resource
269 compilationResult = await this._compile(filePath);
270 // Only cache if compilation was successful
271 if (this.fileCache && compilationResult.success) {
272 this.fileCache.set(normalizedFile, compilationResult);
273 }
274 }
275 return compilationResult.content;
276 }
277 async process(data, mimeType, fileExtension, resourceType, containingFile) {
278 if (data.trim().length === 0) {
279 return '';
280 }
281 const compilationResult = await this._compile(undefined, data, mimeType, fileExtension, resourceType, containingFile);
282 return compilationResult.content;
283 }
284}
285exports.WebpackResourceLoader = WebpackResourceLoader;
Note: See TracBrowser for help on using the repository browser.