@angular-devkit/build-angular 14.0.0-next.10 → 14.0.0-next.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/builders.json CHANGED
@@ -11,6 +11,11 @@
11
11
  "schema": "./src/builders/browser/schema.json",
12
12
  "description": "Build a browser application."
13
13
  },
14
+ "browser-esbuild": {
15
+ "implementation": "./src/builders/browser-esbuild",
16
+ "schema": "./src/builders/browser/schema.json",
17
+ "description": "Build a browser application."
18
+ },
14
19
  "dev-server": {
15
20
  "implementation": "./src/builders/dev-server",
16
21
  "schema": "./src/builders/dev-server/schema.json",
package/package.json CHANGED
@@ -1,15 +1,15 @@
1
1
  {
2
2
  "name": "@angular-devkit/build-angular",
3
- "version": "14.0.0-next.10",
3
+ "version": "14.0.0-next.13",
4
4
  "description": "Angular Webpack Build Facade",
5
5
  "main": "src/index.js",
6
6
  "typings": "src/index.d.ts",
7
7
  "builders": "builders.json",
8
8
  "dependencies": {
9
- "@ampproject/remapping": "2.1.2",
10
- "@angular-devkit/architect": "0.1400.0-next.10",
11
- "@angular-devkit/build-webpack": "0.1400.0-next.10",
12
- "@angular-devkit/core": "14.0.0-next.10",
9
+ "@ampproject/remapping": "2.2.0",
10
+ "@angular-devkit/architect": "0.1400.0-next.13",
11
+ "@angular-devkit/build-webpack": "0.1400.0-next.13",
12
+ "@angular-devkit/core": "14.0.0-next.13",
13
13
  "@babel/core": "7.17.9",
14
14
  "@babel/generator": "7.17.9",
15
15
  "@babel/helper-annotate-as-pure": "7.16.7",
@@ -20,19 +20,19 @@
20
20
  "@babel/runtime": "7.17.9",
21
21
  "@babel/template": "7.16.7",
22
22
  "@discoveryjs/json-ext": "0.5.7",
23
- "@ngtools/webpack": "14.0.0-next.10",
23
+ "@ngtools/webpack": "14.0.0-next.13",
24
24
  "ansi-colors": "4.1.1",
25
- "babel-loader": "8.2.4",
25
+ "babel-loader": "8.2.5",
26
26
  "babel-plugin-istanbul": "6.1.1",
27
27
  "browserslist": "^4.9.1",
28
- "cacache": "16.0.4",
28
+ "cacache": "16.0.7",
29
29
  "copy-webpack-plugin": "10.2.4",
30
30
  "critters": "0.0.16",
31
31
  "css-loader": "6.7.1",
32
- "esbuild-wasm": "0.14.36",
32
+ "esbuild-wasm": "0.14.38",
33
33
  "glob": "8.0.1",
34
34
  "https-proxy-agent": "5.0.1",
35
- "inquirer": "8.2.2",
35
+ "inquirer": "8.2.4",
36
36
  "jsonc-parser": "3.0.0",
37
37
  "karma-source-map-support": "1.4.0",
38
38
  "less": "4.1.2",
@@ -48,21 +48,21 @@
48
48
  "postcss": "8.4.12",
49
49
  "postcss-import": "14.1.0",
50
50
  "postcss-loader": "6.2.1",
51
- "postcss-preset-env": "7.4.3",
51
+ "postcss-preset-env": "7.4.4",
52
52
  "regenerator-runtime": "0.13.9",
53
53
  "resolve-url-loader": "5.0.0",
54
54
  "rxjs": "6.6.7",
55
- "sass": "1.50.1",
55
+ "sass": "1.51.0",
56
56
  "sass-loader": "12.6.0",
57
57
  "semver": "7.3.7",
58
58
  "source-map-loader": "3.0.1",
59
59
  "source-map-support": "0.5.21",
60
60
  "stylus": "0.57.0",
61
61
  "stylus-loader": "6.2.0",
62
- "terser": "5.12.1",
62
+ "terser": "5.13.0",
63
63
  "text-table": "0.2.0",
64
64
  "tree-kill": "1.2.2",
65
- "tslib": "2.3.1",
65
+ "tslib": "2.4.0",
66
66
  "webpack": "5.72.0",
67
67
  "webpack-dev-middleware": "5.3.1",
68
68
  "webpack-dev-server": "4.8.1",
@@ -70,7 +70,7 @@
70
70
  "webpack-subresource-integrity": "5.1.0"
71
71
  },
72
72
  "optionalDependencies": {
73
- "esbuild": "0.14.36"
73
+ "esbuild": "0.14.38"
74
74
  },
75
75
  "peerDependencies": {
76
76
  "@angular/compiler-cli": "^14.0.0 || ^14.0.0-next",
@@ -14,5 +14,6 @@ interface AngularCustomOptions extends Omit<ApplicationPresetOptions, 'instrumen
14
14
  };
15
15
  }
16
16
  export declare type AngularBabelLoaderOptions = AngularCustomOptions & Record<string, unknown>;
17
+ export declare function requiresLinking(path: string, source: string): Promise<boolean>;
17
18
  declare const _default: any;
18
19
  export default _default;
@@ -7,6 +7,7 @@
7
7
  * found in the LICENSE file at https://angular.io/license
8
8
  */
9
9
  Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.requiresLinking = void 0;
10
11
  const babel_loader_1 = require("babel-loader");
11
12
  const typescript_1 = require("typescript");
12
13
  const load_esm_1 = require("../utils/load-esm");
@@ -38,6 +39,7 @@ async function requiresLinking(path, source) {
38
39
  }
39
40
  return needsLinking(path, source);
40
41
  }
42
+ exports.requiresLinking = requiresLinking;
41
43
  // eslint-disable-next-line max-lines-per-function
