_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular-cli/packages/angular_devkit/build_angular/src/builders/web-test-runner/builder-status-warnings.ts_0_1331
/** * @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.dev/license */ import { BuilderContext } from '@angular-devkit/architect'; import { Schema as WtrBuilderOptions } from './schema'; const UNSUPPORTED_OPTIONS: Array<keyof WtrBuilderOptions> = [ 'main', 'assets', 'scripts', 'styles', 'inlineStyleLanguage', 'stylePreprocessorOptions', 'sourceMap', 'progress', 'poll', 'preserveSymlinks', 'browsers', 'codeCoverage', 'codeCoverageExclude', 'fileReplacements', 'webWorkerTsConfig', 'watch', ]; /** Logs a warning for any unsupported options specified. */ export function logBuilderStatusWarnings(options: WtrBuilderOptions, ctx: BuilderContext) { // Validate supported options for (const unsupportedOption of UNSUPPORTED_OPTIONS) { const value = (options as unknown as WtrBuilderOptions)[unsupportedOption]; if (value === undefined || value === false) { continue; } if (Array.isArray(value) && value.length === 0) { continue; } if (typeof value === 'object' && Object.keys(value).length === 0) { continue; } ctx.logger.warn(`The '${unsupportedOption}' option is not yet supported by this builder.`); } }
{ "end_byte": 1331, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/web-test-runner/builder-status-warnings.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/web-test-runner/write-test-files.ts_0_1404
/** * @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.dev/license */ import { BuildOutputFileType } from '@angular/build'; import { ResultFile, emitFilesToDisk } from '@angular/build/private'; import fs from 'node:fs/promises'; import path from 'node:path'; export async function writeTestFiles(files: Record<string, ResultFile>, testDir: string) { const directoryExists = new Set<string>(); // Writes the test related output files to disk and ensures the containing directories are present await emitFilesToDisk(Object.entries(files), async ([filePath, file]) => { if (file.type !== BuildOutputFileType.Browser && file.type !== BuildOutputFileType.Media) { return; } const fullFilePath = path.join(testDir, filePath); // Ensure output subdirectories exist const fileBasePath = path.dirname(fullFilePath); if (fileBasePath && !directoryExists.has(fileBasePath)) { await fs.mkdir(fileBasePath, { recursive: true }); directoryExists.add(fileBasePath); } if (file.origin === 'memory') { // Write file contents await fs.writeFile(fullFilePath, file.contents); } else { // Copy file contents await fs.copyFile(file.inputPath, fullFilePath, fs.constants.COPYFILE_FICLONE); } }); }
{ "end_byte": 1404, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/web-test-runner/write-test-files.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/web-test-runner/jasmine_runner.js_0_2785
/** * @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.dev/license */ import { getTestBed } from '@angular/core/testing'; import { BrowserDynamicTestingModule, platformBrowserDynamicTesting, } from '@angular/platform-browser-dynamic/testing'; import { getConfig, sessionFailed, sessionFinished, sessionStarted, } from '@web/test-runner-core/browser/session.js'; /** Executes Angular Jasmine tests in the given environment and reports the results to Web Test Runner. */ export async function runJasmineTests(jasmineEnv) { const allSpecs = []; const failedSpecs = []; jasmineEnv.addReporter({ specDone(result) { const expectations = [...result.passedExpectations, ...result.failedExpectations]; allSpecs.push(...expectations.map((e) => ({ name: e.fullName, passed: e.passed }))); for (const e of result.failedExpectations) { const message = `${result.fullName}\n${e.message}\n${e.stack}`; // eslint-disable-next-line no-console console.error(message); failedSpecs.push({ message, name: e.fullName, stack: e.stack, expected: e.expected, actual: e.actual, }); } }, async jasmineDone(result) { // eslint-disable-next-line no-console console.log(`Tests ${result.overallStatus}!`); await sessionFinished({ passed: result.overallStatus === 'passed', errors: failedSpecs, testResults: { name: '', suites: [], tests: allSpecs, }, }); }, }); await sessionStarted(); // Web Test Runner uses a different HTML page for every test, so we only get one `testFile` for the single `*.js` file we need to execute. const { testFile, testFrameworkConfig } = await getConfig(); const config = { defaultTimeoutInterval: 60_000, ...(testFrameworkConfig ?? {}) }; // eslint-disable-next-line no-undef jasmine.DEFAULT_TIMEOUT_INTERVAL = config.defaultTimeoutInterval; // Initialize `TestBed` automatically for users. This assumes we already evaluated `zone.js/testing`. getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), { errorOnUnknownElements: true, errorOnUnknownProperties: true, }); // Load the test file and evaluate it. try { // eslint-disable-next-line no-undef await import(new URL(testFile, document.baseURI).href); // Execute the test functions. // eslint-disable-next-line no-undef jasmineEnv.execute(); } catch (err) { // eslint-disable-next-line no-console console.error(err); await sessionFailed(err); } }
{ "end_byte": 2785, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/web-test-runner/jasmine_runner.js" }
angular-cli/packages/angular_devkit/build_angular/src/builders/web-test-runner/options_spec.ts_0_1797
/** * @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.dev/license */ import { normalizeOptions } from './options'; import { Schema as WtrBuilderSchema } from './schema'; describe('options', () => { describe('normalizeOptions()', () => { const GOLDEN_SCHEMA: WtrBuilderSchema = { include: ['**/included/*.ts'], exclude: ['**/excluded/*.ts'], tsConfig: './tsconfig.json', }; it('requires include and exclude properties', () => { const options = normalizeOptions({ ...GOLDEN_SCHEMA, include: ['**/*.ts'], exclude: ['**/*.d.ts'], }); expect(options).toContain({ include: ['**/*.ts'], exclude: ['**/*.d.ts'], }); // @ts-expect-error `undefined` should not be in the `include` type. options.include = undefined; // @ts-expect-error `undefined` should not be in the `exclude` type. options.exclude = undefined; }); it('normalizes polyfills', () => { const stringPolyfillOptions = normalizeOptions({ ...GOLDEN_SCHEMA, polyfills: './polyfills.ts', }); expect(stringPolyfillOptions.polyfills).toEqual(['./polyfills.ts']); const arrayPolyfillOptions = normalizeOptions({ ...GOLDEN_SCHEMA, polyfills: ['./first.ts', './second.ts'], }); expect(arrayPolyfillOptions.polyfills).toEqual(['./first.ts', './second.ts']); }); it('passes through other options', () => { const options = normalizeOptions({ ...GOLDEN_SCHEMA, assets: ['./path/to/file.txt'], }); expect(options.assets).toEqual(['./path/to/file.txt']); }); }); });
{ "end_byte": 1797, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/web-test-runner/options_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/web-test-runner/test_page.html_0_1929
<!DOCTYPE html> <html> <head> <meta charset="utf8"> <title>Unit tests</title> <script type="module"> (async () => { // To initialize tests correctly we load things in a very particular order. // Step 1. Load user polyfills (including `zone.js`). Does *not* include `zone.js/testing`, which gets executed after Jasmine. await import('./polyfills.js'); // Step 2. Import Jasmine. // Jasmine gets wrapped into a CommonJS context by the bundling process which makes it think it is running in NodeJS, so it does not // find the `window` global. Assign this to the NodeJS `global` symbol so Jasmine initializes correctly. window.global = window; const { default: jasmineRequire } = await import('./jasmine.js'); delete window.global; // Avoid leaking `global` into user tests or libraries, which might think they are running in NodeJS. // Step 3. Initialize Jasmine on the page. Doing this after `zone.js` means Zone can patch browser globals before Jasmine runs. // Doing this before `zone.js/testing`, means Zone can patch Jasmine-defined globals. const jasmine = jasmineRequire.core(jasmineRequire); const jasmineGlobal = jasmine.getGlobal(); jasmineGlobal.jasmine = jasmine; const jasmineEnv = jasmine.getEnv(); Object.assign(window, jasmineRequire.interface(jasmine, jasmineEnv)); // Step 4. Import `zone.js/testing`, which will find and patch Jasmine globals from steps 2. and 3. // https://github.com/angular/angular/blob/af4f5df150d527a1b523def1eb51d2b661a25f83/packages/zone.js/lib/jasmine/jasmine.ts await import('./testing.js'); // Step 5. Run the actual tests. const { runJasmineTests } = await import('./jasmine_runner.js'); await runJasmineTests(jasmineEnv); })(); </script> </head> <body></body> </html>
{ "end_byte": 1929, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/web-test-runner/test_page.html" }
angular-cli/packages/angular_devkit/build_angular/src/builders/web-test-runner/index.ts_0_6813
/** * @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.dev/license */ import { Result, ResultKind, buildApplicationInternal } from '@angular/build/private'; import { BuilderContext, BuilderOutput, createBuilder } from '@angular-devkit/architect'; import type * as WebTestRunner from '@web/test-runner'; import { randomUUID } from 'node:crypto'; import fs from 'node:fs/promises'; import { createRequire } from 'node:module'; import path from 'node:path'; import { findTestFiles } from '../../utils/test-files'; import { OutputHashing } from '../browser-esbuild/schema'; import { logBuilderStatusWarnings } from './builder-status-warnings'; import { WtrBuilderOptions, normalizeOptions } from './options'; import { Schema } from './schema'; import { writeTestFiles } from './write-test-files'; export default createBuilder( async (schema: Schema, ctx: BuilderContext): Promise<BuilderOutput> => { ctx.logger.warn( 'NOTE: The Web Test Runner builder is currently EXPERIMENTAL and not ready for production use.', ); logBuilderStatusWarnings(schema, ctx); // Dynamic import `@web/test-runner` from the user's workspace. As an optional peer dep, it may not be installed // and may not be resolvable from `@angular-devkit/build-angular`. const require = createRequire(`${ctx.workspaceRoot}/`); let wtr: typeof WebTestRunner; try { wtr = require('@web/test-runner'); } catch { return { success: false, // TODO(dgp1130): Display a more accurate message for non-NPM users. error: 'Web Test Runner is not installed, most likely you need to run `npm install @web/test-runner --save-dev` in your project.', }; } const options = normalizeOptions(schema); const testDir = path.join(ctx.workspaceRoot, 'dist/test-out', randomUUID()); // Parallelize startup work. const [testFiles] = await Promise.all([ // Glob for files to test. findTestFiles(options.include, options.exclude, ctx.workspaceRoot), // Clean build output path. fs.rm(testDir, { recursive: true, force: true }), ]); // Build the tests and abort on any build failure. const buildOutput = await buildTests(testFiles, testDir, options, ctx); if (buildOutput.kind === ResultKind.Failure) { return { success: false }; } else if (buildOutput.kind !== ResultKind.Full) { return { success: false, error: 'A full build result is required from the application builder.', }; } // Write test files await writeTestFiles(buildOutput.files, testDir); // Run the built tests. return await runTests(wtr, testDir, options); }, ); /** Build all the given test files and write the result to the given output path. */ async function buildTests( testFiles: ReadonlySet<string>, outputPath: string, options: WtrBuilderOptions, ctx: BuilderContext, ): Promise<Result> { const entryPoints = new Set([ ...testFiles, 'jasmine-core/lib/jasmine-core/jasmine.js', '@angular-devkit/build-angular/src/builders/web-test-runner/jasmine_runner.js', ]); // Extract `zone.js/testing` to a separate entry point because it needs to be loaded after Jasmine. const [polyfills, hasZoneTesting] = extractZoneTesting(options.polyfills); if (hasZoneTesting) { entryPoints.add('zone.js/testing'); } // Build tests with `application` builder, using test files as entry points. // Also bundle in Jasmine and the Jasmine runner script, which need to share chunked dependencies. const buildOutput = await first( buildApplicationInternal( { entryPoints, tsConfig: options.tsConfig, outputPath, aot: false, index: false, outputHashing: OutputHashing.None, optimization: false, externalDependencies: [ // Resolved by `@web/test-runner` at runtime with dynamically generated code. '@web/test-runner-core', ], sourceMap: { scripts: true, styles: true, vendor: true, }, polyfills, }, ctx, ), ); return buildOutput; } function extractZoneTesting( polyfills: readonly string[], ): [polyfills: string[], hasZoneTesting: boolean] { const polyfillsWithoutZoneTesting = polyfills.filter( (polyfill) => polyfill !== 'zone.js/testing', ); const hasZoneTesting = polyfills.length !== polyfillsWithoutZoneTesting.length; return [polyfillsWithoutZoneTesting, hasZoneTesting]; } /** Run Web Test Runner on the given directory of bundled JavaScript tests. */ async function runTests( wtr: typeof WebTestRunner, testDir: string, options: WtrBuilderOptions, ): Promise<BuilderOutput> { const testPagePath = path.resolve(__dirname, 'test_page.html'); const testPage = await fs.readFile(testPagePath, 'utf8'); const runner = await wtr.startTestRunner({ config: { rootDir: testDir, files: [ `${testDir}/**/*.js`, `!${testDir}/polyfills.js`, `!${testDir}/chunk-*.js`, `!${testDir}/jasmine.js`, `!${testDir}/jasmine_runner.js`, `!${testDir}/testing.js`, // `zone.js/testing` ], testFramework: { config: { defaultTimeoutInterval: 5_000, }, }, nodeResolve: true, port: 9876, watch: options.watch ?? false, testRunnerHtml: (_testFramework, _config) => testPage, }, readCliArgs: false, readFileConfig: false, autoExitProcess: false, }); if (!runner) { throw new Error('Failed to start Web Test Runner.'); } // Wait for the tests to complete and stop the runner. const passed = (await once(runner, 'finished')) as boolean; await runner.stop(); // No need to return error messages because Web Test Runner already printed them to the console. return { success: passed }; } /** Returns the first item yielded by the given generator and cancels the execution. */ async function first<T>(generator: AsyncIterable<T>): Promise<T> { for await (const value of generator) { return value; } throw new Error('Expected generator to emit at least once.'); } /** Listens for a single emission of an event and returns the value emitted. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function once<Map extends Record<string, any>, EventKey extends string & keyof Map>( emitter: WebTestRunner.EventEmitter<Map>, event: EventKey, ): Promise<Map[EventKey]> { return new Promise((resolve) => { const onEmit = (arg: Map[EventKey]): void => { emitter.off(event, onEmit); resolve(arg); }; emitter.on(event, onEmit); }); }
{ "end_byte": 6813, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/web-test-runner/index.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/web-test-runner/options.ts_0_1293
/** * @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.dev/license */ import { Schema as WtrBuilderSchema } from './schema'; /** * Options supported for the Web Test Runner builder. The schema is an approximate * representation of the options type, but this is a more precise version. */ export type WtrBuilderOptions = Overwrite< WtrBuilderSchema, { include: string[]; exclude: string[]; polyfills: string[]; } >; type Overwrite<Obj extends {}, Overrides extends {}> = Omit<Obj, keyof Overrides> & Overrides; /** * Normalizes input options validated by the schema to a more precise and useful * options type in {@link WtrBuilderOptions}. */ export function normalizeOptions(schema: WtrBuilderSchema): WtrBuilderOptions { return { ...schema, // Options with default values can't actually be null, even if the types say so. /* eslint-disable @typescript-eslint/no-non-null-assertion */ include: schema.include!, exclude: schema.exclude!, /* eslint-enable @typescript-eslint/no-non-null-assertion */ polyfills: typeof schema.polyfills === 'string' ? [schema.polyfills] : schema.polyfills ?? [], }; }
{ "end_byte": 1293, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/web-test-runner/options.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/server/platform-server-exports-loader.ts_0_1032
/** * @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.dev/license */ /** * This loader is needed to add additional exports and is a workaround for a Webpack bug that doesn't * allow exports from multiple files in the same entry. * @see https://github.com/webpack/webpack/issues/15936. */ export default function ( this: import('webpack').LoaderContext<{ angularSSRInstalled: boolean }>, content: string, map: Parameters<import('webpack').LoaderDefinitionFunction>[1], ) { const { angularSSRInstalled } = this.getOptions(); let source = `${content} // EXPORTS added by @angular-devkit/build-angular export { renderApplication, renderModule, ɵSERVER_CONTEXT } from '@angular/platform-server'; `; if (angularSSRInstalled) { source += ` export { ɵgetRoutesFromAngularRouterConfig } from '@angular/ssr'; `; } this.callback(null, source, map); return; }
{ "end_byte": 1032, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/server/platform-server-exports-loader.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/server/index.ts_0_9083
/** * @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.dev/license */ import { assertCompatibleAngularVersion, purgeStaleBuildCache } from '@angular/build/private'; import { BuilderContext, BuilderOutput, createBuilder } from '@angular-devkit/architect'; import { runWebpack } from '@angular-devkit/build-webpack'; import { readFile } from 'node:fs/promises'; import * as path from 'node:path'; import { Observable, concatMap, from } from 'rxjs'; import webpack, { Configuration } from 'webpack'; import { getCommonConfig, getStylesConfig } from '../../tools/webpack/configs'; import { isPackageInstalled } from '../../tools/webpack/utils/helpers'; import { statsErrorsToString, statsHasErrors, statsHasWarnings, statsWarningsToString, webpackStatsLogger, } from '../../tools/webpack/utils/stats'; import { ExecutionTransformer } from '../../transforms'; import { NormalizedBrowserBuilderSchema, deleteOutputDir, normalizeAssetPatterns, } from '../../utils'; import { colors } from '../../utils/color'; import { copyAssets } from '../../utils/copy-assets'; import { assertIsError } from '../../utils/error'; import { i18nInlineEmittedFiles } from '../../utils/i18n-inlining'; import { I18nOptions } from '../../utils/i18n-webpack'; import { ensureOutputPaths } from '../../utils/output-paths'; import { Spinner } from '../../utils/spinner'; import { BrowserWebpackConfigOptions, generateI18nBrowserWebpackConfigFromContext, } from '../../utils/webpack-browser-config'; import { Schema as ServerBuilderOptions } from './schema'; /** * @experimental Direct usage of this type is considered experimental. */ export type ServerBuilderOutput = BuilderOutput & { baseOutputPath: string; outputPath: string; outputs: { locale?: string; path: string; }[]; }; export type { ServerBuilderOptions }; /** * @experimental Direct usage of this function is considered experimental. */ export function execute( options: ServerBuilderOptions, context: BuilderContext, transforms: { webpackConfiguration?: ExecutionTransformer<webpack.Configuration>; } = {}, ): Observable<ServerBuilderOutput> { const root = context.workspaceRoot; // Check Angular version. assertCompatibleAngularVersion(root); const baseOutputPath = path.resolve(root, options.outputPath); let outputPaths: undefined | Map<string, string>; return from(initialize(options, context, transforms.webpackConfiguration)).pipe( concatMap(({ config, i18n, projectRoot, projectSourceRoot }) => { return runWebpack(config, context, { webpackFactory: require('webpack') as typeof webpack, logging: (stats, config) => { if (options.verbose && config.stats !== false) { const statsOptions = config.stats === true ? undefined : config.stats; context.logger.info(stats.toString(statsOptions)); } }, }).pipe( concatMap(async (output) => { const { emittedFiles = [], outputPath, webpackStats, success } = output; if (!webpackStats) { throw new Error('Webpack stats build result is required.'); } if (!success) { if (statsHasWarnings(webpackStats)) { context.logger.warn(statsWarningsToString(webpackStats, { colors: true })); } if (statsHasErrors(webpackStats)) { context.logger.error(statsErrorsToString(webpackStats, { colors: true })); } return output; } const spinner = new Spinner(); spinner.enabled = options.progress !== false; outputPaths = ensureOutputPaths(baseOutputPath, i18n); // Copy assets if (!options.watch && options.assets?.length) { spinner.start('Copying assets...'); try { await copyAssets( normalizeAssetPatterns( options.assets, context.workspaceRoot, projectRoot, projectSourceRoot, ), Array.from(outputPaths.values()), context.workspaceRoot, ); spinner.succeed('Copying assets complete.'); } catch (err) { spinner.fail(colors.redBright('Copying of assets failed.')); assertIsError(err); return { ...output, success: false, error: 'Unable to copy assets: ' + err.message, }; } } if (i18n.shouldInline) { const success = await i18nInlineEmittedFiles( context, emittedFiles, i18n, baseOutputPath, Array.from(outputPaths.values()), [], outputPath, options.i18nMissingTranslation, ); if (!success) { return { ...output, success: false, }; } } webpackStatsLogger(context.logger, webpackStats, config); return output; }), ); }), concatMap(async (output) => { if (!output.success) { return output as ServerBuilderOutput; } return { ...output, baseOutputPath, outputs: (outputPaths && [...outputPaths.entries()].map(([locale, path]) => ({ locale, path, }))) || { path: baseOutputPath, }, } as ServerBuilderOutput; }), ); } export default createBuilder<ServerBuilderOptions, ServerBuilderOutput>(execute); async function initialize( options: ServerBuilderOptions, context: BuilderContext, webpackConfigurationTransform?: ExecutionTransformer<webpack.Configuration>, ): Promise<{ config: webpack.Configuration; i18n: I18nOptions; projectRoot: string; projectSourceRoot?: string; }> { // Purge old build disk cache. await purgeStaleBuildCache(context); await checkTsConfigForPreserveWhitespacesSetting(context, options.tsConfig); const browserslist = (await import('browserslist')).default; const originalOutputPath = options.outputPath; // Assets are processed directly by the builder except when watching const adjustedOptions = options.watch ? options : { ...options, assets: [] }; const { config, projectRoot, projectSourceRoot, i18n } = await generateI18nBrowserWebpackConfigFromContext( { ...adjustedOptions, aot: true, platform: 'server', } as NormalizedBrowserBuilderSchema, context, (wco) => { // We use the platform to determine the JavaScript syntax output. wco.buildOptions.supportedBrowsers ??= []; wco.buildOptions.supportedBrowsers.push(...browserslist('maintained node versions')); return [getPlatformServerExportsConfig(wco), getCommonConfig(wco), getStylesConfig(wco)]; }, ); if (options.deleteOutputPath) { await deleteOutputDir(context.workspaceRoot, originalOutputPath); } const transformedConfig = (await webpackConfigurationTransform?.(config)) ?? config; return { config: transformedConfig, i18n, projectRoot, projectSourceRoot }; } async function checkTsConfigForPreserveWhitespacesSetting( context: BuilderContext, tsConfigPath: string, ): Promise<void> { // We don't use the `readTsConfig` method on purpose here. // To only catch cases were `preserveWhitespaces` is set directly in the `tsconfig.server.json`, // which in the majority of cases will cause a mistmatch between client and server builds. // Technically we should check if `tsconfig.server.json` and `tsconfig.app.json` values match. // But: // 1. It is not guaranteed that `tsconfig.app.json` is used to build the client side of this app. // 2. There is no easy way to access the build build config from the server builder. // 4. This will no longer be an issue with a single compilation model were the same tsconfig is used for both browser and server builds. const content = await readFile(path.join(context.workspaceRoot, tsConfigPath), 'utf-8'); const { parse } = await import('jsonc-parser'); const tsConfig = parse(content, [], { allowTrailingComma: true }); if (tsConfig.angularCompilerOptions?.preserveWhitespaces !== undefined) { context.logger.warn( `"preserveWhitespaces" was set in "${tsConfigPath}". ` + 'Make sure that this setting is set consistently in both "tsconfig.server.json" for your server side ' + 'and "tsconfig.app.json" for your client side. A mismatched value will cause hydration to break.\n' + 'For more information see: https://angular.dev/guide/hydration#preserve-whitespaces-configuration', ); } } /** * Add `@angular/platform-server` exports. * This is needed so that DI tokens can be referenced and set at runtime outside of the bundle. */
{ "end_byte": 9083, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/server/index.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/server/index.ts_9084_10047
function getPlatformServerExportsConfig(wco: BrowserWebpackConfigOptions): Partial<Configuration> { // Add `@angular/platform-server` exports. // This is needed so that DI tokens can be referenced and set at runtime outside of the bundle. // Only add `@angular/platform-server` exports when it is installed. // In some cases this builder is used when `@angular/platform-server` is not installed. // Example: when using `@nguniversal/common/clover` which does not need `@angular/platform-server`. return isPackageInstalled(wco.root, '@angular/platform-server') ? { module: { rules: [ { loader: require.resolve('./platform-server-exports-loader'), include: [path.resolve(wco.root, wco.buildOptions.main)], options: { angularSSRInstalled: isPackageInstalled(wco.root, '@angular/ssr'), }, }, ], }, } : {}; }
{ "end_byte": 10047, "start_byte": 9084, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/server/index.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/server/tests/setup.ts_0_822
/** * @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.dev/license */ import { Schema } from '../schema'; export { describeBuilder } from '../../../testing'; export const SERVER_BUILDER_INFO = Object.freeze({ name: '@angular-devkit/build-angular:server', schemaPath: __dirname + '/../schema.json', }); /** * Contains all required Server builder fields. * Also disables progress reporting to minimize logging output. */ export const BASE_OPTIONS = Object.freeze<Schema>({ main: 'src/main.server.ts', tsConfig: 'src/tsconfig.server.json', progress: false, watch: false, outputPath: 'dist', // Disable optimizations optimization: false, buildOptimizer: false, });
{ "end_byte": 822, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/server/tests/setup.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/server/tests/behavior/preserve_whitespaces_check_spec.ts_0_1555
/** * @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.dev/license */ import { logging } from '@angular-devkit/core'; import { execute } from '../../index'; import { BASE_OPTIONS, SERVER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(execute, SERVER_BUILDER_INFO, (harness) => { describe('Behavior: "preserveWhitespaces warning"', () => { it('should not show warning when "preserveWhitespaces" is not set.', async () => { harness.useTarget('server', { ...BASE_OPTIONS, }); const { logs } = await harness.executeOnce(); expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching('"preserveWhitespaces" was set in'), }), ); }); it('should show warning when "preserveWhitespaces" is set.', async () => { harness.useTarget('server', { ...BASE_OPTIONS, }); await harness.modifyFile('src/tsconfig.server.json', (content) => { const tsconfig = JSON.parse(content); (tsconfig.angularCompilerOptions ??= {}).preserveWhitespaces = false; return JSON.stringify(tsconfig); }); const { logs } = await harness.executeOnce(); expect(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching('"preserveWhitespaces" was set in'), }), ); }); }); });
{ "end_byte": 1555, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/server/tests/behavior/preserve_whitespaces_check_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/server/tests/behavior/web-workers_spec.ts_0_1316
/** * @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.dev/license */ import { execute } from '../../index'; import { BASE_OPTIONS, SERVER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(execute, SERVER_BUILDER_INFO, (harness) => { describe('Behavior: "Errors"', () => { it('should not try to resolve web-workers', async () => { harness.useTarget('server', { ...BASE_OPTIONS, }); await harness.writeFiles({ 'src/app/app.worker.ts': ` /// <reference lib="webworker" /> const foo: string = 'hello world'; addEventListener('message', ({ data }) => { postMessage(foo); }); `, 'src/main.server.ts': ` if (typeof Worker !== 'undefined') { const worker = new Worker(new URL('./app/app.worker', import.meta.url), { type: 'module' }); worker.onmessage = ({ data }) => { console.log('page got message:', data); }; worker.postMessage('hello'); } `, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); }); }); });
{ "end_byte": 1316, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/server/tests/behavior/web-workers_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/server/tests/behavior/build-errors_spec.ts_0_1034
/** * @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.dev/license */ import { logging } from '@angular-devkit/core'; import { execute } from '../../index'; import { BASE_OPTIONS, SERVER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(execute, SERVER_BUILDER_INFO, (harness) => { describe('Behavior: "Build Error"', () => { it('emits errors', async () => { harness.useTarget('server', { ...BASE_OPTIONS, }); // Generate an error await harness.appendToFile('src/main.server.ts', `const foo: = 'abc';`); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false, }); expect(result?.success).toBeFalse(); expect(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching(/TS1110:.*Type expected/), }), ); }); }); });
{ "end_byte": 1034, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/server/tests/behavior/build-errors_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/server/tests/options/resources-output-path_spec.ts_0_2237
/** * @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.dev/license */ import { execute } from '../../index'; import { BASE_OPTIONS, SERVER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(execute, SERVER_BUILDER_INFO, (harness) => { describe('Option: "resourcesOutputPath"', () => { beforeEach(async () => { const img = await harness.readFile('src/spectrum.png'); await harness.writeFiles({ 'src/assets/component-img-relative.png': img, 'src/assets/component-img-absolute.png': img, 'src/app/app.component.css': ` h3 { background: url('/assets/component-img-absolute.png'); } h4 { background: url('../assets/component-img-relative.png'); } `, }); }); it(`should prepend value of "resourcesOutputPath" as part of the resource urls`, async () => { harness.useTarget('server', { ...BASE_OPTIONS, resourcesOutputPath: 'out-assets', }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/main.js') .content.toContain(`url('/assets/component-img-absolute.png')`); harness .expectFile('dist/main.js') .content.toContain(`url('out-assets/component-img-relative.png')`); // Assets are not emitted during a server builds. harness.expectFile('dist/out-assets/component-img-relative.png').toNotExist(); }); it(`should not prepend anything when value of "resourcesOutputPath" is unset.`, async () => { harness.useTarget('server', { ...BASE_OPTIONS, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/main.js') .content.toContain(`url('/assets/component-img-absolute.png')`); harness.expectFile('dist/main.js').content.toContain(`url('component-img-relative.png')`); // Assets are not emitted during a server builds. harness.expectFile('dist/component-img-relative.png').toNotExist(); }); }); });
{ "end_byte": 2237, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/server/tests/options/resources-output-path_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/server/tests/options/assets_spec.ts_0_4010
/** * @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.dev/license */ import { execute } from '../../index'; import { BASE_OPTIONS, SERVER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(execute, SERVER_BUILDER_INFO, (harness) => { describe('Option: "assets"', () => { beforeEach(async () => { // Application code is not needed for asset tests await harness.writeFile('src/main.server.ts', ''); }); it('supports an empty array value', async () => { harness.useTarget('server', { ...BASE_OPTIONS, assets: [], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); }); it('supports mixing shorthand and longhand syntax', async () => { await harness.writeFile('src/files/test.svg', '<svg></svg>'); await harness.writeFile('src/files/another.file', 'asset file'); await harness.writeFile('src/extra.file', 'extra file'); harness.useTarget('server', { ...BASE_OPTIONS, assets: ['src/extra.file', { glob: '*', input: 'src/files', output: '.' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/extra.file').content.toBe('extra file'); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/another.file').content.toBe('asset file'); }); describe('shorthand syntax', () => { it('copies a single asset', async () => { await harness.writeFile('src/test.svg', '<svg></svg>'); harness.useTarget('server', { ...BASE_OPTIONS, assets: ['src/test.svg'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); }); it('copies multiple assets', async () => { await harness.writeFile('src/test.svg', '<svg></svg>'); await harness.writeFile('src/another.file', 'asset file'); harness.useTarget('server', { ...BASE_OPTIONS, assets: ['src/test.svg', 'src/another.file'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/another.file').content.toBe('asset file'); }); it('copies an asset with directory and maintains directory in output', async () => { await harness.writeFile('src/subdirectory/test.svg', '<svg></svg>'); harness.useTarget('server', { ...BASE_OPTIONS, assets: ['src/subdirectory/test.svg'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/subdirectory/test.svg').content.toBe('<svg></svg>'); }); it('does not fail if asset does not exist', async () => { harness.useTarget('server', { ...BASE_OPTIONS, assets: ['src/test.svg'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/test.svg').toNotExist(); }); it('fails if output option is not within project output path', async () => { await harness.writeFile('test.svg', '<svg></svg>'); harness.useTarget('server', { ...BASE_OPTIONS, assets: [{ glob: 'test.svg', input: 'src', output: '..' }], }); const { result } = await harness.executeOnce(); expect(result?.error).toMatch( 'An asset cannot be written to a location outside of the output path', ); harness.expectFile('dist/test.svg').toNotExist(); }); });
{ "end_byte": 4010, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/server/tests/options/assets_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/server/tests/options/assets_spec.ts_4016_12720
describe('longhand syntax', () => { it('copies a single asset', async () => { await harness.writeFile('src/test.svg', '<svg></svg>'); harness.useTarget('server', { ...BASE_OPTIONS, assets: [{ glob: 'test.svg', input: 'src', output: '.' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); }); it('copies multiple assets as separate entries', async () => { await harness.writeFile('src/test.svg', '<svg></svg>'); await harness.writeFile('src/another.file', 'asset file'); harness.useTarget('server', { ...BASE_OPTIONS, assets: [ { glob: 'test.svg', input: 'src', output: '.' }, { glob: 'another.file', input: 'src', output: '.' }, ], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/another.file').content.toBe('asset file'); }); it('copies multiple assets with a single entry glob pattern', async () => { await harness.writeFile('src/test.svg', '<svg></svg>'); await harness.writeFile('src/another.file', 'asset file'); harness.useTarget('server', { ...BASE_OPTIONS, assets: [{ glob: '{test.svg,another.file}', input: 'src', output: '.' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/another.file').content.toBe('asset file'); }); it('copies multiple assets with a wildcard glob pattern', async () => { await harness.writeFile('src/files/test.svg', '<svg></svg>'); await harness.writeFile('src/files/another.file', 'asset file'); harness.useTarget('server', { ...BASE_OPTIONS, assets: [{ glob: '*', input: 'src/files', output: '.' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/another.file').content.toBe('asset file'); }); it('copies multiple assets with a recursive wildcard glob pattern', async () => { await harness.writeFiles({ 'src/files/test.svg': '<svg></svg>', 'src/files/another.file': 'asset file', 'src/files/nested/extra.file': 'extra file', }); harness.useTarget('server', { ...BASE_OPTIONS, assets: [{ glob: '**/*', input: 'src/files', output: '.' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/another.file').content.toBe('asset file'); harness.expectFile('dist/nested/extra.file').content.toBe('extra file'); }); it('automatically ignores "." prefixed files when using wildcard glob pattern', async () => { await harness.writeFile('src/files/.gitkeep', ''); harness.useTarget('server', { ...BASE_OPTIONS, assets: [{ glob: '*', input: 'src/files', output: '.' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/.gitkeep').toNotExist(); }); it('supports ignoring a specific file when using a glob pattern', async () => { await harness.writeFiles({ 'src/files/test.svg': '<svg></svg>', 'src/files/another.file': 'asset file', 'src/files/nested/extra.file': 'extra file', }); harness.useTarget('server', { ...BASE_OPTIONS, assets: [{ glob: '**/*', input: 'src/files', output: '.', ignore: ['another.file'] }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/another.file').toNotExist(); harness.expectFile('dist/nested/extra.file').content.toBe('extra file'); }); it('supports ignoring with a glob pattern when using a glob pattern', async () => { await harness.writeFiles({ 'src/files/test.svg': '<svg></svg>', 'src/files/another.file': 'asset file', 'src/files/nested/extra.file': 'extra file', }); harness.useTarget('server', { ...BASE_OPTIONS, assets: [{ glob: '**/*', input: 'src/files', output: '.', ignore: ['**/*.file'] }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/another.file').toNotExist(); harness.expectFile('dist/nested/extra.file').toNotExist(); }); it('copies an asset with directory and maintains directory in output', async () => { await harness.writeFile('src/subdirectory/test.svg', '<svg></svg>'); harness.useTarget('server', { ...BASE_OPTIONS, assets: [{ glob: 'subdirectory/test.svg', input: 'src', output: '.' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/subdirectory/test.svg').content.toBe('<svg></svg>'); }); it('does not fail if asset does not exist', async () => { harness.useTarget('server', { ...BASE_OPTIONS, assets: [{ glob: 'test.svg', input: 'src', output: '.' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/test.svg').toNotExist(); }); it('uses project output path when output option is empty string', async () => { await harness.writeFile('src/test.svg', '<svg></svg>'); harness.useTarget('server', { ...BASE_OPTIONS, assets: [{ glob: 'test.svg', input: 'src', output: '' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); }); it('uses project output path when output option is "."', async () => { await harness.writeFile('src/test.svg', '<svg></svg>'); harness.useTarget('server', { ...BASE_OPTIONS, assets: [{ glob: 'test.svg', input: 'src', output: '.' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); }); it('uses project output path when output option is "/"', async () => { await harness.writeFile('src/test.svg', '<svg></svg>'); harness.useTarget('server', { ...BASE_OPTIONS, assets: [{ glob: 'test.svg', input: 'src', output: '/' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); }); it('creates a project output sub-path when output option path does not exist', async () => { await harness.writeFile('src/test.svg', '<svg></svg>'); harness.useTarget('server', { ...BASE_OPTIONS, assets: [{ glob: 'test.svg', input: 'src', output: 'subdirectory' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/subdirectory/test.svg').content.toBe('<svg></svg>'); }); it('fails if output option is not within project output path', async () => { await harness.writeFile('test.svg', '<svg></svg>'); harness.useTarget('server', { ...BASE_OPTIONS, assets: [{ glob: 'test.svg', input: 'src', output: '..' }], }); const { result } = await harness.executeOnce(); expect(result?.error).toMatch( 'An asset cannot be written to a location outside of the output path', ); harness.expectFile('dist/test.svg').toNotExist(); }); }); }); });
{ "end_byte": 12720, "start_byte": 4016, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/server/tests/options/assets_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/server/tests/options/source-map_spec.ts_0_5241
/** * @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.dev/license */ import { execute } from '../../index'; import { BASE_OPTIONS, SERVER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(execute, SERVER_BUILDER_INFO, (harness) => { describe('Option: "sourceMap"', () => { const INLINE_SOURCEMAP_MARKER = '/*# sourceMappingURL=data:application/json;charset=utf-8;base64,'; beforeEach(async () => { await harness.writeFiles({ 'src/app/app.component.css': `p { color: red; }`, }); }); it(`should not generate sourceMaps when "sourceMap" option is unset`, async () => { harness.useTarget('server', { ...BASE_OPTIONS, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/main.js.map').toNotExist(); }); it(`should generate sourceMaps when "sourceMap" option is true`, async () => { harness.useTarget('server', { ...BASE_OPTIONS, sourceMap: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/main.js.map').toExist(); }); it(`should not generate sourceMaps when "sourceMap" option is false`, async () => { harness.useTarget('server', { ...BASE_OPTIONS, sourceMap: false, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/main.js.map').toNotExist(); }); it(`should not generate components sourceMaps when "styles" option is false`, async () => { harness.useTarget('server', { ...BASE_OPTIONS, // Components sourcemaps are only present when optimization is false. optimization: false, sourceMap: { styles: false, scripts: true, }, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/main.js.map').toExist(); harness.expectFile('dist/main.js').content.toContain('sourceMappingURL=main.js.map'); console.log(await harness.readFile('dist/main.js')); harness.expectFile('dist/main.js').content.not.toContain(INLINE_SOURCEMAP_MARKER); }); it(`should generate components sourceMaps when "styles" option is true`, async () => { harness.useTarget('server', { ...BASE_OPTIONS, // Components sourcemaps are only present when optimization is false. optimization: false, sourceMap: { styles: true, scripts: true, }, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/main.js.map').toExist(); harness.expectFile('dist/main.js').content.toContain('sourceMappingURL=main.js.map'); harness .expectFile('dist/main.js') .content.toContain('sourceMappingURL=data:application/json'); }); it(`should generate components sourceMaps when "styles" option is unset`, async () => { harness.useTarget('server', { ...BASE_OPTIONS, // Components sourcemaps are only present when optimization is false. optimization: false, sourceMap: { scripts: true, }, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/main.js.map').toExist(); harness.expectFile('dist/main.js').content.toContain('sourceMappingURL=main.js.map'); harness.expectFile('dist/main.js').content.toContain(INLINE_SOURCEMAP_MARKER); }); it(`should generate scripts sourceMaps when "scripts" option is unset`, async () => { harness.useTarget('server', { ...BASE_OPTIONS, sourceMap: {}, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/main.js.map').toExist(); harness.expectFile('dist/main.js').content.toContain('sourceMappingURL=main.js.map'); }); it(`should not generate scripts sourceMaps when "scripts" option is false`, async () => { harness.useTarget('server', { ...BASE_OPTIONS, sourceMap: { scripts: false, }, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/main.js.map').toNotExist(); harness.expectFile('dist/main.js').content.not.toContain('sourceMappingURL=main.js.map'); }); it(`should generate scripts sourceMaps when "scripts" option is true`, async () => { harness.useTarget('server', { ...BASE_OPTIONS, sourceMap: { scripts: true, }, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/main.js.map').toExist(); harness.expectFile('dist/main.js').content.toContain('sourceMappingURL=main.js.map'); }); }); });
{ "end_byte": 5241, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/server/tests/options/source-map_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/server/tests/options/external-dependencies_spec.ts_0_1403
/** * @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.dev/license */ import { execute } from '../../index'; import { BASE_OPTIONS, SERVER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(execute, SERVER_BUILDER_INFO, (harness) => { describe('Option: "externalDependencies"', () => { it(`should not bundle dependency when set "externalDependencies" is set.`, async () => { harness.useTarget('server', { ...BASE_OPTIONS, externalDependencies: ['@angular/core'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/main.js').content.toContain('require("@angular/core")'); harness.expectFile('dist/main.js').content.not.toContain('require("@angular/common")'); }); it(`should bundle all dependencies when "externalDependencies" is unset`, async () => { harness.useTarget('server', { ...BASE_OPTIONS, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/main.js').content.not.toContain('require("@angular/core")'); harness.expectFile('dist/main.js').content.not.toContain('require("@angular/common")'); }); }); });
{ "end_byte": 1403, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/server/tests/options/external-dependencies_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/server/tests/options/extract-licenses_spec.ts_0_1553
/** * @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.dev/license */ import { execute } from '../../index'; import { BASE_OPTIONS, SERVER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(execute, SERVER_BUILDER_INFO, (harness) => { describe('Option: "extractLicenses"', () => { it(`should generate '3rdpartylicenses.txt' when 'extractLicenses' is true`, async () => { harness.useTarget('server', { ...BASE_OPTIONS, extractLicenses: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/3rdpartylicenses.txt').content.toContain('MIT'); }); it(`should not generate '3rdpartylicenses.txt' when 'extractLicenses' is false`, async () => { harness.useTarget('server', { ...BASE_OPTIONS, extractLicenses: false, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/3rdpartylicenses.txt').toNotExist(); }); it(`should generate '3rdpartylicenses.txt' when 'extractLicenses' is not set`, async () => { harness.useTarget('server', { ...BASE_OPTIONS, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/3rdpartylicenses.txt').content.toContain('MIT'); }); }); });
{ "end_byte": 1553, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/server/tests/options/extract-licenses_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/extract-i18n/ivy-extract-loader.ts_0_4629
/** * @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.dev/license */ import * as nodePath from 'path'; import { loadEsmModule } from '../../utils/load-esm'; // Extract loader source map parameter type since it is not exported directly type LoaderSourceMap = Parameters<import('webpack').LoaderDefinitionFunction>[1]; interface LocalizeExtractLoaderOptions { messageHandler: (messages: import('@angular/localize').ɵParsedMessage[]) => void; } export default function localizeExtractLoader( this: import('webpack').LoaderContext<LocalizeExtractLoaderOptions>, content: string, map: LoaderSourceMap, ) { // This loader is not cacheable due to how message extraction works. // Extracted messages are not part of webpack pipeline and hence they cannot be retrieved from cache. // TODO: We should investigate in the future on making this deterministic and more cacheable. this.cacheable(false); const options = this.getOptions(); const callback = this.async(); extract(this, content, map, options).then( () => { // Pass through the original content now that messages have been extracted callback(undefined, content, map); }, (error) => { callback(error); }, ); } async function extract( loaderContext: import('webpack').LoaderContext<LocalizeExtractLoaderOptions>, content: string, map: string | LoaderSourceMap | undefined, options: LocalizeExtractLoaderOptions, ) { // Try to load the `@angular/localize` message extractor. // All the localize usages are setup to first try the ESM entry point then fallback to the deep imports. // This provides interim compatibility while the framework is transitioned to bundled ESM packages. let MessageExtractor; try { // Load ESM `@angular/localize/tools` using the TypeScript dynamic import workaround. // Once TypeScript provides support for keeping the dynamic import this workaround can be // changed to a direct dynamic import. const localizeToolsModule = await loadEsmModule<typeof import('@angular/localize/tools')>('@angular/localize/tools'); MessageExtractor = localizeToolsModule.MessageExtractor; } catch { throw new Error( `Unable to load message extractor. Please ensure '@angular/localize' is installed.`, ); } // Setup a Webpack-based logger instance const logger = { // level 2 is warnings level: 2, debug(...args: string[]): void { // eslint-disable-next-line no-console console.debug(...args); }, info(...args: string[]): void { loaderContext.emitWarning(new Error(args.join(''))); }, warn(...args: string[]): void { loaderContext.emitWarning(new Error(args.join(''))); }, error(...args: string[]): void { loaderContext.emitError(new Error(args.join(''))); }, }; let filename = loaderContext.resourcePath; const mapObject = typeof map === 'string' ? (JSON.parse(map) as Exclude<LoaderSourceMap, string>) : map; if (mapObject?.file) { // The extractor's internal sourcemap handling expects the filenames to match filename = nodePath.join(loaderContext.context, mapObject.file); } // Setup a virtual file system instance for the extractor // * MessageExtractor itself uses readFile, relative and resolve // * Internal SourceFileLoader (sourcemap support) uses dirname, exists, readFile, and resolve const filesystem = { readFile(path: string): string { if (path === filename) { return content; } else if (path === filename + '.map') { return typeof map === 'string' ? map : JSON.stringify(map); } else { throw new Error('Unknown file requested: ' + path); } }, relative(from: string, to: string): string { return nodePath.relative(from, to); }, resolve(...paths: string[]): string { return nodePath.resolve(...paths); }, exists(path: string): boolean { return path === filename || path === filename + '.map'; }, dirname(path: string): string { return nodePath.dirname(path); }, }; // eslint-disable-next-line @typescript-eslint/no-explicit-any const extractor = new MessageExtractor(filesystem as any, logger, { // eslint-disable-next-line @typescript-eslint/no-explicit-any basePath: loaderContext.rootContext as any, useSourceMaps: !!map, }); const messages = extractor.extractMessages(filename); if (messages.length > 0) { options?.messageHandler(messages); } }
{ "end_byte": 4629, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/extract-i18n/ivy-extract-loader.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/extract-i18n/webpack-extraction.ts_0_3773
/** * @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.dev/license */ import type { ɵParsedMessage as LocalizeMessage } from '@angular/localize'; import { BuilderContext } from '@angular-devkit/architect'; import { BuildResult, runWebpack } from '@angular-devkit/build-webpack'; import { lastValueFrom } from 'rxjs'; import webpack, { type Configuration } from 'webpack'; import { getCommonConfig } from '../../tools/webpack/configs'; import { createWebpackLoggingCallback } from '../../tools/webpack/utils/stats'; import { ExecutionTransformer } from '../../transforms'; import { generateBrowserWebpackConfigFromContext } from '../../utils/webpack-browser-config'; import { OutputHashing, Schema } from '../browser/schema'; import { NormalizedExtractI18nOptions } from './options'; class NoEmitPlugin { apply(compiler: webpack.Compiler): void { compiler.hooks.shouldEmit.tap('angular-no-emit', () => false); } } export async function extractMessages( options: NormalizedExtractI18nOptions, builderName: string, context: BuilderContext, transforms: { webpackConfiguration?: ExecutionTransformer<webpack.Configuration>; } = {}, ): Promise<{ builderResult: BuildResult; basePath: string; messages: LocalizeMessage[]; useLegacyIds: boolean; }> { const messages: LocalizeMessage[] = []; let useLegacyIds = true; const browserOptions = await context.validateOptions( await context.getTargetOptions(options.buildTarget), builderName, ); const builderOptions = { ...browserOptions, optimization: false, sourceMap: { scripts: true, styles: false, vendor: true, }, buildOptimizer: false, aot: true, progress: options.progress, budgets: [], assets: [], scripts: [], styles: [], deleteOutputPath: false, extractLicenses: false, subresourceIntegrity: false, outputHashing: OutputHashing.None, namedChunks: true, allowedCommonJsDependencies: undefined, } as unknown as Schema; const { config } = await generateBrowserWebpackConfigFromContext( builderOptions, context, (wco) => { // Default value for legacy message ids is currently true useLegacyIds = wco.tsConfig.options.enableI18nLegacyMessageIdFormat ?? true; const partials: (Promise<Configuration> | Configuration)[] = [ { plugins: [new NoEmitPlugin()] }, getCommonConfig(wco), ]; // Add Ivy application file extractor support partials.unshift({ module: { rules: [ { test: /\.[cm]?[tj]sx?$/, loader: require.resolve('./ivy-extract-loader'), options: { messageHandler: (fileMessages: LocalizeMessage[]) => messages.push(...fileMessages), }, }, ], }, }); // Replace all stylesheets with empty content partials.push({ module: { rules: [ { test: /\.(css|scss|sass|less)$/, loader: require.resolve('./empty-loader'), }, ], }, }); return partials; }, // During extraction we don't need specific browser support. { supportedBrowsers: undefined }, ); const builderResult = await lastValueFrom( runWebpack((await transforms?.webpackConfiguration?.(config)) || config, context, { logging: createWebpackLoggingCallback(builderOptions, context.logger), webpackFactory: webpack, }), ); return { builderResult, basePath: config.context || options.projectRoot, messages, useLegacyIds, }; }
{ "end_byte": 3773, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/extract-i18n/webpack-extraction.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/extract-i18n/builder.ts_0_6742
/** * @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.dev/license */ import { assertCompatibleAngularVersion, purgeStaleBuildCache } from '@angular/build/private'; import type { Diagnostics } from '@angular/localize/tools'; import type { BuilderContext, BuilderOutput } from '@angular-devkit/architect'; import fs from 'node:fs'; import path from 'node:path'; import type webpack from 'webpack'; import type { ExecutionTransformer } from '../../transforms'; import { loadEsmModule } from '../../utils/load-esm'; import { normalizeOptions } from './options'; import { Schema as ExtractI18nBuilderOptions, Format } from './schema'; /** * @experimental Direct usage of this function is considered experimental. */ export async function execute( options: ExtractI18nBuilderOptions, context: BuilderContext, transforms?: { webpackConfiguration?: ExecutionTransformer<webpack.Configuration>; }, ): Promise<BuilderOutput> { // Determine project name from builder context target const projectName = context.target?.project; if (!projectName) { context.logger.error(`The 'extract-i18n' builder requires a target to be specified.`); return { success: false }; } const { projectType } = (await context.getProjectMetadata(projectName)) as { projectType?: string; }; if (projectType !== 'application') { context.logger.error( `Tried to extract from ${projectName} with 'projectType' ${projectType}, which is not supported.` + ` The 'extract-i18n' builder can only extract from applications.`, ); return { success: false }; } // Check Angular version. assertCompatibleAngularVersion(context.workspaceRoot); // Load the Angular localize package. // The package is a peer dependency and might not be present let localizeToolsModule; try { localizeToolsModule = await loadEsmModule<typeof import('@angular/localize/tools')>('@angular/localize/tools'); } catch { return { success: false, error: `i18n extraction requires the '@angular/localize' package.` + ` You can add it by using 'ng add @angular/localize'.`, }; } // Normalize options const normalizedOptions = await normalizeOptions(context, projectName, options); const builderName = await context.getBuilderNameForTarget(normalizedOptions.buildTarget); // Extract messages based on configured builder let extractionResult; if ( builderName === '@angular-devkit/build-angular:application' || builderName === '@angular-devkit/build-angular:browser-esbuild' ) { const { extractMessages } = await import('./application-extraction'); extractionResult = await extractMessages( normalizedOptions, builderName, context, localizeToolsModule.MessageExtractor, ); if (!extractionResult.success) { return { success: false }; } } else { // Purge old build disk cache. // Other build systems handle stale cache purging directly. await purgeStaleBuildCache(context); const { extractMessages } = await import('./webpack-extraction'); extractionResult = await extractMessages(normalizedOptions, builderName, context, transforms); // Return the builder result if it failed if (!extractionResult.builderResult.success) { return extractionResult.builderResult; } } // Perform duplicate message checks const { checkDuplicateMessages } = localizeToolsModule; // The filesystem is used to create a relative path for each file // from the basePath. This relative path is then used in the error message. const checkFileSystem = { relative(from: string, to: string): string { return path.relative(from, to); }, }; const diagnostics = checkDuplicateMessages( // eslint-disable-next-line @typescript-eslint/no-explicit-any checkFileSystem as any, extractionResult.messages, 'warning', // eslint-disable-next-line @typescript-eslint/no-explicit-any extractionResult.basePath as any, ); if (diagnostics.messages.length > 0) { context.logger.warn(diagnostics.formatDiagnostics('')); } // Serialize all extracted messages const serializer = await createSerializer( localizeToolsModule, normalizedOptions.format, normalizedOptions.i18nOptions.sourceLocale, extractionResult.basePath, extractionResult.useLegacyIds, diagnostics, ); const content = serializer.serialize(extractionResult.messages); // Ensure directory exists const outputPath = path.dirname(normalizedOptions.outFile); if (!fs.existsSync(outputPath)) { fs.mkdirSync(outputPath, { recursive: true }); } // Write translation file fs.writeFileSync(normalizedOptions.outFile, content); if (normalizedOptions.progress) { context.logger.info(`Extraction Complete. (Messages: ${extractionResult.messages.length})`); } return { success: true, outputPath: normalizedOptions.outFile }; } async function createSerializer( localizeToolsModule: typeof import('@angular/localize/tools'), format: Format, sourceLocale: string, basePath: string, useLegacyIds: boolean, diagnostics: Diagnostics, ) { const { XmbTranslationSerializer, LegacyMessageIdMigrationSerializer, ArbTranslationSerializer, Xliff1TranslationSerializer, Xliff2TranslationSerializer, SimpleJsonTranslationSerializer, } = localizeToolsModule; switch (format) { case Format.Xmb: // eslint-disable-next-line @typescript-eslint/no-explicit-any return new XmbTranslationSerializer(basePath as any, useLegacyIds); case Format.Xlf: case Format.Xlif: case Format.Xliff: // eslint-disable-next-line @typescript-eslint/no-explicit-any return new Xliff1TranslationSerializer(sourceLocale, basePath as any, useLegacyIds, {}); case Format.Xlf2: case Format.Xliff2: // eslint-disable-next-line @typescript-eslint/no-explicit-any return new Xliff2TranslationSerializer(sourceLocale, basePath as any, useLegacyIds, {}); case Format.Json: return new SimpleJsonTranslationSerializer(sourceLocale); case Format.LegacyMigrate: return new LegacyMessageIdMigrationSerializer(diagnostics); case Format.Arb: return new ArbTranslationSerializer( sourceLocale, // eslint-disable-next-line @typescript-eslint/no-explicit-any basePath as any, { relative(from: string, to: string): string { return path.relative(from, to); }, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any, ); } }
{ "end_byte": 6742, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/extract-i18n/builder.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/extract-i18n/works_spec.ts_0_5748
/** * @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.dev/license */ import { Architect } from '@angular-devkit/architect'; import { join, logging, normalize, virtualFs } from '@angular-devkit/core'; import { createArchitect, extractI18nTargetSpec, host } from '../../testing/test-utils'; describe('Extract i18n Target', () => { const extractionFile = join(normalize('src'), 'messages.xlf'); let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(() => host.restore().toPromise()); it('generates an extraction file', async () => { host.appendToFile('src/app/app.component.html', '<p i18n>i18n test</p>'); const run = await architect.scheduleTarget(extractI18nTargetSpec); await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); await run.stop(); const exists = host.scopedSync().exists(extractionFile); expect(exists).toBe(true); if (exists) { const content = virtualFs.fileBufferToString(host.scopedSync().read(extractionFile)); expect(content).toContain('i18n test'); } }); it('does not emit the application files', async () => { host.appendToFile('src/app/app.component.html', '<p i18n>i18n test</p>'); const run = await architect.scheduleTarget(extractI18nTargetSpec); await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); await run.stop(); expect(host.scopedSync().exists(normalize('dist/app/main.js'))).toBeFalse(); }); it('shows errors', async () => { const logger = new logging.Logger(''); const logs: string[] = []; logger.subscribe((e) => logs.push(e.message)); host.appendToFile( 'src/app/app.component.html', '<p i18n>Hello world <span i18n>inner</span></p>', ); const run = await architect.scheduleTarget(extractI18nTargetSpec, undefined, { logger }); await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: false })); await run.stop(); expect(logs.join()).toMatch( 'Cannot mark an element as translatable inside of a translatable section', ); }); it('supports out file', async () => { host.appendToFile('src/app/app.component.html', '<p i18n>i18n test</p>'); const outFile = 'messages.fr.xlf'; const extractionFile = join(normalize('src'), outFile); const overrides = { outFile }; const run = await architect.scheduleTarget(extractI18nTargetSpec, overrides); await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); await run.stop(); expect(host.scopedSync().exists(extractionFile)).toBe(true); expect(virtualFs.fileBufferToString(host.scopedSync().read(extractionFile))).toMatch( /i18n test/, ); }); it('supports output path', async () => { host.appendToFile('src/app/app.component.html', '<p i18n>i18n test</p>'); // Note: this folder will not be created automatically. It must exist beforehand. const outputPath = 'src/i18n'; const extractionFile = join(normalize('src'), 'i18n', 'messages.xlf'); const overrides = { outputPath }; const run = await architect.scheduleTarget(extractI18nTargetSpec, overrides); await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); await run.stop(); expect(host.scopedSync().exists(extractionFile)).toBe(true); expect(virtualFs.fileBufferToString(host.scopedSync().read(extractionFile))).toMatch( /i18n test/, ); }); it('supports i18n format', async () => { host.appendToFile('src/app/app.component.html', '<p i18n>i18n test</p>'); const extractionFile = join(normalize('src'), 'messages.xmb'); const overrides = { format: 'xmb' }; const run = await architect.scheduleTarget(extractI18nTargetSpec, overrides); await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); await run.stop(); expect(host.scopedSync().exists(extractionFile)).toBe(true); expect(virtualFs.fileBufferToString(host.scopedSync().read(extractionFile))).toMatch( /i18n test/, ); }); it('issues warnings for duplicate message identifiers', async () => { host.appendToFile( 'src/app/app.component.ts', 'const c = $localize`:@@message-2:message contents`; const d = $localize`:@@message-2:different message contents`;', ); const logger = new logging.Logger(''); const logs: string[] = []; logger.subscribe((e) => logs.push(e.message)); const run = await architect.scheduleTarget(extractI18nTargetSpec, undefined, { logger }); await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); await run.stop(); expect(host.scopedSync().exists(extractionFile)).toBe(true); const fullLog = logs.join(); expect(fullLog).toContain('Duplicate messages with id'); }); it('ignores inline styles', async () => { host.appendToFile('src/app/app.component.html', '<p i18n>i18n test</p>'); host.replaceInFile('src/app/app.component.ts', 'styleUrls', 'styles'); host.replaceInFile('src/app/app.component.ts', './app.component.css', 'h1 { color: green; }'); const run = await architect.scheduleTarget(extractI18nTargetSpec); // This will fail if a style is processed since the style rules are not included during extraction await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); await run.stop(); }); });
{ "end_byte": 5748, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/extract-i18n/works_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/extract-i18n/application-extraction.ts_0_5689
/** * @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.dev/license */ import type { ApplicationBuilderOptions } from '@angular/build'; import { ResultFile, ResultKind, buildApplicationInternal } from '@angular/build/private'; import type { ɵParsedMessage as LocalizeMessage } from '@angular/localize'; import type { MessageExtractor } from '@angular/localize/tools'; import type { BuilderContext } from '@angular-devkit/architect'; import { readFileSync } from 'node:fs'; import nodePath from 'node:path'; import { BrowserBuilderOptions, convertBrowserOptions } from '../browser-esbuild'; import type { NormalizedExtractI18nOptions } from './options'; export async function extractMessages( options: NormalizedExtractI18nOptions, builderName: string, context: BuilderContext, extractorConstructor: typeof MessageExtractor, ): Promise<{ success: boolean; basePath: string; messages: LocalizeMessage[]; useLegacyIds: boolean; }> { const messages: LocalizeMessage[] = []; // Setup the build options for the application based on the buildTarget option let buildOptions; if (builderName === '@angular-devkit/build-angular:application') { buildOptions = (await context.validateOptions( await context.getTargetOptions(options.buildTarget), builderName, )) as unknown as ApplicationBuilderOptions; } else { buildOptions = convertBrowserOptions( (await context.validateOptions( await context.getTargetOptions(options.buildTarget), builderName, )) as unknown as BrowserBuilderOptions, ); } buildOptions.optimization = false; buildOptions.sourceMap = { scripts: true, vendor: true, styles: false }; buildOptions.localize = false; buildOptions.budgets = undefined; buildOptions.index = false; buildOptions.serviceWorker = false; buildOptions.server = undefined; buildOptions.ssr = false; buildOptions.appShell = undefined; buildOptions.prerender = undefined; buildOptions.outputMode = undefined; const builderResult = await first(buildApplicationInternal(buildOptions, context)); let success = false; if (!builderResult || builderResult.kind === ResultKind.Failure) { context.logger.error('Application build failed.'); } else if (builderResult.kind !== ResultKind.Full) { context.logger.error('Application build did not provide a full output.'); } else { // Setup the localize message extractor based on the in-memory files const extractor = setupLocalizeExtractor(extractorConstructor, builderResult.files, context); // Extract messages from each output JavaScript file. // Output files are only present on a successful build. for (const filePath of Object.keys(builderResult.files)) { if (!filePath.endsWith('.js')) { continue; } const fileMessages = extractor.extractMessages(filePath); messages.push(...fileMessages); } success = true; } return { success, basePath: context.workspaceRoot, messages, // Legacy i18n identifiers are not supported with the new application builder useLegacyIds: false, }; } function setupLocalizeExtractor( extractorConstructor: typeof MessageExtractor, files: Record<string, ResultFile>, context: BuilderContext, ): MessageExtractor { const textDecoder = new TextDecoder(); // Setup a virtual file system instance for the extractor // * MessageExtractor itself uses readFile, relative and resolve // * Internal SourceFileLoader (sourcemap support) uses dirname, exists, readFile, and resolve const filesystem = { readFile(path: string): string { // Output files are stored as relative to the workspace root const requestedPath = nodePath.relative(context.workspaceRoot, path); const file = files[requestedPath]; let content; if (file?.origin === 'memory') { content = textDecoder.decode(file.contents); } else if (file?.origin === 'disk') { content = readFileSync(file.inputPath, 'utf-8'); } if (content === undefined) { throw new Error('Unknown file requested: ' + requestedPath); } return content; }, relative(from: string, to: string): string { return nodePath.relative(from, to); }, resolve(...paths: string[]): string { return nodePath.resolve(...paths); }, exists(path: string): boolean { // Output files are stored as relative to the workspace root const requestedPath = nodePath.relative(context.workspaceRoot, path); return files[requestedPath] !== undefined; }, dirname(path: string): string { return nodePath.dirname(path); }, }; const logger = { // level 2 is warnings level: 2, debug(...args: string[]): void { // eslint-disable-next-line no-console console.debug(...args); }, info(...args: string[]): void { context.logger.info(args.join('')); }, warn(...args: string[]): void { context.logger.warn(args.join('')); }, error(...args: string[]): void { context.logger.error(args.join('')); }, }; // eslint-disable-next-line @typescript-eslint/no-explicit-any const extractor = new extractorConstructor(filesystem as any, logger, { // eslint-disable-next-line @typescript-eslint/no-explicit-any basePath: context.workspaceRoot as any, useSourceMaps: true, }); return extractor; } async function first<T>(iterable: AsyncIterable<T>): Promise<T | undefined> { for await (const value of iterable) { return value; } }
{ "end_byte": 5689, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/extract-i18n/application-extraction.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/extract-i18n/empty-loader.ts_0_266
/** * @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.dev/license */ export default function () { return `export default '';`; }
{ "end_byte": 266, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/extract-i18n/empty-loader.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/extract-i18n/index.ts_0_483
/** * @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.dev/license */ import { createBuilder } from '@angular-devkit/architect'; import { execute } from './builder'; import type { Schema as ExtractI18nBuilderOptions } from './schema'; export { ExtractI18nBuilderOptions, execute }; export default createBuilder<ExtractI18nBuilderOptions>(execute);
{ "end_byte": 483, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/extract-i18n/index.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/extract-i18n/options.ts_0_2834
/** * @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.dev/license */ import { createI18nOptions } from '@angular/build/private'; import { BuilderContext, targetFromTargetString } from '@angular-devkit/architect'; import { fail } from 'node:assert'; import path from 'node:path'; import { Schema as ExtractI18nOptions, Format } from './schema'; export type NormalizedExtractI18nOptions = Awaited<ReturnType<typeof normalizeOptions>>; /** * Normalize the user provided options by creating full paths for all path based options * and converting multi-form options into a single form that can be directly used * by the build process. * * @param context The context for current builder execution. * @param projectName The name of the project for the current execution. * @param options An object containing the options to use for the build. * @returns An object containing normalized options required to perform the build. */ export async function normalizeOptions( context: BuilderContext, projectName: string, options: ExtractI18nOptions, ) { const workspaceRoot = context.workspaceRoot; const projectMetadata = await context.getProjectMetadata(projectName); const projectRoot = path.join(workspaceRoot, (projectMetadata.root as string | undefined) ?? ''); // Target specifier defaults to the current project's build target with no specified configuration const buildTargetSpecifier = options.buildTarget ?? ':'; const buildTarget = targetFromTargetString(buildTargetSpecifier, projectName, 'build'); const i18nOptions = createI18nOptions(projectMetadata); // Normalize xliff format extensions let format = options.format; switch (format) { // Default format is xliff1 case undefined: case Format.Xlf: case Format.Xlif: case Format.Xliff: format = Format.Xliff; break; case Format.Xlf2: case Format.Xliff2: format = Format.Xliff2; break; } let outFile = options.outFile || getDefaultOutFile(format); if (options.outputPath) { outFile = path.join(options.outputPath, outFile); } outFile = path.resolve(context.workspaceRoot, outFile); return { workspaceRoot, projectRoot, buildTarget, i18nOptions, format, outFile, progress: options.progress ?? true, }; } function getDefaultOutFile(format: Format) { switch (format) { case Format.Xmb: return 'messages.xmb'; case Format.Xliff: case Format.Xliff2: return 'messages.xlf'; case Format.Json: case Format.LegacyMigrate: return 'messages.json'; case Format.Arb: return 'messages.arb'; default: fail(`Invalid Format enum value: ${format as unknown}`); } }
{ "end_byte": 2834, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/extract-i18n/options.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/index.ts_0_3799
/** * @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.dev/license */ import { BudgetCalculatorResult, FileInfo, IndexHtmlGenerator, IndexHtmlTransform, ThresholdSeverity, assertCompatibleAngularVersion, augmentAppWithServiceWorker, checkBudgets, purgeStaleBuildCache, } from '@angular/build/private'; import { BuilderContext, BuilderOutput, createBuilder } from '@angular-devkit/architect'; import { EmittedFiles, WebpackLoggingCallback, runWebpack } from '@angular-devkit/build-webpack'; import { imageDomains } from '@ngtools/webpack'; import * as fs from 'fs'; import * as path from 'path'; import { Observable, concatMap, from, map, switchMap } from 'rxjs'; import webpack, { StatsCompilation } from 'webpack'; import { getCommonConfig, getStylesConfig } from '../../tools/webpack/configs'; import { markAsyncChunksNonInitial } from '../../tools/webpack/utils/async-chunks'; import { normalizeExtraEntryPoints } from '../../tools/webpack/utils/helpers'; import { BuildEventStats, generateBuildEventStats, statsErrorsToString, statsHasErrors, statsHasWarnings, statsWarningsToString, webpackStatsLogger, } from '../../tools/webpack/utils/stats'; import { ExecutionTransformer } from '../../transforms'; import { deleteOutputDir, normalizeAssetPatterns, normalizeOptimization, urlJoin, } from '../../utils'; import { colors } from '../../utils/color'; import { copyAssets } from '../../utils/copy-assets'; import { assertIsError } from '../../utils/error'; import { i18nInlineEmittedFiles } from '../../utils/i18n-inlining'; import { I18nOptions } from '../../utils/i18n-webpack'; import { normalizeCacheOptions } from '../../utils/normalize-cache'; import { ensureOutputPaths } from '../../utils/output-paths'; import { generateEntryPoints } from '../../utils/package-chunk-sort'; import { Spinner } from '../../utils/spinner'; import { generateI18nBrowserWebpackConfigFromContext, getIndexInputFile, getIndexOutputFile, } from '../../utils/webpack-browser-config'; import { Schema as BrowserBuilderSchema } from './schema'; /** * @experimental Direct usage of this type is considered experimental. */ export type BrowserBuilderOutput = BuilderOutput & { stats: BuildEventStats; baseOutputPath: string; outputs: { locale?: string; path: string; baseHref?: string; }[]; }; /** * Maximum time in milliseconds for single build/rebuild * This accounts for CI variability. */ export const BUILD_TIMEOUT = 30_000; async function initialize( options: BrowserBuilderSchema, context: BuilderContext, webpackConfigurationTransform?: ExecutionTransformer<webpack.Configuration>, ): Promise<{ config: webpack.Configuration; projectRoot: string; projectSourceRoot?: string; i18n: I18nOptions; }> { const originalOutputPath = options.outputPath; // Assets are processed directly by the builder except when watching const adjustedOptions = options.watch ? options : { ...options, assets: [] }; const { config, projectRoot, projectSourceRoot, i18n } = await generateI18nBrowserWebpackConfigFromContext(adjustedOptions, context, (wco) => [ getCommonConfig(wco), getStylesConfig(wco), ]); let transformedConfig; if (webpackConfigurationTransform) { transformedConfig = await webpackConfigurationTransform(config); } if (options.deleteOutputPath) { await deleteOutputDir(context.workspaceRoot, originalOutputPath); } return { config: transformedConfig || config, projectRoot, projectSourceRoot, i18n }; } /** * @experimental Direct usage of this function is considered experimental. */ // eslint-disable-next-line max-lines-per-function
{ "end_byte": 3799, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/index.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/index.ts_3800_16484
export function buildWebpackBrowser( options: BrowserBuilderSchema, context: BuilderContext, transforms: { webpackConfiguration?: ExecutionTransformer<webpack.Configuration>; logging?: WebpackLoggingCallback; indexHtml?: IndexHtmlTransform; } = {}, ): Observable<BrowserBuilderOutput> { const projectName = context.target?.project; if (!projectName) { throw new Error('The builder requires a target.'); } const baseOutputPath = path.resolve(context.workspaceRoot, options.outputPath); let outputPaths: undefined | Map<string, string>; // Check Angular version. assertCompatibleAngularVersion(context.workspaceRoot); return from(context.getProjectMetadata(projectName)).pipe( switchMap(async (projectMetadata) => { // Purge old build disk cache. await purgeStaleBuildCache(context); // Initialize builder const initialization = await initialize(options, context, transforms.webpackConfiguration); // Add index file to watched files. if (options.watch) { const indexInputFile = path.join(context.workspaceRoot, getIndexInputFile(options.index)); initialization.config.plugins ??= []; initialization.config.plugins.push({ apply: (compiler: webpack.Compiler) => { compiler.hooks.thisCompilation.tap('build-angular', (compilation) => { compilation.fileDependencies.add(indexInputFile); }); }, }); } return { ...initialization, cacheOptions: normalizeCacheOptions(projectMetadata, context.workspaceRoot), }; }), switchMap( // eslint-disable-next-line max-lines-per-function ({ config, projectRoot, projectSourceRoot, i18n, cacheOptions }) => { const normalizedOptimization = normalizeOptimization(options.optimization); return runWebpack(config, context, { webpackFactory: require('webpack') as typeof webpack, logging: transforms.logging || ((stats, config) => { if (options.verbose && config.stats !== false) { const statsOptions = config.stats === true ? undefined : config.stats; context.logger.info(stats.toString(statsOptions)); } }), }).pipe( concatMap( // eslint-disable-next-line max-lines-per-function async ( buildEvent, ): Promise<{ output: BuilderOutput; webpackStats: StatsCompilation }> => { const spinner = new Spinner(); spinner.enabled = options.progress !== false; const { success, emittedFiles = [], outputPath: webpackOutputPath } = buildEvent; const webpackRawStats = buildEvent.webpackStats; if (!webpackRawStats) { throw new Error('Webpack stats build result is required.'); } // Fix incorrectly set `initial` value on chunks. const extraEntryPoints = [ ...normalizeExtraEntryPoints(options.styles || [], 'styles'), ...normalizeExtraEntryPoints(options.scripts || [], 'scripts'), ]; const webpackStats = { ...webpackRawStats, chunks: markAsyncChunksNonInitial(webpackRawStats, extraEntryPoints), }; if (!success) { // If using bundle downleveling then there is only one build // If it fails show any diagnostic messages and bail if (statsHasWarnings(webpackStats)) { context.logger.warn(statsWarningsToString(webpackStats, { colors: true })); } if (statsHasErrors(webpackStats)) { context.logger.error(statsErrorsToString(webpackStats, { colors: true })); } return { webpackStats: webpackRawStats, output: { success: false }, }; } else { outputPaths = ensureOutputPaths(baseOutputPath, i18n); const scriptsEntryPointName = normalizeExtraEntryPoints( options.scripts || [], 'scripts', ).map((x) => x.bundleName); if (i18n.shouldInline) { const success = await i18nInlineEmittedFiles( context, emittedFiles, i18n, baseOutputPath, Array.from(outputPaths.values()), scriptsEntryPointName, webpackOutputPath, options.i18nMissingTranslation, ); if (!success) { return { webpackStats: webpackRawStats, output: { success: false }, }; } } // Check for budget errors and display them to the user. const budgets = options.budgets; let budgetFailures: BudgetCalculatorResult[] | undefined; if (budgets?.length) { budgetFailures = [...checkBudgets(budgets, webpackStats)]; for (const { severity, message } of budgetFailures) { switch (severity) { case ThresholdSeverity.Warning: webpackStats.warnings?.push({ message }); break; case ThresholdSeverity.Error: webpackStats.errors?.push({ message }); break; default: assertNever(severity); } } } const buildSuccess = success && !statsHasErrors(webpackStats); if (buildSuccess) { // Copy assets if (!options.watch && options.assets?.length) { spinner.start('Copying assets...'); try { await copyAssets( normalizeAssetPatterns( options.assets, context.workspaceRoot, projectRoot, projectSourceRoot, ), Array.from(outputPaths.values()), context.workspaceRoot, ); spinner.succeed('Copying assets complete.'); } catch (err) { spinner.fail(colors.redBright('Copying of assets failed.')); assertIsError(err); return { output: { success: false, error: 'Unable to copy assets: ' + err.message, }, webpackStats: webpackRawStats, }; } } if (options.index) { spinner.start('Generating index html...'); const entrypoints = generateEntryPoints({ scripts: options.scripts ?? [], styles: options.styles ?? [], }); const indexHtmlGenerator = new IndexHtmlGenerator({ cache: cacheOptions, indexPath: path.join(context.workspaceRoot, getIndexInputFile(options.index)), entrypoints, deployUrl: options.deployUrl, sri: options.subresourceIntegrity, optimization: normalizedOptimization, crossOrigin: options.crossOrigin, postTransform: transforms.indexHtml, imageDomains: Array.from(imageDomains), }); let hasErrors = false; for (const [locale, outputPath] of outputPaths.entries()) { try { const { csrContent: content, warnings, errors, } = await indexHtmlGenerator.process({ baseHref: getLocaleBaseHref(i18n, locale) ?? options.baseHref, // i18nLocale is used when Ivy is disabled lang: locale || undefined, outputPath, files: mapEmittedFilesToFileInfo(emittedFiles), }); if (warnings.length || errors.length) { spinner.stop(); warnings.forEach((m) => context.logger.warn(m)); errors.forEach((m) => { context.logger.error(m); hasErrors = true; }); spinner.start(); } const indexOutput = path.join( outputPath, getIndexOutputFile(options.index), ); await fs.promises.mkdir(path.dirname(indexOutput), { recursive: true }); await fs.promises.writeFile(indexOutput, content); } catch (error) { spinner.fail('Index html generation failed.'); assertIsError(error); return { webpackStats: webpackRawStats, output: { success: false, error: error.message }, }; } } if (hasErrors) { spinner.fail('Index html generation failed.'); return { webpackStats: webpackRawStats, output: { success: false }, }; } else { spinner.succeed('Index html generation complete.'); } } if (options.serviceWorker) { spinner.start('Generating service worker...'); for (const [locale, outputPath] of outputPaths.entries()) { try { await augmentAppWithServiceWorker( projectRoot, context.workspaceRoot, outputPath, getLocaleBaseHref(i18n, locale) ?? options.baseHref ?? '/', options.ngswConfigPath, ); } catch (error) { spinner.fail('Service worker generation failed.'); assertIsError(error); return { webpackStats: webpackRawStats, output: { success: false, error: error.message }, }; } } spinner.succeed('Service worker generation complete.'); } } webpackStatsLogger(context.logger, webpackStats, config, budgetFailures); return { webpackStats: webpackRawStats, output: { success: buildSuccess }, }; } }, ), map( ({ output: event, webpackStats }) => ({ ...event, stats: generateBuildEventStats(webpackStats, options), baseOutputPath, outputs: (outputPaths && [...outputPaths.entries()].map(([locale, path]) => ({ locale, path, baseHref: getLocaleBaseHref(i18n, locale) ?? options.baseHref, }))) || { path: baseOutputPath, baseHref: options.baseHref, }, }) as BrowserBuilderOutput, ), ); }, ), ); function getLocaleBaseHref(i18n: I18nOptions, locale: string): string | undefined { if (i18n.locales[locale] && i18n.locales[locale]?.baseHref !== '') { return urlJoin(options.baseHref || '', i18n.locales[locale].baseHref ?? `/${locale}/`); } return undefined; } }
{ "end_byte": 16484, "start_byte": 3800, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/index.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/index.ts_16486_17064
function assertNever(input: never): never { throw new Error( `Unexpected call to assertNever() with input: ${JSON.stringify( input, null /* replacer */, 4 /* tabSize */, )}`, ); } function mapEmittedFilesToFileInfo(files: EmittedFiles[] = []): FileInfo[] { const filteredFiles: FileInfo[] = []; for (const { file, name, extension, initial } of files) { if (name && initial) { filteredFiles.push({ file, extension, name }); } } return filteredFiles; } export default createBuilder<BrowserBuilderSchema>(buildWebpackBrowser);
{ "end_byte": 17064, "start_byte": 16486, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/index.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/resources-output-path_spec.ts_0_3860
/** * @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.dev/license */ import { Architect } from '@angular-devkit/architect'; import { normalize } from '@angular-devkit/core'; import { browserBuild, createArchitect, host } from '../../../testing/test-utils'; describe('Browser Builder styles resources output path', () => { const imgSvg = ` <svg width="100" height="100" xmlns="http://www.w3.org/2000/svg"> <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" /> </svg> `; function writeFiles() { // Use a large image for the relative ref so it cannot be inlined. host.copyFile('src/spectrum.png', './src/assets/global-img-relative.png'); host.copyFile('src/spectrum.png', './src/assets/component-img-relative.png'); host.writeMultipleFiles({ 'src/styles.css': ` h1 { background: url('/assets/global-img-absolute.svg'); } h2 { background: url('./assets/global-img-relative.png'); } `, 'src/app/app.component.css': ` h3 { background: url('/assets/component-img-absolute.svg'); } h4 { background: url('../assets/component-img-relative.png'); } `, 'src/assets/global-img-absolute.svg': imgSvg, 'src/assets/component-img-absolute.svg': imgSvg, }); } const target = { project: 'app', target: 'build' }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(async () => host.restore().toPromise()); it(`supports resourcesOutputPath in resource urls`, async () => { writeFiles(); // Check base paths are correctly generated. const overrides = { aot: true, resourcesOutputPath: 'out-assets', }; const { files } = await browserBuild(architect, host, target, overrides); const styles = await files['styles.css']; const main = await files['main.js']; expect(styles).toContain(`url('/assets/global-img-absolute.svg')`); expect(styles).toContain(`url('out-assets/global-img-relative.png')`); expect(main).toContain(`url('/assets/component-img-absolute.svg')`); expect(main).toContain(`url('out-assets/component-img-relative.png')`); expect(host.scopedSync().exists(normalize('dist/assets/global-img-absolute.svg'))).toBe(true); expect(host.scopedSync().exists(normalize('dist/out-assets/global-img-relative.png'))).toBe( true, ); expect(host.scopedSync().exists(normalize('dist/assets/component-img-absolute.svg'))).toBe( true, ); expect(host.scopedSync().exists(normalize('dist/out-assets/component-img-relative.png'))).toBe( true, ); }); it(`supports blank resourcesOutputPath`, async () => { writeFiles(); // Check base paths are correctly generated. const overrides = { aot: true }; const { files } = await browserBuild(architect, host, target, overrides); const styles = await files['styles.css']; const main = await files['main.js']; expect(styles).toContain(`url('/assets/global-img-absolute.svg')`); expect(styles).toContain(`url('global-img-relative.png')`); expect(main).toContain(`url('/assets/component-img-absolute.svg')`); expect(main).toContain(`url('component-img-relative.png')`); expect(host.scopedSync().exists(normalize('dist/assets/global-img-absolute.svg'))).toBe(true); expect(host.scopedSync().exists(normalize('dist/global-img-relative.png'))).toBe(true); expect(host.scopedSync().exists(normalize('dist/assets/component-img-absolute.svg'))).toBe( true, ); expect(host.scopedSync().exists(normalize('dist/component-img-relative.png'))).toBe(true); }); });
{ "end_byte": 3860, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/resources-output-path_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/no-entry-module_spec.ts_0_1029
/** * @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.dev/license */ import { Architect } from '@angular-devkit/architect'; import { browserBuild, createArchitect, host } from '../../../testing/test-utils'; describe('Browser Builder no entry module', () => { const target = { project: 'app', target: 'build' }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(async () => host.restore().toPromise()); it('works', async () => { // Remove the bootstrap but keep a reference to AppModule so the import is not elided. host.replaceInFile('src/main.ts', /platformBrowserDynamic.*?bootstrapModule.*?;/, ''); host.appendToFile('src/main.ts', 'console.log(AppModule);'); await browserBuild(architect, host, target, { baseHref: '/myUrl' }); }); });
{ "end_byte": 1029, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/no-entry-module_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/scripts-array_spec.ts_0_5564
/** * @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.dev/license */ import { Architect } from '@angular-devkit/architect'; import { logging } from '@angular-devkit/core'; import { browserBuild, createArchitect, host } from '../../../testing/test-utils'; describe('Browser Builder scripts array', () => { const scripts: { [path: string]: string } = { 'src/input-script.js': "console.log('input-script'); var number = 1+1;", 'src/zinput-script.js': "console.log('zinput-script');", 'src/finput-script.js': "console.log('finput-script');", 'src/uinput-script.js': "console.log('uinput-script');", 'src/binput-script.js': "console.log('binput-script');", 'src/ainput-script.js': "console.log('ainput-script');", 'src/cinput-script.js': "console.log('cinput-script');", 'src/lazy-script.js': "console.log('lazy-script');", 'src/pre-rename-script.js': "console.log('pre-rename-script');", 'src/pre-rename-lazy-script.js': "console.log('pre-rename-lazy-script');", }; const getScriptsOption = () => [ 'src/input-script.js', 'src/zinput-script.js', 'src/finput-script.js', 'src/uinput-script.js', 'src/binput-script.js', 'src/ainput-script.js', 'src/cinput-script.js', { input: 'src/lazy-script.js', bundleName: 'lazy-script', inject: false }, { input: 'src/pre-rename-script.js', bundleName: 'renamed-script' }, { input: 'src/pre-rename-lazy-script.js', bundleName: 'renamed-lazy-script', inject: false }, ]; const target = { project: 'app', target: 'build' }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(async () => host.restore().toPromise()); it('works', async () => { const matches: Record<string, string> = { 'scripts.js': 'input-script', 'lazy-script.js': 'lazy-script', 'renamed-script.js': 'pre-rename-script', 'renamed-lazy-script.js': 'pre-rename-lazy-script', 'main.js': 'input-script', 'index.html': '<script src="runtime.js" type="module"></script>' + '<script src="polyfills.js" type="module"></script>' + '<script src="scripts.js" defer></script>' + '<script src="renamed-script.js" defer></script>' + '<script src="vendor.js" type="module"></script>' + '<script src="main.js" type="module"></script>', }; host.writeMultipleFiles(scripts); host.appendToFile('src/main.ts', "\nimport './input-script.js';"); // Remove styles so we don't have to account for them in the index.html order check. const { files } = await browserBuild(architect, host, target, { styles: [], scripts: getScriptsOption(), } as {}); for (const [fileName, content] of Object.entries(matches)) { expect(await files[fileName]).toMatch(content); } }); it('uglifies, uses sourcemaps, and adds hashes', async () => { host.writeMultipleFiles(scripts); const { files } = await browserBuild(architect, host, target, { optimization: true, sourceMap: true, outputHashing: 'all', scripts: getScriptsOption(), } as {}); const fileNames = Object.keys(files); const scriptsBundle = fileNames.find((n) => /scripts\.[0-9a-f]{16}\.js/.test(n)); expect(scriptsBundle).toBeTruthy(); expect(await files[scriptsBundle || '']).toMatch('var number=2;'); expect(fileNames.some((n) => /scripts\.[0-9a-f]{16}\.js\.map/.test(n))).toBeTruthy(); expect(fileNames.some((n) => /renamed-script\.[0-9a-f]{16}\.js/.test(n))).toBeTruthy(); expect(fileNames.some((n) => /renamed-script\.[0-9a-f]{16}\.js\.map/.test(n))).toBeTruthy(); expect(fileNames.some((n) => /script\.[0-9a-f]{16}\.js/.test(n))).toBeTruthy(); expect(await files['lazy-script.js']).not.toBeUndefined(); expect(await files['lazy-script.js.map']).not.toBeUndefined(); expect(await files['renamed-lazy-script.js']).not.toBeUndefined(); expect(await files['renamed-lazy-script.js.map']).not.toBeUndefined(); }); it('preserves script order', async () => { host.writeMultipleFiles(scripts); const { files } = await browserBuild(architect, host, target, { scripts: getScriptsOption(), } as {}); expect(await files['scripts.js']).toMatch( new RegExp( /.*['"]input-script['"](.|\n|\r)*/.source + /['"]zinput-script['"](.|\n|\r)*/.source + /['"]finput-script['"](.|\n|\r)*/.source + /['"]uinput-script['"](.|\n|\r)*/.source + /['"]binput-script['"](.|\n|\r)*/.source + /['"]ainput-script['"](.|\n|\r)*/.source + /['"]cinput-script['"]/.source, ), ); }); it('chunk in entry', async () => { host.writeMultipleFiles(scripts); const logger = new logging.Logger('build-script-chunk-entry'); const logs: string[] = []; logger.subscribe(({ message }) => { logs.push(message); }); await browserBuild( architect, host, target, { scripts: getScriptsOption(), } as {}, { logger }, ); const joinedLogs = logs.join('\n'); expect(joinedLogs).toMatch(/lazy-script.+\d+ bytes/); expect(joinedLogs).toMatch(/renamed-script.+\d+ bytes/); expect(joinedLogs).toMatch(/renamed-lazy-script.+\d+ bytes/); expect(joinedLogs).not.toContain('Lazy chunks'); }); });
{ "end_byte": 5564, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/scripts-array_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/aot_spec.ts_0_2050
/** * @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.dev/license */ import { Architect } from '@angular-devkit/architect'; import { BrowserBuilderOutput } from '@angular-devkit/build-angular'; import { join, logging, normalize, virtualFs } from '@angular-devkit/core'; import { lastValueFrom } from 'rxjs'; import { createArchitect, host } from '../../../testing/test-utils'; describe('Browser Builder AOT', () => { const targetSpec = { project: 'app', target: 'build' }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(async () => host.restore().toPromise()); it('works', async () => { const overrides = { aot: true }; const run = await architect.scheduleTarget(targetSpec, overrides); const output = (await run.result) as BrowserBuilderOutput; expect(output.success).toBeTrue(); const fileName = join(normalize(output.outputs[0].path), 'main.js'); const content = virtualFs.fileBufferToString( await lastValueFrom(host.read(normalize(fileName))), ); expect(content).toContain('AppComponent_Factory'); await run.stop(); }); it('shows error when component stylesheet contains SCSS syntax error', async () => { const overrides = { aot: true, }; host.replaceInFile('src/app/app.component.ts', 'app.component.css', 'app.component.scss'); host.writeMultipleFiles({ 'src/app/app.component.scss': ` .foo { `, }); const logger = new logging.Logger(''); const logs: string[] = []; logger.subscribe((e) => logs.push(e.message)); const run = await architect.scheduleTarget(targetSpec, overrides, { logger }); const output = await run.result; expect(output.success).toBe(false); expect(logs.join()).toContain('expected "}".'); await run.stop(); }); });
{ "end_byte": 2050, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/aot_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/rebuild_spec.ts_0_573
/** * @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.dev/license */ import { Architect } from '@angular-devkit/architect'; import { join, logging, normalize, virtualFs } from '@angular-devkit/core'; import { debounceTime, take, takeWhile, tap, timeout } from 'rxjs'; import { createArchitect, host, lazyModuleFiles, lazyModuleFnImport, outputPath, } from '../../../testing/test-utils'; import { BUILD_TIMEOUT } from '../index';
{ "end_byte": 573, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/rebuild_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/rebuild_spec.ts_575_8931
describe('Browser Builder rebuilds', () => { const target = { project: 'app', target: 'build' }; // Rebuild tests are especially sensitive to time between writes due to file watcher // behaviour. Give them a while. const rebuildDebounceTime = 3000; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(async () => host.restore().toPromise()); it('rebuilds on TS file changes', async () => { const goldenValueFiles: { [path: string]: string } = { 'src/app/app.module.ts': ` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } console.log('$$_E2E_GOLDEN_VALUE_1'); export let X = '$$_E2E_GOLDEN_VALUE_2'; `, 'src/main.ts': ` import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; platformBrowserDynamic().bootstrapModule(AppModule); import * as m from './app/app.module'; console.log(m.X); console.log('$$_E2E_GOLDEN_VALUE_3'); `, }; const overrides = { watch: true }; let phase = 1; const run = await architect.scheduleTarget(target, overrides); await run.output .pipe( timeout(BUILD_TIMEOUT), debounceTime(rebuildDebounceTime), tap((result) => { expect(result.success).toBeTrue(); const hasLazyChunk = host .scopedSync() .exists(normalize('dist/src_app_lazy_lazy_module_ts.js')); switch (phase) { case 1: // No lazy chunk should exist. if (!hasLazyChunk) { phase = 2; host.writeMultipleFiles({ ...lazyModuleFiles, ...lazyModuleFnImport }); } break; case 2: // A lazy chunk should have been with the filename. if (hasLazyChunk) { phase = 3; host.writeMultipleFiles(goldenValueFiles); } break; case 3: // The golden values should be present and in the right order. const re = new RegExp( /\$\$_E2E_GOLDEN_VALUE_1(.|\n|\r)*/.source + /\$\$_E2E_GOLDEN_VALUE_2(.|\n|\r)*/.source + /\$\$_E2E_GOLDEN_VALUE_3/.source, ); const fileName = './dist/main.js'; const content = virtualFs.fileBufferToString( host.scopedSync().read(normalize(fileName)), ); if (re.test(content)) { phase = 4; } break; } }), takeWhile(() => phase < 4), ) .toPromise(); await run.stop(); }); it('rebuilds on CSS changes', async () => { const overrides = { watch: true }; const run = await architect.scheduleTarget(target, overrides); await run.output .pipe( timeout(BUILD_TIMEOUT), debounceTime(rebuildDebounceTime), tap((buildEvent) => expect(buildEvent.success).toBe(true)), tap(() => host.appendToFile('src/app/app.component.css', ':host { color: blue; }')), take(2), ) .toPromise(); await run.stop(); }); it('type checks on rebuilds', async () => { host.writeMultipleFiles({ 'src/funky2.ts': `export const funky2 = (value: string) => value + 'hello';`, 'src/funky.ts': `export * from './funky2';`, }); host.appendToFile( 'src/main.ts', ` import { funky2 } from './funky'; console.log(funky2('town')); `, ); const overrides = { watch: true }; const logger = new logging.Logger(''); let logs: string[] = []; logger.subscribe((e) => logs.push(e.message)); const typeError = `is not assignable to parameter of type 'number'`; let buildNumber = 0; const run = await architect.scheduleTarget(target, overrides, { logger }); await run.output .pipe( timeout(BUILD_TIMEOUT), debounceTime(rebuildDebounceTime), tap((buildEvent) => { buildNumber += 1; switch (buildNumber) { case 1: expect(buildEvent.success).toBe(true); // Make an invalid version of the file. // Should trigger a rebuild, this time an error is expected. host.writeMultipleFiles({ 'src/funky2.ts': `export const funky2 = (value: number) => value + 1;`, }); break; case 2: // The second build should error out with a type error on the type of an argument. expect(buildEvent.success).toBe(false); expect(logs.join().includes(typeError)).toBe(true); logs = []; // Change an UNRELATED file and the error should still happen. // Should trigger a rebuild, this time an error is also expected. host.appendToFile('src/app/app.module.ts', `console.log(1);`); break; case 3: // The third build should have the same error as the first. expect(buildEvent.success).toBe(false); expect(logs.join().includes(typeError)).toBe(true); logs = []; // Fix the error. host.writeMultipleFiles({ 'src/funky2.ts': `export const funky2 = (value: string) => value + 'hello';`, }); break; default: expect(buildEvent.success).toBe(true); break; } }), take(4), ) .toPromise(); await run.stop(); }); it('rebuilds on type changes', async () => { host.writeMultipleFiles({ 'src/type.ts': `export type MyType = number;` }); host.appendToFile('src/main.ts', `import { MyType } from './type';`); const overrides = { watch: true }; const run = await architect.scheduleTarget(target, overrides); await run.output .pipe( timeout(BUILD_TIMEOUT), debounceTime(rebuildDebounceTime), tap((buildEvent) => expect(buildEvent.success).toBe(true)), tap(() => host.writeMultipleFiles({ 'src/type.ts': `export type MyType = string;` })), take(2), ) .toPromise(); await run.stop(); }); it('rebuilds on transitive type-only file changes', async () => { host.writeMultipleFiles({ 'src/interface1.ts': ` import { Interface2 } from './interface2'; export interface Interface1 extends Interface2 { } `, 'src/interface2.ts': ` import { Interface3 } from './interface3'; export interface Interface2 extends Interface3 { } `, 'src/interface3.ts': `export interface Interface3 { nbr: number; }`, }); host.appendToFile( 'src/main.ts', ` import { Interface1 } from './interface1'; const something: Interface1 = { nbr: 43 }; `, ); const overrides = { watch: true }; const run = await architect.scheduleTarget(target, overrides); let buildNumber = 0; await run.output .pipe( timeout(BUILD_TIMEOUT), debounceTime(rebuildDebounceTime), tap((buildEvent) => expect(buildEvent.success).toBe(true)), tap(() => { // NOTE: this only works for transitive type deps after the first build, and only if the // typedep file was there on the previous build. // Make sure the first rebuild is triggered on a direct dep (typedep or not). buildNumber++; if (buildNumber < 4) { host.appendToFile(`src/interface${buildNumber}.ts`, `export type MyType = string;`); } else { host.appendToFile(`src/typings.d.ts`, `export type MyType = string;`); } }), take(5), ) .toPromise(); await run.stop(); });
{ "end_byte": 8931, "start_byte": 575, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/rebuild_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/rebuild_spec.ts_8935_15715
it('rebuilds on transitive non node package DTS file changes', async () => { host.writeMultipleFiles({ 'src/interface1.d.ts': ` import { Interface2 } from './interface2'; export interface Interface1 extends Interface2 { } `, 'src/interface2.d.ts': ` import { Interface3 } from './interface3'; export interface Interface2 extends Interface3 { } `, 'src/interface3.d.ts': `export interface Interface3 { nbr: number; }`, }); host.appendToFile( 'src/main.ts', ` import { Interface1 } from './interface1'; const something: Interface1 = { nbr: 43 }; `, ); const overrides = { watch: true }; const run = await architect.scheduleTarget(target, overrides); let buildNumber = 0; await run.output .pipe( timeout(BUILD_TIMEOUT), debounceTime(rebuildDebounceTime), tap((buildEvent) => expect(buildEvent.success).toBe(true)), tap(() => { buildNumber++; if (buildNumber === 1) { host.appendToFile('src/interface3.d.ts', 'export declare type MyType = string;'); } }), take(2), ) .toPromise(); await run.stop(); }); it('rebuilds after errors in JIT', async () => { const origContent = virtualFs.fileBufferToString( host.scopedSync().read(normalize('src/app/app.component.ts')), ); host.appendToFile('./src/app/app.component.ts', `]]]]`); const overrides = { watch: true, aot: false }; let buildNumber = 0; const run = await architect.scheduleTarget(target, overrides); await run.output .pipe( timeout(BUILD_TIMEOUT), debounceTime(rebuildDebounceTime), tap((buildEvent) => { buildNumber++; switch (buildNumber) { case 1: // The first build should fail. expect(buildEvent.success).toBe(false); // Fix the error. host.writeMultipleFiles({ 'src/app/app.component.ts': origContent }); break; case 2: // The second build should have everything fixed. expect(buildEvent.success).toBe(true); break; } }), take(2), ) .toPromise(); await run.stop(); }); it('rebuilds after errors in AOT', async () => { // Save the original contents of `./src/app/app.component.ts`. const origContent = virtualFs.fileBufferToString( host.scopedSync().read(normalize('src/app/app.component.ts')), ); // Add a major static analysis error on a non-main file to the initial build. host.replaceInFile('./src/app/app.component.ts', `'app-root'`, `(() => 'app-root')()`); // `selector must be a string` errors on VE are part of the emit result, but on Ivy they only // show up in getNgSemanticDiagnostics. Since getNgSemanticDiagnostics is only called on the // type checker, we must disable it to get a failing fourth build with Ivy. const overrides = { watch: true, aot: true }; const logger = new logging.Logger(''); let logs: string[] = []; logger.subscribe((e) => logs.push(e.message)); const staticAnalysisError = 'selector must be a string'; const syntaxError = 'Declaration or statement expected.'; let buildNumber = 0; const run = await architect.scheduleTarget(target, overrides, { logger }); await run.output .pipe( timeout(BUILD_TIMEOUT), debounceTime(rebuildDebounceTime), tap((buildEvent) => { buildNumber += 1; switch (buildNumber) { case 1: // The first build should error out with a static analysis error. expect(buildEvent.success).toBe(false, 'First build should not succeed.'); expect(logs.join().includes(staticAnalysisError)).toBe( true, 'First build should have static analysis error.', ); logs = []; // Fix the static analysis error. host.writeMultipleFiles({ 'src/app/app.component.ts': origContent }); break; case 2: expect(buildEvent.success).toBe(true, 'Second build should succeed.'); expect(logs.join().includes(staticAnalysisError)).toBe( false, 'Second build should not have static analysis error.', ); logs = []; // Add an syntax error to a non-main file. host.appendToFile('src/app/app.component.ts', `]]]`); break; case 3: // The third build should have TS syntax error. expect(buildEvent.success).toBe(false, 'Third build should not succeed.'); expect(logs.join().includes(syntaxError)).toBe( true, 'Third build should have syntax analysis error.', ); expect(logs.join().includes(staticAnalysisError)).toBe( false, 'Third build should not have static analysis error.', ); logs = []; // Fix the syntax error, but add the static analysis error again. host.writeMultipleFiles({ 'src/app/app.component.ts': origContent.replace( `'app-root'`, `(() => 'app-root')()`, ), }); break; case 4: expect(buildEvent.success).toBe(false, 'Fourth build should not succeed.'); expect(logs.join().includes(syntaxError)).toBe( false, 'Fourth build should not have syntax analysis error.', ); expect(logs.join().includes(staticAnalysisError)).toBe( true, 'Fourth build should have static analysis error.', ); logs = []; // Restore the file to a error-less state. host.writeMultipleFiles({ 'src/app/app.component.ts': origContent }); break; case 5: // The fifth build should have everything fixed.. expect(buildEvent.success).toBe(true, 'Fifth build should succeed.'); expect(logs.join().includes(syntaxError)).toBe( false, 'Fifth build should not have syntax analysis error.', ); expect(logs.join().includes(staticAnalysisError)).toBe( false, 'Fifth build should not have static analysis error.', ); break; } }), take(5), ) .toPromise(); await run.stop(); });
{ "end_byte": 15715, "start_byte": 8935, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/rebuild_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/rebuild_spec.ts_15719_22155
it('rebuilds AOT factories', async () => { host.writeMultipleFiles({ 'src/app/app.component.css': ` @import './imported-styles.css'; body {background-color: #00f;} `, 'src/app/imported-styles.css': 'p {color: #f00;}', }); const overrides = { watch: true, aot: true }; let buildNumber = 0; const run = await architect.scheduleTarget(target, overrides); await run.output .pipe( timeout(BUILD_TIMEOUT), debounceTime(rebuildDebounceTime), tap((buildEvent) => { buildNumber += 1; const fileName = './dist/main.js'; let content; switch (buildNumber) { case 1: // Trigger a few rebuilds first. // The AOT compiler is still optimizing rebuilds on the first rebuilds. expect(buildEvent.success).toBe(true); host.appendToFile('src/main.ts', 'console.log(1);'); break; case 2: expect(buildEvent.success).toBe(true); host.appendToFile('src/main.ts', 'console.log(1);'); break; case 3: // Change the component html. expect(buildEvent.success).toBe(true); host.appendToFile('src/app/app.component.html', '<p>HTML_REBUILD_STRING<p>'); break; case 4: // Check if html changes are added to factories. expect(buildEvent.success).toBe(true); content = virtualFs.fileBufferToString(host.scopedSync().read(normalize(fileName))); expect(content).toContain('HTML_REBUILD_STRING'); // Change the component css. host.appendToFile('src/app/app.component.css', 'CSS_REBUILD_STRING {color: #f00;}'); break; case 5: // Check if css changes are added to factories. expect(buildEvent.success).toBe(true); content = virtualFs.fileBufferToString(host.scopedSync().read(normalize(fileName))); expect(content).toContain('CSS_REBUILD_STRING'); // Change the component css import. host.appendToFile( 'src/app/imported-styles.css', 'CSS_DEP_REBUILD_STRING {color: #f00;}', ); break; case 6: // Check if css import changes are added to factories. expect(buildEvent.success).toBe(true); content = virtualFs.fileBufferToString(host.scopedSync().read(normalize(fileName))); expect(content).toContain('CSS_DEP_REBUILD_STRING'); // Change the component itself. host.replaceInFile( 'src/app/app.component.ts', 'app-root', 'app-root-FACTORY_REBUILD_STRING', ); break; case 7: // Check if component changes are added to factories. expect(buildEvent.success).toBe(true); content = virtualFs.fileBufferToString(host.scopedSync().read(normalize(fileName))); expect(content).toContain('FACTORY_REBUILD_STRING'); break; } }), take(7), ) .toPromise(); await run.stop(); }); it('rebuilds on changes in barrel file dependency', async () => { host.writeMultipleFiles({ 'src/index.ts': `export * from './interface'`, 'src/interface.ts': `export interface Foo { bar: boolean };`, }); host.appendToFile( 'src/main.ts', ` import { Foo } from './index'; const x: Foo = { bar: true }; `, ); const overrides = { watch: true, aot: false }; let buildNumber = 0; const run = await architect.scheduleTarget(target, overrides); await run.output .pipe( timeout(BUILD_TIMEOUT), debounceTime(rebuildDebounceTime), tap((buildEvent) => { buildNumber += 1; switch (buildNumber) { case 1: expect(buildEvent.success).toBe(true); host.writeMultipleFiles({ 'src/interface.ts': `export interface Foo { bar: boolean; baz?: string; };`, }); break; case 2: expect(buildEvent.success).toBe(true); break; } }), take(2), ) .toPromise(); await run.stop(); }); it('rebuilds AOT on CSS changes', async () => { const overrides = { watch: true, aot: true }; let buildCount = 1; const run = await architect.scheduleTarget(target, overrides); await run.output .pipe( debounceTime(rebuildDebounceTime), tap(() => { const content = virtualFs.fileBufferToString( host.scopedSync().read(join(outputPath, 'main.js')), ); switch (buildCount) { case 1: expect(content).not.toContain('color: green'); host.appendToFile('src/app/app.component.css', 'h1 { color: green; }'); break; case 2: expect(content).toContain('color: green'); break; } buildCount++; }), tap((buildEvent) => expect(buildEvent.success).toBe(true)), take(2), ) .toPromise(); await run.stop(); }); it('rebuilds AOT on HTML changes', async () => { const overrides = { watch: true, aot: true }; let buildCount = 1; const run = await architect.scheduleTarget(target, overrides); await run.output .pipe( timeout(BUILD_TIMEOUT), debounceTime(rebuildDebounceTime), tap(() => { const content = virtualFs.fileBufferToString( host.scopedSync().read(join(outputPath, 'main.js')), ); switch (buildCount) { case 1: expect(content).not.toContain('New Updated Content'); host.appendToFile('src/app/app.component.html', 'New Updated Content'); break; case 2: expect(content).toContain('New Updated Content'); break; } buildCount++; }), tap((buildEvent) => expect(buildEvent.success).toBe(true)), take(2), ) .toPromise(); await run.stop(); }); });
{ "end_byte": 22155, "start_byte": 15719, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/rebuild_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/source-map_spec.ts_0_5543
/** * @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.dev/license */ import { Architect } from '@angular-devkit/architect'; import { OutputHashing } from '@angular-devkit/build-angular'; import { browserBuild, createArchitect, host } from '../../../testing/test-utils'; describe('Browser Builder source map', () => { const target = { project: 'app', target: 'build' }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(async () => host.restore().toPromise()); it('works', async () => { const overrides = { sourceMap: true, styles: ['src/styles.css'], }; host.writeMultipleFiles({ 'src/styles.css': `div { flex: 1 }`, }); const { files } = await browserBuild(architect, host, target, overrides); expect(await files['main.js.map']).not.toBeUndefined(); expect(await files['styles.css.map']).not.toBeUndefined(); }); it(`sourcemaps sources should not start with '/'`, async () => { // If sourcemaps sources start with a '/' it will break VS code breakpoints // Unless 'sourceMapPathOverrides' are provided const overrides = { sourceMap: true, }; const { files } = await browserBuild(architect, host, target, overrides); const mainJSMap = await files['main.js.map']; expect(mainJSMap).not.toBeUndefined(); const sources: string[] = JSON.parse(mainJSMap).sources; for (const source of sources) { expect(source.startsWith('/')).toBe(false, `${source} started with an '/'.`); } }); it('works with outputHashing', async () => { const { files } = await browserBuild(architect, host, target, { sourceMap: true, outputHashing: OutputHashing.All, }); expect(Object.keys(files).some((name) => /main\.[0-9a-f]{16}\.js.map/.test(name))).toBeTruthy(); }); it('does not output source map when disabled', async () => { const { files } = await browserBuild(architect, host, target, { sourceMap: false, }); expect(files['main.js.map']).toBeUndefined(); }); it('supports hidden sourcemaps', async () => { const overrides = { sourceMap: { hidden: true, styles: true, scripts: true, }, styles: ['src/styles.scss'], }; host.writeMultipleFiles({ 'src/styles.scss': `div { flex: 1 }`, }); const { files } = await browserBuild(architect, host, target, overrides); expect('main.js.map' in files).toBe(true); expect('styles.css.map' in files).toBe(true); expect(await files['main.js']).not.toContain('sourceMappingURL=main.js.map'); expect(await files['styles.css']).not.toContain('sourceMappingURL=styles.css.map'); }); it('supports styles only sourcemaps', async () => { const overrides = { sourceMap: { styles: true, scripts: false, }, styles: ['src/styles.scss'], }; host.writeMultipleFiles({ 'src/styles.scss': `div { flex: 1 }`, }); const { files } = await browserBuild(architect, host, target, overrides); expect('main.js.map' in files).toBe(false); expect('styles.css.map' in files).toBe(true); expect(await files['main.js']).not.toContain('sourceMappingURL=main.js.map'); expect(await files['styles.css']).toContain('sourceMappingURL=styles.css.map'); }); it('supports scripts only sourcemaps', async () => { const overrides = { sourceMap: { styles: false, scripts: true, }, styles: ['src/styles.scss'], }; host.writeMultipleFiles({ 'src/styles.scss': `div { flex: 1 }`, }); const { files } = await browserBuild(architect, host, target, overrides); expect('main.js.map' in files).toBe(true); expect('styles.css.map' in files).toBe(false); expect(await files['main.js']).toContain('sourceMappingURL=main.js.map'); expect(await files['styles.css']).not.toContain('sourceMappingURL=styles.css.map'); }); it('should not inline component styles sourcemaps when hidden', async () => { const overrides = { sourceMap: { hidden: true, styles: true, scripts: true, }, styles: ['src/styles.scss'], }; host.writeMultipleFiles({ 'src/styles.scss': `div { flex: 1 }`, 'src/app/app.component.css': `p { color: red; }`, }); const { files } = await browserBuild(architect, host, target, overrides); expect('main.js.map' in files).toBe(true); expect('styles.css.map' in files).toBe(true); expect(await files['main.js']).not.toContain('sourceMappingURL=main.js.map'); expect(await files['main.js']).not.toContain('sourceMappingURL=data:application/json'); expect(await files['styles.css']).not.toContain('sourceMappingURL=styles.css.map'); expect(await files['styles.css']).not.toContain('sourceMappingURL=data:application/json'); }); it('should resolve sources to partial SCSS files', async () => { const overrides = { sourceMap: true, styles: ['src/styles.scss'], }; host.writeMultipleFiles({ 'src/styles.scss': `@import './partial';`, 'src/_partial.scss': `p { color: red; }`, }); const { files } = await browserBuild(architect, host, target, overrides); expect(await files['styles.css.map']).toContain('_partial.scss'); }); });
{ "end_byte": 5543, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/source-map_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/vendor-chunk_spec.ts_0_840
/** * @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.dev/license */ import { Architect } from '@angular-devkit/architect'; import { browserBuild, createArchitect, host } from '../../../testing/test-utils'; describe('Browser Builder vendor chunk', () => { const target = { project: 'app', target: 'build' }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(async () => host.restore().toPromise()); it('works', async () => { const { files } = await browserBuild(architect, host, target, { vendorChunk: true }); expect('vendor.js' in files).toBe(true); }); });
{ "end_byte": 840, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/vendor-chunk_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/unused-files-warning_spec.ts_0_8260
/** * @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.dev/license */ import { Architect } from '@angular-devkit/architect'; import { BrowserBuilderOutput } from '@angular-devkit/build-angular'; import { logging } from '@angular-devkit/core'; import { debounceTime, take, tap } from 'rxjs'; import { createArchitect, host } from '../../../testing/test-utils'; describe('Browser Builder unused files warnings', () => { const warningMessageSuffix = `is part of the TypeScript compilation but it's unused`; const targetSpec = { project: 'app', target: 'build' }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(async () => host.restore().toPromise()); it('should not show warning when all files are used', async () => { const logger = new logging.Logger(''); const logs: string[] = []; logger.subscribe((e) => logs.push(e.message)); const run = await architect.scheduleTarget(targetSpec, undefined, { logger }); const output = (await run.result) as BrowserBuilderOutput; expect(output.success).toBe(true); expect(logs.join().includes(warningMessageSuffix)).toBe(false); await run.stop(); }); it('should show warning when some files are unused', async () => { host.writeMultipleFiles({ 'src/unused-file.ts': `export const unused = '1';`, }); host.replaceInFile('src/tsconfig.app.json', '"main.ts"', '"main.ts", "unused-file.ts"'); const logger = new logging.Logger(''); const logs: string[] = []; logger.subscribe((e) => logs.push(e.message)); const run = await architect.scheduleTarget(targetSpec, undefined, { logger }); const output = (await run.result) as BrowserBuilderOutput; expect(output.success).toBe(true); expect(logs.join().includes(`unused-file.ts ${warningMessageSuffix}`)).toBe(true); await run.stop(); }); it('should not show warning when excluded files are unused', async () => { const ignoredFiles = { 'src/file.d.ts': 'export type MyType = number;', }; host.writeMultipleFiles(ignoredFiles); host.replaceInFile( 'src/tsconfig.app.json', '"main.ts"', `"main.ts", ${Object.keys(ignoredFiles) .map((f) => `"${f.replace('src/', '')}"`) .join(',')}`, ); host.replaceInFile( 'src/tsconfig.app.json', '"compilerOptions":', '"angularCompilerOptions": { "strictTemplates": true }, "compilerOptions":', ); const logger = new logging.Logger(''); const logs: string[] = []; logger.subscribe((e) => logs.push(e.message)); const run = await architect.scheduleTarget(targetSpec, { aot: true }, { logger }); const output = (await run.result) as BrowserBuilderOutput; expect(output.success).toBe(true); expect(logs.join().includes(warningMessageSuffix)).toBe(false); await run.stop(); }); it('should not show warning when type files are used', async () => { host.writeMultipleFiles({ 'src/app/type.ts': 'export type MyType = number;', }); host.replaceInFile( 'src/app/app.component.ts', `'@angular/core';`, `'@angular/core';\nimport { MyType } from './type';\n`, ); const logger = new logging.Logger(''); const logs: string[] = []; logger.subscribe((e) => logs.push(e.message)); const run = await architect.scheduleTarget(targetSpec, undefined, { logger }); const output = (await run.result) as BrowserBuilderOutput; expect(output.success).toBe(true); expect(logs.join().includes(warningMessageSuffix)).toBe(false); await run.stop(); }); it('should not show warning when type files are used transitively', async () => { host.writeMultipleFiles({ 'src/app/type.ts': `import {Myinterface} from './interface'; export type MyType = Myinterface;`, 'src/app/interface.ts': 'export interface Myinterface {nbr: number;}', }); host.replaceInFile( 'src/app/app.component.ts', `'@angular/core';`, `'@angular/core';\nimport { MyType } from './type';\n`, ); const logger = new logging.Logger(''); const logs: string[] = []; logger.subscribe((e) => logs.push(e.message)); const run = await architect.scheduleTarget(targetSpec, undefined, { logger }); const output = (await run.result) as BrowserBuilderOutput; expect(output.success).toBe(true); expect(logs.join().includes(warningMessageSuffix)).toBe(false); await run.stop(); }); it('works for rebuilds', async () => { host.replaceInFile('src/tsconfig.app.json', '"**/*.d.ts"', '"**/*.d.ts", "testing/**/*.ts"'); const logger = new logging.Logger(''); let logs: string[] = []; logger.subscribe((e) => logs.push(e.message)); let buildNumber = 0; const run = await architect.scheduleTarget(targetSpec, { watch: true }, { logger }); await run.output .pipe( debounceTime(1000), tap((buildEvent) => { expect(buildEvent.success).toBe(true); buildNumber++; switch (buildNumber) { case 1: // The first should not have unused files expect(logs.join().includes(warningMessageSuffix)).toBe( false, `Case ${buildNumber} failed.`, ); // Write a used file host.writeMultipleFiles({ 'src/testing/type.ts': 'export type MyType = number;', }); // touch file to trigger build host.replaceInFile( 'src/app/app.component.ts', `'@angular/core';`, `'@angular/core';\n`, ); break; case 2: // The second should have type.ts as unused expect(logs.join().includes(`type.ts ${warningMessageSuffix}`)).toBe( true, `Case ${buildNumber} failed.`, ); host.replaceInFile( 'src/app/app.component.ts', `'@angular/core';`, `'@angular/core';\nimport { MyType } from '../testing/type';`, ); break; case 3: // The third should not have any unused files expect(logs.join().includes(warningMessageSuffix)).toBe( false, `Case ${buildNumber} failed.`, ); break; } logs = []; }), take(3), ) .toPromise(); await run.stop(); }); it('should only show warning once per file', async () => { host.replaceInFile('src/tsconfig.app.json', '"**/*.d.ts"', '"**/*.d.ts", "testing/**/*.ts"'); // Write a used file host.writeMultipleFiles({ 'src/testing/type.ts': 'export type MyType = number;', }); const logger = new logging.Logger(''); let logs: string[] = []; logger.subscribe((e) => logs.push(e.message)); let buildNumber = 0; const run = await architect.scheduleTarget(targetSpec, { watch: true }, { logger }); await run.output .pipe( debounceTime(1000), tap((buildEvent) => { expect(buildEvent.success).toBe(true); buildNumber++; switch (buildNumber) { case 1: // The first should have type.ts as unused. expect(logs.join().includes(`type.ts ${warningMessageSuffix}`)).toBe( true, `Case ${buildNumber} failed.`, ); // touch a file to trigger a rebuild host.appendToFile('src/main.ts', ''); break; case 2: // The second should should have type.ts as unused but shouldn't warn. expect(logs.join().includes(warningMessageSuffix)).toBe( false, `Case ${buildNumber} failed.`, ); break; } logs = []; }), take(2), ) .toPromise(); await run.stop(); }); });
{ "end_byte": 8260, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/unused-files-warning_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/vendor-source-map_spec.ts_0_4852
/** * @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.dev/license */ import { Architect } from '@angular-devkit/architect'; import * as path from 'path'; import { browserBuild, createArchitect, host } from '../../../testing/test-utils'; // Following the naming conventions from // https://sourcemaps.info/spec.html#h.ghqpj1ytqjbm const IGNORE_LIST = 'x_google_ignoreList'; describe('Browser Builder external source map', () => { const target = { project: 'app', target: 'build' }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(async () => host.restore().toPromise()); it('works', async () => { const overrides = { sourceMap: { scripts: true, styles: true, vendor: true, }, }; const { files } = await browserBuild(architect, host, target, overrides); const sourcePaths: string[] = JSON.parse(await files['vendor.js.map']).sources; const hasTsSourcePaths = sourcePaths.some((p) => path.extname(p) == '.ts'); expect(hasTsSourcePaths).toBe(true, `vendor.js.map should have '.ts' extentions`); }); it('does not map sourcemaps from external library when disabled', async () => { const overrides = { sourceMap: { scripts: true, styles: true, vendor: false, }, }; const { files } = await browserBuild(architect, host, target, overrides); const sourcePaths: string[] = JSON.parse(await files['vendor.js.map']).sources; const hasTsSourcePaths = sourcePaths.some((p) => path.extname(p) == '.ts'); expect(hasTsSourcePaths).toBe(false, `vendor.js.map not should have '.ts' extentions`); }); }); describe('Identifying third-party code in source maps', () => { interface SourceMap { sources: string[]; [IGNORE_LIST]: number[]; } const target = { project: 'app', target: 'build' }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(async () => host.restore().toPromise()); it('specifies which sources are third party when vendor processing is disabled', async () => { const overrides = { sourceMap: { scripts: true, vendor: false, }, }; const { files } = await browserBuild(architect, host, target, overrides); const mainMap: SourceMap = JSON.parse(await files['main.js.map']); const polyfillsMap: SourceMap = JSON.parse(await files['polyfills.js.map']); const runtimeMap: SourceMap = JSON.parse(await files['runtime.js.map']); const vendorMap: SourceMap = JSON.parse(await files['vendor.js.map']); expect(mainMap[IGNORE_LIST]).not.toBeUndefined(); expect(polyfillsMap[IGNORE_LIST]).not.toBeUndefined(); expect(runtimeMap[IGNORE_LIST]).not.toBeUndefined(); expect(vendorMap[IGNORE_LIST]).not.toBeUndefined(); expect(mainMap[IGNORE_LIST].length).toEqual(0); expect(polyfillsMap[IGNORE_LIST].length).not.toEqual(0); expect(runtimeMap[IGNORE_LIST].length).not.toEqual(0); expect(vendorMap[IGNORE_LIST].length).not.toEqual(0); const thirdPartyInMain = mainMap.sources.some((s) => s.includes('node_modules')); const thirdPartyInPolyfills = polyfillsMap.sources.some((s) => s.includes('node_modules')); const thirdPartyInRuntime = runtimeMap.sources.some((s) => s.includes('webpack')); const thirdPartyInVendor = vendorMap.sources.some((s) => s.includes('node_modules')); expect(thirdPartyInMain).toBe(false, `main.js.map should not include any node modules`); expect(thirdPartyInPolyfills).toBe(true, `polyfills.js.map should include some node modules`); expect(thirdPartyInRuntime).toBe(true, `runtime.js.map should include some webpack code`); expect(thirdPartyInVendor).toBe(true, `vendor.js.map should include some node modules`); // All sources in the main map are first-party. expect(mainMap.sources.filter((_, i) => !mainMap[IGNORE_LIST].includes(i))).toEqual([ './src/app/app.component.ts', './src/app/app.module.ts', './src/main.ts', './src/app/app.component.css', ]); // Only some sources in the polyfills map are first-party. expect(polyfillsMap.sources.filter((_, i) => !polyfillsMap[IGNORE_LIST].includes(i))).toEqual([ './src/polyfills.ts', ]); // None of the sources in the runtime and vendor maps are first-party. expect(runtimeMap.sources.filter((_, i) => !runtimeMap[IGNORE_LIST].includes(i))).toEqual([]); expect(vendorMap.sources.filter((_, i) => !vendorMap[IGNORE_LIST].includes(i))).toEqual([]); }); });
{ "end_byte": 4852, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/vendor-source-map_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/resolve-json-module_spec.ts_0_1959
/** * @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.dev/license */ import { Architect } from '@angular-devkit/architect'; import { join, virtualFs } from '@angular-devkit/core'; import { take, tap } from 'rxjs'; import { createArchitect, host, outputPath } from '../../../testing/test-utils'; describe('Browser Builder resolve json module', () => { const target = { project: 'app', target: 'build' }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(async () => host.restore().toPromise()); it('works with watch', async () => { host.writeMultipleFiles({ 'src/my-json-file.json': `{"foo": "1"}`, 'src/main.ts': `import * as a from './my-json-file.json'; console.log(a);`, }); host.replaceInFile( 'tsconfig.json', '"target": "es2022"', '"target": "es2022", "resolveJsonModule": true', ); const overrides = { watch: true }; let buildCount = 1; const run = await architect.scheduleTarget(target, overrides); await run.output .pipe( tap(() => { const content = virtualFs.fileBufferToString( host.scopedSync().read(join(outputPath, 'main.js')), ); switch (buildCount) { case 1: expect(content).toContain('"foo":"1"'); host.writeMultipleFiles({ 'src/my-json-file.json': `{"foo": "2"}`, }); break; case 2: expect(content).toContain('"foo":"2"'); break; } buildCount++; }), tap((buildEvent) => expect(buildEvent.success).toBe(true)), take(2), ) .toPromise(); await run.stop(); }); });
{ "end_byte": 1959, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/resolve-json-module_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/base-href_spec.ts_0_2950
/** * @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.dev/license */ import { Architect } from '@angular-devkit/architect'; import { BrowserBuilderOutput } from '@angular-devkit/build-angular'; import { join, normalize, tags, virtualFs } from '@angular-devkit/core'; import { lastValueFrom } from 'rxjs'; import { createArchitect, host } from '../../../testing/test-utils'; describe('Browser Builder base href', () => { const targetSpec = { project: 'app', target: 'build' }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(async () => host.restore().toPromise()); it('works', async () => { host.writeMultipleFiles({ 'src/my-js-file.js': `console.log(1); export const a = 2;`, 'src/main.ts': `import { a } from './my-js-file'; console.log(a);`, }); const overrides = { baseHref: '/myUrl' }; const run = await architect.scheduleTarget(targetSpec, overrides); const output = (await run.result) as BrowserBuilderOutput; expect(output.success).toBe(true); const fileName = join(normalize(output.outputs[0].path), 'index.html'); const content = virtualFs.fileBufferToString(await lastValueFrom(host.read(fileName))); expect(content).toMatch(/<base href="\/myUrl">/); await run.stop(); }); it('should not override base href in HTML when option is not set', async () => { host.writeMultipleFiles({ 'src/index.html': ` <html> <head><base href="."></head> <body></body> </html> `, }); const run = await architect.scheduleTarget(targetSpec); const output = (await run.result) as BrowserBuilderOutput; expect(output.success).toBeTrue(); const fileName = join(normalize(output.outputs[0].path), 'index.html'); const content = virtualFs.fileBufferToString(await lastValueFrom(host.read(fileName))); expect(content).toContain(`<base href=".">`); await run.stop(); }); it('should insert base href in the correct position', async () => { host.writeMultipleFiles({ 'src/index.html': tags.oneLine` <html><head><meta charset="UTF-8"></head> <body><app-root></app-root></body></html> `, }); const overrides = { baseHref: '/myUrl' }; const run = await architect.scheduleTarget(targetSpec, overrides); const output = (await run.result) as BrowserBuilderOutput; expect(output.success).toBe(true); const fileName = join(normalize(output.outputs[0].path), 'index.html'); const content = virtualFs.fileBufferToString( await lastValueFrom(host.read(normalize(fileName))), ); expect(content).toContain('<head><base href="/myUrl"><meta charset="UTF-8">'); await run.stop(); }); });
{ "end_byte": 2950, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/base-href_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/stats-json_spec.ts_0_1152
/** * @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.dev/license */ import { Architect } from '@angular-devkit/architect'; import { browserBuild, createArchitect, host } from '../../../testing/test-utils'; describe('Browser Builder stats json', () => { const target = { project: 'app', target: 'build' }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(async () => host.restore().toPromise()); it('works', async () => { const { files } = await browserBuild(architect, host, target, { statsJson: true }); expect('stats.json' in files).toBe(true); }); it('works with profile flag', async () => { const { files } = await browserBuild(architect, host, target, { statsJson: true }); expect('stats.json' in files).toBe(true); const stats = JSON.parse(await files['stats.json']); expect(stats.chunks[0].modules[0].profile.building).toBeDefined(); }); });
{ "end_byte": 1152, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/stats-json_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/web-worker_spec.ts_0_6566
/** * @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.dev/license */ import { Architect } from '@angular-devkit/architect'; import { join, logging, virtualFs } from '@angular-devkit/core'; import { debounceTime, lastValueFrom, map, switchMap, takeWhile, tap, timer } from 'rxjs'; import { browserBuild, createArchitect, host, outputPath } from '../../../testing/test-utils'; describe('Browser Builder Web Worker support', () => { const target = { project: 'app', target: 'build' }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(async () => host.restore().toPromise()); const workerFiles: { [k: string]: string } = { 'src/app/dep.ts': `export const foo = 'bar';`, 'src/app/app.worker.ts': ` /// <reference lib="webworker" /> import { foo } from './dep'; console.log('hello from worker'); addEventListener('message', ({ data }) => { console.log('worker got message:', data); if (data === 'hello') { postMessage(foo); } }); `, 'src/main.ts': ` import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; platformBrowserDynamic().bootstrapModule(AppModule).catch(err => console.error(err)); const worker = new Worker(new URL('./app/app.worker', import.meta.url), { type: 'module' }); worker.onmessage = ({ data }) => { console.log('page got message:', data); }; worker.postMessage('hello'); `, // Make a new tsconfig for the *.worker.ts files. // The final place for this tsconfig must take into consideration editor tooling, unit // tests, and integration with other build targets. './src/tsconfig.worker.json': ` { "extends": "../tsconfig.json", "compilerOptions": { "outDir": "../out-tsc/worker", "lib": [ "es2018", "webworker" ], "types": [] }, "include": [ "**/*.worker.ts", ] }`, // Alter the app tsconfig to not include *.worker.ts files. './src/tsconfig.app.json': ` { "extends": "../tsconfig.json", "compilerOptions": { "outDir": "../out-tsc/worker", "types": [] }, "files": [ "main.ts", "polyfills.ts" ] }`, }; it('bundles TS worker', async () => { host.writeMultipleFiles(workerFiles); const logger = new logging.Logger(''); const logs: string[] = []; logger.subscribe((e) => logs.push(e.message)); const overrides = { webWorkerTsConfig: 'src/tsconfig.worker.json' }; await browserBuild(architect, host, target, overrides, { logger }); // Worker bundle contains worker code. const workerContent = virtualFs.fileBufferToString( host.scopedSync().read(join(outputPath, 'src_app_app_worker_ts.js')), ); expect(workerContent).toContain('hello from worker'); expect(workerContent).toContain('bar'); // Main bundle references worker. const mainContent = virtualFs.fileBufferToString( host.scopedSync().read(join(outputPath, 'main.js')), ); expect(mainContent).toContain('src_app_app_worker_ts'); expect(logs.join().includes('Warning')).toBe(false, 'Should show no warnings.'); }); it('minimizes and hashes worker', async () => { host.writeMultipleFiles(workerFiles); const overrides = { webWorkerTsConfig: 'src/tsconfig.worker.json', outputHashing: 'all', optimization: true, }; await browserBuild(architect, host, target, overrides); // Worker bundle should have hash and minified code. const workerBundle = host.fileMatchExists( outputPath, /src_app_app_worker_ts\.[0-9a-f]{16}\.js/, ) as string; expect(workerBundle).toBeTruthy('workerBundle should exist'); const workerContent = virtualFs.fileBufferToString( host.scopedSync().read(join(outputPath, workerBundle)), ); expect(workerContent).toContain('hello from worker'); expect(workerContent).toContain('bar'); expect(workerContent).toContain('"hello"===e&&postMessage'); // Main bundle should reference hashed worker bundle. const mainBundle = host.fileMatchExists(outputPath, /main\.[0-9a-f]{16}\.js/) as string; expect(mainBundle).toBeTruthy('mainBundle should exist'); const mainContent = virtualFs.fileBufferToString( host.scopedSync().read(join(outputPath, mainBundle)), ); expect(mainContent).toContain('src_app_app_worker_ts'); }); it('rebuilds TS worker', async () => { host.writeMultipleFiles(workerFiles); const overrides = { webWorkerTsConfig: 'src/tsconfig.worker.json', watch: true, }; let phase = 1; const workerPath = join(outputPath, 'src_app_app_worker_ts.js'); let workerContent = ''; // The current linux-based CI environments may not fully settled in regards to filesystem // changes from previous tests which reuse the same directory and fileset. // The initial delay helps mitigate false positive rebuild triggers in such scenarios. const { run } = await lastValueFrom( timer(1000).pipe( switchMap(() => architect.scheduleTarget(target, overrides)), switchMap((run) => run.output.pipe(map((output) => ({ run, output })))), debounceTime(1000), tap(({ output }) => expect(output.success).toBe(true, 'build should succeed')), tap(() => { switch (phase) { case 1: // Original worker content should be there. workerContent = virtualFs.fileBufferToString(host.scopedSync().read(workerPath)); expect(workerContent).toContain('bar'); // Change content of worker dependency. host.writeMultipleFiles({ 'src/app/dep.ts': `export const foo = 'baz';` }); phase = 2; break; case 2: workerContent = virtualFs.fileBufferToString(host.scopedSync().read(workerPath)); // Worker content should have changed. expect(workerContent).toContain('baz'); phase = 3; break; } }), takeWhile(() => phase < 3), ), ); await run.stop(); }); });
{ "end_byte": 6566, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/web-worker_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/output-path_spec.ts_0_3227
/** * @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.dev/license */ import { Architect } from '@angular-devkit/architect'; import { getSystemPath, join, virtualFs } from '@angular-devkit/core'; import * as fs from 'fs'; import { browserBuild, createArchitect, host } from '../../../testing/test-utils'; describe('Browser Builder output path', () => { const target = { project: 'app', target: 'build' }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(async () => host.restore().toPromise()); it('deletes output path content', async () => { // Write a file to the output path to later verify it was deleted. await host .write(join(host.root(), 'dist/file.txt'), virtualFs.stringToFileBuffer('file')) .toPromise(); // Delete an app file to force a failed compilation. // Failed compilations still delete files, but don't output any. await host.delete(join(host.root(), 'src', 'app', 'app.component.ts')).toPromise(); const run = await architect.scheduleTarget(target); const output = await run.result; expect(output.success).toBe(false); expect(await host.exists(join(host.root(), 'dist/file.txt')).toPromise()).toBe(false); await run.stop(); }); it('deletes output path content and unlink symbolic link', async () => { // Write a file to the output path to later verify it was deleted. host.writeMultipleFiles({ 'src-link/a.txt': '', 'dist/file.txt': virtualFs.stringToFileBuffer('file'), }); const distLinked = join(host.root(), 'dist', 'linked'); // create symbolic link fs.symlinkSync( getSystemPath(join(host.root(), 'src-link')), getSystemPath(distLinked), 'junction', ); expect(await host.exists(distLinked).toPromise()).toBe(true); // Delete an app file to force a failed compilation. // Failed compilations still delete files, but don't output any. await host.delete(join(host.root(), 'src', 'app', 'app.component.ts')).toPromise(); const run = await architect.scheduleTarget(target); const output = await run.result; expect(output.success).toBe(false); expect(await host.exists(join(host.root(), 'dist/file.txt')).toPromise()).toBe(false); expect(await host.exists(join(host.root(), 'src-link/a.txt')).toPromise()).toBe(true); await run.stop(); }); it('does not allow output path to be project root', async () => { const overrides = { outputPath: './' }; const run = await architect.scheduleTarget(target, overrides); try { await run.result; expect('THE ABOVE LINE SHOULD THROW').toBe(''); } catch {} await run.stop(); }); it('works with absolute outputPath', async () => { const overrides = { outputPath: getSystemPath(join(host.root(), 'dist')), }; const { files } = await browserBuild(architect, host, target, overrides); expect('main.js' in files).toBe(true); expect('index.html' in files).toBe(true); }); });
{ "end_byte": 3227, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/output-path_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/build-optimizer_spec.ts_0_2853
/** * @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.dev/license */ import { Architect } from '@angular-devkit/architect'; import { BrowserBuilderOutput } from '@angular-devkit/build-angular'; import { join, normalize } from '@angular-devkit/core'; import { lastValueFrom } from 'rxjs'; import { browserBuild, createArchitect, host } from '../../../testing/test-utils'; describe('Browser Builder build optimizer', () => { const targetSpec = { project: 'app', target: 'build' }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(async () => host.restore().toPromise()); it('works', async () => { const overrides = { aot: true, buildOptimizer: true }; const { files } = await browserBuild(architect, host, targetSpec, overrides); expect(await files['main.js']).not.toMatch(/\.decorators =/); }); it('fails if AOT is disabled', async () => { const overrides = { aot: false, buildOptimizer: true }; const run = await architect.scheduleTarget(targetSpec, overrides); await expectAsync(run.result).toBeRejectedWithError(); await run.stop(); }); it('reduces bundle size', async () => { const noBoOverrides = { aot: true, optimization: true, vendorChunk: false }; const boOverrides = { ...noBoOverrides, buildOptimizer: true }; const run = await architect.scheduleTarget(targetSpec, noBoOverrides); const output = (await run.result) as BrowserBuilderOutput; expect(output.success).toBe(true); const noBoStats = await lastValueFrom( host.stat(join(normalize(output.outputs[0].path), 'main.js')), ); if (!noBoStats) { throw new Error('Main file has no stats'); } const noBoSize = noBoStats.size; await run.stop(); const boRun = await architect.scheduleTarget(targetSpec, boOverrides); const boOutput = (await run.result) as BrowserBuilderOutput; expect(boOutput.success).toBe(true); const boStats = await lastValueFrom( host.stat(join(normalize(output.outputs[0].path), 'main.js')), ); if (!boStats) { throw new Error('Main file has no stats'); } const boSize = boStats.size; await boRun.stop(); const sizeDiff = Math.round(((boSize - noBoSize) / noBoSize) * 10000) / 100; if (sizeDiff > -1 && sizeDiff < 0) { throw new Error( 'Total size difference is too small, ' + 'build optimizer does not seem to have made any optimizations.', ); } if (sizeDiff > 1) { throw new Error( 'Total size difference is positive, ' + 'build optimizer made the bundle bigger.', ); } }); });
{ "end_byte": 2853, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/build-optimizer_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/font-optimization_spec.ts_0_2304
/** * @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.dev/license */ import { Architect } from '@angular-devkit/architect'; import { browserBuild, createArchitect, host } from '../../../testing/test-utils'; describe('Browser Builder font optimization', () => { const target = { project: 'app', target: 'build' }; const overrides = { optimization: { styles: false, fonts: true, }, }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; host.replaceInFile( '/src/index.html', '<head>', `<head><link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet">`, ); }); afterEach(async () => host.restore().toPromise()); it('works', async () => { const { files } = await browserBuild(architect, host, target, overrides); const html = await files['index.html']; expect(html).not.toContain('href="https://fonts.googleapis.com/css?family=Roboto:300,400,500"'); expect(html).toContain(`font-family: 'Roboto'`); }); it('should not add woff', async () => { const { files } = await browserBuild(architect, host, target, overrides); const html = await files['index.html']; expect(html).toContain(`format('woff2');`); expect(html).not.toContain(`format('woff');`); }); it('should remove comments and line breaks when styles optimization is true', async () => { const { files } = await browserBuild(architect, host, target, { optimization: { styles: true, fonts: true, }, }); const html = await files['index.html']; expect(html).not.toContain('/*'); expect(html).toContain(';font-style:normal;'); }); it('should not remove comments and line breaks when styles optimization is false', async () => { const { files } = await browserBuild(architect, host, target, { optimization: { styles: false, fonts: true, }, }); const html = await files['index.html']; expect(html).toContain('/*'); expect(html).toContain(' font-style: normal;\n'); }); });
{ "end_byte": 2304, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/font-optimization_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/tsconfig-paths_spec.ts_0_2316
/** * @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.dev/license */ import { Architect } from '@angular-devkit/architect'; import { browserBuild, createArchitect, host } from '../../../testing/test-utils'; describe('Browser Builder tsconfig paths', () => { const target = { project: 'app', target: 'build' }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(async () => host.restore().toPromise()); it('works', async () => { host.replaceInFile('src/app/app.module.ts', './app.component', '@root/app/app.component'); host.replaceInFile( 'tsconfig.json', /"baseUrl": ".\/",/, ` "baseUrl": "./", "paths": { "@root/*": [ "./src/*" ] }, `, ); await browserBuild(architect, host, target); }); it('works', async () => { host.writeMultipleFiles({ 'src/meaning-too.ts': 'export var meaning = 42;', 'src/app/shared/meaning.ts': 'export var meaning = 42;', 'src/app/shared/index.ts': `export * from './meaning'`, }); host.replaceInFile( 'tsconfig.json', /"baseUrl": ".\/",/, ` "baseUrl": "./", "paths": { "@shared": [ "src/app/shared" ], "@shared/*": [ "src/app/shared/*" ], "*": [ "*", "src/app/shared/*" ] }, `, ); host.appendToFile( 'src/app/app.component.ts', ` import { meaning } from 'src/app/shared/meaning'; import { meaning as meaning2 } from '@shared'; import { meaning as meaning3 } from '@shared/meaning'; import { meaning as meaning4 } from 'meaning'; import { meaning as meaning5 } from 'src/meaning-too'; // need to use imports otherwise they are ignored and // no error is outputted, even if baseUrl/paths don't work console.log(meaning) console.log(meaning2) console.log(meaning3) console.log(meaning4) console.log(meaning5) `, ); await browserBuild(architect, host, target); }); });
{ "end_byte": 2316, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/tsconfig-paths_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/works_spec.ts_0_1611
/** * @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.dev/license */ import { describeBuilder } from '../../../testing'; import { buildWebpackBrowser } from '../index'; const BROWSER_BUILDER_INFO = { name: '@angular-devkit/build-angular:browser', schemaPath: __dirname + '/../schema.json', }; describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { describe('basic test', () => { it('works', async () => { // Provide a target and options for builder execution harness.useTarget('build', { outputPath: 'dist', index: 'src/index.html', main: 'src/main.ts', polyfills: 'src/polyfills.ts', tsConfig: 'src/tsconfig.app.json', progress: false, vendorChunk: true, assets: ['src/favicon.ico', 'src/assets'], styles: ['src/styles.css'], scripts: [], }); // Execute builder with above provided project, target, and options await harness.executeOnce(); // Default files should be in outputPath. expect(harness.hasFile('dist/runtime.js')).toBeTrue(); expect(harness.hasFile('dist/main.js')).toBeTrue(); expect(harness.hasFile('dist/polyfills.js')).toBeTrue(); expect(harness.hasFile('dist/vendor.js')).toBeTrue(); expect(harness.hasFile('dist/favicon.ico')).toBeTrue(); expect(harness.hasFile('dist/styles.css')).toBeTrue(); expect(harness.hasFile('dist/index.html')).toBeTrue(); }); }); });
{ "end_byte": 1611, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/works_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/deploy-url_spec.ts_0_2534
/** * @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.dev/license */ import { Architect } from '@angular-devkit/architect'; import { BrowserBuilderOutput } from '@angular-devkit/build-angular'; import { join, normalize, virtualFs } from '@angular-devkit/core'; import { lastValueFrom } from 'rxjs'; import { createArchitect, host } from '../../../testing/test-utils'; describe('Browser Builder deploy url', () => { const targetSpec = { project: 'app', target: 'build' }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(async () => host.restore().toPromise()); it('uses deploy url for bundles urls and runtime', async () => { const overrides = { deployUrl: 'deployUrl/' }; const overrides2 = { deployUrl: 'http://example.com/some/path/' }; // Add lazy loaded chunk to provide a usage of the deploy URL // Webpack 5+ will not include the deploy URL in the code unless needed host.appendToFile('src/main.ts', '\nimport("./lazy");'); host.writeMultipleFiles({ 'src/lazy.ts': 'export const foo = "bar";', }); const run = await architect.scheduleTarget(targetSpec, overrides); const output = (await run.result) as BrowserBuilderOutput; expect(output.success).toBe(true); expect(output.outputs[0].path).not.toBeUndefined(); const outputPath = normalize(output.outputs[0].path); const fileName = join(outputPath, 'index.html'); const runtimeFileName = join(outputPath, 'runtime.js'); const content = virtualFs.fileBufferToString( await lastValueFrom(host.read(normalize(fileName))), ); expect(content).toContain('deployUrl/main.js'); const runtimeContent = virtualFs.fileBufferToString( await lastValueFrom(host.read(normalize(runtimeFileName))), ); expect(runtimeContent).toContain('deployUrl/'); const run2 = await architect.scheduleTarget(targetSpec, overrides2); const output2 = (await run2.result) as BrowserBuilderOutput; expect(output2.outputs[0].path).toEqual(outputPath); // These should be the same. const content2 = virtualFs.fileBufferToString( await lastValueFrom(host.read(normalize(fileName))), ); expect(content2).toContain('http://example.com/some/path/main.js'); await run.stop(); await run2.stop(); }); });
{ "end_byte": 2534, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/deploy-url_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/service-worker_spec.ts_0_442
/** * @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.dev/license */ import { Architect } from '@angular-devkit/architect'; import { join, normalize, virtualFs } from '@angular-devkit/core'; import { debounceTime, take, tap } from 'rxjs'; import { createArchitect, host } from '../../../testing/test-utils';
{ "end_byte": 442, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/service-worker_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/service-worker_spec.ts_444_8270
describe('Browser Builder service worker', () => { const manifest = { index: '/index.html', assetGroups: [ { name: 'app', installMode: 'prefetch', resources: { files: ['/favicon.ico', '/index.html', '/*.bundle.css', '/*.bundle.js', '/*.chunk.js'], }, }, { name: 'assets', installMode: 'lazy', updateMode: 'prefetch', resources: { files: ['/assets/**', '/*.(svg|cur|jpg|jpeg|png|apng|webp|avif|gif|otf|ttf|woff|woff2)'], }, }, ], }; const target = { project: 'app', target: 'build' }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(async () => host.restore().toPromise()); it('errors if no ngsw-config.json is present', async () => { const overrides = { serviceWorker: true }; await host.delete(join(host.root(), 'src/ngsw-config.json')).toPromise(); const run = await architect.scheduleTarget(target, overrides); await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: false })); await run.stop(); }); it('supports specifying a custom service worker configuration file', async () => { host.writeMultipleFiles({ 'src/configs/ngsw.json': JSON.stringify(manifest), 'src/assets/folder-asset.txt': 'folder-asset.txt', 'src/styles.css': `body { background: url(./spectrum.png); }`, }); const overrides = { serviceWorker: true, ngswConfigPath: 'src/configs/ngsw.json' }; const run = await architect.scheduleTarget(target, overrides); await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); await run.stop(); expect(host.scopedSync().exists(normalize('dist/ngsw.json'))).toBeTrue(); }); it('works with service worker', async () => { host.writeMultipleFiles({ 'src/ngsw-config.json': JSON.stringify(manifest), 'src/assets/folder-asset.txt': 'folder-asset.txt', 'src/styles.css': `body { background: url(./spectrum.png); }`, }); const overrides = { serviceWorker: true }; const run = await architect.scheduleTarget(target, overrides); await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); expect(host.scopedSync().exists(normalize('dist/ngsw.json'))).toBeTrue(); const ngswJson = JSON.parse( virtualFs.fileBufferToString(host.scopedSync().read(normalize('dist/ngsw.json'))), ); // Verify index and assets are there. expect(ngswJson).toEqual( jasmine.objectContaining({ configVersion: 1, index: '/index.html', navigationUrls: [ { positive: true, regex: '^\\/.*$' }, { positive: false, regex: '^\\/(?:.+\\/)?[^/]*\\.[^/]*$' }, { positive: false, regex: '^\\/(?:.+\\/)?[^/]*__[^/]*$' }, { positive: false, regex: '^\\/(?:.+\\/)?[^/]*__[^/]*\\/.*$' }, ], assetGroups: [ { name: 'app', installMode: 'prefetch', updateMode: 'prefetch', urls: ['/favicon.ico', '/index.html'], cacheQueryOptions: { ignoreVary: true, }, patterns: [], }, { name: 'assets', installMode: 'lazy', updateMode: 'prefetch', urls: ['/assets/folder-asset.txt', '/spectrum.png'], cacheQueryOptions: { ignoreVary: true, }, patterns: [], }, ], dataGroups: [], hashTable: { '/favicon.ico': '84161b857f5c547e3699ddfbffc6d8d737542e01', '/assets/folder-asset.txt': '617f202968a6a81050aa617c2e28e1dca11ce8d4', '/index.html': '8964a35a8b850942f8d18ba919f248762ff3154d', '/spectrum.png': '8d048ece46c0f3af4b598a95fd8e4709b631c3c0', }, }), ); await run.stop(); }); it('works in watch mode', async () => { host.writeMultipleFiles({ 'src/ngsw-config.json': JSON.stringify(manifest), 'src/assets/folder-asset.txt': 'folder-asset.txt', 'src/styles.css': `body { background: url(./spectrum.png); }`, }); const overrides = { serviceWorker: true, watch: true }; const run = await architect.scheduleTarget(target, overrides); let buildNumber = 0; await run.output .pipe( debounceTime(3000), tap((buildEvent) => { expect(buildEvent.success).toBeTrue(); const ngswJsonPath = normalize('dist/ngsw.json'); expect(host.scopedSync().exists(ngswJsonPath)).toBeTrue(); const ngswJson = JSON.parse( virtualFs.fileBufferToString(host.scopedSync().read(ngswJsonPath)), ); const hashTableEntries = Object.keys(ngswJson.hashTable); buildNumber += 1; switch (buildNumber) { case 1: expect(hashTableEntries).toEqual([ '/assets/folder-asset.txt', '/favicon.ico', '/index.html', '/spectrum.png', ]); host.copyFile('src/assets/folder-asset.txt', 'src/assets/folder-new-asset.txt'); break; case 2: expect(hashTableEntries).toEqual([ '/assets/folder-asset.txt', '/assets/folder-new-asset.txt', '/favicon.ico', '/index.html', '/spectrum.png', ]); break; } }), take(2), ) .toPromise(); await run.stop(); }); it('works with service worker and baseHref', async () => { host.writeMultipleFiles({ 'src/ngsw-config.json': JSON.stringify(manifest), 'src/assets/folder-asset.txt': 'folder-asset.txt', }); const overrides = { serviceWorker: true, baseHref: '/foo/bar' }; const run = await architect.scheduleTarget(target, overrides); await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); expect(host.scopedSync().exists(normalize('dist/ngsw.json'))).toBeTrue(); const ngswJson = JSON.parse( virtualFs.fileBufferToString(host.scopedSync().read(normalize('dist/ngsw.json'))), ); // Verify index and assets include the base href. expect(ngswJson).toEqual( jasmine.objectContaining({ configVersion: 1, index: '/foo/bar/index.html', navigationUrls: [ { positive: true, regex: '^\\/.*$' }, { positive: false, regex: '^\\/(?:.+\\/)?[^/]*\\.[^/]*$' }, { positive: false, regex: '^\\/(?:.+\\/)?[^/]*__[^/]*$' }, { positive: false, regex: '^\\/(?:.+\\/)?[^/]*__[^/]*\\/.*$' }, ], assetGroups: [ { name: 'app', installMode: 'prefetch', updateMode: 'prefetch', urls: ['/foo/bar/favicon.ico', '/foo/bar/index.html'], patterns: [], cacheQueryOptions: { ignoreVary: true, }, }, { name: 'assets', installMode: 'lazy', updateMode: 'prefetch', urls: ['/foo/bar/assets/folder-asset.txt'], patterns: [], cacheQueryOptions: { ignoreVary: true, }, }, ], dataGroups: [], hashTable: { '/foo/bar/favicon.ico': '84161b857f5c547e3699ddfbffc6d8d737542e01', '/foo/bar/assets/folder-asset.txt': '617f202968a6a81050aa617c2e28e1dca11ce8d4', '/foo/bar/index.html': '5c99755c1e7cfd1c8aba34ad1155afc72a288fec', }, }), ); await run.stop(); }); });
{ "end_byte": 8270, "start_byte": 444, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/service-worker_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/optimization-level_spec.ts_0_2882
/** * @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.dev/license */ import { Architect } from '@angular-devkit/architect'; import { browserBuild, createArchitect, host } from '../../../testing/test-utils'; describe('Browser Builder optimization level', () => { const target = { project: 'app', target: 'build' }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(async () => host.restore().toPromise()); it('works', async () => { const overrides = { optimization: true }; const { files } = await browserBuild(architect, host, target, overrides); expect(await files['main.js']).not.toContain('AppComponent'); }); it('supports styles only optimizations', async () => { const overrides = { optimization: { styles: true, scripts: false, }, aot: true, styles: ['src/styles.css'], }; host.appendToFile('src/main.ts', '/** js comment should not be dropped */'); host.appendToFile('src/app/app.component.css', 'div { color: white }'); host.writeMultipleFiles({ 'src/styles.css': `div { color: white }`, }); const { files } = await browserBuild(architect, host, target, overrides); expect(await files['main.js']).toContain('js comment should not be dropped'); expect(await files['main.js']).toContain('color:#fff'); expect(await files['styles.css']).toContain('color:#fff'); }); it('supports scripts only optimizations', async () => { const overrides = { optimization: { styles: false, scripts: true, }, aot: true, styles: ['src/styles.css'], }; host.appendToFile('src/main.ts', '/** js comment should be dropped */'); host.appendToFile('src/app/app.component.css', 'div { color: white }'); host.writeMultipleFiles({ 'src/styles.css': `div { color: white }`, }); const { files } = await browserBuild(architect, host, target, overrides); expect(await files['main.js']).not.toContain('js comment should be dropped'); expect(await files['main.js']).toContain('color: white'); expect(await files['styles.css']).toContain('color: white'); }); it('outputs ASCII only content', async () => { const overrides = { aot: true, optimization: true }; host.writeMultipleFiles({ 'src/app/app.component.html': `<p>€€€</p>`, }); const { files } = await browserBuild(architect, host, target, overrides); expect(await files['main.js']).not.toContain('ɵ'); expect(await files['main.js']).not.toContain('€€€'); expect(await files['main.js']).toContain('\\u20ac\\u20ac\\u20ac'); }); });
{ "end_byte": 2882, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/optimization-level_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/replacements_spec.ts_0_6306
/** * @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.dev/license */ import { Architect } from '@angular-devkit/architect'; import { logging, normalize, virtualFs } from '@angular-devkit/core'; import { delay, filter, map, of, race, take, takeUntil, takeWhile, tap, timeout } from 'rxjs'; import { browserBuild, createArchitect, host } from '../../../testing/test-utils'; describe('Browser Builder file replacements', () => { const target = { project: 'app', target: 'build' }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(async () => host.restore().toPromise()); beforeEach(() => host.writeMultipleFiles({ 'src/meaning-too.ts': 'export var meaning = 42;', 'src/meaning.ts': `export var meaning = 10;`, 'src/main.ts': ` import { meaning } from './meaning'; console.log(meaning); `, }), ); it('allows file replacements', async () => { const overrides = { fileReplacements: [ { replace: normalize('/src/meaning.ts'), with: normalize('/src/meaning-too.ts'), }, ], }; const { files } = await browserBuild(architect, host, target, overrides); expect(await files['main.js']).toMatch(/meaning\s*=\s*42/); expect(await files['main.js']).not.toMatch(/meaning\s*=\s*10/); }); it(`allows file replacements with deprecated format`, async () => { const overrides = { fileReplacements: [ { src: normalize('/src/meaning.ts'), replaceWith: normalize('/src/meaning-too.ts'), }, ], }; const { files } = await browserBuild(architect, host, target, overrides); expect(await files['main.js']).toMatch(/meaning\s*=\s*42/); expect(await files['main.js']).not.toMatch(/meaning\s*=\s*10/); }); it(`fails compilation with missing 'replace' file`, async () => { const overrides = { fileReplacements: [ { replace: normalize('/src/meaning.ts'), with: normalize('/src/meaning-three.ts'), }, ], }; const run = await architect.scheduleTarget(target, overrides); await expectAsync(run.result).toBeRejectedWithError(); await run.stop(); }); it(`fails compilation with missing 'with' file`, async () => { const overrides = { fileReplacements: [ { replace: normalize('/src/meaning-three.ts'), with: normalize('/src/meaning-too.ts'), }, ], }; const run = await architect.scheduleTarget(target, overrides); await expectAsync(run.result).toBeRejectedWithError(); await run.stop(); }); it('file replacements work with watch mode', async () => { const overrides = { fileReplacements: [ { replace: normalize('/src/meaning.ts'), with: normalize('/src/meaning-too.ts'), }, ], watch: true, }; let buildCount = 0; let phase = 1; const run = await architect.scheduleTarget(target, overrides); await run.output .pipe( timeout(30000), tap((result) => { expect(result.success).toBe(true, 'build should succeed'); const fileName = normalize('dist/main.js'); const content = virtualFs.fileBufferToString(host.scopedSync().read(fileName)); const has42 = /meaning\s*=\s*42/.test(content); buildCount++; switch (phase) { case 1: const has10 = /meaning\s*=\s*10/.test(content); if (has42 && !has10) { phase = 2; host.writeMultipleFiles({ 'src/meaning-too.ts': 'export var meaning = 84;', }); } break; case 2: const has84 = /meaning\s*=\s*84/.test(content); if (has84 && !has42) { phase = 3; } else { // try triggering a rebuild again host.writeMultipleFiles({ 'src/meaning-too.ts': 'export var meaning = 84;', }); } break; } }), takeWhile(() => phase < 3), ) .toPromise() .catch(() => { throw new Error(`stuck at phase ${phase} [builds: ${buildCount}]`); }); await run.stop(); }); it('file replacements work with forked type checker on watch mode', async () => { host.writeMultipleFiles({ 'src/file-replaced.ts': 'export var obj = { one: 1, two: 2 };', 'src/file.ts': `export var obj = { one: 1 };`, 'src/main.ts': ` import { obj } from './file'; console.log(obj.two); `, }); const overrides = { fileReplacements: [ { replace: normalize('/src/file.ts'), with: normalize('/src/file-replaced.ts'), }, ], watch: true, }; const unexpectedError = `Property 'two' does not exist on type '{ one: number; }'`; const expectedError = `Property 'prop' does not exist on type '{}'`; const logger = new logging.Logger(''); // Race between a timeout and the expected log entry. const stop$ = race( of(null).pipe(delay((45000 * 2) / 3)), logger.pipe( filter((entry) => entry.message.includes(expectedError)), map((entry) => entry.message), take(1), ), ); let errorAdded = false; const run = await architect.scheduleTarget(target, overrides, { logger }); run.output .pipe( tap((buildEvent) => expect(buildEvent.success).toBe(true, 'build should succeed')), tap(() => { // Introduce a known type error to detect in the logger filter. if (!errorAdded) { host.appendToFile('src/main.ts', 'console.log({}.prop);'); errorAdded = true; } }), takeUntil(stop$), ) .subscribe(); const res = await stop$.toPromise(); expect(res).toBeDefined(); expect(res).not.toContain(unexpectedError); await run.stop(); }); });
{ "end_byte": 6306, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/replacements_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/allow-js_spec.ts_0_3685
/** * @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.dev/license */ import { Architect } from '@angular-devkit/architect'; import { BrowserBuilderOutput } from '@angular-devkit/build-angular'; import { join, normalize, relative, virtualFs } from '@angular-devkit/core'; import { Observable, lastValueFrom, take, tap } from 'rxjs'; import { createArchitect, host } from '../../../testing/test-utils'; describe('Browser Builder allow js', () => { const targetSpec = { project: 'app', target: 'build' }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(async () => host.restore().toPromise()); it('works', async () => { host.writeMultipleFiles({ 'src/my-js-file.js': `console.log(1); export const a = 2;`, 'src/main.ts': `import { a } from './my-js-file'; console.log(a);`, }); host.replaceInFile( 'tsconfig.json', '"target": "es2022"', '"target": "es2022", "allowJs": true', ); const run = await architect.scheduleTarget(targetSpec); const output = (await run.result) as BrowserBuilderOutput; expect(output.success).toBe(true); const content = virtualFs.fileBufferToString( await lastValueFrom(host.read(join(normalize(output.outputs[0].path), 'main.js'))), ); expect(content).toContain('const a = 2'); await run.stop(); }); it('works with aot', async () => { host.writeMultipleFiles({ 'src/my-js-file.js': `console.log(1); export const a = 2;`, 'src/main.ts': `import { a } from './my-js-file'; console.log(a);`, }); host.replaceInFile( 'tsconfig.json', '"target": "es2022"', '"target": "es2022", "allowJs": true', ); const overrides = { aot: true }; const run = await architect.scheduleTarget(targetSpec, overrides); const output = (await run.result) as BrowserBuilderOutput; expect(output.success).toBe(true); const content = virtualFs.fileBufferToString( await lastValueFrom(host.read(join(normalize(output.outputs[0].path), 'main.js'))), ); expect(content).toContain('const a = 2'); await run.stop(); }); it('works with watch', async () => { host.writeMultipleFiles({ 'src/my-js-file.js': `console.log(1); export const a = 2;`, 'src/main.ts': `import { a } from './my-js-file'; console.log(a);`, }); host.replaceInFile( 'tsconfig.json', '"target": "es2022"', '"target": "es2022", "allowJs": true', ); const overrides = { watch: true }; let buildCount = 1; const run = await architect.scheduleTarget(targetSpec, overrides); await lastValueFrom( (run.output as Observable<BrowserBuilderOutput>).pipe( tap((output) => { const path = relative(host.root(), join(normalize(output.outputs[0].path), 'main.js')); const content = virtualFs.fileBufferToString(host.scopedSync().read(path)); switch (buildCount) { case 1: expect(content).toContain('const a = 2'); host.writeMultipleFiles({ 'src/my-js-file.js': `console.log(1); export const a = 1;`, }); break; case 2: expect(content).toContain('const a = 1'); break; } buildCount++; }), tap((buildEvent) => expect(buildEvent.success).toBe(true)), take(2), ), ); await run.stop(); }); });
{ "end_byte": 3685, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/allow-js_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/poll_spec.ts_0_1697
/** * @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.dev/license */ import { Architect } from '@angular-devkit/architect'; import { debounceTime, take, tap, timeout } from 'rxjs'; import { createArchitect, host } from '../../../testing/test-utils'; import { BUILD_TIMEOUT } from '../index'; describe('Browser Builder poll', () => { const target = { project: 'app', target: 'build' }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(async () => host.restore().toPromise()); it('works', async () => { const overrides = { watch: true, poll: 4000 }; const intervals: number[] = []; let startTime: number | undefined; const run = await architect.scheduleTarget(target, overrides); await run.output .pipe( timeout(BUILD_TIMEOUT), // Debounce 1s, otherwise changes are too close together and polling doesn't work. debounceTime(1000), tap((buildEvent) => { expect(buildEvent.success).toBe(true); if (startTime != undefined) { intervals.push(Date.now() - startTime - 1000); } startTime = Date.now(); host.appendToFile('src/main.ts', 'console.log(1);'); }), take(4), ) .toPromise(); intervals.sort(); const median = intervals[Math.trunc(intervals.length / 2)]; expect(median).toBeGreaterThan(2950); expect(median).toBeLessThan(12000); await run.stop(); }); });
{ "end_byte": 1697, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/poll_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/styles_spec.ts_0_7173
/** * @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.dev/license */ import { Architect } from '@angular-devkit/architect'; import { normalize, tags } from '@angular-devkit/core'; import { dirname } from 'path'; import { browserBuild, createArchitect, host } from '../../../testing/test-utils'; describe('Browser Builder styles', () => { const extensionsWithImportSupport = ['css', 'scss', 'less']; const extensionsWithVariableSupport = ['scss', 'less']; const imgSvg = ` <svg width="100" height="100" xmlns="http://www.w3.org/2000/svg"> <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" /> </svg> `; const target = { project: 'app', target: 'build' }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(async () => host.restore().toPromise()); it('supports global styles', async () => { const styles = [ 'src/input-style.css', { input: 'src/lazy-style.css', bundleName: 'lazy-style', inject: false }, { input: 'src/pre-rename-style.css', bundleName: 'renamed-style' }, { input: 'src/pre-rename-lazy-style.css', bundleName: 'renamed-lazy-style', inject: false }, ] as {}; const cssMatches: { [path: string]: string } = { 'styles.css': '.input-style', 'lazy-style.css': '.lazy-style', 'renamed-style.css': '.pre-rename-style', 'renamed-lazy-style.css': '.pre-rename-lazy-style', }; const cssIndexMatches: { [path: string]: string } = { 'index.html': '<link rel="stylesheet" href="styles.css">' + '<link rel="stylesheet" href="renamed-style.css">', }; host.writeMultipleFiles({ 'src/string-style.css': '.string-style { color: red }', 'src/input-style.css': '.input-style { color: red }', 'src/lazy-style.css': '.lazy-style { color: red }', 'src/pre-rename-style.css': '.pre-rename-style { color: red }', 'src/pre-rename-lazy-style.css': '.pre-rename-lazy-style { color: red }', }); const { files } = await browserBuild(architect, host, target, { styles }); // Check css files were created. for (const cssFileName of Object.keys(cssMatches)) { expect(await files[cssFileName]).toMatch(cssMatches[cssFileName]); } // Check check index has styles in the right order. for (const cssIndexFileName of Object.keys(cssIndexMatches)) { expect(await files[cssIndexFileName]).toMatch(cssIndexMatches[cssIndexFileName]); } }); it('supports empty styleUrls in components', async () => { host.writeMultipleFiles({ './src/app/app.component.ts': ` import { Component } from '@angular/core'; @Component({ selector: 'app-root', standalone: false, templateUrl: './app.component.html', styleUrls: [] }) export class AppComponent { title = 'app'; } `, }); await browserBuild(architect, host, target); }); it('supports autoprefixer with inline component styles in JIT mode', async () => { host.writeMultipleFiles({ './src/app/app.component.ts': ` import { Component } from '@angular/core'; @Component({ selector: 'app-root', standalone: false, templateUrl: './app.component.html', styles: ['div { mask-composite: add; }'], }) export class AppComponent { title = 'app'; } `, '.browserslistrc': ` Safari 15.4 Edge 104 Firefox 91 `, }); const { files } = await browserBuild(architect, host, target, { aot: false }); expect(await files['main.js']).toContain('-webkit-mask-composite'); }); it('supports autoprefixer with inline component styles in AOT mode', async () => { host.writeMultipleFiles({ './src/app/app.component.ts': ` import { Component } from '@angular/core'; @Component({ selector: 'app-root', standalone: false, templateUrl: './app.component.html', styles: ['div { mask-composite: add; }'], }) export class AppComponent { title = 'app'; } `, '.browserslistrc': ` Safari 15.4 Edge 104 Firefox 91 `, }); const { files } = await browserBuild(architect, host, target, { aot: true }); expect(await files['main.js']).toContain('-webkit-mask-composite'); }); extensionsWithImportSupport.forEach((ext) => { it(`supports imports in ${ext} files`, async () => { host.writeMultipleFiles({ [`src/styles.${ext}`]: ` @import './imported-styles.${ext}'; body { background-color: #00f; } `, [`src/imported-styles.${ext}`]: 'p { background-color: #f00; }', [`src/app/app.component.${ext}`]: ` @import './imported-component-styles.${ext}'; .outer { .inner { background: #fff; } } `, [`src/app/imported-component-styles.${ext}`]: 'h1 { background: #000; }', }); const matches: { [path: string]: RegExp } = { 'styles.css': new RegExp( // The global style should be there /p\s*{\s*background-color: #f00;\s*}(.|\n|\r)*/.source + // The global style via import should be there /body\s*{\s*background-color: #00f;\s*}/.source, ), 'styles.css.map': /"mappings":".+"/, 'main.js': new RegExp( // The component style should be there /h1(.|\n|\r)*background:\s*#000(.|\n|\r)*/.source + // The component style via import should be there /.outer(.|\n|\r)*.inner(.|\n|\r)*background:\s*#[fF]+/.source, ), }; const overrides = { aot: true, sourceMap: true, styles: [`src/styles.${ext}`], }; host.replaceInFile( 'src/app/app.component.ts', './app.component.css', `./app.component.${ext}`, ); const { files } = await browserBuild(architect, host, target, overrides); for (const fileName of Object.keys(matches)) { expect(await files[fileName]).toMatch(matches[fileName]); } }); }); extensionsWithImportSupport.forEach((ext) => { it(`supports material imports in ${ext} files`, async () => { host.writeMultipleFiles({ [`src/styles.${ext}`]: ` @import "@angular/material/prebuilt-themes/indigo-pink.css"; `, [`src/app/app.component.${ext}`]: ` @import "@angular/material/prebuilt-themes/indigo-pink.css"; `, }); host.replaceInFile( 'src/app/app.component.ts', './app.component.css', `./app.component.${ext}`, ); const overrides = { styles: [{ input: `src/styles.${ext}` }], }; await browserBuild(architect, host, target, overrides); }); });
{ "end_byte": 7173, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/styles_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/styles_spec.ts_7177_15392
extensionsWithVariableSupport.forEach((ext) => { it(`supports ${ext} includePaths`, async () => { let variableAssignment = ''; let variablereference = ''; if (ext === 'scss') { variableAssignment = '$primary-color:'; variablereference = '$primary-color'; } else if (ext === 'less') { variableAssignment = '@primary-color:'; variablereference = '@primary-color'; } host.writeMultipleFiles({ [`src/style-paths/variables.${ext}`]: `${variableAssignment} #f00;`, [`src/styles.${ext}`]: ` @import 'variables'; h1 { color: ${variablereference}; } `, [`src/app/app.component.${ext}`]: ` @import 'variables'; h2 { color: ${variablereference}; } `, }); const matches: { [path: string]: RegExp } = { 'styles.css': /h1\s*{\s*color: #f00;\s*}/, 'main.js': /h2\s*{\s*color: #f00;\s*}/, }; host.replaceInFile( 'src/app/app.component.ts', './app.component.css', `./app.component.${ext}`, ); const overrides = { styles: [`src/styles.${ext}`], stylePreprocessorOptions: { includePaths: ['src/style-paths'], }, }; const { files } = await browserBuild(architect, host, target, overrides); for (const [fileName, match] of Object.entries(matches)) { expect(await files[fileName]).toMatch(match); } }); }); it(`supports font-awesome imports`, async () => { // font-awesome mock to avoid having an extra dependency. host.writeMultipleFiles({ 'node_modules/font-awesome/scss/font-awesome.scss': ` * { color: red } `, }); host.writeMultipleFiles({ 'src/styles.scss': ` @import "font-awesome/scss/font-awesome"; `, }); const overrides = { styles: [`src/styles.scss`] }; await browserBuild(architect, host, target, overrides); }); it(`uses autoprefixer`, async () => { host.writeMultipleFiles({ 'src/styles.css': tags.stripIndents` @import url(imported-styles.css); /* normal-comment */ /*! important-comment */ div { mask-composite: add; }`, 'src/imported-styles.css': tags.stripIndents` /* normal-comment */ /*! important-comment */ section { mask-composite: add; }`, '.browserslistrc': ` Safari 15.4 Edge 104 Firefox 91 `, }); const overrides = { optimization: false }; const { files } = await browserBuild(architect, host, target, overrides); const content = await files['styles.css']; expect(content).toContain(tags.stripIndents` /* normal-comment */ /*! important-comment */ section { -webkit-mask-composite: source-over; mask-composite: add; }`); // Check separately because Webpack may add source file comments inbetween the rules expect(content).toContain(tags.stripIndents` /* normal-comment */ /*! important-comment */ div { -webkit-mask-composite: source-over; mask-composite: add; }`); }); it(`minimizes css`, async () => { host.writeMultipleFiles({ 'src/styles.css': tags.stripIndents` /* normal-comment */ /*! important-comment */ div { flex: 1 }`, }); const overrides = { optimization: true }; const { files } = await browserBuild(architect, host, target, overrides); expect(await files['styles.css']).toContain('/*! important-comment */'); }); // TODO: consider making this a unit test in the url processing plugins. it( `supports baseHref/deployUrl in resource urls`, async () => { // Use a large image for the relative ref so it cannot be inlined. host.copyFile('src/spectrum.png', './src/assets/global-img-relative.png'); host.copyFile('src/spectrum.png', './src/assets/component-img-relative.png'); host.writeMultipleFiles({ 'src/styles.css': ` h1 { background: url('/assets/global-img-absolute.svg'); } h2 { background: url('./assets/global-img-relative.png'); } `, 'src/app/app.component.css': ` h3 { background: url('/assets/component-img-absolute.svg'); } h4 { background: url('../assets/component-img-relative.png'); } `, 'src/assets/global-img-absolute.svg': imgSvg, 'src/assets/component-img-absolute.svg': imgSvg, }); let { files } = await browserBuild(architect, host, target, { aot: true }); // Check base paths are correctly generated. let styles = await files['styles.css']; let main = await files['main.js']; expect(styles).toContain(`url('/assets/global-img-absolute.svg')`); expect(styles).toContain(`url('global-img-relative.png')`); expect(main).toContain(`url('/assets/component-img-absolute.svg')`); expect(main).toContain(`url('component-img-relative.png')`); expect(host.scopedSync().exists(normalize('dist/assets/global-img-absolute.svg'))).toBe(true); expect(host.scopedSync().exists(normalize('dist/global-img-relative.png'))).toBe(true); expect(host.scopedSync().exists(normalize('dist/assets/component-img-absolute.svg'))).toBe( true, ); expect(host.scopedSync().exists(normalize('dist/component-img-relative.png'))).toBe(true); // Check urls with deploy-url scheme are used as is. files = ( await browserBuild(architect, host, target, { baseHref: '/base/', deployUrl: 'http://deploy.url/', }) ).files; styles = await files['styles.css']; main = await files['main.js']; expect(styles).toContain(`url('/assets/global-img-absolute.svg')`); expect(main).toContain(`url('/assets/component-img-absolute.svg')`); // Check urls with base-href scheme are used as is (with deploy-url). files = ( await browserBuild(architect, host, target, { baseHref: 'http://base.url/', deployUrl: 'deploy/', }) ).files; styles = await files['styles.css']; main = await files['main.js']; expect(styles).toContain(`url('/assets/global-img-absolute.svg')`); expect(main).toContain(`url('/assets/component-img-absolute.svg')`); // Check urls with deploy-url and base-href scheme only use deploy-url. files = ( await browserBuild(architect, host, target, { baseHref: 'http://base.url/', deployUrl: 'http://deploy.url/', }) ).files; styles = await files['styles.css']; main = await files['main.js']; expect(styles).toContain(`url('/assets/global-img-absolute.svg')`); expect(main).toContain(`url('/assets/component-img-absolute.svg')`); // Check with schemeless base-href and deploy-url flags. files = ( await browserBuild(architect, host, target, { baseHref: '/base/', deployUrl: 'deploy/', }) ).files; styles = await files['styles.css']; main = await files['main.js']; expect(styles).toContain(`url('/assets/global-img-absolute.svg')`); expect(main).toContain(`url('/assets/component-img-absolute.svg')`); // Check with identical base-href and deploy-url flags. files = ( await browserBuild(architect, host, target, { baseHref: '/base/', deployUrl: '/base/', }) ).files; styles = await files['styles.css']; main = await files['main.js']; expect(styles).toContain(`url('/assets/global-img-absolute.svg')`); expect(main).toContain(`url('/assets/component-img-absolute.svg')`); // Check with only base-href flag. files = ( await browserBuild(architect, host, target, { baseHref: '/base/', }) ).files; styles = await files['styles.css']; main = await files['main.js']; expect(styles).toContain(`url('/assets/global-img-absolute.svg')`); expect(main).toContain(`url('/assets/component-img-absolute.svg')`); // NOTE: Timeout for large amount of builds in test. Test should be split up when refactored. }, 4 * 60 * 1000, );
{ "end_byte": 15392, "start_byte": 7177, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/styles_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/styles_spec.ts_15396_23112
it(`supports inline javascript in less`, async () => { const overrides = { styles: [`src/styles.less`] }; host.writeMultipleFiles({ 'src/styles.less': ` .myFunction() { @functions: ~\`(function () { return ''; })()\`; } .myFunction(); `, }); await browserBuild(architect, host, target, overrides); }); it('causes equal failure for tilde and tilde-slash url()', async () => { host.writeMultipleFiles({ 'src/styles.css': ` body { background-image: url('~/does-not-exist.jpg'); } `, }); const overrides = { optimization: true }; const run = await architect.scheduleTarget(target, overrides); await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: false })); host.writeMultipleFiles({ 'src/styles.css': ` body { background-image: url('~does-not-exist.jpg'); } `, }); const run2 = await architect.scheduleTarget(target, overrides); await expectAsync(run2.result).toBeResolvedTo(jasmine.objectContaining({ success: false })); await run2.stop(); await run.stop(); }); it('supports Protocol-relative Url', async () => { host.writeMultipleFiles({ 'src/styles.css': ` body { background-image: url('//cdn.com/classic-bg.jpg'); } `, }); const overrides = { optimization: true }; const { files } = await browserBuild(architect, host, target, overrides); expect(await files['styles.css']).toContain('background-image:url(//cdn.com/classic-bg.jpg)'); }); it('supports fonts with space in filename', async () => { host.writeMultipleFiles({ 'src/styles.css': ` @font-face { font-family: "Font Awesome"; src: url("./assets/fa solid-900.woff2") format("woff2"); } body { font-family: "Font Awesome"; } `, 'src/assets/fa solid-900.woff2': '', }); const { output } = await browserBuild(architect, host, target); expect(output.success).toBe(true); }); extensionsWithImportSupport.forEach((ext) => { it(`retains declarations order in ${ext} files when using @import`, async () => { host.writeMultipleFiles({ [`src/styles-one.${ext}`]: tags.stripIndents` .one { color: #fff; } `, [`src/styles-two.${ext}`]: tags.stripIndents` .two { color: #fff; } `, // LESS doesn't support css imports by default. // See: https://github.com/less/less.js/issues/3188#issuecomment-374690630 [`src/styles-three.${ext}`]: tags.stripIndents` @import ${ ext === 'less' ? ' (css) ' : '' }url("https://fonts.googleapis.com/css?family=Roboto:400"); .three { color: #fff; } `, }); const overrides = { styles: [`src/styles-one.${ext}`, `src/styles-two.${ext}`, `src/styles-three.${ext}`], }; const { files } = await browserBuild(architect, host, target, overrides); expect(await files['styles.css']).toMatch(/\.one(.|\n|\r)*\.two(.|\n|\r)*\.three/); }); }); extensionsWithImportSupport.forEach((ext) => { it(`adjusts relative resource URLs when using @import in ${ext} (global)`, async () => { host.copyFile('src/spectrum.png', './src/more-styles/images/global-img-relative.png'); host.writeMultipleFiles({ [`src/styles-one.${ext}`]: tags.stripIndents` @import "more-styles/styles-two.${ext}"; `, [`src/more-styles/styles-two.${ext}`]: tags.stripIndents` .two { background-image: url(images/global-img-relative.png); } `, }); const overrides = { sourceMap: false, styles: [`src/styles-one.${ext}`], }; const { files } = await browserBuild(architect, host, target, overrides); expect(await files['styles.css']).toContain("'global-img-relative.png'"); }); it(`adjusts relative resource URLs when using @import in ${ext} (component)`, async () => { host.copyFile('src/spectrum.png', './src/app/images/component-img-relative.png'); host.writeMultipleFiles({ [`src/app/styles/component-styles.${ext}`]: ` div { background-image: url(../images/component-img-relative.png); } `, [`src/app/app.component.${ext}`]: ` @import "styles/component-styles.${ext}"; `, }); host.replaceInFile( 'src/app/app.component.ts', './app.component.css', `./app.component.${ext}`, ); const overrides = { sourceMap: false, }; await browserBuild(architect, host, target, overrides); }); }); it('should minify colors based on browser support', async () => { host.writeMultipleFiles({ 'src/styles.css': ` div { box-shadow: 0 3px 10px, rgba(0, 0, 0, 0.15); } `, }); let result = await browserBuild(architect, host, target, { optimization: true }); expect(await result.files['styles.css']).toContain('#00000026'); await host.restore().toPromise(); await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; // Edge 17 doesn't support #rrggbbaa colors // https://github.com/angular/angular-cli/issues/21594#:~:text=%23rrggbbaa%20hex%20color%20notation // While this browser is un-supported, this is used as a base case to test that the underlying // logic to pass the list of supported browsers to the css optimizer works. host.writeMultipleFiles({ 'src/styles.css': ` div { box-shadow: 0 3px 10px, rgba(0, 0, 0, 0.15); } `, '.browserslistrc': `edge 18`, }); result = await browserBuild(architect, host, target, { optimization: true }); expect(await result.files['styles.css']).toContain('rgba(0,0,0,.15)'); }); it('works when using the same css file in `styles` and `stylesUrl`', async () => { host.writeMultipleFiles({ 'src/styles.css': ` div { color: red } `, './src/app/app.component.ts': ` import { Component } from '@angular/core'; @Component({ selector: 'app-root', standalone: false, templateUrl: './app.component.html', styleUrls: ['../styles.css'] }) export class AppComponent { title = 'app'; } `, }); await browserBuild(architect, host, target, { styles: ['src/styles.css'] }); }); it('works when Data URI has escaped quote', async () => { const svgData = `"data:image/svg+xml;charset=utf-8,<svg width=/"16/" height=/"15/"></svg>"`; host.writeMultipleFiles({ 'src/styles.css': ` div { background: url(${svgData}) } `, }); const result = await browserBuild(architect, host, target, { styles: ['src/styles.css'] }); expect(await result.files['styles.css']).toContain(svgData); }); it('works when Data URI has parenthesis', async () => { const svgData = '"data:image/svg+xml;charset=utf-8,<svg>' + `<mask id='clip'><g><circle mask='url(%23clip)' cx='11.5' cy='11.5' r='9.25'/><use xlink:href='#text' mask='url(#clip)'/></g>` + '</svg>"'; host.writeMultipleFiles({ 'src/styles.css': ` div { background: url(${svgData}) } `, }); const result = await browserBuild(architect, host, target, { styles: ['src/styles.css'] }); expect(await result.files['styles.css']).toContain(svgData); }); });
{ "end_byte": 23112, "start_byte": 15396, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/styles_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/svg_spec.ts_0_2060
/** * @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.dev/license */ import { Architect } from '@angular-devkit/architect'; import { join, normalize, virtualFs } from '@angular-devkit/core'; import { createArchitect, host, outputPath } from '../../../testing/test-utils'; describe('Browser Builder allow svg', () => { const target = { project: 'app', target: 'build' }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(async () => host.restore().toPromise()); it('works with aot', async () => { const svg = ` <svg xmlns="http://www.w3.org/2000/svg"> <text x="20" y="20" font-size="20" fill="red">Hello World</text> </svg>`; host.writeMultipleFiles({ './src/app/app.component.svg': svg, './src/app/app.component.ts': ` import { Component } from '@angular/core'; @Component({ selector: 'app-root', standalone: false, templateUrl: './app.component.svg', styleUrls: [] }) export class AppComponent { title = 'app'; } `, }); const overrides = { aot: true }; const run = await architect.scheduleTarget(target, overrides); await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); const exists = host.scopedSync().exists(join(outputPath, 'main.js')); expect(exists).toBe(true, '"main.js" should exist'); if (exists) { const content = virtualFs.fileBufferToString( host.scopedSync().read(join(outputPath, 'main.js')), ); expect(content).toContain('ɵɵnamespaceSVG'); expect(host.scopedSync().exists(normalize('dist/app.component.svg'))).toBe( false, 'should not copy app.component.svg to dist', ); } await run.stop(); }); });
{ "end_byte": 2060, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/svg_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/errors_spec.ts_0_3119
/** * @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.dev/license */ import { Architect } from '@angular-devkit/architect'; import { logging } from '@angular-devkit/core'; import { createArchitect, host } from '../../../testing/test-utils'; describe('Browser Builder errors', () => { const targetSpec = { project: 'app', target: 'build' }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(async () => host.restore().toPromise()); it('shows error when files are not part of the compilation', async () => { host.replaceInFile('src/tsconfig.app.json', /,\r?\n?\s*"polyfills\.ts"/, ''); host.replaceInFile('src/tsconfig.app.json', '"**/*.ts"', '"**/*.d.ts"'); const logger = new logging.Logger(''); const logs: string[] = []; logger.subscribe((e) => logs.push(e.message)); const run = await architect.scheduleTarget(targetSpec, {}, { logger }); const output = await run.result; expect(output.success).toBe(false); expect(logs.join()).toContain('polyfills.ts is missing from the TypeScript'); await run.stop(); }); it('shows TS syntax errors', async () => { host.appendToFile('src/app/app.component.ts', ']]]'); const logger = new logging.Logger(''); const logs: string[] = []; logger.subscribe((e) => logs.push(e.message)); const run = await architect.scheduleTarget(targetSpec, {}, { logger }); const output = await run.result; expect(output.success).toBe(false); expect(logs.join()).toContain('Declaration or statement expected'); await run.stop(); }); it('shows static analysis errors', async () => { host.replaceInFile('src/app/app.component.ts', `'app-root'`, `(() => 'app-root')()`); const logger = new logging.Logger(''); const logs: string[] = []; logger.subscribe((e) => logs.push(e.message)); const run = await architect.scheduleTarget(targetSpec, { aot: true }, { logger }); const output = await run.result; expect(output.success).toBe(false); // Wait for the builder to complete await run.stop(); expect(logs.join()).toContain('selector must be a string'); }); it('shows missing export errors', async () => { host.writeMultipleFiles({ 'src/not-main.js': ` import { missingExport } from 'rxjs'; console.log(missingExport); `, }); const overrides = { main: 'src/not-main.js' }; const logger = new logging.Logger(''); const logs: string[] = []; logger.subscribe((e) => logs.push(e.message)); const run = await architect.scheduleTarget(targetSpec, overrides, { logger }); const output = await run.result; expect(output.success).toBe(false); // Wait for the builder to complete await run.stop(); expect(logs.join()).toContain( `export 'missingExport' (imported as 'missingExport') was not found in 'rxjs'`, ); }); });
{ "end_byte": 3119, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/errors_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/index_spec.ts_0_520
/** * @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.dev/license */ import { Architect } from '@angular-devkit/architect'; import { BrowserBuilderOutput } from '@angular-devkit/build-angular'; import { join, normalize, tags, virtualFs, workspaces } from '@angular-devkit/core'; import { lastValueFrom } from 'rxjs'; import { createArchitect, host } from '../../../testing/test-utils';
{ "end_byte": 520, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/index_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/index_spec.ts_522_8649
describe('Browser Builder index HTML processing', () => { const targetSpec = { project: 'app', target: 'build' }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(async () => host.restore().toPromise()); it('works with UTF-8 BOM', async () => { host.writeMultipleFiles({ 'src/index.html': Buffer.from( '\ufeff<html><head><base href="/"></head><body><app-root></app-root></body></html>', 'utf8', ), }); const run = await architect.scheduleTarget(targetSpec); const output = (await run.result) as BrowserBuilderOutput; expect(output.success).toBe(true); const fileName = join(normalize(output.outputs[0].path), 'index.html'); const content = virtualFs.fileBufferToString( await lastValueFrom(host.read(normalize(fileName))), ); expect(content).toBe( `<html><head><base href="/"><link rel="stylesheet" href="styles.css"></head>` + `<body><app-root></app-root><script src="runtime.js" type="module"></script>` + `<script src="polyfills.js" type="module"></script>` + `<script src="vendor.js" type="module"></script><script src="main.js" type="module"></script></body></html>`, ); await run.stop(); }); // todo: enable when utf16 is supported xit('works with UTF16 LE BOM', async () => { host.writeMultipleFiles({ 'src/index.html': Buffer.from( '\ufeff<html><head><base href="/"></head><body><app-root></app-root></body></html>', 'utf16le', ), }); const run = await architect.scheduleTarget(targetSpec); const output = (await run.result) as BrowserBuilderOutput; expect(output.success).toBe(true); const fileName = join(normalize(output.outputs[0].path), 'index.html'); const content = virtualFs.fileBufferToString( await lastValueFrom(host.read(normalize(fileName))), ); expect(content).toBe( `<html><head><base href="/"><link rel="stylesheet" href="styles.css"></head>` + `<body><app-root></app-root>` + `<script src="runtime.js" type="module"></script><script src="polyfills.js" type="module"></script>` + `<script src="vendor.js" type="module"></script>` + `<script src="main.js" type="module"></script></body></html>`, ); await run.stop(); }); it('keeps escaped charaters', async () => { host.writeMultipleFiles({ 'src/index.html': tags.oneLine` <html><head><title>&iacute;</title><base href="/"></head> <body><app-root></app-root></body></html> `, }); const run = await architect.scheduleTarget(targetSpec); const output = (await run.result) as BrowserBuilderOutput; expect(output.success).toBe(true); const fileName = join(normalize(output.outputs[0].path), 'index.html'); const content = virtualFs.fileBufferToString( await lastValueFrom(host.read(normalize(fileName))), ); expect(content).toBe( `<html><head><title>&iacute;</title><base href="/"><link rel="stylesheet" href="styles.css"></head> ` + `<body><app-root></app-root><script src="runtime.js" type="module"></script>` + `<script src="polyfills.js" type="module"></script>` + `<script src="vendor.js" type="module"></script><script src="main.js" type="module"></script></body></html>`, ); await run.stop(); }); it('keeps custom template charaters', async () => { host.writeMultipleFiles({ 'src/index.html': tags.oneLine` <html><head><base href="/"><%= csrf_meta_tags %></head> <body><app-root></app-root></body></html> `, }); const run = await architect.scheduleTarget(targetSpec); const output = (await run.result) as BrowserBuilderOutput; expect(output.success).toBe(true); const fileName = join(normalize(output.outputs[0].path), 'index.html'); const content = virtualFs.fileBufferToString( await lastValueFrom(host.read(normalize(fileName))), ); expect(content).toBe( `<html><head><base href="/"><%= csrf_meta_tags %><link rel="stylesheet" href="styles.css"></head> ` + `<body><app-root></app-root><script src="runtime.js" type="module"></script>` + `<script src="polyfills.js" type="module"></script>` + `<script src="vendor.js" type="module"></script><script src="main.js" type="module"></script></body></html>`, ); await run.stop(); }); it('uses the input value from the index option longform', async () => { const { workspace } = await workspaces.readWorkspace( host.root(), workspaces.createWorkspaceHost(host), ); const app = workspace.projects.get('app'); if (!app) { fail('Test application "app" not found.'); return; } const target = app.targets.get('build'); if (!target) { fail('Test application "app" target "build" not found.'); return; } if (!target.options) { target.options = {}; } target.options.index = { input: 'src/index-2.html' }; await workspaces.writeWorkspace(workspace, workspaces.createWorkspaceHost(host)); host.writeMultipleFiles({ 'src/index-2.html': tags.oneLine` <html><head><base href="/"><%= csrf_meta_tags %></head> <body><app-root></app-root></body></html> `, }); await host.delete(join(host.root(), normalize('src/index.html'))).toPromise(); // Recreate architect to use update angular.json architect = (await createArchitect(host.root())).architect; const run = await architect.scheduleTarget(targetSpec); await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); const outputIndexPath = join(host.root(), 'dist', 'index.html'); const content = await lastValueFrom(host.read(normalize(outputIndexPath))); expect(virtualFs.fileBufferToString(content)).toBe( `<html><head><base href="/"><%= csrf_meta_tags %><link rel="stylesheet" href="styles.css"></head> ` + `<body><app-root></app-root><script src="runtime.js" type="module"></script>` + `<script src="polyfills.js" type="module"></script>` + `<script src="vendor.js" type="module"></script><script src="main.js" type="module"></script></body></html>`, ); await run.stop(); }); it('uses the output value from the index option longform', async () => { const { workspace } = await workspaces.readWorkspace( host.root(), workspaces.createWorkspaceHost(host), ); const app = workspace.projects.get('app'); if (!app) { fail('Test application "app" not found.'); return; } const target = app.targets.get('build'); if (!target) { fail('Test application "app" target "build" not found.'); return; } if (!target.options) { target.options = {}; } target.options.index = { input: 'src/index.html', output: 'main.html' }; await workspaces.writeWorkspace(workspace, workspaces.createWorkspaceHost(host)); host.writeMultipleFiles({ 'src/index.html': tags.oneLine` <html><head><base href="/"></head> <body><app-root></app-root></body></html> `, }); // Recreate architect to use update angular.json architect = (await createArchitect(host.root())).architect; const run = await architect.scheduleTarget(targetSpec); await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); const outputIndexPath = join(host.root(), 'dist', 'main.html'); const content = await lastValueFrom(host.read(normalize(outputIndexPath))); expect(virtualFs.fileBufferToString(content)).toBe( `<html><head><base href="/"><link rel="stylesheet" href="styles.css"></head> ` + `<body><app-root></app-root><script src="runtime.js" type="module"></script>` + `<script src="polyfills.js" type="module"></script>` + `<script src="vendor.js" type="module"></script><script src="main.js" type="module"></script></body></html>`, ); await run.stop(); });
{ "end_byte": 8649, "start_byte": 522, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/index_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/index_spec.ts_8653_10444
it('creates subdirectories for output value from the index option longform', async () => { const { workspace } = await workspaces.readWorkspace( host.root(), workspaces.createWorkspaceHost(host), ); const app = workspace.projects.get('app'); if (!app) { fail('Test application "app" not found.'); return; } const target = app.targets.get('build'); if (!target) { fail('Test application "app" target "build" not found.'); return; } if (!target.options) { target.options = {}; } target.options.index = { input: 'src/index.html', output: 'extra/main.html' }; await workspaces.writeWorkspace(workspace, workspaces.createWorkspaceHost(host)); host.writeMultipleFiles({ 'src/index.html': tags.oneLine` <html><head><base href="/"></head> <body><app-root></app-root></body></html> `, }); // Recreate architect to use update angular.json architect = (await createArchitect(host.root())).architect; const run = await architect.scheduleTarget(targetSpec); await expectAsync(run.result).toBeResolvedTo(jasmine.objectContaining({ success: true })); const outputIndexPath = join(host.root(), 'dist', 'extra', 'main.html'); const content = await lastValueFrom(host.read(normalize(outputIndexPath))); expect(virtualFs.fileBufferToString(content)).toBe( `<html><head><base href="/"><link rel="stylesheet" href="styles.css"></head> ` + `<body><app-root></app-root><script src="runtime.js" type="module"></script>` + `<script src="polyfills.js" type="module"></script>` + `<script src="vendor.js" type="module"></script><script src="main.js" type="module"></script></body></html>`, ); await run.stop(); }); });
{ "end_byte": 10444, "start_byte": 8653, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/index_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/cross-origin_spec.ts_0_4802
/** * @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.dev/license */ import { Architect } from '@angular-devkit/architect'; import { BrowserBuilderOutput, CrossOrigin } from '@angular-devkit/build-angular'; import { join, normalize, virtualFs } from '@angular-devkit/core'; import { lastValueFrom } from 'rxjs'; import { createArchitect, host } from '../../../testing/test-utils'; describe('Browser Builder crossOrigin', () => { const targetSpec = { project: 'app', target: 'build' }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; host.writeMultipleFiles({ 'src/index.html': Buffer.from( '\ufeff<html><head><base href="/"></head><body><app-root></app-root></body></html>', 'utf8', ), }); }); afterEach(async () => host.restore().toPromise()); it('works with use-credentials', async () => { const overrides = { crossOrigin: CrossOrigin.UseCredentials }; const run = await architect.scheduleTarget(targetSpec, overrides); const output = (await run.result) as BrowserBuilderOutput; expect(output.success).toBe(true); const fileName = join(normalize(output.outputs[0].path), 'index.html'); const content = virtualFs.fileBufferToString( await lastValueFrom(host.read(normalize(fileName))), ); expect(content).toBe( `<html><head><base href="/"><link rel="stylesheet" href="styles.css" crossorigin="use-credentials"></head>` + `<body><app-root></app-root>` + `<script src="runtime.js" type="module" crossorigin="use-credentials"></script>` + `<script src="polyfills.js" type="module" crossorigin="use-credentials"></script>` + `<script src="vendor.js" type="module" crossorigin="use-credentials"></script>` + `<script src="main.js" type="module" crossorigin="use-credentials"></script></body></html>`, ); await run.stop(); }); it('works with anonymous', async () => { const overrides = { crossOrigin: CrossOrigin.Anonymous }; const run = await architect.scheduleTarget(targetSpec, overrides); const output = (await run.result) as BrowserBuilderOutput; expect(output.success).toBe(true); const fileName = join(normalize(output.outputs[0].path), 'index.html'); const content = virtualFs.fileBufferToString( await lastValueFrom(host.read(normalize(fileName))), ); expect(content).toBe( `<html><head><base href="/">` + `<link rel="stylesheet" href="styles.css" crossorigin="anonymous"></head>` + `<body><app-root></app-root>` + `<script src="runtime.js" type="module" crossorigin="anonymous"></script>` + `<script src="polyfills.js" type="module" crossorigin="anonymous"></script>` + `<script src="vendor.js" type="module" crossorigin="anonymous"></script>` + `<script src="main.js" type="module" crossorigin="anonymous"></script></body></html>`, ); await run.stop(); }); it('works with none', async () => { const overrides = { crossOrigin: CrossOrigin.None }; const run = await architect.scheduleTarget(targetSpec, overrides); const output = (await run.result) as BrowserBuilderOutput; expect(output.success).toBe(true); const fileName = join(normalize(output.outputs[0].path), 'index.html'); const content = virtualFs.fileBufferToString( await lastValueFrom(host.read(normalize(fileName))), ); expect(content).toBe( `<html><head><base href="/">` + `<link rel="stylesheet" href="styles.css"></head>` + `<body><app-root></app-root>` + `<script src="runtime.js" type="module"></script>` + `<script src="polyfills.js" type="module"></script>` + `<script src="vendor.js" type="module"></script>` + `<script src="main.js" type="module"></script></body></html>`, ); await run.stop(); }); it('works for lazy chunks', async () => { host.writeMultipleFiles({ 'src/lazy-module.ts': 'export const value = 100;', 'src/main.ts': `import('./lazy-module');`, }); const overrides = { crossOrigin: CrossOrigin.UseCredentials }; const run = await architect.scheduleTarget(targetSpec, overrides); const output = (await run.result) as BrowserBuilderOutput; expect(output.success).toBe(true); const fileName = join(normalize(output.outputs[0].path), 'runtime.js'); const content = virtualFs.fileBufferToString( await lastValueFrom(host.read(normalize(fileName))), ); expect(content).toContain('script.crossOrigin = "use-credentials"'); await run.stop(); }); });
{ "end_byte": 4802, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/cross-origin_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/specs/lazy-module_spec.ts_0_6204
/** * @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.dev/license */ import { Architect } from '@angular-devkit/architect'; import { TestProjectHost } from '@angular-devkit/architect/testing'; import { logging } from '@angular-devkit/core'; import { debounceTime, take, tap } from 'rxjs'; import { browserBuild, createArchitect, host, lazyModuleFiles, lazyModuleFnImport, } from '../../../testing/test-utils'; describe('Browser Builder lazy modules', () => { const target = { project: 'app', target: 'build' }; let architect: Architect; beforeEach(async () => { await host.initialize().toPromise(); architect = (await createArchitect(host.root())).architect; }); afterEach(async () => host.restore().toPromise()); function addLazyLoadedModulesInTsConfig( host: TestProjectHost, lazyModuleFiles: Record<string, string>, ) { const files = [...Object.keys(lazyModuleFiles), 'main.ts'] .map((f) => '"' + f.replace('src/', '') + '"') .join(', '); host.replaceInFile('src/tsconfig.app.json', '"main.ts"', `${files}`); } function hasMissingModuleError(logs: string): boolean { // TS type error when using import(). return ( logs.includes('Cannot find module') || // Webpack error when using import() on a rebuild. // There is no TS error because the type checker is forked on rebuilds. logs.includes('Module not found') ); } describe(`Load children syntax`, () => { it('supports lazy bundle for lazy routes with JIT', async () => { host.writeMultipleFiles(lazyModuleFiles); host.writeMultipleFiles(lazyModuleFnImport); const { files } = await browserBuild(architect, host, target); expect('src_app_lazy_lazy_module_ts.js' in files).toBe(true); }); it('supports lazy bundle for lazy routes with AOT', async () => { host.writeMultipleFiles(lazyModuleFiles); host.writeMultipleFiles(lazyModuleFnImport); addLazyLoadedModulesInTsConfig(host, lazyModuleFiles); const { files } = await browserBuild(architect, host, target, { aot: true }); const data = await files['src_app_lazy_lazy_module_ts.js']; expect(data).toContain('static ɵmod'); }); }); // Errors for missing lazy routes are only supported with function syntax. // `ngProgram.listLazyRoutes` will ignore invalid lazy routes in the route map. describe(`Load children errors with function syntax`, () => { it('should show error when lazy route is invalid', async () => { host.writeMultipleFiles(lazyModuleFiles); host.writeMultipleFiles(lazyModuleFnImport); host.replaceInFile('src/app/app.module.ts', 'lazy.module', 'invalid.module'); const logger = new logging.Logger(''); const logs: string[] = []; logger.subscribe((e) => logs.push(e.message)); const run = await architect.scheduleTarget(target, {}, { logger }); const output = await run.result; expect(output.success).toBe(false); expect(hasMissingModuleError(logs.join())).toBeTrue(); await run.stop(); }); it('should show error when lazy route is invalid on watch mode AOT', async () => { host.writeMultipleFiles(lazyModuleFiles); host.writeMultipleFiles(lazyModuleFnImport); let buildNumber = 0; const overrides = { watch: true, aot: true }; const run = await architect.scheduleTarget(target, overrides); await run.output .pipe( debounceTime(1500), tap((buildEvent) => { buildNumber++; switch (buildNumber) { case 1: expect(buildEvent.success).toBe(true); host.replaceInFile('src/app/app.module.ts', 'lazy.module', 'invalid.module'); break; case 2: expect(buildEvent.success).toBe(false); break; } }), take(2), ) .toPromise(); await run.stop(); }); }); it(`supports lazy bundle for import() calls`, async () => { host.writeMultipleFiles({ 'src/lazy-module.ts': 'export const value = 42;', 'src/main.ts': `import('./lazy-module');`, }); const { files } = await browserBuild(architect, host, target); expect(files['src_lazy-module_ts.js']).toBeDefined(); }); it(`supports lazy bundle for dynamic import() calls`, async () => { host.writeMultipleFiles({ 'src/lazy-module.ts': 'export const value = 42;', 'src/main.ts': ` const lazyFileName = 'module'; import('./lazy-' + lazyFileName); `, }); host.replaceInFile('src/tsconfig.app.json', '"main.ts"', `"main.ts","lazy-module.ts"`); const { files } = await browserBuild(architect, host, target); expect(files['common.js']).toBeDefined(); }); it(`supports making a common bundle for shared lazy modules`, async () => { host.writeMultipleFiles({ 'src/one.ts': `import * as http from '@angular/common/http'; console.log(http);`, 'src/two.ts': `import * as http from '@angular/common/http'; console.log(http);`, 'src/main.ts': `import('./one'); import('./two');`, }); const { files } = await browserBuild(architect, host, target); expect(files['src_one_ts.js']).toBeDefined(); expect(files['src_two_ts.js']).toBeDefined(); expect(files['default-node_modules_angular_common_fesm2022_http_mjs.js']).toBeDefined(); }); it(`supports disabling the common bundle`, async () => { host.writeMultipleFiles({ 'src/one.ts': `import * as http from '@angular/common/http'; console.log(http);`, 'src/two.ts': `import * as http from '@angular/common/http'; console.log(http);`, 'src/main.ts': `import('./one'); import('./two');`, }); const { files } = await browserBuild(architect, host, target, { commonChunk: false }); expect(files['src_one_ts.js']).toBeDefined(); expect(files['src_two_ts.js']).toBeDefined(); expect(files['default-node_modules_angular_common_fesm2022_http_mjs.js']).toBeUndefined(); }); });
{ "end_byte": 6204, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/specs/lazy-module_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/tests/setup.ts_0_826
/** * @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.dev/license */ import { Schema } from '../schema'; export { describeBuilder } from '../../../testing'; export const BROWSER_BUILDER_INFO = Object.freeze({ name: '@angular-devkit/build-angular:browser', schemaPath: __dirname + '/../schema.json', }); /** * Contains all required browser builder fields. * Also disables progress reporting to minimize logging output. */ export const BASE_OPTIONS = Object.freeze<Schema>({ index: 'src/index.html', main: 'src/main.ts', outputPath: 'dist', tsConfig: 'src/tsconfig.app.json', progress: false, // Disable optimizations optimization: false, buildOptimizer: false, });
{ "end_byte": 826, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/tests/setup.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/tests/behavior/browser-support_spec.ts_0_3745
/** * @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.dev/license */ import { buildWebpackBrowser } from '../../index'; import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { describe('Behavior: "Browser support"', () => { it('creates correct sourcemaps when downleveling async functions', async () => { // Add a JavaScript file with async code await harness.writeFile( 'src/async-test.js', 'async function testJs() { console.log("from-async-js-function"); }', ); // Add an async function to the project as well as JavaScript file // The type `Void123` is used as a unique identifier for the final sourcemap // If sourcemaps are not properly propagated then it will not be in the final sourcemap await harness.modifyFile( 'src/main.ts', (content) => 'import "./async-test";\n' + content + '\ntype Void123 = void;' + `\nasync function testApp(): Promise<Void123> { console.log("from-async-app-function"); }`, ); harness.useTarget('build', { ...BASE_OPTIONS, vendorChunk: true, sourceMap: { scripts: true, }, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/main.js').content.not.toMatch(/\sasync\s/); harness.expectFile('dist/main.js.map').content.toContain('Promise<Void123>'); }); it('downlevels async functions ', async () => { // Add an async function to the project await harness.writeFile( 'src/main.ts', 'async function test(): Promise<void> { console.log("from-async-function"); }', ); harness.useTarget('build', { ...BASE_OPTIONS, vendorChunk: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/main.js').content.not.toMatch(/\sasync\s/); harness.expectFile('dist/main.js').content.toContain('"from-async-function"'); }); it('warns when IE is present in browserslist', async () => { await harness.appendToFile( '.browserslistrc', ` IE 9 IE 11 `, ); harness.useTarget('build', { ...BASE_OPTIONS, }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBeTrue(); expect(logs).toContain( jasmine.objectContaining({ level: 'warn', message: `One or more browsers which are configured in the project's Browserslist ` + 'configuration will be ignored as ES5 output is not supported by the Angular CLI.\n' + 'Ignored browsers: ie 11, ie 9', }), ); }); it('downlevels "for await...of"', async () => { // Add an async function to the project await harness.writeFile( 'src/main.ts', ` (async () => { for await (const o of [1, 2, 3]) { console.log("for await...of"); } })(); `, ); harness.useTarget('build', { ...BASE_OPTIONS, vendorChunk: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/main.js').content.not.toMatch(/\sawait\s/); harness.expectFile('dist/main.js').content.toContain('"for await...of"'); }); }); });
{ "end_byte": 3745, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/tests/behavior/browser-support_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/tests/behavior/localize_watch_spec.ts_0_2876
/** * @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.dev/license */ import { concatMap, count, take, timeout } from 'rxjs'; import { BUILD_TIMEOUT, buildWebpackBrowser } from '../../index'; import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { describe('Behavior: "localize works in watch mode"', () => { beforeEach(() => { harness.useProject('test', { root: '.', sourceRoot: 'src', cli: { cache: { enabled: false, }, }, i18n: { locales: { 'fr': 'src/locales/messages.fr.xlf', }, }, }); }); it('localize works in watch mode', async () => { harness.useTarget('build', { ...BASE_OPTIONS, watch: true, localize: true, }); await harness.writeFile( 'src/app/app.component.html', ` <p id="hello" i18n="An introduction header for this sample">Hello {{ title }}! </p> `, ); await harness.writeFile('src/locales/messages.fr.xlf', TRANSLATION_FILE_CONTENT); const buildCount = await harness .execute() .pipe( timeout(BUILD_TIMEOUT), concatMap(async ({ result }, index) => { expect(result?.success).toBe(true); switch (index) { case 0: { harness.expectFile('dist/fr/main.js').content.toContain('Bonjour'); // Trigger rebuild await harness.appendToFile('src/app/app.component.html', '\n\n'); break; } case 1: { harness.expectFile('dist/fr/main.js').content.toContain('Bonjour'); break; } } }), take(2), count(), ) .toPromise(); expect(buildCount).toBe(2); }); }); }); const TRANSLATION_FILE_CONTENT = ` <?xml version="1.0" encoding="UTF-8" ?> <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"> <file target-language="en-US" datatype="plaintext" original="ng2.template"> <body> <trans-unit id="4286451273117902052" datatype="html"> <target>Bonjour <x id="INTERPOLATION" equiv-text="{{ title }}"/>! </target> <context-group purpose="location"> <context context-type="targetfile">src/app/app.component.html</context> <context context-type="linenumber">2,3</context> </context-group> <note priority="1" from="description">An introduction header for this sample</note> </trans-unit> </body> </file> </xliff> `;
{ "end_byte": 2876, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/tests/behavior/localize_watch_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/tests/behavior/index_watch_spec.ts_0_1677
/** * @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.dev/license */ import { concatMap, count, take, timeout } from 'rxjs'; import { BUILD_TIMEOUT, buildWebpackBrowser } from '../../index'; import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { describe('Behavior: "index is updated during watch mode"', () => { it('index is watched in watch mode', async () => { harness.useTarget('build', { ...BASE_OPTIONS, watch: true, }); const buildCount = await harness .execute() .pipe( timeout(BUILD_TIMEOUT), concatMap(async ({ result }, index) => { expect(result?.success).toBe(true); switch (index) { case 0: { harness.expectFile('dist/index.html').content.toContain('HelloWorldApp'); harness.expectFile('dist/index.html').content.not.toContain('UpdatedPageTitle'); // Trigger rebuild await harness.modifyFile('src/index.html', (s) => s.replace('HelloWorldApp', 'UpdatedPageTitle'), ); break; } case 1: { harness.expectFile('dist/index.html').content.toContain('UpdatedPageTitle'); break; } } }), take(2), count(), ) .toPromise(); expect(buildCount).toBe(2); }); }); });
{ "end_byte": 1677, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/tests/behavior/index_watch_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/tests/behavior/styles_unsupported_spec.ts_0_1160
/** * @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.dev/license */ import { logging } from '@angular-devkit/core'; import { buildWebpackBrowser } from '../../index'; import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { describe('Behavior: "Style Unsupported"', () => { it('errors when importing a css file as an ECMA module (Webpack specific behaviour)', async () => { await harness.writeFiles({ 'src/test-style.css': '.test-a {color: red}', 'src/main.ts': `import './test-style.css'`, }); harness.useTarget('build', { ...BASE_OPTIONS, styles: [], }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBeFalse(); expect(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching('./src/test-style.css:1:0 - Error'), }), ); }); }); });
{ "end_byte": 1160, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/tests/behavior/styles_unsupported_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/tests/behavior/rebuild-errors_spec.ts_0_453
/** * @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.dev/license */ import { logging } from '@angular-devkit/core'; import { concatMap, count, take, timeout } from 'rxjs'; import { BUILD_TIMEOUT, buildWebpackBrowser } from '../../index'; import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup';
{ "end_byte": 453, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/tests/behavior/rebuild-errors_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/tests/behavior/rebuild-errors_spec.ts_455_11436
describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { describe('Behavior: "Rebuild Error"', () => { it('detects template errors with no AOT codegen or TS emit differences', async () => { harness.useTarget('build', { ...BASE_OPTIONS, aot: true, watch: true, }); const goodDirectiveContents = ` import { Directive, Input } from '@angular/core'; @Directive({ selector: 'dir', standalone: false }) export class Dir { @Input() foo: number; } `; const typeErrorText = `Type 'number' is not assignable to type 'string'.`; // Create a directive and add to application await harness.writeFile('src/app/dir.ts', goodDirectiveContents); await harness.writeFile( 'src/app/app.module.ts', ` import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { Dir } from './dir'; @NgModule({ declarations: [ AppComponent, Dir, ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } `, ); // Create app component that uses the directive await harness.writeFile( 'src/app/app.component.ts', ` import { Component } from '@angular/core' @Component({ selector: 'app-root', standalone: false, template: '<dir [foo]="123">', }) export class AppComponent { } `, ); const buildCount = await harness .execute({ outputLogsOnFailure: false }) .pipe( timeout(BUILD_TIMEOUT), concatMap(async ({ result, logs }, index) => { switch (index) { case 0: expect(result?.success).toBeTrue(); // Update directive to use a different input type for 'foo' (number -> string) // Should cause a template error await harness.writeFile( 'src/app/dir.ts', ` import { Directive, Input } from '@angular/core'; @Directive({ selector: 'dir', standalone: false }) export class Dir { @Input() foo: string; } `, ); break; case 1: expect(result?.success).toBeFalse(); expect(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching(typeErrorText), }), ); // Make an unrelated change to verify error cache was updated // Should persist error in the next rebuild await harness.modifyFile('src/main.ts', (content) => content + '\n'); break; case 2: expect(result?.success).toBeFalse(); expect(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching(typeErrorText), }), ); // Revert the directive change that caused the error // Should remove the error await harness.writeFile('src/app/dir.ts', goodDirectiveContents); break; case 3: expect(result?.success).toBeTrue(); expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching(typeErrorText), }), ); // Make an unrelated change to verify error cache was updated // Should continue showing no error await harness.modifyFile('src/main.ts', (content) => content + '\n'); break; case 4: expect(result?.success).toBeTrue(); expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching(typeErrorText), }), ); break; } }), take(5), count(), ) .toPromise(); expect(buildCount).toBe(5); }); it('detects template errors with AOT codegen differences', async () => { harness.useTarget('build', { ...BASE_OPTIONS, aot: true, watch: true, }); const typeErrorText = `Type 'number' is not assignable to type 'string'.`; // Create two directives and add to application await harness.writeFile( 'src/app/dir.ts', ` import { Directive, Input } from '@angular/core'; @Directive({ selector: 'dir', standalone: false }) export class Dir { @Input() foo: number; } `, ); // Same selector with a different type on the `foo` property but initially no `@Input` const goodDirectiveContents = ` import { Directive } from '@angular/core'; @Directive({ selector: 'dir', standalone: false }) export class Dir2 { foo: string; } `; await harness.writeFile('src/app/dir2.ts', goodDirectiveContents); await harness.writeFile( 'src/app/app.module.ts', ` import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { Dir } from './dir'; import { Dir2 } from './dir2'; @NgModule({ declarations: [ AppComponent, Dir, Dir2, ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } `, ); // Create app component that uses the directive await harness.writeFile( 'src/app/app.component.ts', ` import { Component } from '@angular/core' @Component({ selector: 'app-root', standalone: false, template: '<dir [foo]="123">', }) export class AppComponent { } `, ); const buildCount = await harness .execute({ outputLogsOnFailure: false }) .pipe( timeout(BUILD_TIMEOUT), concatMap(async ({ result, logs }, index) => { switch (index) { case 0: expect(result?.success).toBeTrue(); // Update second directive to use string property `foo` as an Input // Should cause a template error await harness.writeFile( 'src/app/dir2.ts', ` import { Directive, Input } from '@angular/core'; @Directive({ selector: 'dir', standalone: false }) export class Dir2 { @Input() foo: string; } `, ); break; case 1: expect(result?.success).toBeFalse(); expect(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching(typeErrorText), }), ); // Make an unrelated change to verify error cache was updated // Should persist error in the next rebuild await harness.modifyFile('src/main.ts', (content) => content + '\n'); break; case 2: expect(result?.success).toBeFalse(); expect(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching(typeErrorText), }), ); // Revert the directive change that caused the error // Should remove the error await harness.writeFile('src/app/dir2.ts', goodDirectiveContents); break; case 3: expect(result?.success).toBeTrue(); expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching(typeErrorText), }), ); // Make an unrelated change to verify error cache was updated // Should continue showing no error await harness.modifyFile('src/main.ts', (content) => content + '\n'); break; case 4: expect(result?.success).toBeTrue(); expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching(typeErrorText), }), ); break; } }), take(5), count(), ) .toPromise(); expect(buildCount).toBe(5); }); it('recovers from component stylesheet error', async () => { harness.useTarget('build', { ...BASE_OPTIONS, watch: true, aot: false, }); const buildCount = await harness .execute({ outputLogsOnFailure: false }) .pipe( timeout(BUILD_TIMEOUT), concatMap(async ({ result, logs }, index) => { switch (index) { case 0: expect(result?.success).toBeTrue(); await harness.writeFile('src/app/app.component.css', 'invalid-css-content'); break; case 1: expect(result?.success).toBeFalse(); expect(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching('invalid-css-content'), }), ); await harness.writeFile('src/app/app.component.css', 'p { color: green }'); break; case 2: expect(result?.success).toBeTrue(); expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching('invalid-css-content'), }), ); harness.expectFile('dist/main.js').content.toContain('p { color: green }'); break; } }), take(3), count(), ) .toPromise(); expect(buildCount).toBe(3); }); }); });
{ "end_byte": 11436, "start_byte": 455, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/tests/behavior/rebuild-errors_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/tests/options/assets_spec.ts_0_3936
/** * @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.dev/license */ import { buildWebpackBrowser } from '../../index'; import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { describe('Option: "assets"', () => { beforeEach(async () => { // Application code is not needed for asset tests await harness.writeFile('src/main.ts', ''); }); it('supports an empty array value', async () => { harness.useTarget('build', { ...BASE_OPTIONS, assets: [], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); }); it('supports mixing shorthand and longhand syntax', async () => { await harness.writeFile('src/files/test.svg', '<svg></svg>'); await harness.writeFile('src/files/another.file', 'asset file'); await harness.writeFile('src/extra.file', 'extra file'); harness.useTarget('build', { ...BASE_OPTIONS, assets: ['src/extra.file', { glob: '*', input: 'src/files', output: '.' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/extra.file').content.toBe('extra file'); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/another.file').content.toBe('asset file'); }); describe('shorthand syntax', () => { it('copies a single asset', async () => { await harness.writeFile('src/test.svg', '<svg></svg>'); harness.useTarget('build', { ...BASE_OPTIONS, assets: ['src/test.svg'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); }); it('copies multiple assets', async () => { await harness.writeFile('src/test.svg', '<svg></svg>'); await harness.writeFile('src/another.file', 'asset file'); harness.useTarget('build', { ...BASE_OPTIONS, assets: ['src/test.svg', 'src/another.file'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/another.file').content.toBe('asset file'); }); it('copies an asset with directory and maintains directory in output', async () => { await harness.writeFile('src/subdirectory/test.svg', '<svg></svg>'); harness.useTarget('build', { ...BASE_OPTIONS, assets: ['src/subdirectory/test.svg'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/subdirectory/test.svg').content.toBe('<svg></svg>'); }); it('does not fail if asset does not exist', async () => { harness.useTarget('build', { ...BASE_OPTIONS, assets: ['src/test.svg'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/test.svg').toNotExist(); }); it('fail if asset path is not within project source root', async () => { await harness.writeFile('test.svg', '<svg></svg>'); harness.useTarget('build', { ...BASE_OPTIONS, assets: ['test.svg'], }); const { result } = await harness.executeOnce(); expect(result?.error).toMatch('path must start with the project source root'); harness.expectFile('dist/test.svg').toNotExist(); }); });
{ "end_byte": 3936, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/tests/options/assets_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/tests/options/assets_spec.ts_3942_12631
describe('longhand syntax', () => { it('copies a single asset', async () => { await harness.writeFile('src/test.svg', '<svg></svg>'); harness.useTarget('build', { ...BASE_OPTIONS, assets: [{ glob: 'test.svg', input: 'src', output: '.' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); }); it('copies multiple assets as separate entries', async () => { await harness.writeFile('src/test.svg', '<svg></svg>'); await harness.writeFile('src/another.file', 'asset file'); harness.useTarget('build', { ...BASE_OPTIONS, assets: [ { glob: 'test.svg', input: 'src', output: '.' }, { glob: 'another.file', input: 'src', output: '.' }, ], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/another.file').content.toBe('asset file'); }); it('copies multiple assets with a single entry glob pattern', async () => { await harness.writeFile('src/test.svg', '<svg></svg>'); await harness.writeFile('src/another.file', 'asset file'); harness.useTarget('build', { ...BASE_OPTIONS, assets: [{ glob: '{test.svg,another.file}', input: 'src', output: '.' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/another.file').content.toBe('asset file'); }); it('copies multiple assets with a wildcard glob pattern', async () => { await harness.writeFile('src/files/test.svg', '<svg></svg>'); await harness.writeFile('src/files/another.file', 'asset file'); harness.useTarget('build', { ...BASE_OPTIONS, assets: [{ glob: '*', input: 'src/files', output: '.' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/another.file').content.toBe('asset file'); }); it('copies multiple assets with a recursive wildcard glob pattern', async () => { await harness.writeFiles({ 'src/files/test.svg': '<svg></svg>', 'src/files/another.file': 'asset file', 'src/files/nested/extra.file': 'extra file', }); harness.useTarget('build', { ...BASE_OPTIONS, assets: [{ glob: '**/*', input: 'src/files', output: '.' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/another.file').content.toBe('asset file'); harness.expectFile('dist/nested/extra.file').content.toBe('extra file'); }); it('automatically ignores "." prefixed files when using wildcard glob pattern', async () => { await harness.writeFile('src/files/.gitkeep', ''); harness.useTarget('build', { ...BASE_OPTIONS, assets: [{ glob: '*', input: 'src/files', output: '.' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/.gitkeep').toNotExist(); }); it('supports ignoring a specific file when using a glob pattern', async () => { await harness.writeFiles({ 'src/files/test.svg': '<svg></svg>', 'src/files/another.file': 'asset file', 'src/files/nested/extra.file': 'extra file', }); harness.useTarget('build', { ...BASE_OPTIONS, assets: [{ glob: '**/*', input: 'src/files', output: '.', ignore: ['another.file'] }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/another.file').toNotExist(); harness.expectFile('dist/nested/extra.file').content.toBe('extra file'); }); it('supports ignoring with a glob pattern when using a glob pattern', async () => { await harness.writeFiles({ 'src/files/test.svg': '<svg></svg>', 'src/files/another.file': 'asset file', 'src/files/nested/extra.file': 'extra file', }); harness.useTarget('build', { ...BASE_OPTIONS, assets: [{ glob: '**/*', input: 'src/files', output: '.', ignore: ['**/*.file'] }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/another.file').toNotExist(); harness.expectFile('dist/nested/extra.file').toNotExist(); }); it('copies an asset with directory and maintains directory in output', async () => { await harness.writeFile('src/subdirectory/test.svg', '<svg></svg>'); harness.useTarget('build', { ...BASE_OPTIONS, assets: [{ glob: 'subdirectory/test.svg', input: 'src', output: '.' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/subdirectory/test.svg').content.toBe('<svg></svg>'); }); it('does not fail if asset does not exist', async () => { harness.useTarget('build', { ...BASE_OPTIONS, assets: [{ glob: 'test.svg', input: 'src', output: '.' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/test.svg').toNotExist(); }); it('uses project output path when output option is empty string', async () => { await harness.writeFile('src/test.svg', '<svg></svg>'); harness.useTarget('build', { ...BASE_OPTIONS, assets: [{ glob: 'test.svg', input: 'src', output: '' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); }); it('uses project output path when output option is "."', async () => { await harness.writeFile('src/test.svg', '<svg></svg>'); harness.useTarget('build', { ...BASE_OPTIONS, assets: [{ glob: 'test.svg', input: 'src', output: '.' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); }); it('uses project output path when output option is "/"', async () => { await harness.writeFile('src/test.svg', '<svg></svg>'); harness.useTarget('build', { ...BASE_OPTIONS, assets: [{ glob: 'test.svg', input: 'src', output: '/' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/test.svg').content.toBe('<svg></svg>'); }); it('creates a project output sub-path when output option path does not exist', async () => { await harness.writeFile('src/test.svg', '<svg></svg>'); harness.useTarget('build', { ...BASE_OPTIONS, assets: [{ glob: 'test.svg', input: 'src', output: 'subdirectory' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/subdirectory/test.svg').content.toBe('<svg></svg>'); }); it('fails if output option is not within project output path', async () => { await harness.writeFile('test.svg', '<svg></svg>'); harness.useTarget('build', { ...BASE_OPTIONS, assets: [{ glob: 'test.svg', input: 'src', output: '..' }], }); const { result } = await harness.executeOnce(); expect(result?.error).toMatch( 'An asset cannot be written to a location outside of the output path', ); harness.expectFile('dist/test.svg').toNotExist(); }); }); }); });
{ "end_byte": 12631, "start_byte": 3942, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/tests/options/assets_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/tests/options/main_spec.ts_0_2084
/** * @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.dev/license */ import { buildWebpackBrowser } from '../../index'; import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { describe('Option: "main"', () => { it('uses a provided TypeScript file', async () => { harness.useTarget('build', { ...BASE_OPTIONS, main: 'src/main.ts', }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/runtime.js').toExist(); harness.expectFile('dist/main.js').toExist(); harness.expectFile('dist/index.html').toExist(); }); it('uses a provided JavaScript file', async () => { await harness.writeFile('src/main.js', `console.log('main');`); harness.useTarget('build', { ...BASE_OPTIONS, main: 'src/main.js', }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/runtime.js').toExist(); harness.expectFile('dist/main.js').toExist(); harness.expectFile('dist/index.html').toExist(); harness.expectFile('dist/main.js').content.toContain(`console.log('main')`); }); it('fails and shows an error when file does not exist', async () => { harness.useTarget('build', { ...BASE_OPTIONS, main: 'src/missing.ts', }); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBe(false); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching('Module not found:') }), ); harness.expectFile('dist/runtime.js').toNotExist(); harness.expectFile('dist/main.js').toNotExist(); harness.expectFile('dist/index.html').toNotExist(); }); }); });
{ "end_byte": 2084, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/tests/options/main_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/tests/options/inline-style-language_spec.ts_0_5251
/** * @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.dev/license */ import { concatMap, count, take, timeout } from 'rxjs'; import { buildWebpackBrowser } from '../../index'; import { InlineStyleLanguage } from '../../schema'; import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { describe('Option: "inlineStyleLanguage"', () => { beforeEach(async () => { // Setup application component with inline style property await harness.modifyFile('src/app/app.component.ts', (content) => { return content .replace('styleUrls', 'styles') .replace('./app.component.css', '__STYLE_MARKER__'); }); }); for (const aot of [true, false]) { describe(`[${aot ? 'AOT' : 'JIT'}]`, () => { it('supports SCSS inline component styles when set to "scss"', async () => { harness.useTarget('build', { ...BASE_OPTIONS, inlineStyleLanguage: InlineStyleLanguage.Scss, aot, }); await harness.modifyFile('src/app/app.component.ts', (content) => content.replace('__STYLE_MARKER__', '$primary: indianred;\\nh1 { color: $primary; }'), ); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/main.js').content.toContain('color: indianred'); }); it('supports Sass inline component styles when set to "sass"', async () => { harness.useTarget('build', { ...BASE_OPTIONS, inlineStyleLanguage: InlineStyleLanguage.Sass, aot, }); await harness.modifyFile('src/app/app.component.ts', (content) => content.replace('__STYLE_MARKER__', '$primary: indianred\\nh1\\n\\tcolor: $primary'), ); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/main.js').content.toContain('color: indianred'); }); it('supports Less inline component styles when set to "less"', async () => { harness.useTarget('build', { ...BASE_OPTIONS, inlineStyleLanguage: InlineStyleLanguage.Less, aot, }); await harness.modifyFile('src/app/app.component.ts', (content) => content.replace('__STYLE_MARKER__', '@primary: indianred;\\nh1 { color: @primary; }'), ); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/main.js').content.toContain('color: indianred'); }); it('updates produced stylesheet in watch mode', async () => { harness.useTarget('build', { ...BASE_OPTIONS, main: 'src/main.ts', inlineStyleLanguage: InlineStyleLanguage.Scss, aot, watch: true, }); await harness.modifyFile('src/app/app.component.ts', (content) => content.replace('__STYLE_MARKER__', '$primary: indianred;\\nh1 { color: $primary; }'), ); const buildCount = await harness .execute() .pipe( timeout(30000), concatMap(async ({ result }, index) => { expect(result?.success).toBe(true); switch (index) { case 0: harness.expectFile('dist/main.js').content.toContain('color: indianred'); harness.expectFile('dist/main.js').content.not.toContain('color: aqua'); await harness.modifyFile('src/app/app.component.ts', (content) => content.replace( '$primary: indianred;\\nh1 { color: $primary; }', '$primary: aqua;\\nh1 { color: $primary; }', ), ); break; case 1: harness.expectFile('dist/main.js').content.not.toContain('color: indianred'); harness.expectFile('dist/main.js').content.toContain('color: aqua'); await harness.modifyFile('src/app/app.component.ts', (content) => content.replace( '$primary: aqua;\\nh1 { color: $primary; }', '$primary: blue;\\nh1 { color: $primary; }', ), ); break; case 2: harness.expectFile('dist/main.js').content.not.toContain('color: indianred'); harness.expectFile('dist/main.js').content.not.toContain('color: aqua'); harness.expectFile('dist/main.js').content.toContain('color: blue'); break; } }), take(3), count(), ) .toPromise(); expect(buildCount).toBe(3); }); }); } }); });
{ "end_byte": 5251, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/tests/options/inline-style-language_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/tests/options/inline-critical_spec.ts_0_5135
/** * @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.dev/license */ import { buildWebpackBrowser } from '../../index'; import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { describe('Option: "inlineCritical"', () => { beforeEach(async () => { await harness.writeFile('src/styles.css', 'body { color: #000 }'); }); it(`should extract critical css when 'inlineCritical' is true`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, optimization: { scripts: false, styles: { minify: true, inlineCritical: true, }, fonts: false, }, styles: ['src/styles.css'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/index.html') .content.toContain( `<link rel="stylesheet" href="styles.css" media="print" onload="this.media='all'">`, ); harness.expectFile('dist/index.html').content.toContain(`body{color:#000}`); }); it(`should extract critical css when 'optimization' is unset`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.css'], optimization: undefined, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/index.html') .content.toContain( `<link rel="stylesheet" href="styles.css" media="print" onload="this.media='all'">`, ); harness.expectFile('dist/index.html').content.toContain(`body{color:#000}`); }); it(`should extract critical css when 'optimization' is true`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.css'], optimization: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/index.html') .content.toContain( `<link rel="stylesheet" href="styles.css" media="print" onload="this.media='all'">`, ); harness.expectFile('dist/index.html').content.toContain(`body{color:#000}`); }); it(`should not extract critical css when 'optimization' is false`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.css'], optimization: false, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/index.html').content.not.toContain(`<style`); }); it(`should not extract critical css when 'inlineCritical' is false`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.css'], optimization: { scripts: false, styles: { minify: false, inlineCritical: false, }, fonts: false, }, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/index.html').content.not.toContain(`<style`); }); it(`should extract critical css when 'inlineCritical' when using 'deployUrl'`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, deployUrl: 'http://cdn.com/', optimization: { scripts: false, styles: { minify: true, inlineCritical: true, }, fonts: false, }, styles: ['src/styles.css'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/index.html') .content.toContain( `<link rel="stylesheet" href="http://cdn.com/styles.css" media="print" onload="this.media='all'">`, ); harness.expectFile('dist/index.html').content.toContain(`body{color:#000}`); }); it(`should extract critical css when using '@media all {}' and 'minify' is set to true`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.css'], optimization: { scripts: false, styles: { minify: true, inlineCritical: true, }, fonts: false, }, }); await harness.writeFile('src/styles.css', '@media all { body { color: #000 } }'); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/index.html') .content.toContain( `<link rel="stylesheet" href="styles.css" media="print" onload="this.media='all'">`, ); harness.expectFile('dist/index.html').content.toContain(`body{color:#000}`); }); }); });
{ "end_byte": 5135, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/tests/options/inline-critical_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/tests/options/bundle-budgets_spec.ts_0_6889
/** * @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.dev/license */ import { logging } from '@angular-devkit/core'; import { lazyModuleFiles, lazyModuleFnImport } from '../../../../testing/test-utils'; import { buildWebpackBrowser } from '../../index'; import { Type } from '../../schema'; import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { const CSS_EXTENSIONS = ['css', 'scss', 'less']; const BUDGET_NOT_MET_REGEXP = /Budget .+ was not met by/; describe('Option: "bundleBudgets"', () => { it(`should not warn when size is below threshold`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, optimization: true, budgets: [{ type: Type.All, maximumWarning: '100mb' }], }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ level: 'warn', message: jasmine.stringMatching(BUDGET_NOT_MET_REGEXP), }), ); }); it(`should error when size is above 'maximumError' threshold`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, optimization: true, budgets: [{ type: Type.All, maximumError: '100b' }], }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(false); expect(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ level: 'error', message: jasmine.stringMatching(BUDGET_NOT_MET_REGEXP), }), ); }); it(`should warn when size is above 'maximumWarning' threshold`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, optimization: true, budgets: [{ type: Type.All, maximumWarning: '100b' }], }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ level: 'warn', message: jasmine.stringMatching(BUDGET_NOT_MET_REGEXP), }), ); }); it(`should warn when lazy bundle is above 'maximumWarning' threshold`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, optimization: true, budgets: [{ type: Type.Bundle, name: 'lazy-lazy-module', maximumWarning: '100b' }], }); await harness.writeFiles(lazyModuleFiles); await harness.writeFiles(lazyModuleFnImport); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ level: 'warn', message: jasmine.stringMatching('lazy-lazy-module exceeded maximum budget'), }), ); }); CSS_EXTENSIONS.forEach((ext) => { it(`shows warnings for large component ${ext} when using 'anyComponentStyle' when AOT`, async () => { const cssContent = ` .foo { color: white; padding: 1px; } .buz { color: white; padding: 2px; } .bar { color: white; padding: 3px; } `; await harness.writeFiles({ [`src/app/app.component.${ext}`]: cssContent, [`src/assets/foo.${ext}`]: cssContent, [`src/styles.${ext}`]: cssContent, }); await harness.modifyFile('src/app/app.component.ts', (content) => content.replace('app.component.css', `app.component.${ext}`), ); harness.useTarget('build', { ...BASE_OPTIONS, optimization: true, aot: true, styles: [`src/styles.${ext}`], budgets: [{ type: Type.AnyComponentStyle, maximumWarning: '1b' }], }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ level: 'warn', message: jasmine.stringMatching(new RegExp(`Warning.+app.component.${ext}`)), }), ); }); }); describe(`should ignore '.map' files`, () => { it(`when 'bundle' budget`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, sourceMap: true, optimization: true, extractLicenses: true, budgets: [{ type: Type.Bundle, name: 'main', maximumError: '1mb' }], }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ level: 'error', message: jasmine.stringMatching(BUDGET_NOT_MET_REGEXP), }), ); }); it(`when 'intial' budget`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, sourceMap: true, optimization: true, extractLicenses: true, budgets: [{ type: Type.Initial, name: 'main', maximumError: '1mb' }], }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ level: 'error', message: jasmine.stringMatching(BUDGET_NOT_MET_REGEXP), }), ); }); it(`when 'all' budget`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, sourceMap: true, optimization: true, extractLicenses: true, budgets: [{ type: Type.All, maximumError: '1mb' }], }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ level: 'error', message: jasmine.stringMatching(BUDGET_NOT_MET_REGEXP), }), ); }); it(`when 'any' budget`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, sourceMap: true, optimization: true, extractLicenses: true, budgets: [{ type: Type.Any, maximumError: '1mb' }], }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ level: 'error', message: jasmine.stringMatching(BUDGET_NOT_MET_REGEXP), }), ); }); }); }); });
{ "end_byte": 6889, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/tests/options/bundle-budgets_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/tests/options/stats-json_spec.ts_0_2444
/** * @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.dev/license */ import { buildWebpackBrowser } from '../../index'; import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { describe('Option: "statsJson"', () => { beforeEach(async () => { // Application code is not needed for stat JSON tests await harness.writeFile('src/main.ts', ''); }); it('generates a Webpack Stats file in output when true', async () => { harness.useTarget('build', { ...BASE_OPTIONS, statsJson: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); if (harness.expectFile('dist/stats.json').toExist()) { const content = harness.readFile('dist/stats.json'); expect(() => JSON.parse(content)) .withContext('Expected Webpack Stats file to be valid JSON.') .not.toThrow(); } }); // TODO: Investigate why this profiling object is no longer present in Webpack 5.90.3+ and if this should even be tested xit('includes Webpack profiling information', async () => { harness.useTarget('build', { ...BASE_OPTIONS, statsJson: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); if (harness.expectFile('dist/stats.json').toExist()) { const stats = JSON.parse(harness.readFile('dist/stats.json')); expect(stats?.chunks?.[0]?.modules?.[0]?.profile?.building).toBeDefined(); } }); it('does not generate a Webpack Stats file in output when false', async () => { harness.useTarget('build', { ...BASE_OPTIONS, statsJson: false, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/stats.json').toNotExist(); }); it('does not generate a Webpack Stats file in output when not present', async () => { harness.useTarget('build', { ...BASE_OPTIONS, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/stats.json').toNotExist(); }); }); });
{ "end_byte": 2444, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/tests/options/stats-json_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/tests/options/subresource-integrity_spec.ts_0_2254
/** * @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.dev/license */ import { logging } from '@angular-devkit/core'; import { buildWebpackBrowser } from '../../index'; import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { describe('Option: "subresourceIntegrity"', () => { it(`does not add integrity attribute when not present`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/index.html').content.not.toContain('integrity='); }); it(`does not add integrity attribute when 'false'`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, subresourceIntegrity: false, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/index.html').content.not.toContain('integrity='); }); it(`does add integrity attribute when 'true'`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, subresourceIntegrity: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/index.html').content.toMatch(/integrity="\w+-[A-Za-z0-9/+=]+"/); }); it(`does not issue a warning when 'true' and 'scripts' is set.`, async () => { await harness.writeFile('src/script.js', ''); harness.useTarget('build', { ...BASE_OPTIONS, subresourceIntegrity: true, scripts: ['src/script.js'], }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/index.html').content.toMatch(/integrity="\w+-[A-Za-z0-9/+=]+"/); expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching(/subresource-integrity/), }), ); }); }); });
{ "end_byte": 2254, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/tests/options/subresource-integrity_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/tests/options/allowed-common-js-dependencies_spec.ts_0_4756
/** * @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.dev/license */ import { logging } from '@angular-devkit/core'; import { buildWebpackBrowser } from '../../index'; import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { describe('Option: "allowedCommonJsDependencies"', () => { describe('given option is not set', () => { for (const aot of [true, false]) { it(`should show warning when depending on a Common JS bundle in ${ aot ? 'AOT' : 'JIT' } Mode`, async () => { // Add a Common JS dependency await harness.appendToFile('src/app/app.component.ts', `import 'ajv';`); harness.useTarget('build', { ...BASE_OPTIONS, allowedCommonJsDependencies: [], aot, }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching( /Warning: .+app\.component\.ts depends on 'ajv'\. CommonJS or AMD dependencies/, ), }), ); expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching('require-from-string'), }), 'Should not warn on transitive CommonJS packages which parent is also CommonJS.', ); }); } }); it('should not show warning when depending on a Common JS bundle which is allowed', async () => { // Add a Common JS dependency await harness.appendToFile( 'src/app/app.component.ts', ` import 'ajv'; import 'zone.js'; `, ); harness.useTarget('build', { ...BASE_OPTIONS, allowedCommonJsDependencies: ['ajv', 'zone.js'], }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching(/CommonJS or AMD dependencies/), }), ); }); it('should not show warning when all dependencies are allowed by wildcard', async () => { // Add a Common JS dependency await harness.appendToFile( 'src/app/app.component.ts', ` import 'ajv'; import 'zone.js'; `, ); harness.useTarget('build', { ...BASE_OPTIONS, allowedCommonJsDependencies: ['*'], }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching(/CommonJS or AMD dependencies/), }), ); }); it(`should not show warning when importing non global local data '@angular/common/locale/fr'`, async () => { await harness.appendToFile( 'src/app/app.component.ts', `import '@angular/common/locales/fr';`, ); harness.useTarget('build', { ...BASE_OPTIONS, allowedCommonJsDependencies: [], }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching(/CommonJS or AMD dependencies/), }), ); }); it('should not show warning in JIT for templateUrl and styleUrl when using paths', async () => { await harness.modifyFile('tsconfig.json', (content) => { return content.replace( /"baseUrl": ".\/",/, ` "baseUrl": "./", "paths": { "@app/*": [ "src/app/*" ] }, `, ); }); await harness.modifyFile('src/app/app.module.ts', (content) => content.replace('./app.component', '@app/app.component'), ); harness.useTarget('build', { ...BASE_OPTIONS, allowedCommonJsDependencies: [], aot: false, }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching(/CommonJS or AMD dependencies/), }), ); }); }); });
{ "end_byte": 4756, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/tests/options/allowed-common-js-dependencies_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/tests/options/output-hashing_spec.ts_0_6787
/** * @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.dev/license */ import { buildWebpackBrowser } from '../../index'; import { OutputHashing } from '../../schema'; import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { describe('Option: "outputHashing"', () => { beforeEach(async () => { // Application code is not needed for asset tests await harness.writeFile('src/main.ts', ''); await harness.writeFile('src/polyfills.ts', ''); }); it('hashes all filenames when set to "all"', async () => { await harness.writeFile('src/styles.css', `h1 { background: url('./spectrum.png')}`); harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.css'], polyfills: 'src/polyfills.ts', outputHashing: OutputHashing.All, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(harness.hasFileMatch('dist', /runtime\.[0-9a-f]{16}\.js$/)).toBeTrue(); expect(harness.hasFileMatch('dist', /main\.[0-9a-f]{16}\.js$/)).toBeTrue(); expect(harness.hasFileMatch('dist', /polyfills\.[0-9a-f]{16}\.js$/)).toBeTrue(); expect(harness.hasFileMatch('dist', /styles\.[0-9a-f]{16}\.css$/)).toBeTrue(); expect(harness.hasFileMatch('dist', /spectrum\.[0-9a-f]{16}\.png$/)).toBeTrue(); }); it(`doesn't hash any filenames when not set`, async () => { await harness.writeFile('src/styles.css', `h1 { background: url('./spectrum.png')}`); harness.useTarget('build', { ...BASE_OPTIONS, polyfills: 'src/polyfills.ts', styles: ['src/styles.css'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(harness.hasFileMatch('dist', /runtime\.[0-9a-f]{16}\.js$/)).toBeFalse(); expect(harness.hasFileMatch('dist', /main\.[0-9a-f]{16}\.js$/)).toBeFalse(); expect(harness.hasFileMatch('dist', /polyfills\.[0-9a-f]{16}\.js$/)).toBeFalse(); expect(harness.hasFileMatch('dist', /styles\.[0-9a-f]{16}\.css$/)).toBeFalse(); expect(harness.hasFileMatch('dist', /spectrum\.[0-9a-f]{16}\.png$/)).toBeFalse(); }); it(`doesn't hash any filenames when set to "none"`, async () => { await harness.writeFile('src/styles.css', `h1 { background: url('./spectrum.png')}`); harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.css'], polyfills: 'src/polyfills.ts', outputHashing: OutputHashing.None, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(harness.hasFileMatch('dist', /runtime\.[0-9a-f]{16}\.js$/)).toBeFalse(); expect(harness.hasFileMatch('dist', /main\.[0-9a-f]{16}\.js$/)).toBeFalse(); expect(harness.hasFileMatch('dist', /polyfills\.[0-9a-f]{16}\.js$/)).toBeFalse(); expect(harness.hasFileMatch('dist', /styles\.[0-9a-f]{16}\.css$/)).toBeFalse(); expect(harness.hasFileMatch('dist', /spectrum\.[0-9a-f]{16}\.png$/)).toBeFalse(); }); it(`hashes CSS resources filenames only when set to "media"`, async () => { await harness.writeFile('src/styles.css', `h1 { background: url('./spectrum.png')}`); harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.css'], polyfills: 'src/polyfills.ts', outputHashing: OutputHashing.Media, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(harness.hasFileMatch('dist', /runtime\.[0-9a-f]{16}\.js$/)).toBeFalse(); expect(harness.hasFileMatch('dist', /main\.[0-9a-f]{16}\.js$/)).toBeFalse(); expect(harness.hasFileMatch('dist', /polyfills\.[0-9a-f]{16}\.js$/)).toBeFalse(); expect(harness.hasFileMatch('dist', /styles\.[0-9a-f]{16}\.css$/)).toBeFalse(); expect(harness.hasFileMatch('dist', /spectrum\.[0-9a-f]{16}\.png$/)).toBeTrue(); }); it(`hashes bundles filenames only when set to "bundles"`, async () => { await harness.writeFile('src/styles.css', `h1 { background: url('./spectrum.png')}`); harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.css'], polyfills: 'src/polyfills.ts', outputHashing: OutputHashing.Bundles, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(harness.hasFileMatch('dist', /runtime\.[0-9a-f]{16}\.js$/)).toBeTrue(); expect(harness.hasFileMatch('dist', /main\.[0-9a-f]{16}\.js$/)).toBeTrue(); expect(harness.hasFileMatch('dist', /polyfills\.[0-9a-f]{16}\.js$/)).toBeTrue(); expect(harness.hasFileMatch('dist', /styles\.[0-9a-f]{16}\.css$/)).toBeTrue(); expect(harness.hasFileMatch('dist', /spectrum\.[0-9a-f]{16}\.png$/)).toBeFalse(); }); it('does not hash non injected styles', async () => { harness.useTarget('build', { ...BASE_OPTIONS, outputHashing: OutputHashing.All, sourceMap: true, styles: [ { input: 'src/styles.css', inject: false, }, ], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(harness.hasFileMatch('dist', /styles\.[0-9a-f]{16}\.js$/)).toBeFalse(); expect(harness.hasFileMatch('dist', /styles\.[0-9a-f]{16}\.js.map$/)).toBeFalse(); harness.expectFile('dist/styles.css').toExist(); harness.expectFile('dist/styles.css.map').toExist(); }); it('does not override different files which has the same filenames when hashing is "none"', async () => { await harness.writeFiles({ 'src/styles.css': ` h1 { background: url('./test.svg')} h2 { background: url('./small/test.svg')} `, './src/test.svg': `<svg xmlns="http://www.w3.org/2000/svg"> <text x="20" y="20" font-size="20" fill="red">Hello World</text> </svg>`, './src/small/test.svg': `<svg xmlns="http://www.w3.org/2000/svg"> <text x="10" y="10" font-size="10" fill="red">Hello World</text> </svg>`, }); harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.css'], outputHashing: OutputHashing.None, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/test.svg').toExist(); harness.expectFile('dist/small-test.svg').toExist(); }); }); });
{ "end_byte": 6787, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/tests/options/output-hashing_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/tests/options/watch_spec.ts_0_2991
/** * @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.dev/license */ import { concatMap, count, take, timeout } from 'rxjs'; import { buildWebpackBrowser } from '../../index'; import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { describe('Option: "watch"', () => { beforeEach(async () => { // Application code is not needed for these tests await harness.writeFile('src/main.ts', ''); }); it('does not wait for file changes when false', (done) => { harness.useTarget('build', { ...BASE_OPTIONS, watch: false, }); // If the build waits then it will timeout with the custom timeout. // A single build should not take more than 15 seconds. let count = 0; harness .execute() .pipe(timeout(15000)) .subscribe({ complete() { expect(count).toBe(1); done(); }, next({ result }) { count++; expect(result?.success).toBe(true); }, error(error) { done.fail(error); }, }); }); it('does not wait for file changes when not present', (done) => { harness.useTarget('build', { ...BASE_OPTIONS, }); // If the build waits then it will timeout with the custom timeout. // A single build should not take more than 15 seconds. let count = 0; harness .execute() .pipe(timeout(15000)) .subscribe({ complete() { expect(count).toBe(1); done(); }, next({ result }) { count++; expect(result?.success).toBe(true); }, error(error) { done.fail(error); }, }); }); it('watches for file changes when true', async () => { harness.useTarget('build', { ...BASE_OPTIONS, main: 'src/main.ts', watch: true, }); const buildCount = await harness .execute() .pipe( timeout(30000), concatMap(async ({ result }, index) => { expect(result?.success).toBe(true); switch (index) { case 0: harness.expectFile('dist/main.js').content.not.toContain('abcd1234'); await harness.modifyFile( 'src/main.ts', (content) => content + 'console.log("abcd1234");', ); break; case 1: harness.expectFile('dist/main.js').content.toContain('abcd1234'); break; } }), take(2), count(), ) .toPromise(); expect(buildCount).toBe(2); }); }); });
{ "end_byte": 2991, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/tests/options/watch_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/tests/options/scripts_spec.ts_0_4980
/** * @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.dev/license */ import { buildWebpackBrowser } from '../../index'; import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { describe('Option: "scripts"', () => { beforeEach(async () => { // Application code is not needed for scripts tests await harness.writeFile('src/main.ts', ''); }); it('supports an empty array value', async () => { harness.useTarget('build', { ...BASE_OPTIONS, scripts: [], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); }); it('processes an empty script when optimizing', async () => { await harness.writeFile('src/test-script-a.js', ''); harness.useTarget('build', { ...BASE_OPTIONS, optimization: { scripts: true, }, scripts: ['src/test-script-a.js'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/scripts.js').toExist(); harness .expectFile('dist/index.html') .content.toContain('<script src="scripts.js" defer></script>'); }); describe('shorthand syntax', () => { it('processes a single script into a single output', async () => { await harness.writeFile('src/test-script-a.js', 'console.log("a");'); harness.useTarget('build', { ...BASE_OPTIONS, scripts: ['src/test-script-a.js'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/scripts.js').content.toContain('console.log("a")'); harness .expectFile('dist/index.html') .content.toContain('<script src="scripts.js" defer></script>'); }); it('processes multiple scripts into a single output', async () => { await harness.writeFile('src/test-script-a.js', 'console.log("a");'); await harness.writeFile('src/test-script-b.js', 'console.log("b");'); harness.useTarget('build', { ...BASE_OPTIONS, scripts: ['src/test-script-a.js', 'src/test-script-b.js'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/scripts.js').content.toContain('console.log("a")'); harness.expectFile('dist/scripts.js').content.toContain('console.log("b")'); harness .expectFile('dist/index.html') .content.toContain('<script src="scripts.js" defer></script>'); }); it('preserves order of multiple scripts in single output', async () => { await harness.writeFile('src/test-script-a.js', 'console.log("a");'); await harness.writeFile('src/test-script-b.js', 'console.log("b");'); await harness.writeFile('src/test-script-c.js', 'console.log("c");'); await harness.writeFile('src/test-script-d.js', 'console.log("d");'); harness.useTarget('build', { ...BASE_OPTIONS, scripts: [ 'src/test-script-c.js', 'src/test-script-d.js', 'src/test-script-b.js', 'src/test-script-a.js', ], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/scripts.js') .content.toMatch( /console\.log\("c"\)[;\s]+console\.log\("d"\)[;\s]+console\.log\("b"\)[;\s]+console\.log\("a"\)/, ); }); it('fails and shows an error if script does not exist', async () => { harness.useTarget('build', { ...BASE_OPTIONS, scripts: ['src/test-script-a.js'], }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBeFalse(); expect(logs).toContain( jasmine.objectContaining({ level: 'error', message: jasmine.stringMatching(`Can't resolve 'src/test-script-a.js'`), }), ); harness.expectFile('dist/scripts.js').toNotExist(); }); it('shows the output script as a chunk entry in the logging output', async () => { await harness.writeFile('src/test-script-a.js', 'console.log("a");'); harness.useTarget('build', { ...BASE_OPTIONS, scripts: ['src/test-script-a.js'], }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching(/scripts\.js.+\d+ bytes/) }), ); }); });
{ "end_byte": 4980, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/tests/options/scripts_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/tests/options/scripts_spec.ts_4986_13349
describe('longhand syntax', () => { it('processes a single script into a single output', async () => { await harness.writeFile('src/test-script-a.js', 'console.log("a");'); harness.useTarget('build', { ...BASE_OPTIONS, scripts: [{ input: 'src/test-script-a.js' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/scripts.js').content.toContain('console.log("a")'); harness .expectFile('dist/index.html') .content.toContain('<script src="scripts.js" defer></script>'); }); it('processes a single script into a single output named with bundleName', async () => { await harness.writeFile('src/test-script-a.js', 'console.log("a");'); harness.useTarget('build', { ...BASE_OPTIONS, scripts: [{ input: 'src/test-script-a.js', bundleName: 'extra' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/extra.js').content.toContain('console.log("a")'); harness .expectFile('dist/index.html') .content.toContain('<script src="extra.js" defer></script>'); }); it('uses default bundleName when bundleName is empty string', async () => { await harness.writeFile('src/test-script-a.js', 'console.log("a");'); harness.useTarget('build', { ...BASE_OPTIONS, scripts: [{ input: 'src/test-script-a.js', bundleName: '' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/scripts.js').content.toContain('console.log("a")'); harness .expectFile('dist/index.html') .content.toContain('<script src="scripts.js" defer></script>'); }); it('processes multiple scripts with no bundleName into a single output', async () => { await harness.writeFiles({ 'src/test-script-a.js': 'console.log("a");', 'src/test-script-b.js': 'console.log("b");', }); harness.useTarget('build', { ...BASE_OPTIONS, scripts: [{ input: 'src/test-script-a.js' }, { input: 'src/test-script-b.js' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/scripts.js').content.toContain('console.log("a")'); harness.expectFile('dist/scripts.js').content.toContain('console.log("b")'); harness .expectFile('dist/index.html') .content.toContain('<script src="scripts.js" defer></script>'); }); it('processes multiple scripts with same bundleName into a single output', async () => { await harness.writeFiles({ 'src/test-script-a.js': 'console.log("a");', 'src/test-script-b.js': 'console.log("b");', }); harness.useTarget('build', { ...BASE_OPTIONS, scripts: [ { input: 'src/test-script-a.js', bundleName: 'extra' }, { input: 'src/test-script-b.js', bundleName: 'extra' }, ], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/extra.js').content.toContain('console.log("a")'); harness.expectFile('dist/extra.js').content.toContain('console.log("b")'); harness .expectFile('dist/index.html') .content.toContain('<script src="extra.js" defer></script>'); }); it('processes multiple scripts with different bundleNames into separate outputs', async () => { await harness.writeFiles({ 'src/test-script-a.js': 'console.log("a");', 'src/test-script-b.js': 'console.log("b");', }); harness.useTarget('build', { ...BASE_OPTIONS, scripts: [ { input: 'src/test-script-a.js', bundleName: 'extra' }, { input: 'src/test-script-b.js', bundleName: 'other' }, ], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/extra.js').content.toContain('console.log("a")'); harness.expectFile('dist/other.js').content.toContain('console.log("b")'); harness .expectFile('dist/index.html') .content.toContain('<script src="extra.js" defer></script>'); harness .expectFile('dist/index.html') .content.toContain('<script src="other.js" defer></script>'); }); it('preserves order of multiple scripts in single output', async () => { await harness.writeFiles({ 'src/test-script-a.js': 'console.log("a");', 'src/test-script-b.js': 'console.log("b");', 'src/test-script-c.js': 'console.log("c");', 'src/test-script-d.js': 'console.log("d");', }); harness.useTarget('build', { ...BASE_OPTIONS, scripts: [ { input: 'src/test-script-c.js' }, { input: 'src/test-script-d.js' }, { input: 'src/test-script-b.js' }, { input: 'src/test-script-a.js' }, ], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/scripts.js') .content.toMatch( /console\.log\("c"\)[;\s]+console\.log\("d"\)[;\s]+console\.log\("b"\)[;\s]+console\.log\("a"\)/, ); }); it('preserves order of multiple scripts with different bundleNames', async () => { await harness.writeFiles({ 'src/test-script-a.js': 'console.log("a");', 'src/test-script-b.js': 'console.log("b");', 'src/test-script-c.js': 'console.log("c");', 'src/test-script-d.js': 'console.log("d");', }); harness.useTarget('build', { ...BASE_OPTIONS, scripts: [ { input: 'src/test-script-c.js', bundleName: 'other' }, { input: 'src/test-script-d.js', bundleName: 'extra' }, { input: 'src/test-script-b.js', bundleName: 'extra' }, { input: 'src/test-script-a.js', bundleName: 'other' }, ], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/other.js') .content.toMatch(/console\.log\("c"\)[;\s]+console\.log\("a"\)/); harness .expectFile('dist/extra.js') .content.toMatch(/console\.log\("d"\)[;\s]+console\.log\("b"\)/); harness .expectFile('dist/index.html') .content.toMatch( /<script src="other.js" defer><\/script>\s*<script src="extra.js" defer><\/script>/, ); }); it('adds script element to index when inject is true', async () => { await harness.writeFile('src/test-script-a.js', 'console.log("a");'); harness.useTarget('build', { ...BASE_OPTIONS, scripts: [{ input: 'src/test-script-a.js', inject: true }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/scripts.js').content.toContain('console.log("a")'); harness .expectFile('dist/index.html') .content.toContain('<script src="scripts.js" defer></script>'); }); it('does not add script element to index when inject is false', async () => { await harness.writeFile('src/test-script-a.js', 'console.log("a");'); harness.useTarget('build', { ...BASE_OPTIONS, scripts: [{ input: 'src/test-script-a.js', inject: false }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); // `inject: false` causes the bundleName to be the input file name harness.expectFile('dist/test-script-a.js').content.toContain('console.log("a")'); harness .expectFile('dist/index.html') .content.not.toContain('<script src="test-script-a.js" defer></script>'); });
{ "end_byte": 13349, "start_byte": 4986, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/tests/options/scripts_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/tests/options/scripts_spec.ts_13357_15203
it('does not add script element to index with bundleName when inject is false', async () => { await harness.writeFile('src/test-script-a.js', 'console.log("a");'); harness.useTarget('build', { ...BASE_OPTIONS, scripts: [{ input: 'src/test-script-a.js', bundleName: 'extra', inject: false }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/extra.js').content.toContain('console.log("a")'); harness .expectFile('dist/index.html') .content.not.toContain('<script src="extra.js" defer></script>'); }); it('shows the output script as a chunk entry in the logging output', async () => { await harness.writeFile('src/test-script-a.js', 'console.log("a");'); harness.useTarget('build', { ...BASE_OPTIONS, scripts: [{ input: 'src/test-script-a.js' }], }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching(/scripts\.js.+\d+ bytes/) }), ); }); it('shows the output script as a chunk entry with bundleName in the logging output', async () => { await harness.writeFile('src/test-script-a.js', 'console.log("a");'); harness.useTarget('build', { ...BASE_OPTIONS, scripts: [{ input: 'src/test-script-a.js', bundleName: 'extra' }], }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching(/extra\.js.+\d+ bytes/) }), ); }); }); }); });
{ "end_byte": 15203, "start_byte": 13357, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/tests/options/scripts_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/tests/options/named-chunks_spec.ts_0_2142
/** * @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.dev/license */ import { buildWebpackBrowser } from '../../index'; import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; const MAIN_OUTPUT = 'dist/main.js'; const NAMED_LAZY_OUTPUT = 'dist/src_lazy-module_ts.js'; const UNNAMED_LAZY_OUTPUT = 'dist/358.js'; describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { describe('Option: "namedChunks"', () => { beforeEach(async () => { // Setup a lazy loaded chunk await harness.writeFiles({ 'src/lazy-module.ts': 'export const value = 42;', 'src/main.ts': `import('./lazy-module');`, }); }); it('generates named files in output when true', async () => { harness.useTarget('build', { ...BASE_OPTIONS, namedChunks: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile(MAIN_OUTPUT).toExist(); harness.expectFile(NAMED_LAZY_OUTPUT).toExist(); harness.expectFile(UNNAMED_LAZY_OUTPUT).toNotExist(); }); it('does not generate named files in output when false', async () => { harness.useTarget('build', { ...BASE_OPTIONS, namedChunks: false, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile(MAIN_OUTPUT).toExist(); harness.expectFile(NAMED_LAZY_OUTPUT).toNotExist(); harness.expectFile(UNNAMED_LAZY_OUTPUT).toExist(); }); it('does not generate named files in output when not present', async () => { harness.useTarget('build', { ...BASE_OPTIONS, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); debugger; harness.expectFile(MAIN_OUTPUT).toExist(); harness.expectFile(NAMED_LAZY_OUTPUT).toNotExist(); harness.expectFile(UNNAMED_LAZY_OUTPUT).toExist(); }); }); });
{ "end_byte": 2142, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/tests/options/named-chunks_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/tests/options/styles_spec.ts_0_4852
/** * @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.dev/license */ import { buildWebpackBrowser } from '../../index'; import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { describe('Option: "styles"', () => { beforeEach(async () => { // Application code is not needed for styles tests await harness.writeFile('src/main.ts', ''); }); it('supports an empty array value', async () => { harness.useTarget('build', { ...BASE_OPTIONS, styles: [], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/styles.css').toNotExist(); }); it('does not create an output styles file when option is not present', async () => { harness.useTarget('build', { ...BASE_OPTIONS, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/styles.css').toNotExist(); }); describe('shorthand syntax', () => { it('processes a single style into a single output', async () => { await harness.writeFile('src/test-style-a.css', '.test-a {color: red}'); harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/test-style-a.css'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/styles.css').content.toContain('.test-a {color: red}'); harness .expectFile('dist/index.html') .content.toContain('<link rel="stylesheet" href="styles.css">'); }); it('processes multiple styles into a single output', async () => { await harness.writeFiles({ 'src/test-style-a.css': '.test-a {color: red}', 'src/test-style-b.css': '.test-b {color: green}', }); harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/test-style-a.css', 'src/test-style-b.css'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/styles.css').content.toContain('.test-a {color: red}'); harness.expectFile('dist/styles.css').content.toContain('.test-b {color: green}'); harness .expectFile('dist/index.html') .content.toContain('<link rel="stylesheet" href="styles.css">'); }); it('preserves order of multiple styles in single output', async () => { await harness.writeFiles({ 'src/test-style-a.css': '.test-a {color: red}', 'src/test-style-b.css': '.test-b {color: green}', 'src/test-style-c.css': '.test-c {color: blue}', 'src/test-style-d.css': '.test-d {color: yellow}', }); harness.useTarget('build', { ...BASE_OPTIONS, styles: [ 'src/test-style-c.css', 'src/test-style-d.css', 'src/test-style-b.css', 'src/test-style-a.css', ], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/styles.css') .content.toMatch( /\.test-c {color: blue}[\s|\S]+\.test-d {color: yellow}[\s|\S]+\.test-b {color: green}[\s|\S]+\.test-a {color: red}/m, ); }); it('fails and shows an error if style does not exist', async () => { harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/test-style-a.css'], }); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBeFalse(); expect(logs).toContain( jasmine.objectContaining({ level: 'error', message: jasmine.stringMatching(`Can't resolve 'src/test-style-a.css'`), }), ); harness.expectFile('dist/styles.css').toNotExist(); }); it('shows the output style as a chunk entry in the logging output', async () => { await harness.writeFile('src/test-style-a.css', '.test-a {color: red}'); harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/test-style-a.css'], }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching(/styles\.css.+\d+ bytes/) }), ); }); }); describe('longhand syntax',
{ "end_byte": 4852, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/tests/options/styles_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/tests/options/styles_spec.ts_4853_13352
() => { it('processes a single style into a single output', async () => { await harness.writeFile('src/test-style-a.css', '.test-a {color: red}'); harness.useTarget('build', { ...BASE_OPTIONS, styles: [{ input: 'src/test-style-a.css' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/styles.css').content.toContain('.test-a {color: red}'); harness .expectFile('dist/index.html') .content.toContain('<link rel="stylesheet" href="styles.css">'); }); it('processes a single style into a single output named with bundleName', async () => { await harness.writeFile('src/test-style-a.css', '.test-a {color: red}'); harness.useTarget('build', { ...BASE_OPTIONS, styles: [{ input: 'src/test-style-a.css', bundleName: 'extra' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/extra.css').content.toContain('.test-a {color: red}'); harness .expectFile('dist/index.html') .content.toContain('<link rel="stylesheet" href="extra.css">'); }); it('uses default bundleName when bundleName is empty string', async () => { await harness.writeFile('src/test-style-a.css', '.test-a {color: red}'); harness.useTarget('build', { ...BASE_OPTIONS, styles: [{ input: 'src/test-style-a.css', bundleName: '' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/styles.css').content.toContain('.test-a {color: red}'); harness .expectFile('dist/index.html') .content.toContain('<link rel="stylesheet" href="styles.css">'); }); it('processes multiple styles with no bundleName into a single output', async () => { await harness.writeFiles({ 'src/test-style-a.css': '.test-a {color: red}', 'src/test-style-b.css': '.test-b {color: green}', }); harness.useTarget('build', { ...BASE_OPTIONS, styles: [{ input: 'src/test-style-a.css' }, { input: 'src/test-style-b.css' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/styles.css').content.toContain('.test-a {color: red}'); harness.expectFile('dist/styles.css').content.toContain('.test-b {color: green}'); harness .expectFile('dist/index.html') .content.toContain('<link rel="stylesheet" href="styles.css">'); }); it('processes multiple styles with same bundleName into a single output', async () => { await harness.writeFiles({ 'src/test-style-a.css': '.test-a {color: red}', 'src/test-style-b.css': '.test-b {color: green}', }); harness.useTarget('build', { ...BASE_OPTIONS, styles: [ { input: 'src/test-style-a.css', bundleName: 'extra' }, { input: 'src/test-style-b.css', bundleName: 'extra' }, ], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/extra.css').content.toContain('.test-a {color: red}'); harness.expectFile('dist/extra.css').content.toContain('.test-b {color: green}'); harness .expectFile('dist/index.html') .content.toContain('<link rel="stylesheet" href="extra.css">'); }); it('processes multiple styles with different bundleNames into separate outputs', async () => { await harness.writeFiles({ 'src/test-style-a.css': '.test-a {color: red}', 'src/test-style-b.css': '.test-b {color: green}', }); harness.useTarget('build', { ...BASE_OPTIONS, styles: [ { input: 'src/test-style-a.css', bundleName: 'extra' }, { input: 'src/test-style-b.css', bundleName: 'other' }, ], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/extra.css').content.toContain('.test-a {color: red}'); harness.expectFile('dist/other.css').content.toContain('.test-b {color: green}'); harness .expectFile('dist/index.html') .content.toContain('<link rel="stylesheet" href="extra.css">'); harness .expectFile('dist/index.html') .content.toContain('<link rel="stylesheet" href="other.css">'); }); it('preserves order of multiple styles in single output', async () => { await harness.writeFiles({ 'src/test-style-a.css': '.test-a {color: red}', 'src/test-style-b.css': '.test-b {color: green}', 'src/test-style-c.css': '.test-c {color: blue}', 'src/test-style-d.css': '.test-d {color: yellow}', }); harness.useTarget('build', { ...BASE_OPTIONS, styles: [ { input: 'src/test-style-c.css' }, { input: 'src/test-style-d.css' }, { input: 'src/test-style-b.css' }, { input: 'src/test-style-a.css' }, ], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/styles.css') .content.toMatch( /\.test-c {color: blue}[\s|\S]+\.test-d {color: yellow}[\s|\S]+\.test-b {color: green}[\s|\S]+\.test-a {color: red}/, ); }); it('preserves order of multiple styles with different bundleNames', async () => { await harness.writeFiles({ 'src/test-style-a.css': '.test-a {color: red}', 'src/test-style-b.css': '.test-b {color: green}', 'src/test-style-c.css': '.test-c {color: blue}', 'src/test-style-d.css': '.test-d {color: yellow}', }); harness.useTarget('build', { ...BASE_OPTIONS, styles: [ { input: 'src/test-style-c.css', bundleName: 'other' }, { input: 'src/test-style-d.css', bundleName: 'extra' }, { input: 'src/test-style-b.css', bundleName: 'extra' }, { input: 'src/test-style-a.css', bundleName: 'other' }, ], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/other.css') .content.toMatch(/\.test-c {color: blue}[\s|\S]+\.test-a {color: red}/); harness .expectFile('dist/extra.css') .content.toMatch(/\.test-d {color: yellow}[\s|\S]+\.test-b {color: green}/); harness .expectFile('dist/index.html') .content.toMatch( /<link rel="stylesheet" href="other.css">\s*<link rel="stylesheet" href="extra.css">/, ); }); it('adds link element to index when inject is true', async () => { await harness.writeFile('src/test-style-a.css', '.test-a {color: red}'); harness.useTarget('build', { ...BASE_OPTIONS, styles: [{ input: 'src/test-style-a.css', inject: true }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/styles.css').content.toContain('.test-a {color: red}'); harness .expectFile('dist/index.html') .content.toContain('<link rel="stylesheet" href="styles.css">'); }); it('does not add link element to index when inject is false', async () => { await harness.writeFile('src/test-style-a.css', '.test-a {color: red}'); harness.useTarget('build', { ...BASE_OPTIONS, styles: [{ input: 'src/test-style-a.css', inject: false }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); // `inject: false` causes the bundleName to be the input file name harness.expectFile('dist/test-style-a.css').content.toContain('.test-a {color: red}'); harness .expectFile('dist/index.html') .content.not.toContain('<link rel="stylesheet" href="test-style-a.css">'); });
{ "end_byte": 13352, "start_byte": 4853, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/tests/options/styles_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/tests/options/styles_spec.ts_13360_15216
it('does not add link element to index with bundleName when inject is false', async () => { await harness.writeFile('src/test-style-a.css', '.test-a {color: red}'); harness.useTarget('build', { ...BASE_OPTIONS, styles: [{ input: 'src/test-style-a.css', bundleName: 'extra', inject: false }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/extra.css').content.toContain('.test-a {color: red}'); harness .expectFile('dist/index.html') .content.not.toContain('<link rel="stylesheet" href="extra.css">'); }); it('shows the output style as a chunk entry in the logging output', async () => { await harness.writeFile('src/test-style-a.css', '.test-a {color: red}'); harness.useTarget('build', { ...BASE_OPTIONS, styles: [{ input: 'src/test-style-a.css' }], }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching(/styles\.css.+\d+ bytes/) }), ); }); it('shows the output style as a chunk entry with bundleName in the logging output', async () => { await harness.writeFile('src/test-style-a.css', '.test-a {color: red}'); harness.useTarget('build', { ...BASE_OPTIONS, styles: [{ input: 'src/test-style-a.css', bundleName: 'extra' }], }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching(/extra\.css.+\d+ bytes/) }), ); }); }); }); });
{ "end_byte": 15216, "start_byte": 13360, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/tests/options/styles_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/tests/options/verbose_spec.ts_0_4985
/** * @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.dev/license */ import { logging } from '@angular-devkit/core'; import { concatMap, count, take, timeout } from 'rxjs'; import { BUILD_TIMEOUT, buildWebpackBrowser } from '../../index'; import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; // The below plugin is only enabled when verbose option is set to true. const VERBOSE_LOG_TEXT = 'LOG from webpack.'; describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { describe('Option: "verbose"', () => { beforeEach(async () => { // Application code is not needed for verbose output await harness.writeFile('src/main.ts', ''); }); it('should include verbose logs when true', async () => { harness.useTarget('build', { ...BASE_OPTIONS, verbose: true, }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBeTrue(); expect(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching(VERBOSE_LOG_TEXT), }), ); }); it('should not include verbose logs when undefined', async () => { harness.useTarget('build', { ...BASE_OPTIONS, verbose: undefined, }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBeTrue(); expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching(VERBOSE_LOG_TEXT), }), ); }); it('should not include verbose logs when false', async () => { harness.useTarget('build', { ...BASE_OPTIONS, verbose: false, }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBeTrue(); expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching(VERBOSE_LOG_TEXT), }), ); }); it('should list modified files when verbose is set to true', async () => { harness.useTarget('build', { ...BASE_OPTIONS, verbose: true, watch: true, }); await harness .execute() .pipe( timeout(BUILD_TIMEOUT), concatMap(async ({ result, logs }, index) => { expect(result?.success).toBeTrue(); switch (index) { case 0: // Amend file await harness.appendToFile('/src/main.ts', ' '); break; case 1: expect(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching( /angular\.watch-files-logs-plugin\n\s+Modified files:\n.+main\.ts/, ), }), ); break; } }), take(2), count(), ) .toPromise(); }); it('should not include error stacktraces when false', async () => { harness.useTarget('build', { ...BASE_OPTIONS, verbose: false, styles: ['./src/styles.scss'], }); // Create a compilatation error. await harness.writeFile('./src/styles.scss', `@import 'invalid-module';`); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBeFalse(); expect(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching(`Can't find stylesheet to import`), }), ); expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching('styles.scss.webpack'), }), ); expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching('at Object.loader'), }), ); }); it('should include error stacktraces when true', async () => { harness.useTarget('build', { ...BASE_OPTIONS, verbose: true, styles: ['./src/styles.scss'], }); // Create a compilatation error. await harness.writeFile('./src/styles.scss', `@import 'invalid-module';`); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBeFalse(); expect(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching('styles.scss.webpack'), }), ); expect(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching('at Object.loader'), }), ); }); }); });
{ "end_byte": 4985, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/tests/options/verbose_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/tests/options/tsconfig_spec.ts_0_961
/** * @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.dev/license */ import { buildWebpackBrowser } from '../../index'; import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { describe('Option: "tsConfig"', () => { it('throws an exception when TypeScript Configuration file does not exist', async () => { harness.useTarget('build', { ...BASE_OPTIONS, tsConfig: 'src/missing.json', }); const { result, error } = await harness.executeOnce({ outputLogsOnException: false }); expect(result).toBeUndefined(); expect(error).toEqual( jasmine.objectContaining({ message: jasmine.stringMatching('no such file or directory'), }), ); }); }); });
{ "end_byte": 961, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/tests/options/tsconfig_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/tests/options/polyfills_spec.ts_0_2089
/** * @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.dev/license */ import { buildWebpackBrowser } from '../../index'; import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { describe('Option: "polyfills"', () => { it('uses a provided TypeScript file', async () => { harness.useTarget('build', { ...BASE_OPTIONS, polyfills: 'src/polyfills.ts', }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/polyfills.js').toExist(); }); it('uses a provided JavaScript file', async () => { await harness.writeFile('src/polyfills.js', `console.log('main');`); harness.useTarget('build', { ...BASE_OPTIONS, polyfills: 'src/polyfills.js', }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/polyfills.js').content.toContain(`console.log('main')`); }); it('fails and shows an error when file does not exist', async () => { harness.useTarget('build', { ...BASE_OPTIONS, polyfills: 'src/missing.ts', }); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBe(false); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching('Module not found:') }), ); harness.expectFile('dist/polyfills.js').toNotExist(); }); it('resolves module specifiers in array', async () => { harness.useTarget('build', { ...BASE_OPTIONS, polyfills: ['zone.js', 'zone.js/testing'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/polyfills.js').toExist(); }); }); });
{ "end_byte": 2089, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/tests/options/polyfills_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/browser/tests/options/extract-licenses_spec.ts_0_1576
/** * @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.dev/license */ import { buildWebpackBrowser } from '../../index'; import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { describe('Option: "extractLicenses"', () => { it(`should generate '3rdpartylicenses.txt' when 'extractLicenses' is true`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, extractLicenses: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/3rdpartylicenses.txt').content.toContain('MIT'); }); it(`should not generate '3rdpartylicenses.txt' when 'extractLicenses' is false`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, extractLicenses: false, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/3rdpartylicenses.txt').toNotExist(); }); it(`should generate '3rdpartylicenses.txt' when 'extractLicenses' is not set`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/3rdpartylicenses.txt').content.toContain('MIT'); }); }); });
{ "end_byte": 1576, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/browser/tests/options/extract-licenses_spec.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/karma/find-tests.ts_0_3323
/** * @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.dev/license */ import glob, { isDynamicPattern } from 'fast-glob'; import { PathLike, constants, promises as fs } from 'fs'; import { basename, dirname, extname, join, relative } from 'path'; /* Go through all patterns and find unique list of files */ export async function findTests( include: string[], exclude: string[], workspaceRoot: string, projectSourceRoot: string, ): Promise<string[]> { const matchingTestsPromises = include.map((pattern) => findMatchingTests(pattern, exclude, workspaceRoot, projectSourceRoot), ); const files = await Promise.all(matchingTestsPromises); // Unique file names return [...new Set(files.flat())]; } const normalizePath = (path: string): string => path.replace(/\\/g, '/'); const removeLeadingSlash = (pattern: string): string => { if (pattern.charAt(0) === '/') { return pattern.substring(1); } return pattern; }; const removeRelativeRoot = (path: string, root: string): string => { if (path.startsWith(root)) { return path.substring(root.length); } return path; }; async function findMatchingTests( pattern: string, ignore: string[], workspaceRoot: string, projectSourceRoot: string, ): Promise<string[]> { // normalize pattern, glob lib only accepts forward slashes let normalizedPattern = normalizePath(pattern); normalizedPattern = removeLeadingSlash(normalizedPattern); const relativeProjectRoot = normalizePath(relative(workspaceRoot, projectSourceRoot) + '/'); // remove relativeProjectRoot to support relative paths from root // such paths are easy to get when running scripts via IDEs normalizedPattern = removeRelativeRoot(normalizedPattern, relativeProjectRoot); // special logic when pattern does not look like a glob if (!isDynamicPattern(normalizedPattern)) { if (await isDirectory(join(projectSourceRoot, normalizedPattern))) { normalizedPattern = `${normalizedPattern}/**/*.spec.@(ts|tsx)`; } else { // see if matching spec file exists const fileExt = extname(normalizedPattern); // Replace extension to `.spec.ext`. Example: `src/app/app.component.ts`-> `src/app/app.component.spec.ts` const potentialSpec = join( projectSourceRoot, dirname(normalizedPattern), `${basename(normalizedPattern, fileExt)}.spec${fileExt}`, ); if (await exists(potentialSpec)) { return [potentialSpec]; } } } // normalize the patterns in the ignore list const normalizedIgnorePatternList = ignore.map((pattern: string) => removeRelativeRoot(removeLeadingSlash(normalizePath(pattern)), relativeProjectRoot), ); return glob(normalizedPattern, { cwd: projectSourceRoot, absolute: true, ignore: ['**/node_modules/**', ...normalizedIgnorePatternList], }); } async function isDirectory(path: PathLike): Promise<boolean> { try { const stats = await fs.stat(path); return stats.isDirectory(); } catch { return false; } } async function exists(path: PathLike): Promise<boolean> { try { await fs.access(path, constants.F_OK); return true; } catch { return false; } }
{ "end_byte": 3323, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/karma/find-tests.ts" }
angular-cli/packages/angular_devkit/build_angular/src/builders/karma/init_test_bed.js_0_596
/** * @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.dev/license */ import { getTestBed } from '@angular/core/testing'; import { BrowserDynamicTestingModule, platformBrowserDynamicTesting, } from '@angular/platform-browser-dynamic/testing'; // Initialize the Angular testing environment. getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), { errorOnUnknownElements: true, errorOnUnknownProperties: true, });
{ "end_byte": 596, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/src/builders/karma/init_test_bed.js" }