42
44
  exports.default = (0, babel_loader_1.custom)(() => {
43
45
  const baseOptions = Object.freeze({
@@ -95,7 +95,7 @@ async function _renderUniversal(options, context, browserResult, serverResult, s
95
95
  }
96
96
  await fs.promises.writeFile(outputIndexPath, html);
97
97
  if (browserOptions.serviceWorker) {
98
- await (0, service_worker_1.augmentAppWithServiceWorker)(projectRoot, outputPath, browserOptions.baseHref || '/', browserOptions.ngswConfigPath);
98
+ await (0, service_worker_1.augmentAppWithServiceWorker)(projectRoot, root, outputPath, browserOptions.baseHref || '/', browserOptions.ngswConfigPath);
99
99
  }
100
100
  }
101
101
  return browserResult;
@@ -252,7 +252,7 @@ function buildWebpackBrowser(options, context, transforms = {}) {
252
252
  spinner.start('Generating service worker...');
253
253
  for (const [locale, outputPath] of outputPaths.entries()) {
254
254
  try {
255
- await (0, service_worker_1.augmentAppWithServiceWorker)(projectRoot, outputPath, getLocaleBaseHref(i18n, locale) || options.baseHref || '/', options.ngswConfigPath);
255
+ await (0, service_worker_1.augmentAppWithServiceWorker)(projectRoot, context.workspaceRoot, outputPath, getLocaleBaseHref(i18n, locale) || options.baseHref || '/', options.ngswConfigPath);
256
256
  }
257
257
  catch (error) {
258
258
  spinner.fail('Service worker generation failed.');
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @license
3
+ * Copyright Google LLC All Rights Reserved.
4
+ *
5
+ * Use of this source code is governed by an MIT-style license that can be
6
+ * found in the LICENSE file at https://angular.io/license
7
+ */
8
+ import type { Plugin } from 'esbuild';
9
+ import { BundleStylesheetOptions } from './stylesheets';
10
+ export declare function createCompilerPlugin(pluginOptions: {
11
+ sourcemap: boolean;
12
+ tsconfig: string;
13
+ advancedOptimizations?: boolean;
14
+ }, styleOptions: BundleStylesheetOptions): Plugin;
@@ -0,0 +1,338 @@
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
+ */
9
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ var desc = Object.getOwnPropertyDescriptor(m, k);
12
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
13
+ desc = { enumerable: true, get: function() { return m[k]; } };
14
+ }
15
+ Object.defineProperty(o, k2, desc);
16
+ }) : (function(o, m, k, k2) {
17
+ if (k2 === undefined) k2 = k;
18
+ o[k2] = m[k];
19
+ }));
20
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
21
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
22
+ }) : function(o, v) {
23
+ o["default"] = v;
24
+ });
25
+ var __importStar = (this && this.__importStar) || function (mod) {
26
+ if (mod && mod.__esModule) return mod;
27
+ var result = {};
28
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
29
+ __setModuleDefault(result, mod);
30
+ return result;
31
+ };
32
+ var __importDefault = (this && this.__importDefault) || function (mod) {
33
+ return (mod && mod.__esModule) ? mod : { "default": mod };
34
+ };
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.createCompilerPlugin = void 0;
37
+ const core_1 = require("@babel/core");
38
+ const assert = __importStar(require("assert"));
39
+ const fs_1 = require("fs");
40
+ const path = __importStar(require("path"));
41
+ const typescript_1 = __importDefault(require("typescript"));
42
+ const application_1 = __importDefault(require("../../babel/presets/application"));
43
+ const webpack_loader_1 = require("../../babel/webpack-loader");
44
+ const load_esm_1 = require("../../utils/load-esm");
45
+ const stylesheets_1 = require("./stylesheets");
46
+ /**
47
+ * Converts TypeScript Diagnostic related information into an esbuild compatible note object.
48
+ * Related information is a subset of a full TypeScript Diagnostic and also used for diagnostic
49
+ * notes associated with the main Diagnostic.
50
+ * @param diagnostic The TypeScript diagnostic relative information to convert.
51
+ * @param host A TypeScript FormatDiagnosticsHost instance to use during conversion.
52
+ * @returns An esbuild diagnostic message as a PartialMessage object
53
+ */
54
+ function convertTypeScriptDiagnosticInfo(info, host, textPrefix) {
55
+ let text = typescript_1.default.flattenDiagnosticMessageText(info.messageText, host.getNewLine());
56
+ if (textPrefix) {
57
+ text = textPrefix + text;
58
+ }
59
+ const note = { text };
60
+ if (info.file) {
61
+ note.location = {
62
+ file: info.file.fileName,
63
+ length: info.length,
64
+ };
65
+ // Calculate the line/column location and extract the full line text that has the diagnostic
66
+ if (info.start) {
67
+ const { line, character } = typescript_1.default.getLineAndCharacterOfPosition(info.file, info.start);
68
+ note.location.line = line + 1;
69
+ note.location.column = character;
70
+ // The start position for the slice is the first character of the error line
71
+ const lineStartPosition = typescript_1.default.getPositionOfLineAndCharacter(info.file, line, 0);
72
+ // The end position for the slice is the first character of the next line or the length of
73
+ // the entire file if the line is the last line of the file (getPositionOfLineAndCharacter
74
+ // will error if a nonexistent line is passed).
75
+ const { line: lastLineOfFile } = typescript_1.default.getLineAndCharacterOfPosition(info.file, info.file.text.length - 1);
76
+ const lineEndPosition = line < lastLineOfFile
77
+ ? typescript_1.default.getPositionOfLineAndCharacter(info.file, line + 1, 0)
78
+ : info.file.text.length;
79
+ note.location.lineText = info.file.text.slice(lineStartPosition, lineEndPosition).trimEnd();
80
+ }
81
+ }
82
+ return note;
83
+ }
84
+ /**
85
+ * Converts a TypeScript Diagnostic message into an esbuild compatible message object.
86
+ * @param diagnostic The TypeScript diagnostic to convert.
87
+ * @param host A TypeScript FormatDiagnosticsHost instance to use during conversion.
88
+ * @returns An esbuild diagnostic message as a PartialMessage object
89
+ */
90
+ function convertTypeScriptDiagnostic(diagnostic, host) {
91
+ var _a;
92
+ let codePrefix = 'TS';
93
+ let code = `${diagnostic.code}`;
94
+ if (diagnostic.source === 'ngtsc') {
95
+ codePrefix = 'NG';
96
+ // Remove `-99` Angular prefix from diagnostic code
97
+ code = code.slice(3);
98
+ }
99
+ const message = {
100
+ ...convertTypeScriptDiagnosticInfo(diagnostic, host, `${codePrefix}${code}: `),
101
+ // Store original diagnostic for reference if needed downstream
102
+ detail: diagnostic,
103
+ };
104
+ if ((_a = diagnostic.relatedInformation) === null || _a === void 0 ? void 0 : _a.length) {
105
+ message.notes = diagnostic.relatedInformation.map((info) => convertTypeScriptDiagnosticInfo(info, host));
106
+ }
107
+ return message;
108
+ }
109
+ // This is a non-watch version of the compiler code from `@ngtools/webpack` augmented for esbuild
110
+ // eslint-disable-next-line max-lines-per-function
111
+ function createCompilerPlugin(pluginOptions, styleOptions) {
112
+ return {
113
+ name: 'angular-compiler',
114
+ // eslint-disable-next-line max-lines-per-function
115
+ async setup(build) {
116
+ var _a;
117
+ var _b;
118
+ // This uses a wrapped dynamic import to load `@angular/compiler-cli` which is ESM.
119
+ // Once TypeScript provides support for retaining dynamic imports this workaround can be dropped.
120
+ const compilerCli = await (0, load_esm_1.loadEsmModule)('@angular/compiler-cli');
121
+ // Temporary deep import for transformer support
122
+ const { createAotTransformers, mergeTransformers, } = require('@ngtools/webpack/src/ivy/transformation');
123
+ // Setup defines based on the values provided by the Angular compiler-cli
124
+ (_a = (_b = build.initialOptions).define) !== null && _a !== void 0 ? _a : (_b.define = {});
125
+ for (const [key, value] of Object.entries(compilerCli.GLOBAL_DEFS_FOR_TERSER_WITH_AOT)) {
126
+ if (key in build.initialOptions.define) {
127
+ // Skip keys that have been manually provided
128
+ continue;
129
+ }
130
+ // esbuild requires values to be a string (actual strings need to be quoted).
131
+ // In this case, all provided values are booleans.
132
+ build.initialOptions.define[key] = value.toString();
133
+ }
134
+ // The tsconfig is loaded in setup instead of in start to allow the esbuild target build option to be modified.
135
+ // esbuild build options can only be modified in setup prior to starting the build.
136
+ const { options: compilerOptions, rootNames, errors: configurationDiagnostics, } = compilerCli.readConfiguration(pluginOptions.tsconfig, {
137
+ enableIvy: true,
138
+ noEmitOnError: false,
139
+ suppressOutputPathCheck: true,
140
+ outDir: undefined,
141
+ inlineSources: pluginOptions.sourcemap,
142
+ inlineSourceMap: pluginOptions.sourcemap,
143
+ sourceMap: false,
144
+ mapRoot: undefined,
145
+ sourceRoot: undefined,
146
+ declaration: false,
147
+ declarationMap: false,
148
+ allowEmptyCodegenFiles: false,
149
+ annotationsAs: 'decorators',
150
+ enableResourceInlining: false,
151
+ });
152
+ // Adjust the esbuild output target based on the tsconfig target
153
+ if (compilerOptions.target === undefined ||
154
+ compilerOptions.target <= typescript_1.default.ScriptTarget.ES2015) {
155
+ build.initialOptions.target = 'es2015';
156
+ }
157
+ else if (compilerOptions.target >= typescript_1.default.ScriptTarget.ESNext) {
158
+ build.initialOptions.target = 'esnext';
159
+ }
160
+ else {
161
+ build.initialOptions.target = typescript_1.default.ScriptTarget[compilerOptions.target].toLowerCase();
162
+ }
163
+ // The file emitter created during `onStart` that will be used during the build in `onLoad` callbacks for TS files
164
+ let fileEmitter;
165
+ build.onStart(async () => {
166
+ var _a, _b;
167
+ const result = {};
168
+ // Create TypeScript compiler host
169
+ const host = typescript_1.default.createIncrementalCompilerHost(compilerOptions);
170
+ // Temporarily add a readResource hook to allow for a transformResource hook.
171
+ // Once the AOT compiler allows only a transformResource hook this can be removed.
172
+ host.readResource = function (fileName) {
173
+ var _a;
174
+ // Provide same no file found behavior as @ngtools/webpack
175
+ return (_a = this.readFile(fileName)) !== null && _a !== void 0 ? _a : '';
176
+ };
177
+ // Add an AOT compiler resource transform hook
178
+ host.transformResource = async function (data, context) {
179
+ var _a, _b, _c;
180
+ // Only style resources are transformed currently
181
+ if (context.type !== 'style') {
182
+ return null;
183
+ }
184
+ // The file with the resource content will either be an actual file (resourceFile)
185
+ // or the file containing the inline component style text (containingFile).
186
+ const file = (_a = context.resourceFile) !== null && _a !== void 0 ? _a : context.containingFile;
187
+ const { contents, errors, warnings } = await (0, stylesheets_1.bundleStylesheetText)(data, {
188
+ resolvePath: path.dirname(file),
189
+ virtualName: file,
190
+ }, styleOptions);
191
+ ((_b = result.errors) !== null && _b !== void 0 ? _b : (result.errors = [])).push(...errors);
192
+ ((_c = result.warnings) !== null && _c !== void 0 ? _c : (result.warnings = [])).push(...warnings);
193
+ return { content: contents };
194
+ };
195
+ // Create the Angular specific program that contains the Angular compiler
196
+ const angularProgram = new compilerCli.NgtscProgram(rootNames, compilerOptions, host);
197
+ const angularCompiler = angularProgram.compiler;
198
+ const { ignoreForDiagnostics, ignoreForEmit } = angularCompiler;
199
+ const typeScriptProgram = angularProgram.getTsProgram();
200
+ const builder = typescript_1.default.createAbstractBuilder(typeScriptProgram, host);
201
+ await angularCompiler.analyzeAsync();
202
+ function* collectDiagnostics() {
203
+ // Collect program level diagnostics
204
+ yield* configurationDiagnostics;
205
+ yield* angularCompiler.getOptionDiagnostics();
206
+ yield* builder.getOptionsDiagnostics();
207
+ yield* builder.getGlobalDiagnostics();
208
+ // Collect source file specific diagnostics
209
+ const OptimizeFor = compilerCli.OptimizeFor;
210
+ for (const sourceFile of builder.getSourceFiles()) {
211
+ if (ignoreForDiagnostics.has(sourceFile)) {
212
+ continue;
213
+ }
214
+ yield* builder.getSyntacticDiagnostics(sourceFile);
215
+ yield* builder.getSemanticDiagnostics(sourceFile);
216
+ const angularDiagnostics = angularCompiler.getDiagnosticsForFile(sourceFile, OptimizeFor.WholeProgram);
217
+ yield* angularDiagnostics;
218
+ }
219
+ }
220
+ for (const diagnostic of collectDiagnostics()) {
221
+ const message = convertTypeScriptDiagnostic(diagnostic, host);
222
+ if (diagnostic.category === typescript_1.default.DiagnosticCategory.Error) {
223
+ ((_a = result.errors) !== null && _a !== void 0 ? _a : (result.errors = [])).push(message);
224
+ }
225
+ else {
226
+ ((_b = result.warnings) !== null && _b !== void 0 ? _b : (result.warnings = [])).push(message);
227
+ }
228
+ }
229
+ fileEmitter = createFileEmitter(builder, mergeTransformers(angularCompiler.prepareEmit().transformers, createAotTransformers(builder, {})), () => []);
230
+ return result;
231
+ });
232
+ build.onLoad({ filter: compilerOptions.allowJs ? /\.[cm]?[jt]sx?$/ : /\.[cm]?tsx?$/ }, async (args) => {
233
+ var _a, _b;
234
+ assert.ok(fileEmitter, 'Invalid plugin execution order');
235
+ const typescriptResult = await fileEmitter(args.path);
236
+ if (!typescriptResult) {
237
+ // No TS result indicates the file is not part of the TypeScript program.
238
+ // If allowJs is enabled and the file is JS then defer to the next load hook.
239
+ if (compilerOptions.allowJs && /\.[cm]?js$/.test(args.path)) {
240
+ return undefined;
241
+ }
242
+ // Otherwise return an error
243
+ return {
244
+ errors: [
245
+ {
246
+ text: 'File is missing from the TypeScript compilation.',
247
+ location: { file: args.path },
248
+ notes: [
249
+ {
250
+ text: `Ensure the file is part of the TypeScript program via the 'files' or 'include' property.`,
251
+ },
252
+ ],
253
+ },
254
+ ],
255
+ };
256
+ }
257
+ const data = (_a = typescriptResult.content) !== null && _a !== void 0 ? _a : '';
258
+ const babelResult = await (0, core_1.transformAsync)(data, {
259
+ filename: args.path,
260
+ inputSourceMap: (pluginOptions.sourcemap ? undefined : false),
261
+ sourceMaps: pluginOptions.sourcemap ? 'inline' : false,
262
+ compact: false,
263
+ configFile: false,
264
+ babelrc: false,
265
+ browserslistConfigFile: false,
266
+ plugins: [],
267
+ presets: [
268
+ [
269
+ application_1.default,
270
+ {
271
+ forceAsyncTransformation: data.includes('async'),
272
+ optimize: pluginOptions.advancedOptimizations && {},
273
+ },
274
+ ],
275
+ ],
276
+ });
277
+ return {
278
+ contents: (_b = babelResult === null || babelResult === void 0 ? void 0 : babelResult.code) !== null && _b !== void 0 ? _b : '',
279
+ loader: 'js',
280
+ };
281
+ });
282
+ build.onLoad({ filter: /\.[cm]?js$/ }, async (args) => {
283
+ var _a;
284
+ const angularPackage = /[\\/]node_modules[\\/]@angular[\\/]/.test(args.path);
285
+ const linkerPluginCreator = (await (0, load_esm_1.loadEsmModule)('@angular/compiler-cli/linker/babel')).createEs2015LinkerPlugin;
286
+ const data = await fs_1.promises.readFile(args.path, 'utf-8');
287
+ const result = await (0, core_1.transformAsync)(data, {
288
+ filename: args.path,
289
+ inputSourceMap: (pluginOptions.sourcemap ? undefined : false),
290
+ sourceMaps: pluginOptions.sourcemap ? 'inline' : false,
291
+ compact: false,
292
+ configFile: false,
293
+ babelrc: false,
294
+ browserslistConfigFile: false,
295
+ plugins: [],
296
+ presets: [
297
+ [
298
+ application_1.default,
299
+ {
300
+ angularLinker: {
301
+ shouldLink: await (0, webpack_loader_1.requiresLinking)(args.path, data),
302
+ jitMode: false,
303
+ linkerPluginCreator,
304
+ },
305
+ forceAsyncTransformation: !/[\\/][_f]?esm2015[\\/]/.test(args.path) && data.includes('async'),
306
+ optimize: pluginOptions.advancedOptimizations && {
307
+ looseEnums: angularPackage,
308
+ pureTopLevel: angularPackage,
309
+ },
310
+ },
311
+ ],
312
+ ],
313
+ });
314
+ return {
315
+ contents: (_a = result === null || result === void 0 ? void 0 : result.code) !== null && _a !== void 0 ? _a : data,
316
+ loader: 'js',
317
+ };
318
+ });
319
+ },
320
+ };
321
+ }
322
+ exports.createCompilerPlugin = createCompilerPlugin;
323
+ function createFileEmitter(program, transformers = {}, onAfterEmit) {
324
+ return async (file) => {
325
+ const sourceFile = program.getSourceFile(file);
326
+ if (!sourceFile) {
327
+ return undefined;
328
+ }
329
+ let content;
330
+ program.emit(sourceFile, (filename, data) => {
331
+ if (/\.[cm]?js$/.test(filename)) {
332
+ content = data;
333
+ }
334
+ }, undefined /* cancellationToken */, undefined /* emitOnlyDtsFiles */, transformers);
335
+ onAfterEmit === null || onAfterEmit === void 0 ? void 0 : onAfterEmit(sourceFile);
336
+ return { content, dependencies: [] };
337
+ };
338
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * @license
3
+ * Copyright Google LLC All Rights Reserved.
4
+ *
5
+ * Use of this source code is governed by an MIT-style license that can be
6
+ * found in the LICENSE file at https://angular.io/license
7
+ */
8
+ import { BuilderContext } from '@angular-devkit/architect';
9
+ import { BuildFailure, BuildOptions, BuildResult, Message, OutputFile } from 'esbuild';
10
+ /**
11
+ * Determines if an unknown value is an esbuild BuildFailure error object thrown by esbuild.
12
+ * @param value A potential esbuild BuildFailure error object.
13
+ * @returns `true` if the object is determined to be a BuildFailure object; otherwise, `false`.
14
+ */
15
+ export declare function isEsBuildFailure(value: unknown): value is BuildFailure;
16
+ /**
17
+ * Executes the esbuild build function and normalizes the build result in the event of a
18
+ * build failure that results in no output being generated.
19
+ * All builds use the `write` option with a value of `false` to allow for the output files
20
+ * build result array to be populated.
21
+ *
22
+ * @param options The esbuild options object to use when building.
23
+ * @returns If output files are generated, the full esbuild BuildResult; if not, the
24
+ * warnings and errors for the attempted build.
25
+ */
26
+ export declare function bundle(options: BuildOptions): Promise<(BuildResult & {
27
+ outputFiles: OutputFile[];
28
+ }) | (BuildFailure & {
29
+ outputFiles?: never;
30
+ })>;
31
+ export declare function logMessages(context: BuilderContext, { errors, warnings }: {
32
+ errors: Message[];
33
+ warnings: Message[];
34
+ }): Promise<void>;
@@ -0,0 +1,59 @@
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
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.logMessages = exports.bundle = exports.isEsBuildFailure = void 0;
11
+ const esbuild_1 = require("esbuild");
12
+ /**
13
+ * Determines if an unknown value is an esbuild BuildFailure error object thrown by esbuild.
14
+ * @param value A potential esbuild BuildFailure error object.
15
+ * @returns `true` if the object is determined to be a BuildFailure object; otherwise, `false`.
16
+ */
17
+ function isEsBuildFailure(value) {
18
+ return !!value && typeof value === 'object' && 'errors' in value && 'warnings' in value;
19
+ }
20
+ exports.isEsBuildFailure = isEsBuildFailure;
21
+ /**
22
+ * Executes the esbuild build function and normalizes the build result in the event of a
23
+ * build failure that results in no output being generated.
24
+ * All builds use the `write` option with a value of `false` to allow for the output files
25
+ * build result array to be populated.
26
+ *
27
+ * @param options The esbuild options object to use when building.
28
+ * @returns If output files are generated, the full esbuild BuildResult; if not, the
29
+ * warnings and errors for the attempted build.
30
+ */
31
+ async function bundle(options) {
32
+ try {
33
+ return await (0, esbuild_1.build)({
34
+ ...options,
35
+ write: false,
36
+ });
37
+ }
38
+ catch (failure) {
39
+ // Build failures will throw an exception which contains errors/warnings
40
+ if (isEsBuildFailure(failure)) {
41
+ return failure;
42
+ }
43
+ else {
44
+ throw failure;
45
+ }
46
+ }
47
+ }
48
+ exports.bundle = bundle;
49
+ async function logMessages(context, { errors, warnings }) {
50
+ if (warnings.length) {
51
+ const warningMessages = await (0, esbuild_1.formatMessages)(warnings, { kind: 'warning', color: true });
52
+ context.logger.warn(warningMessages.join('\n'));
53
+ }
54
+ if (errors.length) {
55
+ const errorMessages = await (0, esbuild_1.formatMessages)(errors, { kind: 'error', color: true });
56
+ context.logger.error(errorMessages.join('\n'));
57
+ }
58
+ }
59
+ exports.logMessages = logMessages;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * @license
3
+ * Copyright Google LLC All Rights Reserved.
4
+ *
5
+ * Use of this source code is governed by an MIT-style license that can be
6
+ * found in the LICENSE file at https://angular.io/license
7
+ */
8
+ import { BuilderContext } from '@angular-devkit/architect';
9
+ import { Schema as BrowserBuilderOptions } from '../browser/schema';
10
+ export declare function logExperimentalWarnings(options: BrowserBuilderOptions, context: BuilderContext): void;
@@ -0,0 +1,65 @@
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
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.logExperimentalWarnings = void 0;
11
+ const UNSUPPORTED_OPTIONS = [
12
+ 'allowedCommonJsDependencies',
13
+ 'budgets',
14
+ 'extractLicenses',
15
+ 'fileReplacements',
16
+ 'progress',
17
+ 'scripts',
18
+ 'statsJson',
19
+ // * i18n support
20
+ 'localize',
21
+ // The following two have no effect when localize is not enabled
22
+ // 'i18nDuplicateTranslation',
23
+ // 'i18nMissingTranslation',
24
+ // * Serviceworker support
25
+ 'ngswConfigPath',
26
+ 'serviceWorker',
27
+ // * Stylesheet preprocessor support
28
+ 'inlineStyleLanguage',
29
+ // The following option has no effect until preprocessors are supported
30
+ // 'stylePreprocessorOptions',
31
+ // * Watch mode
32
+ 'watch',
33
+ 'poll',
34
+ // * Deprecated
35
+ 'deployUrl',
36
+ // * Always enabled with esbuild
37
+ // 'commonChunk',
38
+ // * Currently unsupported by esbuild
39
+ 'namedChunks',
40
+ 'vendorChunk',
41
+ 'webWorkerTsConfig',
42
+ ];
43
+ function logExperimentalWarnings(options, context) {
44
+ // Warn about experimental status of this builder
45
+ context.logger.warn(`The esbuild browser application builder ('browser-esbuild') is currently experimental.`);
46
+ // Validate supported options
47
+ // Currently only a subset of the Webpack-based browser builder options are supported.
48
+ for (const unsupportedOption of UNSUPPORTED_OPTIONS) {
49
+ const value = options[unsupportedOption];
50
+ if (value === undefined || value === false) {
51
+ continue;
52
+ }
53
+ if (Array.isArray(value) && value.length === 0) {
54
+ continue;
55
+ }
56
+ if (typeof value === 'object' && Object.keys(value).length === 0) {
57
+ continue;
58
+ }
59
+ if (unsupportedOption === 'inlineStyleLanguage' && value === 'css') {
60
+ continue;
61
+ }
62
+ context.logger.warn(`The '${unsupportedOption}' option is currently unsupported by this experimental builder and will be ignored.`);
63
+ }
64
+ }
65
+ exports.logExperimentalWarnings = logExperimentalWarnings;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @license
3
+ * Copyright Google LLC All Rights Reserved.
4
+ *
5
+ * Use of this source code is governed by an MIT-style license that can be
6
+ * found in the LICENSE file at https://angular.io/license
7
+ */
8
+ import { BuilderContext, BuilderOutput } from '@angular-devkit/architect';
9
+ import { Schema as BrowserBuilderOptions } from '../browser/schema';
10
+ /**
11
+ * Main execution function for the esbuild-based application builder.
12
+ * The options are compatible with the Webpack-based builder.
13
+ * @param options The browser builder options to use when setting up the application build
14
+ * @param context The Architect builder context object
15
+ * @returns A promise with the builder result output
16
+ */
17
+ export declare function execute(options: BrowserBuilderOptions, context: BuilderContext): Promise<BuilderOutput>;
18
+ declare const _default: import("@angular-devkit/architect/src/internal").Builder<BrowserBuilderOptions & import("../../../../core/src").JsonObject>;
19
+ export default _default;
@@ -0,0 +1,258 @@
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
+ */
9
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ var desc = Object.getOwnPropertyDescriptor(m, k);
12
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
13
+ desc = { enumerable: true, get: function() { return m[k]; } };
14
+ }
15
+ Object.defineProperty(o, k2, desc);
16
+ }) : (function(o, m, k, k2) {
17
+ if (k2 === undefined) k2 = k;
18
+ o[k2] = m[k];
19
+ }));
20
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
21
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
22
+ }) : function(o, v) {
23
+ o["default"] = v;
24
+ });
25
+ var __importStar = (this && this.__importStar) || function (mod) {
26
+ if (mod && mod.__esModule) return mod;
27
+ var result = {};
28
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
29
+ __setModuleDefault(result, mod);
30
+ return result;
31
+ };
32
+ Object.defineProperty(exports, "__esModule", { value: true });
33
+ exports.execute = void 0;
34
+ const architect_1 = require("@angular-devkit/architect");
35
+ const assert = __importStar(require("assert"));
36
+ const fs_1 = require("fs");
37
+ const path = __importStar(require("path"));
38
+ const utils_1 = require("../../utils");
39
+ const copy_assets_1 = require("../../utils/copy-assets");
40
+ const index_html_generator_1 = require("../../utils/index-file/index-html-generator");
41
+ const package_chunk_sort_1 = require("../../utils/package-chunk-sort");
42
+ const webpack_browser_config_1 = require("../../utils/webpack-browser-config");
43
+ const configs_1 = require("../../webpack/configs");
44
+ const compiler_plugin_1 = require("./compiler-plugin");
45
+ const esbuild_1 = require("./esbuild");
46
+ const experimental_warnings_1 = require("./experimental-warnings");
47
+ const options_1 = require("./options");
48
+ const stylesheets_1 = require("./stylesheets");
49
+ /**
50
+ * Main execution function for the esbuild-based application builder.
51
+ * The options are compatible with the Webpack-based builder.
52
+ * @param options The browser builder options to use when setting up the application build
53
+ * @param context The Architect builder context object
54
+ * @returns A promise with the builder result output
55
+ */
56
+ // eslint-disable-next-line max-lines-per-function
57
+ async function execute(options, context) {
58
+ var _a, _b, _c, _d, _e, _f;
59
+ const startTime = Date.now();
60
+ // Only AOT is currently supported
61
+ if (options.aot !== true) {
62
+ context.logger.error('JIT mode is currently not supported by this experimental builder. AOT mode must be used.');
63
+ return { success: false };
64
+ }
65
+ // Inform user of experimental status of builder and options
66
+ (0, experimental_warnings_1.logExperimentalWarnings)(options, context);
67
+ // Determine project name from builder context target
68
+ const projectName = (_a = context.target) === null || _a === void 0 ? void 0 : _a.project;
69
+ if (!projectName) {
70
+ context.logger.error(`The 'browser-esbuild' builder requires a target to be specified.`);
71
+ return { success: false };
72
+ }
73
+ const { workspaceRoot, mainEntryPoint, polyfillsEntryPoint, optimizationOptions, outputPath, sourcemapOptions, tsconfig, assets, outputNames, } = await (0, options_1.normalizeOptions)(context, projectName, options);
74
+ // Clean output path if enabled
75
+ if (options.deleteOutputPath) {
76
+ (0, utils_1.deleteOutputDir)(workspaceRoot, options.outputPath);
77
+ }
78
+ // Setup bundler entry points
79
+ const entryPoints = {
80
+ main: mainEntryPoint,
81
+ };
82
+ if (polyfillsEntryPoint) {
83
+ entryPoints['polyfills'] = polyfillsEntryPoint;
84
+ }
85
+ // Create reverse lookup used during index HTML generation
86
+ const entryPointNameLookup = new Map(Object.entries(entryPoints).map(([name, filePath]) => [path.relative(workspaceRoot, filePath), name]));
87
+ // Execute esbuild
88
+ const result = await bundleCode(workspaceRoot, entryPoints, outputNames, options, optimizationOptions, sourcemapOptions, tsconfig);
89
+ // Log all warnings and errors generated during bundling
90
+ await (0, esbuild_1.logMessages)(context, result);
91
+ // Return if the bundling failed to generate output files or there are errors
92
+ if (!result.outputFiles || result.errors.length) {
93
+ return { success: false };
94
+ }
95
+ // Structure the bundling output files
96
+ const initialFiles = [];
97
+ const outputFiles = [];
98
+ for (const outputFile of result.outputFiles) {
99
+ // Entries in the metafile are relative to the `absWorkingDir` option which is set to the workspaceRoot
100
+ const relativeFilePath = path.relative(workspaceRoot, outputFile.path);
101
+ const entryPoint = (_c = (_b = result.metafile) === null || _b === void 0 ? void 0 : _b.outputs[relativeFilePath]) === null || _c === void 0 ? void 0 : _c.entryPoint;
102
+ if (entryPoint) {
103
+ // An entryPoint value indicates an initial file
104
+ initialFiles.push({
105
+ // Remove leading directory separator
106
+ file: outputFile.path.slice(1),
107
+ name: (_d = entryPointNameLookup.get(entryPoint)) !== null && _d !== void 0 ? _d : '',
108
+ extension: path.extname(outputFile.path),
109
+ });
110
+ }
111
+ outputFiles.push(outputFile);
112
+ }
113
+ // Create output directory if needed
114
+ try {
115
+ await fs_1.promises.mkdir(outputPath, { recursive: true });
116
+ }
117
+ catch (e) {
118
+ const reason = 'message' in e ? e.message : 'Unknown error';
119
+ context.logger.error('Unable to create output directory: ' + reason);
120
+ return { success: false };
121
+ }
122
+ // Process global stylesheets
123
+ if (options.styles) {
124
+ // resolveGlobalStyles is temporarily reused from the Webpack builder code
125
+ const { entryPoints: stylesheetEntrypoints, noInjectNames } = (0, configs_1.resolveGlobalStyles)(options.styles, workspaceRoot, !!options.preserveSymlinks);
126
+ for (const [name, files] of Object.entries(stylesheetEntrypoints)) {
127
+ const virtualEntryData = files.map((file) => `@import '${file}';`).join('\n');
128
+ const sheetResult = await (0, stylesheets_1.bundleStylesheetText)(virtualEntryData, { virtualName: `angular:style/global;${name}`, resolvePath: workspaceRoot }, {
129
+ optimization: !!optimizationOptions.styles.minify,
130
+ sourcemap: !!sourcemapOptions.styles,
131
+ outputNames: noInjectNames.includes(name) ? { media: outputNames.media } : outputNames,
132
+ });
133
+ await (0, esbuild_1.logMessages)(context, sheetResult);
134
+ if (!sheetResult.path) {
135
+ // Failed to process the stylesheet
136
+ assert.ok(sheetResult.errors.length, `Global stylesheet processing for '${name}' failed with no errors.`);
137
+ return { success: false };
138
+ }
139
+ // The virtual stylesheets will be named `stdin` by esbuild. This must be replaced
140
+ // with the actual name of the global style and the leading directory separator must
141
+ // also be removed to make the path relative.
142
+ const sheetPath = sheetResult.path.replace('stdin', name).slice(1);
143
+ outputFiles.push(createOutputFileFromText(sheetPath, sheetResult.contents));
144
+ if (sheetResult.map) {
145
+ outputFiles.push(createOutputFileFromText(sheetPath + '.map', sheetResult.map));
146
+ }
147
+ if (!noInjectNames.includes(name)) {
148
+ initialFiles.push({
149
+ file: sheetPath,
150
+ name,
151
+ extension: '.css',
152
+ });
153
+ }
154
+ outputFiles.push(...sheetResult.resourceFiles);
155
+ }
156
+ }
157
+ // Generate index HTML file
158
+ if (options.index) {
159
+ const entrypoints = (0, package_chunk_sort_1.generateEntryPoints)({
160
+ scripts: (_e = options.scripts) !== null && _e !== void 0 ? _e : [],
161
+ styles: (_f = options.styles) !== null && _f !== void 0 ? _f : [],
162
+ });
163
+ // Create an index HTML generator that reads from the in-memory output files
164
+ const indexHtmlGenerator = new index_html_generator_1.IndexHtmlGenerator({
165
+ indexPath: path.join(context.workspaceRoot, (0, webpack_browser_config_1.getIndexInputFile)(options.index)),
166
+ entrypoints,
167
+ sri: options.subresourceIntegrity,
168
+ optimization: optimizationOptions,
169
+ crossOrigin: options.crossOrigin,
170
+ });
171
+ indexHtmlGenerator.readAsset = async function (path) {
172
+ // Remove leading directory separator
173
+ path = path.slice(1);
174
+ const file = outputFiles.find((file) => file.path === path);
175
+ if (file) {
176
+ return file.text;
177
+ }
178
+ throw new Error(`Output file does not exist: ${path}`);
179
+ };
180
+ const { content, warnings, errors } = await indexHtmlGenerator.process({
181
+ baseHref: options.baseHref,
182
+ lang: undefined,
183
+ outputPath: '/',
184
+ files: initialFiles,
185
+ });
186
+ for (const error of errors) {
187
+ context.logger.error(error);
188
+ }
189
+ for (const warning of warnings) {
190
+ context.logger.warn(warning);
191
+ }
192
+ outputFiles.push(createOutputFileFromText((0, webpack_browser_config_1.getIndexOutputFile)(options.index), content));
193
+ }
194
+ // Copy assets
195
+ if (assets) {
196
+ await (0, copy_assets_1.copyAssets)(assets, [outputPath], workspaceRoot);
197
+ }
198
+ // Write output files
199
+ await Promise.all(outputFiles.map((file) => fs_1.promises.writeFile(path.join(outputPath, file.path), file.contents)));
200
+ context.logger.info(`Complete. [${(Date.now() - startTime) / 1000} seconds]`);
201
+ return { success: true };
202
+ }
203
+ exports.execute = execute;
204
+ function createOutputFileFromText(path, text) {
205
+ return {
206
+ path,
207
+ text,
208
+ get contents() {
209
+ return Buffer.from(this.text, 'utf-8');
210
+ },
211
+ };
212
+ }
213
+ async function bundleCode(workspaceRoot, entryPoints, outputNames, options, optimizationOptions, sourcemapOptions, tsconfig) {
214
+ return (0, esbuild_1.bundle)({
215
+ absWorkingDir: workspaceRoot,
216
+ bundle: true,
217
+ format: 'esm',
218
+ entryPoints,
219
+ entryNames: outputNames.bundles,
220
+ assetNames: outputNames.media,
221
+ target: 'es2020',
222
+ mainFields: ['es2020', 'browser', 'module', 'main'],
223
+ conditions: ['es2020', 'module'],
224
+ resolveExtensions: ['.ts', '.tsx', '.mjs', '.js'],
225
+ logLevel: options.verbose ? 'debug' : 'silent',
226
+ metafile: true,
227
+ minify: optimizationOptions.scripts,
228
+ pure: ['forwardRef'],
229
+ outdir: '/',
230
+ sourcemap: sourcemapOptions.scripts && (sourcemapOptions.hidden ? 'external' : true),
231
+ splitting: true,
232
+ tsconfig,
233
+ write: false,
234
+ platform: 'browser',
235
+ preserveSymlinks: options.preserveSymlinks,
236
+ plugins: [
237
+ (0, compiler_plugin_1.createCompilerPlugin)(
238
+ // JS/TS options
239
+ {
240
+ sourcemap: !!sourcemapOptions.scripts,
241
+ tsconfig,
242
+ advancedOptimizations: options.buildOptimizer,
243
+ },
244
+ // Component stylesheet options
245
+ {
246
+ workspaceRoot,
247
+ optimization: !!optimizationOptions.styles.minify,
248
+ sourcemap: !!sourcemapOptions.styles,
249
+ outputNames,
250
+ }),
251
+ ],
252
+ define: {
253
+ 'ngDevMode': optimizationOptions.scripts ? 'false' : 'true',
254
+ 'ngJitMode': 'false',
255
+ },
256
+ });
257
+ }
258
+ exports.default = (0, architect_1.createBuilder)(execute);
@@ -0,0 +1,34 @@
1
+ /**
2
+ * @license
3
+ * Copyright Google LLC All Rights Reserved.
4
+ *
5
+ * Use of this source code is governed by an MIT-style license that can be
6
+ * found in the LICENSE file at https://angular.io/license
7
+ */
8
+ import { BuilderContext } from '@angular-devkit/architect';
9
+ import { Schema as BrowserBuilderOptions } from '../browser/schema';
10
+ /**
11
+ * Normalize the user provided options by creating full paths for all path based options
12
+ * and converting multi-form options into a single form that can be directly used
13
+ * by the build process.
14
+ *
15
+ * @param context The context for current builder execution.
16
+ * @param projectName The name of the project for the current execution.
17
+ * @param options An object containing the options to use for the build.
18
+ * @returns An object containing normalized options required to perform the build.
19
+ */
20
+ export declare function normalizeOptions(context: BuilderContext, projectName: string, options: BrowserBuilderOptions): Promise<{
21
+ workspaceRoot: string;
22
+ mainEntryPoint: string;
23
+ polyfillsEntryPoint: string | undefined;
24
+ optimizationOptions: import("../../utils").NormalizedOptimizationOptions;
25
+ outputPath: string;
26
+ sourcemapOptions: import("../browser/schema").SourceMapClass;
27
+ tsconfig: string;
28
+ projectRoot: string;
29
+ assets: import("../browser/schema").AssetPatternClass[] | undefined;
30
+ outputNames: {
31
+ bundles: string;
32
+ media: string;
33
+ };
34
+ }>;
@@ -0,0 +1,87 @@
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
+ */
9
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ var desc = Object.getOwnPropertyDescriptor(m, k);
12
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
13
+ desc = { enumerable: true, get: function() { return m[k]; } };
14
+ }
15
+ Object.defineProperty(o, k2, desc);
16
+ }) : (function(o, m, k, k2) {
17
+ if (k2 === undefined) k2 = k;
18
+ o[k2] = m[k];
19
+ }));
20
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
21
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
22
+ }) : function(o, v) {
23
+ o["default"] = v;
24
+ });
25
+ var __importStar = (this && this.__importStar) || function (mod) {
26
+ if (mod && mod.__esModule) return mod;
27
+ var result = {};
28
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
29
+ __setModuleDefault(result, mod);
30
+ return result;
31
+ };
32
+ Object.defineProperty(exports, "__esModule", { value: true });
33
+ exports.normalizeOptions = void 0;
34
+ const path = __importStar(require("path"));
35
+ const utils_1 = require("../../utils");
36
+ const schema_1 = require("../browser/schema");
37
+ /**
38
+ * Normalize the user provided options by creating full paths for all path based options
39
+ * and converting multi-form options into a single form that can be directly used
40
+ * by the build process.
41
+ *
42
+ * @param context The context for current builder execution.
43
+ * @param projectName The name of the project for the current execution.
44
+ * @param options An object containing the options to use for the build.
45
+ * @returns An object containing normalized options required to perform the build.
46
+ */
47
+ async function normalizeOptions(context, projectName, options) {
48
+ var _a, _b, _c, _d;
49
+ const workspaceRoot = context.workspaceRoot;
50
+ const projectMetadata = await context.getProjectMetadata(projectName);
51
+ const projectRoot = path.join(workspaceRoot, (_a = projectMetadata.root) !== null && _a !== void 0 ? _a : '');
52
+ const projectSourceRoot = path.join(workspaceRoot, (_b = projectMetadata.sourceRoot) !== null && _b !== void 0 ? _b : 'src');
53
+ // Normalize options
54
+ const mainEntryPoint = path.join(workspaceRoot, options.main);
55
+ const polyfillsEntryPoint = options.polyfills && path.join(workspaceRoot, options.polyfills);
56
+ const tsconfig = path.join(workspaceRoot, options.tsConfig);
57
+ const outputPath = path.join(workspaceRoot, options.outputPath);
58
+ const optimizationOptions = (0, utils_1.normalizeOptimization)(options.optimization);
59
+ const sourcemapOptions = (0, utils_1.normalizeSourceMaps)((_c = options.sourceMap) !== null && _c !== void 0 ? _c : false);
60
+ const assets = ((_d = options.assets) === null || _d === void 0 ? void 0 : _d.length)
61
+ ? (0, utils_1.normalizeAssetPatterns)(options.assets, workspaceRoot, projectRoot, projectSourceRoot)
62
+ : undefined;
63
+ const outputNames = {
64
+ bundles: options.outputHashing === schema_1.OutputHashing.All || options.outputHashing === schema_1.OutputHashing.Bundles
65
+ ? '[name].[hash]'
66
+ : '[name]',
67
+ media: options.outputHashing === schema_1.OutputHashing.All || options.outputHashing === schema_1.OutputHashing.Media
68
+ ? '[name].[hash]'
69
+ : '[name]',
70
+ };
71
+ if (options.resourcesOutputPath) {
72
+ outputNames.media = path.join(options.resourcesOutputPath, outputNames.media);
73
+ }
74
+ return {
75
+ workspaceRoot,
76
+ mainEntryPoint,
77
+ polyfillsEntryPoint,
78
+ optimizationOptions,
79
+ outputPath,
80
+ sourcemapOptions,
81
+ tsconfig,
82
+ projectRoot,
83
+ assets,
84
+ outputNames,
85
+ };
86
+ }
87
+ exports.normalizeOptions = normalizeOptions;
@@ -0,0 +1,52 @@
1
+ /**
2
+ * @license
3
+ * Copyright Google LLC All Rights Reserved.
4
+ *
5
+ * Use of this source code is governed by an MIT-style license that can be
6
+ * found in the LICENSE file at https://angular.io/license
7
+ */
8
+ import type { OutputFile } from 'esbuild';
9
+ export interface BundleStylesheetOptions {
10
+ workspaceRoot?: string;
11
+ optimization: boolean;
12
+ preserveSymlinks?: boolean;
13
+ sourcemap: boolean | 'external';
14
+ outputNames?: {
15
+ bundles?: string;
16
+ media?: string;
17
+ };
18
+ }
19
+ /**
20
+ * Bundle a stylesheet that exists as a file on the filesystem.
21
+ *
22
+ * @param filename The path to the file to bundle.
23
+ * @param options The stylesheet bundling options to use.
24
+ * @returns The bundle result object.
25
+ */
26
+ export declare function bundleStylesheetFile(filename: string, options: BundleStylesheetOptions): Promise<{
27
+ errors: import("esbuild").Message[];
28
+ warnings: import("esbuild").Message[];
29
+ contents: string;
30
+ map: string | undefined;
31
+ path: string | undefined;
32
+ resourceFiles: OutputFile[];
33
+ }>;
34
+ /**
35
+ * Bundle stylesheet text data from a string.
36
+ *
37
+ * @param data The string content of a stylesheet to bundle.
38
+ * @param dataOptions The options to use to resolve references and name output of the stylesheet data.
39
+ * @param bundleOptions The stylesheet bundling options to use.
40
+ * @returns The bundle result object.
41
+ */
42
+ export declare function bundleStylesheetText(data: string, dataOptions: {
43
+ resolvePath: string;
44
+ virtualName?: string;
45
+ }, bundleOptions: BundleStylesheetOptions): Promise<{
46
+ errors: import("esbuild").Message[];
47
+ warnings: import("esbuild").Message[];
48
+ contents: string;
49
+ map: string | undefined;
50
+ path: string | undefined;
51
+ resourceFiles: OutputFile[];
52
+ }>;
@@ -0,0 +1,118 @@
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
+ */
9
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ var desc = Object.getOwnPropertyDescriptor(m, k);
12
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
13
+ desc = { enumerable: true, get: function() { return m[k]; } };
14
+ }
15
+ Object.defineProperty(o, k2, desc);
16
+ }) : (function(o, m, k, k2) {
17
+ if (k2 === undefined) k2 = k;
18
+ o[k2] = m[k];
19
+ }));
20
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
21
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
22
+ }) : function(o, v) {
23
+ o["default"] = v;
24
+ });
25
+ var __importStar = (this && this.__importStar) || function (mod) {
26
+ if (mod && mod.__esModule) return mod;
27
+ var result = {};
28
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
29
+ __setModuleDefault(result, mod);
30
+ return result;
31
+ };
32
+ Object.defineProperty(exports, "__esModule", { value: true });
33
+ exports.bundleStylesheetText = exports.bundleStylesheetFile = void 0;
34
+ const path = __importStar(require("path"));
35
+ const esbuild_1 = require("./esbuild");
36
+ async function bundleStylesheet(entry, options) {
37
+ var _a, _b;
38
+ // Execute esbuild
39
+ const result = await (0, esbuild_1.bundle)({
40
+ ...entry,
41
+ absWorkingDir: options.workspaceRoot,
42
+ bundle: true,
43
+ entryNames: (_a = options.outputNames) === null || _a === void 0 ? void 0 : _a.bundles,
44
+ assetNames: (_b = options.outputNames) === null || _b === void 0 ? void 0 : _b.media,
45
+ logLevel: 'silent',
46
+ minify: options.optimization,
47
+ sourcemap: options.sourcemap,
48
+ outdir: '/',
49
+ write: false,
50
+ platform: 'browser',
51
+ preserveSymlinks: options.preserveSymlinks,
52
+ conditions: ['style'],
53
+ mainFields: ['style'],
54
+ plugins: [
55
+ // TODO: preprocessor plugins
56
+ ],
57
+ });
58
+ // Extract the result of the bundling from the output files
59
+ let contents = '';
60
+ let map;
61
+ let outputPath;
62
+ const resourceFiles = [];
63
+ if (result.outputFiles) {
64
+ for (const outputFile of result.outputFiles) {
65
+ const filename = path.basename(outputFile.path);
66
+ if (filename.endsWith('.css')) {
67
+ outputPath = outputFile.path;
68
+ contents = outputFile.text;
69
+ }
70
+ else if (filename.endsWith('.css.map')) {
71
+ map = outputFile.text;
72
+ }
73
+ else {
74
+ // The output files could also contain resources (images/fonts/etc.) that were referenced
75
+ resourceFiles.push(outputFile);
76
+ }
77
+ }
78
+ }
79
+ return {
80
+ errors: result.errors,
81
+ warnings: result.warnings,
82
+ contents,
83
+ map,
84
+ path: outputPath,
85
+ resourceFiles,
86
+ };
87
+ }
88
+ /**
89
+ * Bundle a stylesheet that exists as a file on the filesystem.
90
+ *
91
+ * @param filename The path to the file to bundle.
92
+ * @param options The stylesheet bundling options to use.
93
+ * @returns The bundle result object.
94
+ */
95
+ async function bundleStylesheetFile(filename, options) {
96
+ return bundleStylesheet({ entryPoints: [filename] }, options);
97
+ }
98
+ exports.bundleStylesheetFile = bundleStylesheetFile;
99
+ /**
100
+ * Bundle stylesheet text data from a string.
101
+ *
102
+ * @param data The string content of a stylesheet to bundle.
103
+ * @param dataOptions The options to use to resolve references and name output of the stylesheet data.
104
+ * @param bundleOptions The stylesheet bundling options to use.
105
+ * @returns The bundle result object.
106
+ */
107
+ async function bundleStylesheetText(data, dataOptions, bundleOptions) {
108
+ const result = bundleStylesheet({
109
+ stdin: {
110
+ contents: data,
111
+ sourcefile: dataOptions.virtualName,
112
+ resolveDir: dataOptions.resolvePath,
113
+ loader: 'css',
114
+ },
115
+ }, bundleOptions);
116
+ return result;
117
+ }
118
+ exports.bundleStylesheetText = bundleStylesheetText;
@@ -5,4 +5,4 @@
5
5
  * Use of this source code is governed by an MIT-style license that can be
6
6
  * found in the LICENSE file at https://angular.io/license
7
7
  */
8
- export declare function augmentAppWithServiceWorker(appRoot: string, outputPath: string, baseHref: string, ngswConfigPath?: string): Promise<void>;
8
+ export declare function augmentAppWithServiceWorker(appRoot: string, workspaceRoot: string, outputPath: string, baseHref: string, ngswConfigPath?: string): Promise<void>;
@@ -75,10 +75,10 @@ class CliFilesystem {
75
75
  return items;
76
76
  }
77
77
  }
78
- async function augmentAppWithServiceWorker(appRoot, outputPath, baseHref, ngswConfigPath) {
78
+ async function augmentAppWithServiceWorker(appRoot, workspaceRoot, outputPath, baseHref, ngswConfigPath) {
79
79
  // Determine the configuration file path
80
80
  const configPath = ngswConfigPath
81
- ? path.normalize(ngswConfigPath)
81
+ ? path.join(workspaceRoot, ngswConfigPath)
82
82
  : path.join(appRoot, 'ngsw-config.json');
83
83
  // Read the configuration file
84
84
  let config;
@@ -6,5 +6,11 @@
6
6
  * found in the LICENSE file at https://angular.io/license
7
7
  */
8
8
  import { Configuration } from 'webpack';
9
+ import { StyleElement } from '../../builders/browser/schema';
9
10
  import { WebpackConfigOptions } from '../../utils/build-options';
11
+ export declare function resolveGlobalStyles(styleEntrypoints: StyleElement[], root: string, preserveSymlinks: boolean): {
12
+ entryPoints: Record<string, string[]>;
13
+ noInjectNames: string[];
14
+ paths: string[];
15
+ };
10
16
  export declare function getStylesConfig(wco: WebpackConfigOptions): Configuration;
@@ -33,7 +33,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
33
33
  return (mod && mod.__esModule) ? mod : { "default": mod };
34
34
  };
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.getStylesConfig = void 0;
36
+ exports.getStylesConfig = exports.resolveGlobalStyles = void 0;
37
37
  const fs = __importStar(require("fs"));
38
38
  const mini_css_extract_plugin_1 = __importDefault(require("mini-css-extract-plugin"));
39
39
  const path = __importStar(require("path"));
@@ -75,6 +75,7 @@ function resolveGlobalStyles(styleEntrypoints, root, preserveSymlinks) {
75
75
  }
76
76
  return { entryPoints, noInjectNames, paths };
77
77
  }
78
+ exports.resolveGlobalStyles = resolveGlobalStyles;
78
79
  // eslint-disable-next-line max-lines-per-function
79
80
  function getStylesConfig(wco) {
80
81
  var _a, _b, _c;