_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular-cli/packages/angular/build/src/builders/dev-server/output.ts_0_465
/** * @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 { BuilderOutput } from '@angular-devkit/architect'; /** * @experimental Direct usage of this type is considered experimental. */ export interface DevServerBuilderOutput extends BuilderOutput { baseUrl: string; port?: number; address?: string; }
{ "end_byte": 465, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/output.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/vite-server.ts_0_6998
/** * @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 { ɵdestroyAngularServerApp as destroyAngularServerApp } from '@angular/ssr'; import type { BuilderContext } from '@angular-devkit/architect'; import type { Plugin } from 'esbuild'; import assert from 'node:assert'; import { readFile } from 'node:fs/promises'; import { builtinModules, isBuiltin } from 'node:module'; import { join } from 'node:path'; import type { Connect, DepOptimizationConfig, InlineConfig, ViteDevServer } from 'vite'; import { ServerSsrMode, createAngularLocaleDataPlugin, createAngularMemoryPlugin, createAngularSetupMiddlewaresPlugin, createAngularSsrTransformPlugin, createRemoveIdPrefixPlugin, } from '../../tools/vite/plugins'; import { loadProxyConfiguration, normalizeSourceMaps } from '../../utils'; import { useComponentStyleHmr } from '../../utils/environment-options'; import { loadEsmModule } from '../../utils/load-esm'; import { Result, ResultFile, ResultKind } from '../application/results'; import { type ApplicationBuilderInternalOptions, BuildOutputFileType, type ExternalResultMetadata, JavaScriptTransformer, getFeatureSupport, getSupportedBrowsers, isZonelessApp, transformSupportedBrowsersToTargets, } from './internal'; import type { NormalizedDevServerOptions } from './options'; import type { DevServerBuilderOutput } from './output'; interface OutputFileRecord { contents: Uint8Array; size: number; hash: string; updated: boolean; servable: boolean; type: BuildOutputFileType; } interface DevServerExternalResultMetadata extends Omit<ExternalResultMetadata, 'explicit'> { explicitBrowser: string[]; explicitServer: string[]; } export type BuilderAction = ( options: ApplicationBuilderInternalOptions, context: BuilderContext, plugins?: Plugin[], ) => AsyncIterable<Result>; /** * Build options that are also present on the dev server but are only passed * to the build. */ const CONVENIENCE_BUILD_OPTIONS = ['watch', 'poll', 'verbose'] as const; // eslint-disable-next-line max-lines-per-function export async function* serveWithVite( serverOptions: NormalizedDevServerOptions, builderName: string, builderAction: BuilderAction, context: BuilderContext, transformers?: { indexHtml?: (content: string) => Promise<string>; }, extensions?: { middleware?: Connect.NextHandleFunction[]; buildPlugins?: Plugin[]; }, ): AsyncIterableIterator<DevServerBuilderOutput> { // Get the browser configuration from the target name. const rawBrowserOptions = await context.getTargetOptions(serverOptions.buildTarget); // Deploy url is not used in the dev-server. delete rawBrowserOptions.deployUrl; // Copy convenience options to build for (const optionName of CONVENIENCE_BUILD_OPTIONS) { const optionValue = serverOptions[optionName]; if (optionValue !== undefined) { rawBrowserOptions[optionName] = optionValue; } } // TODO: Adjust architect to not force a JsonObject derived return type const browserOptions = (await context.validateOptions( rawBrowserOptions, builderName, )) as unknown as ApplicationBuilderInternalOptions; if (browserOptions.prerender || (browserOptions.outputMode && browserOptions.server)) { // Disable prerendering if enabled and force SSR. // This is so instead of prerendering all the routes for every change, the page is "prerendered" when it is requested. browserOptions.prerender = undefined; browserOptions.ssr ||= true; } // Set all packages as external to support Vite's prebundle caching browserOptions.externalPackages = serverOptions.prebundle; // Disable generating a full manifest with routes. // This is done during runtime when using the dev-server. browserOptions.partialSSRBuild = true; // The development server currently only supports a single locale when localizing. // This matches the behavior of the Webpack-based development server but could be expanded in the future. if ( browserOptions.localize === true || (Array.isArray(browserOptions.localize) && browserOptions.localize.length > 1) ) { context.logger.warn( 'Localization (`localize` option) has been disabled. The development server only supports localizing a single locale per build.', ); browserOptions.localize = false; } else if (browserOptions.localize) { // When localization is enabled with a single locale, force a flat path to maintain behavior with the existing Webpack-based dev server. browserOptions.forceI18nFlatOutput = true; } const { vendor: thirdPartySourcemaps, scripts: scriptsSourcemaps } = normalizeSourceMaps( browserOptions.sourceMap ?? false, ); if (scriptsSourcemaps && browserOptions.server) { // https://nodejs.org/api/process.html#processsetsourcemapsenabledval process.setSourceMapsEnabled(true); } // Enable to support component style hot reloading (`NG_HMR_CSTYLES=0` can be used to disable) browserOptions.externalRuntimeStyles = !!serverOptions.liveReload && useComponentStyleHmr; if (browserOptions.externalRuntimeStyles) { // Preload the @angular/compiler package to avoid first stylesheet request delays. // Once @angular/build is native ESM, this should be re-evaluated. void loadEsmModule('@angular/compiler'); } // Setup the prebundling transformer that will be shared across Vite prebundling requests const prebundleTransformer = new JavaScriptTransformer( // Always enable JIT linking to support applications built with and without AOT. // In a development environment the additional scope information does not // have a negative effect unlike production where final output size is relevant. { sourcemap: true, jit: true, thirdPartySourcemaps }, 1, ); // The index HTML path will be updated from the build results if provided by the builder let htmlIndexPath = 'index.html'; // dynamically import Vite for ESM compatibility const { createServer, normalizePath } = await loadEsmModule<typeof import('vite')>('vite'); let server: ViteDevServer | undefined; let serverUrl: URL | undefined; let hadError = false; const generatedFiles = new Map<string, OutputFileRecord>(); const assetFiles = new Map<string, string>(); const externalMetadata: DevServerExternalResultMetadata = { implicitBrowser: [], implicitServer: [], explicitBrowser: [], explicitServer: [], }; const usedComponentStyles = new Map<string, Set<string>>(); const templateUpdates = new Map<string, string>(); // Add cleanup logic via a builder teardown. let deferred: () => void; context.addTeardown(async () => { await server?.close(); await prebundleTransformer.close(); deferred?.(); }); // TODO: Switch this to an architect schedule call when infrastructure settings are supported
{ "end_byte": 6998, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/vite-server.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/vite-server.ts_7001_15862
or await (const result of builderAction(browserOptions, context, extensions?.buildPlugins)) { switch (result.kind) { case ResultKind.Failure: if (result.errors.length && server) { hadError = true; server.ws.send({ type: 'error', err: { message: result.errors[0].text, stack: '', loc: result.errors[0].location ?? undefined, }, }); } continue; case ResultKind.Full: if (result.detail?.['htmlIndexPath']) { htmlIndexPath = result.detail['htmlIndexPath'] as string; } if (serverOptions.servePath === undefined && result.detail?.['htmlBaseHref']) { const baseHref = result.detail['htmlBaseHref'] as string; // Remove trailing slash serverOptions.servePath = baseHref !== './' && baseHref[baseHref.length - 1] === '/' ? baseHref.slice(0, -1) : baseHref; } assetFiles.clear(); for (const [outputPath, file] of Object.entries(result.files)) { if (file.origin === 'disk') { assetFiles.set('/' + normalizePath(outputPath), normalizePath(file.inputPath)); } } // Clear stale template updates on a code rebuilds templateUpdates.clear(); // Analyze result files for changes analyzeResultFiles(normalizePath, htmlIndexPath, result.files, generatedFiles); break; case ResultKind.Incremental: assert(server, 'Builder must provide an initial full build before incremental results.'); // TODO: Implement support -- application builder currently does not use break; case ResultKind.ComponentUpdate: assert(serverOptions.hmr, 'Component updates are only supported with HMR enabled.'); assert( server, 'Builder must provide an initial full build before component update results.', ); for (const componentUpdate of result.updates) { if (componentUpdate.type === 'template') { templateUpdates.set(componentUpdate.id, componentUpdate.content); server.ws.send('angular:component-update', { id: componentUpdate.id, timestamp: Date.now(), }); } } context.logger.info('Component update sent to client(s).'); continue; default: context.logger.warn(`Unknown result kind [${(result as Result).kind}] provided by build.`); continue; } // Clear existing error overlay on successful result if (hadError && server) { hadError = false; // Send an empty update to clear the error overlay server.ws.send({ 'type': 'update', updates: [], }); } // To avoid disconnecting the array objects from the option, these arrays need to be mutated instead of replaced. let requiresServerRestart = false; if (result.detail?.['externalMetadata']) { const { implicitBrowser, implicitServer, explicit } = result.detail[ 'externalMetadata' ] as ExternalResultMetadata; const implicitServerFiltered = implicitServer.filter( (m) => !isBuiltin(m) && !isAbsoluteUrl(m), ); const implicitBrowserFiltered = implicitBrowser.filter((m) => !isAbsoluteUrl(m)); if (browserOptions.ssr && serverOptions.prebundle !== false) { const previousImplicitServer = new Set(externalMetadata.implicitServer); // Restart the server to force SSR dep re-optimization when a dependency has been added. // This is a workaround for: https://github.com/vitejs/vite/issues/14896 requiresServerRestart = implicitServerFiltered.some( (dep) => !previousImplicitServer.has(dep), ); } // Empty Arrays to avoid growing unlimited with every re-build. externalMetadata.explicitBrowser.length = 0; externalMetadata.explicitServer.length = 0; externalMetadata.implicitServer.length = 0; externalMetadata.implicitBrowser.length = 0; externalMetadata.explicitBrowser.push(...explicit); externalMetadata.explicitServer.push(...explicit, ...builtinModules); externalMetadata.implicitServer.push(...implicitServerFiltered); externalMetadata.implicitBrowser.push(...implicitBrowserFiltered); // The below needs to be sorted as Vite uses these options are part of the hashing invalidation algorithm. // See: https://github.com/vitejs/vite/blob/0873bae0cfe0f0718ad2f5743dd34a17e4ab563d/packages/vite/src/node/optimizer/index.ts#L1203-L1239 externalMetadata.explicitBrowser.sort(); externalMetadata.explicitServer.sort(); externalMetadata.implicitServer.sort(); externalMetadata.implicitBrowser.sort(); } if (server) { // Update fs allow list to include any new assets from the build option. server.config.server.fs.allow = [ ...new Set([...server.config.server.fs.allow, ...assetFiles.values()]), ]; if (requiresServerRestart) { // Restart the server to force SSR dep re-optimization when a dependency has been added. // This is a workaround for: https://github.com/vitejs/vite/issues/14896 await server.restart(); } else { await handleUpdate( normalizePath, generatedFiles, server, serverOptions, context.logger, usedComponentStyles, ); } } else { const projectName = context.target?.project; if (!projectName) { throw new Error('The builder requires a target.'); } context.logger.info( 'NOTE: Raw file sizes do not reflect development server per-request transformations.', ); if (browserOptions.ssr && serverOptions.inspect) { const { host, port } = serverOptions.inspect as { host?: string; port?: number }; const { default: inspector } = await import('node:inspector'); inspector.open(port, host, true); context.addTeardown(() => inspector.close()); } const { root = '' } = await context.getProjectMetadata(projectName); const projectRoot = join(context.workspaceRoot, root as string); const browsers = getSupportedBrowsers(projectRoot, context.logger); const target = transformSupportedBrowsersToTargets(browsers); // Needed for browser-esbuild as polyfills can be a string. const polyfills = Array.isArray((browserOptions.polyfills ??= [])) ? browserOptions.polyfills : [browserOptions.polyfills]; let ssrMode: ServerSsrMode = ServerSsrMode.NoSsr; if ( browserOptions.outputMode && typeof browserOptions.ssr === 'object' && browserOptions.ssr.entry ) { ssrMode = ServerSsrMode.ExternalSsrMiddleware; } else if (browserOptions.ssr) { ssrMode = ServerSsrMode.InternalSsrMiddleware; } if (browserOptions.progress !== false && ssrMode !== ServerSsrMode.NoSsr) { // This is a workaround for https://github.com/angular/angular-cli/issues/28336, which is caused by the interaction between `zone.js` and `listr2`. process.once('SIGINT', () => { process.kill(process.pid); }); } // Setup server and start listening const serverConfiguration = await setupServer( serverOptions, generatedFiles, assetFiles, browserOptions.preserveSymlinks, externalMetadata, ssrMode, prebundleTransformer, target, isZonelessApp(polyfills), usedComponentStyles, templateUpdates, browserOptions.loader as EsbuildLoaderOption | undefined, extensions?.middleware, transformers?.indexHtml, thirdPartySourcemaps, ); server = await createServer(serverConfiguration); await server.listen(); const urls = server.resolvedUrls; if (urls && (urls.local.length || urls.network.length)) { serverUrl = new URL(urls.local[0] ?? urls.network[0]); } // log connection information server.printUrls(); server.bindCLIShortcuts({ print: true, customShortcuts: [ { key: 'r', description: 'force reload browser', action(server) { server.ws.send({ type: 'full-reload', path: '*', }); }, }, ], }); } // TODO: adjust output typings to reflect both development servers yield { success: true, port: serverUrl?.port, baseUrl: serverUrl?.href, } as unknown as DevServerBuilderOutput; } await new Promise<void>((resolve) => (deferred = resolve)); }
{ "end_byte": 15862, "start_byte": 7001, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/vite-server.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/vite-server.ts_15864_20369
sync function handleUpdate( normalizePath: (id: string) => string, generatedFiles: Map<string, OutputFileRecord>, server: ViteDevServer, serverOptions: NormalizedDevServerOptions, logger: BuilderContext['logger'], usedComponentStyles: Map<string, Set<string>>, ): Promise<void> { const updatedFiles: string[] = []; let destroyAngularServerAppCalled = false; // Invalidate any updated files for (const [file, { updated, type }] of generatedFiles) { if (!updated) { continue; } if (type === BuildOutputFileType.ServerApplication && !destroyAngularServerAppCalled) { // Clear the server app cache // This must be done before module invalidation. const { ɵdestroyAngularServerApp } = (await server.ssrLoadModule('/main.server.mjs')) as { ɵdestroyAngularServerApp: typeof destroyAngularServerApp; }; ɵdestroyAngularServerApp(); destroyAngularServerAppCalled = true; } updatedFiles.push(file); const updatedModules = server.moduleGraph.getModulesByFile( normalizePath(join(server.config.root, file)), ); updatedModules?.forEach((m) => server.moduleGraph.invalidateModule(m)); } if (!updatedFiles.length) { return; } if (serverOptions.liveReload || serverOptions.hmr) { if (updatedFiles.every((f) => f.endsWith('.css'))) { const timestamp = Date.now(); server.ws.send({ type: 'update', updates: updatedFiles.flatMap((filePath) => { // For component styles, an HMR update must be sent for each one with the corresponding // component identifier search parameter (`ngcomp`). The Vite client code will not keep // the existing search parameters when it performs an update and each one must be // specified explicitly. Typically, there is only one each though as specific style files // are not typically reused across components. const componentIds = usedComponentStyles.get(filePath); if (componentIds) { return Array.from(componentIds).map((id) => ({ type: 'css-update', timestamp, path: `${filePath}?ngcomp` + (id ? `=${id}` : ''), acceptedPath: filePath, })); } return { type: 'css-update' as const, timestamp, path: filePath, acceptedPath: filePath, }; }), }); logger.info('HMR update sent to client(s).'); return; } } // Send reload command to clients if (serverOptions.liveReload) { server.ws.send({ type: 'full-reload', path: '*', }); logger.info('Page reload sent to client(s).'); } } function analyzeResultFiles( normalizePath: (id: string) => string, htmlIndexPath: string, resultFiles: Record<string, ResultFile>, generatedFiles: Map<string, OutputFileRecord>, ) { const seen = new Set<string>(['/index.html']); for (const [outputPath, file] of Object.entries(resultFiles)) { if (file.origin === 'disk') { continue; } let filePath; if (outputPath === htmlIndexPath) { // Convert custom index output path to standard index path for dev-server usage. // This mimics the Webpack dev-server behavior. filePath = '/index.html'; } else { filePath = '/' + normalizePath(outputPath); } seen.add(filePath); const servable = file.type === BuildOutputFileType.Browser || file.type === BuildOutputFileType.Media; // Skip analysis of sourcemaps if (filePath.endsWith('.map')) { generatedFiles.set(filePath, { contents: file.contents, servable, size: file.contents.byteLength, hash: file.hash, type: file.type, updated: false, }); continue; } const existingRecord = generatedFiles.get(filePath); if ( existingRecord && existingRecord.size === file.contents.byteLength && existingRecord.hash === file.hash ) { // Same file existingRecord.updated = false; continue; } // New or updated file generatedFiles.set(filePath, { contents: file.contents, size: file.contents.byteLength, hash: file.hash, updated: true, type: file.type, servable, }); } // Clear stale output files for (const file of generatedFiles.keys()) { if (!seen.has(file)) { generatedFiles.delete(file); } } } ex
{ "end_byte": 20369, "start_byte": 15864, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/vite-server.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/vite-server.ts_20371_28923
rt async function setupServer( serverOptions: NormalizedDevServerOptions, outputFiles: Map<string, OutputFileRecord>, assets: Map<string, string>, preserveSymlinks: boolean | undefined, externalMetadata: DevServerExternalResultMetadata, ssrMode: ServerSsrMode, prebundleTransformer: JavaScriptTransformer, target: string[], zoneless: boolean, usedComponentStyles: Map<string, Set<string>>, templateUpdates: Map<string, string>, prebundleLoaderExtensions: EsbuildLoaderOption | undefined, extensionMiddleware?: Connect.NextHandleFunction[], indexHtmlTransformer?: (content: string) => Promise<string>, thirdPartySourcemaps = false, ): Promise<InlineConfig> { const proxy = await loadProxyConfiguration( serverOptions.workspaceRoot, serverOptions.proxyConfig, ); // dynamically import Vite for ESM compatibility const { normalizePath } = await loadEsmModule<typeof import('vite')>('vite'); // Path will not exist on disk and only used to provide separate path for Vite requests const virtualProjectRoot = normalizePath( join(serverOptions.workspaceRoot, `.angular/vite-root`, serverOptions.buildTarget.project), ); const cacheDir = join(serverOptions.cacheOptions.path, serverOptions.buildTarget.project, 'vite'); const configuration: InlineConfig = { configFile: false, envFile: false, cacheDir, root: virtualProjectRoot, publicDir: false, esbuild: false, mode: 'development', // We use custom as we do not rely on Vite's htmlFallbackMiddleware and indexHtmlMiddleware. appType: 'custom', css: { devSourcemap: true, }, // Ensure custom 'file' loader build option entries are handled by Vite in application code that // reference third-party libraries. Relative usage is handled directly by the build and not Vite. // Only 'file' loader entries are currently supported directly by Vite. assetsInclude: prebundleLoaderExtensions && Object.entries(prebundleLoaderExtensions) .filter(([, value]) => value === 'file') // Create a file extension glob for each key .map(([key]) => '*' + key), // Vite will normalize the `base` option by adding a leading slash. base: serverOptions.servePath, resolve: { mainFields: ['es2020', 'browser', 'module', 'main'], preserveSymlinks, }, server: { warmup: { ssrFiles: ['./main.server.mjs', './server.mjs'], }, port: serverOptions.port, strictPort: true, host: serverOptions.host, open: serverOptions.open, headers: serverOptions.headers, proxy, cors: { // Allow preflight requests to be proxied. preflightContinue: true, }, // File watching is handled by the build directly. `null` disables file watching for Vite. watch: null, fs: { // Ensure cache directory, node modules, and all assets are accessible by the client. // The first two are required for Vite to function in prebundling mode (the default) and to load // the Vite client-side code for browser reloading. These would be available by default but when // the `allow` option is explicitly configured, they must be included manually. allow: [cacheDir, join(serverOptions.workspaceRoot, 'node_modules'), ...assets.values()], // Temporary disable cached FS checks. // This is because we configure `config.base` to a virtual directory which causes `getRealPath` to fail. // See: https://github.com/vitejs/vite/blob/b2873ac3936de25ca8784327cb9ef16bd4881805/packages/vite/src/node/fsUtils.ts#L45-L67 cachedChecks: false, }, // This is needed when `externalDependencies` is used to prevent Vite load errors. // NOTE: If Vite adds direct support for externals, this can be removed. preTransformRequests: externalMetadata.explicitBrowser.length === 0, }, ssr: { // Note: `true` and `/.*/` have different sematics. When true, the `external` option is ignored. noExternal: /.*/, // Exclude any Node.js built in module and provided dependencies (currently build defined externals) external: externalMetadata.explicitServer, optimizeDeps: getDepOptimizationConfig({ // Only enable with caching since it causes prebundle dependencies to be cached disabled: serverOptions.prebundle === false, // Exclude any explicitly defined dependencies (currently build defined externals and node.js built-ins) exclude: externalMetadata.explicitServer, // Include all implict dependencies from the external packages internal option include: externalMetadata.implicitServer, ssr: true, prebundleTransformer, zoneless, target, loader: prebundleLoaderExtensions, thirdPartySourcemaps, }), }, plugins: [ createAngularLocaleDataPlugin(), createAngularSetupMiddlewaresPlugin({ outputFiles, assets, indexHtmlTransformer, extensionMiddleware, usedComponentStyles, templateUpdates, ssrMode, }), createRemoveIdPrefixPlugin(externalMetadata.explicitBrowser), await createAngularSsrTransformPlugin(serverOptions.workspaceRoot), await createAngularMemoryPlugin({ virtualProjectRoot, outputFiles, external: externalMetadata.explicitBrowser, }), ], // Browser only optimizeDeps. (This does not run for SSR dependencies). optimizeDeps: getDepOptimizationConfig({ // Only enable with caching since it causes prebundle dependencies to be cached disabled: serverOptions.prebundle === false, // Exclude any explicitly defined dependencies (currently build defined externals) exclude: externalMetadata.explicitBrowser, // Include all implict dependencies from the external packages internal option include: externalMetadata.implicitBrowser, ssr: false, prebundleTransformer, target, zoneless, loader: prebundleLoaderExtensions, thirdPartySourcemaps, }), }; if (serverOptions.ssl) { if (serverOptions.sslCert && serverOptions.sslKey) { // server configuration is defined above // eslint-disable-next-line @typescript-eslint/no-non-null-assertion configuration.server!.https = { cert: await readFile(serverOptions.sslCert), key: await readFile(serverOptions.sslKey), }; } else { const { default: basicSslPlugin } = await import('@vitejs/plugin-basic-ssl'); // eslint-disable-next-line @typescript-eslint/no-floating-promises configuration.plugins ??= []; configuration.plugins.push(basicSslPlugin()); } } return configuration; } type ViteEsBuildPlugin = NonNullable< NonNullable<DepOptimizationConfig['esbuildOptions']>['plugins'] >[0]; type EsbuildLoaderOption = Exclude<DepOptimizationConfig['esbuildOptions'], undefined>['loader']; function getDepOptimizationConfig({ disabled, exclude, include, target, zoneless, prebundleTransformer, ssr, loader, thirdPartySourcemaps, }: { disabled: boolean; exclude: string[]; include: string[]; target: string[]; prebundleTransformer: JavaScriptTransformer; ssr: boolean; zoneless: boolean; loader?: EsbuildLoaderOption; thirdPartySourcemaps: boolean; }): DepOptimizationConfig { const plugins: ViteEsBuildPlugin[] = [ { name: `angular-vite-optimize-deps${ssr ? '-ssr' : ''}${ thirdPartySourcemaps ? '-vendor-sourcemap' : '' }`, setup(build) { build.onLoad({ filter: /\.[cm]?js$/ }, async (args) => { return { contents: await prebundleTransformer.transformFile(args.path), loader: 'js', }; }); }, }, ]; return { // Exclude any explicitly defined dependencies (currently build defined externals) exclude, // NB: to disable the deps optimizer, set optimizeDeps.noDiscovery to true and optimizeDeps.include as undefined. // Include all implict dependencies from the external packages internal option include: disabled ? undefined : include, noDiscovery: disabled, // Add an esbuild plugin to run the Angular linker on dependencies esbuildOptions: { // Set esbuild supported targets. target, supported: getFeatureSupport(target, zoneless), plugins, loader, resolveExtensions: ['.mjs', '.js', '.cjs'], }, }; } /*
{ "end_byte": 28923, "start_byte": 20371, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/vite-server.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/vite-server.ts_28925_29318
* Checks if the given value is an absolute URL. * * This function helps in avoiding Vite's prebundling from processing absolute URLs (http://, https://, //) as files. * * @param value - The URL or path to check. * @returns `true` if the value is not an absolute URL; otherwise, `false`. */ function isAbsoluteUrl(value: string): boolean { return /^(?:https?:)?\/\//.test(value); }
{ "end_byte": 29318, "start_byte": 28925, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/vite-server.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/builder.ts_0_3590
/** * @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 { BuilderContext } from '@angular-devkit/architect'; import type { Plugin } from 'esbuild'; import type http from 'node:http'; import { checkPort } from '../../utils/check-port'; import { type IndexHtmlTransform, buildApplicationInternal, purgeStaleBuildCache, } from './internal'; import { normalizeOptions } from './options'; import type { DevServerBuilderOutput } from './output'; import type { Schema as DevServerBuilderOptions } from './schema'; import { serveWithVite } from './vite-server'; /** * A Builder that executes a development server based on the provided browser target option. * * Usage of the `transforms` and/or `extensions` parameters is NOT supported and may cause * unexpected build output or build failures. * * @param options Dev Server options. * @param context The build context. * @param extensions An optional object containing an array of build plugins (esbuild-based) * and/or HTTP request middleware. * * @experimental Direct usage of this function is considered experimental. */ export async function* execute( options: DevServerBuilderOptions, context: BuilderContext, extensions?: { buildPlugins?: Plugin[]; middleware?: (( req: http.IncomingMessage, res: http.ServerResponse, next: (err?: unknown) => void, ) => void)[]; indexHtmlTransformer?: IndexHtmlTransform; }, ): AsyncIterable<DevServerBuilderOutput> { // Determine project name from builder context target const projectName = context.target?.project; if (!projectName) { context.logger.error(`The "dev-server" builder requires a target to be specified.`); return; } const { builderName, normalizedOptions } = await initialize(options, projectName, context); // Warn if the initial options provided by the user enable prebundling but caching is disabled if (options.prebundle && !normalizedOptions.cacheOptions.enabled) { context.logger.warn( `Prebundling has been configured but will not be used because caching has been disabled.`, ); } yield* serveWithVite( normalizedOptions, builderName, (options, context, plugins) => buildApplicationInternal(options, context, { codePlugins: plugins }), context, { indexHtml: extensions?.indexHtmlTransformer }, extensions, ); } async function initialize( initialOptions: DevServerBuilderOptions, projectName: string, context: BuilderContext, ) { // Purge old build disk cache. await purgeStaleBuildCache(context); const normalizedOptions = await normalizeOptions(context, projectName, initialOptions); const builderName = await context.getBuilderNameForTarget(normalizedOptions.buildTarget); if ( !/^127\.\d+\.\d+\.\d+/g.test(normalizedOptions.host) && normalizedOptions.host !== '::1' && normalizedOptions.host !== 'localhost' ) { context.logger.warn(` Warning: This is a simple server for use in testing or debugging Angular applications locally. It hasn't been reviewed for security issues. Binding this server to an open connection can result in compromising your application or computer. Using a different host than the one passed to the "--host" flag might result in websocket connection issues. `); } normalizedOptions.port = await checkPort(normalizedOptions.port, normalizedOptions.host); return { builderName, normalizedOptions, }; }
{ "end_byte": 3590, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/builder.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/index.ts_0_703
/** * @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 { DevServerBuilderOutput } from './output'; import type { Schema as DevServerBuilderOptions } from './schema'; export { type DevServerBuilderOptions, type DevServerBuilderOutput, execute as executeDevServerBuilder, }; export default createBuilder<DevServerBuilderOptions, DevServerBuilderOutput>(execute); // Temporary export to support specs export { execute as executeDevServer };
{ "end_byte": 703, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/index.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/internal.ts_0_1097
/** * @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 { type BuildOutputFile, BuildOutputFileType } from '@angular/build'; export { createRxjsEsmResolutionPlugin } from '../../tools/esbuild/rxjs-esm-resolution-plugin'; export { JavaScriptTransformer } from '../../tools/esbuild/javascript-transformer'; export { getFeatureSupport, isZonelessApp } from '../../tools/esbuild/utils'; export { type IndexHtmlTransform } from '../../utils/index-file/index-html-generator'; export { purgeStaleBuildCache } from '../../utils/purge-cache'; export { getSupportedBrowsers } from '../../utils/supported-browsers'; export { transformSupportedBrowsersToTargets } from '../../tools/esbuild/utils'; export { buildApplicationInternal } from '../../builders/application'; export type { ApplicationBuilderInternalOptions } from '../../builders/application/options'; export type { ExternalResultMetadata } from '../../tools/esbuild/bundler-execution-result';
{ "end_byte": 1097, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/internal.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/options.ts_0_4156
/** * @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, targetFromTargetString } from '@angular-devkit/architect'; import path from 'node:path'; import { normalizeOptimization } from '../../utils'; import { normalizeCacheOptions } from '../../utils/normalize-cache'; import { ApplicationBuilderOptions } from '../application'; import { Schema as DevServerOptions } from './schema'; export type NormalizedDevServerOptions = 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: DevServerOptions, ) { const { workspaceRoot, logger } = context; const projectMetadata = await context.getProjectMetadata(projectName); const projectRoot = path.join(workspaceRoot, (projectMetadata.root as string | undefined) ?? ''); const cacheOptions = normalizeCacheOptions(projectMetadata, workspaceRoot); // Target specifier defaults to the current project's build target using a development configuration const buildTargetSpecifier = options.buildTarget ?? `::development`; const buildTarget = targetFromTargetString(buildTargetSpecifier, projectName, 'build'); // Get the application builder options. const browserBuilderName = await context.getBuilderNameForTarget(buildTarget); const rawBuildOptions = await context.getTargetOptions(buildTarget); const buildOptions = (await context.validateOptions( rawBuildOptions, browserBuilderName, )) as unknown as ApplicationBuilderOptions; const optimization = normalizeOptimization(buildOptions.optimization); if (options.prebundle) { if (!cacheOptions.enabled) { // Warn if the initial options provided by the user enable prebundling but caching is disabled logger.warn( 'Prebundling has been configured but will not be used because caching has been disabled.', ); } else if (optimization.scripts) { // Warn if the initial options provided by the user enable prebundling but script optimization is enabled. logger.warn( 'Prebundling has been configured but will not be used because scripts optimization is enabled.', ); } } let inspect: false | { host?: string; port?: number } = false; const inspectRaw = options.inspect; if (inspectRaw === true || inspectRaw === '' || inspectRaw === 'true') { inspect = { host: undefined, port: undefined, }; } else if (typeof inspectRaw === 'string' && inspectRaw !== 'false') { const port = +inspectRaw; if (isFinite(port)) { inspect = { host: undefined, port, }; } else { const [host, port] = inspectRaw.split(':'); inspect = { host, port: isNaN(+port) ? undefined : +port, }; } } // Initial options to keep const { host, port, poll, open, verbose, watch, liveReload, hmr, headers, proxyConfig, servePath, ssl, sslCert, sslKey, prebundle, } = options; // Return all the normalized options return { buildTarget, host: host ?? 'localhost', port: port ?? 4200, poll, open, verbose, watch, liveReload, hmr, headers, workspaceRoot, projectRoot, cacheOptions, proxyConfig, servePath, ssl, sslCert, sslKey, // Prebundling defaults to true but requires caching to function prebundle: cacheOptions.enabled && !optimization.scripts && prebundle, inspect, }; }
{ "end_byte": 4156, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/options.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/tests/jasmine-helpers.ts_0_1419
/** * @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 { BuilderHandlerFn } from '@angular-devkit/architect'; import { json } from '@angular-devkit/core'; import { readFileSync } from 'node:fs'; import { JasmineBuilderHarness, host, setupApplicationTarget } from './setup'; const optionSchemaCache = new Map<string, json.schema.JsonSchema>(); export function describeServeBuilder<T>( builderHandler: BuilderHandlerFn<T & json.JsonObject>, options: { name?: string; schemaPath: string }, specDefinitions: ( harness: JasmineBuilderHarness<T>, setupTarget: typeof setupApplicationTarget, isViteRun: true, ) => void, ): void { let optionSchema = optionSchemaCache.get(options.schemaPath); if (optionSchema === undefined) { optionSchema = JSON.parse(readFileSync(options.schemaPath, 'utf8')) as json.schema.JsonSchema; optionSchemaCache.set(options.schemaPath, optionSchema); } const harness = new JasmineBuilderHarness<T>(builderHandler, host, { builderName: options.name, optionSchema, }); describe(options.name || builderHandler.name, () => { beforeEach(() => host.initialize().toPromise()); afterEach(() => host.restore().toPromise()); specDefinitions(harness, setupApplicationTarget, true); }); }
{ "end_byte": 1419, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/tests/jasmine-helpers.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/tests/setup.ts_0_3233
/** * @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 { json } from '@angular-devkit/core'; import { readFileSync } from 'node:fs'; import path from 'node:path'; import { BuilderHarness } from '../../../../../../../modules/testing/builder/src'; import { ApplicationBuilderOptions as AppilicationSchema, buildApplication } from '@angular/build'; import { Schema } from '../schema'; // TODO: Consider using package.json imports field instead of relative path // after the switch to rules_js. export * from '../../../../../../../modules/testing/builder/src'; // TODO: Remove and use import after Vite-based dev server is moved to new package export const APPLICATION_BUILDER_INFO = Object.freeze({ name: '@angular-devkit/build-angular:application', schemaPath: path.join( path.dirname(require.resolve('@angular/build/package.json')), 'src/builders/application/schema.json', ), }); /** * Contains all required application builder fields. * Also disables progress reporting to minimize logging output. */ export const APPLICATION_BASE_OPTIONS = Object.freeze<AppilicationSchema>({ index: 'src/index.html', browser: 'src/main.ts', outputPath: 'dist', tsConfig: 'src/tsconfig.app.json', progress: false, // Disable optimizations optimization: false, // Enable polling (if a test enables watch mode). // This is a workaround for bazel isolation file watch not triggering in tests. poll: 100, }); export const DEV_SERVER_BUILDER_INFO = Object.freeze({ name: '@angular-devkit/build-angular:dev-server', schemaPath: __dirname + '/../schema.json', }); /** * Contains all required dev-server builder fields. * The port is also set to zero to ensure a free port is used for each test which * supports parallel test execution. */ export const BASE_OPTIONS = Object.freeze<Schema>({ buildTarget: 'test:build', port: 0, // Watch is not supported for testing in vite as currently there is no teardown logic to stop the watchers. watch: false, }); /** * Maximum time for single build/rebuild * This accounts for CI variability. */ export const BUILD_TIMEOUT = 25_000; /** * Cached application builder option schema */ let applicationSchema: json.schema.JsonSchema | undefined; /** * Adds a `build` target to a builder test harness for the application builder with the base options * used by the application builder tests. * * @param harness The builder harness to use when setting up the application builder target * @param extraOptions The additional options that should be used when executing the target. */ export function setupApplicationTarget<T>( harness: BuilderHarness<T>, extraOptions?: Partial<AppilicationSchema>, ): void { applicationSchema ??= JSON.parse( readFileSync(APPLICATION_BUILDER_INFO.schemaPath, 'utf8'), ) as json.schema.JsonSchema; harness.withBuilderTarget( 'build', buildApplication, { ...APPLICATION_BASE_OPTIONS, ...extraOptions, }, { builderName: APPLICATION_BUILDER_INFO.name, optionSchema: applicationSchema, }, ); }
{ "end_byte": 3233, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/tests/setup.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/tests/execute-fetch.ts_0_1446
/** * @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 { lastValueFrom, mergeMap, take, timeout } from 'rxjs'; import { URL } from 'url'; import { BuilderHarness, BuilderHarnessExecutionOptions, BuilderHarnessExecutionResult, } from './setup'; export async function executeOnceAndFetch<T>( harness: BuilderHarness<T>, url: string, options?: Partial<BuilderHarnessExecutionOptions> & { request?: RequestInit }, ): Promise<BuilderHarnessExecutionResult & { response?: Response; content?: string }> { return lastValueFrom( harness.execute().pipe( timeout(30000), mergeMap(async (executionResult) => { let response = undefined; let content = undefined; if (executionResult.result?.success) { let baseUrl = `${executionResult.result.baseUrl}`; baseUrl = baseUrl[baseUrl.length - 1] === '/' ? baseUrl : `${baseUrl}/`; const resolvedUrl = new URL(url, baseUrl); const originalResponse = await fetch(resolvedUrl, options?.request); response = originalResponse.clone(); // Ensure all data is available before stopping server content = await originalResponse.text(); } return { ...executionResult, response, content }; }), take(1), ), ); }
{ "end_byte": 1446, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/tests/execute-fetch.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/tests/behavior/serve_service-worker_spec.ts_0_7257
/** * @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 { executeDevServer } from '../../index'; import { executeOnceAndFetch } from '../execute-fetch'; import { describeServeBuilder } from '../jasmine-helpers'; import { BASE_OPTIONS, BUILD_TIMEOUT, DEV_SERVER_BUILDER_INFO } from '../setup'; const manifest = { index: '/index.html', assetGroups: [ { name: 'app', installMode: 'prefetch', resources: { files: ['/favicon.ico', '/index.html'], }, }, { name: 'assets', installMode: 'lazy', updateMode: 'prefetch', resources: { files: [ '/media/**', '/assets/**', '/*.(svg|cur|jpg|jpeg|png|apng|webp|avif|gif|otf|ttf|woff|woff2)', ], }, }, ], }; describeServeBuilder( executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget, isViteRun) => { describe('Behavior: "dev-server builder serves service worker"', () => { beforeEach(async () => { // Application code is not needed for these tests await harness.writeFile('src/main.ts', ''); await harness.writeFile('src/polyfills.ts', ''); harness.useProject('test', { root: '.', sourceRoot: 'src', cli: { cache: { enabled: false, }, }, i18n: { sourceLocale: { 'code': 'fr', }, }, }); }); it('works with service worker', async () => { setupTarget(harness, { // eslint-disable-next-line @typescript-eslint/no-explicit-any serviceWorker: (isViteRun ? 'ngsw-config.json' : true) as any, assets: ['src/favicon.ico', 'src/assets'], styles: ['src/styles.css'], }); await harness.writeFiles({ 'ngsw-config.json': JSON.stringify(manifest), 'src/assets/folder-asset.txt': 'folder-asset.txt', 'src/styles.css': `body { background: url(./spectrum.png); }`, }); harness.useTarget('serve', { ...BASE_OPTIONS, }); const { result, response } = await executeOnceAndFetch(harness, '/ngsw.json'); expect(result?.success).toBeTrue(); expect(await response?.json()).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', '/media/spectrum.png'], cacheQueryOptions: { ignoreVary: true, }, patterns: [], }, ], dataGroups: [], hashTable: { '/favicon.ico': '84161b857f5c547e3699ddfbffc6d8d737542e01', '/assets/folder-asset.txt': '617f202968a6a81050aa617c2e28e1dca11ce8d4', '/index.html': isViteRun ? 'e5b73e6798d2782bf59dd5272d254d5bde364695' : '9d232e3e13b4605d197037224a2a6303dd337480', '/media/spectrum.png': '8d048ece46c0f3af4b598a95fd8e4709b631c3c0', }, }), ); }); it('works with localize', async () => { setupTarget(harness, { // eslint-disable-next-line @typescript-eslint/no-explicit-any serviceWorker: (isViteRun ? 'ngsw-config.json' : true) as any, assets: ['src/favicon.ico', 'src/assets'], styles: ['src/styles.css'], localize: ['fr'], }); await harness.writeFiles({ 'ngsw-config.json': JSON.stringify(manifest), 'src/assets/folder-asset.txt': 'folder-asset.txt', 'src/styles.css': `body { background: url(./spectrum.png); }`, }); harness.useTarget('serve', { ...BASE_OPTIONS, }); const { result, response } = await executeOnceAndFetch(harness, '/ngsw.json'); expect(result?.success).toBeTrue(); expect(await response?.json()).toBeDefined(); }); // TODO(fix-vite): currently this is broken in vite due to watcher never terminates. (isViteRun ? xit : it)('works in watch mode', async () => { setupTarget(harness, { // eslint-disable-next-line @typescript-eslint/no-explicit-any serviceWorker: (isViteRun ? 'ngsw-config.json' : true) as any, assets: ['src/favicon.ico', 'src/assets'], styles: ['src/styles.css'], }); await harness.writeFiles({ 'ngsw-config.json': JSON.stringify(manifest), 'src/assets/folder-asset.txt': 'folder-asset.txt', 'src/styles.css': `body { background: url(./spectrum.png); }`, }); harness.useTarget('serve', { ...BASE_OPTIONS, watch: true, }); const buildCount = await harness .execute() .pipe( timeout(BUILD_TIMEOUT), concatMap(async ({ result }, index) => { expect(result?.success).toBeTrue(); const response = await fetch(new URL('ngsw.json', `${result?.baseUrl}`)); const { hashTable } = (await response.json()) as { hashTable: object }; const hashTableEntries = Object.keys(hashTable); switch (index) { case 0: expect(hashTableEntries).toEqual([ '/assets/folder-asset.txt', '/favicon.ico', '/index.html', '/media/spectrum.png', ]); await harness.writeFile( 'src/assets/folder-new-asset.txt', harness.readFile('src/assets/folder-asset.txt'), ); break; case 1: expect(hashTableEntries).toEqual([ '/assets/folder-asset.txt', '/assets/folder-new-asset.txt', '/favicon.ico', '/index.html', '/media/spectrum.png', ]); break; } }), take(2), count(), ) .toPromise(); expect(buildCount).toBe(2); }); }); }, );
{ "end_byte": 7257, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/tests/behavior/serve_service-worker_spec.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/tests/behavior/build-assets_spec.ts_0_4281
/** * @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 { executeDevServer } from '../../index'; import { executeOnceAndFetch } from '../execute-fetch'; import { describeServeBuilder } from '../jasmine-helpers'; import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup'; describeServeBuilder(executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget) => { const javascriptFileContent = "import {foo} from 'unresolved'; /* a comment */const foo = `bar`;\n\n\n"; describe('Behavior: "browser builder assets"', () => { it('serves a project JavaScript asset unmodified', async () => { await harness.writeFile('src/extra.js', javascriptFileContent); setupTarget(harness, { assets: ['src/extra.js'], optimization: { scripts: true, }, }); harness.useTarget('serve', { ...BASE_OPTIONS, }); const { result, response } = await executeOnceAndFetch(harness, 'extra.js'); expect(result?.success).toBeTrue(); expect(await response?.text()).toContain(javascriptFileContent); }); it('serves a project TypeScript asset unmodified', async () => { await harness.writeFile('src/extra.ts', javascriptFileContent); setupTarget(harness, { assets: ['src/extra.ts'], }); harness.useTarget('serve', { ...BASE_OPTIONS, }); const { result, response } = await executeOnceAndFetch(harness, 'extra.ts'); expect(result?.success).toBeTrue(); expect(await response?.text()).toContain(javascriptFileContent); }); it('should return 404 for non existing assets', async () => { setupTarget(harness, { assets: [], optimization: { scripts: true, }, }); harness.useTarget('serve', { ...BASE_OPTIONS, }); const { result, response } = await executeOnceAndFetch(harness, 'does-not-exist.js'); expect(result?.success).toBeTrue(); expect(await response?.status).toBe(404); }); it(`should return the asset that matches 'index.html' when path has a trailing '/'`, async () => { await harness.writeFile( 'src/login/index.html', '<html><body><h1>Login page</h1></body><html>', ); setupTarget(harness, { assets: ['src/login'], optimization: { scripts: true, }, }); harness.useTarget('serve', { ...BASE_OPTIONS, }); const { result, response } = await executeOnceAndFetch(harness, 'login/'); expect(result?.success).toBeTrue(); expect(await response?.status).toBe(200); expect(await response?.text()).toContain('<h1>Login page</h1>'); }); it(`should return the asset that matches '.html' when path has no trailing '/'`, async () => { await harness.writeFile('src/login/new.html', '<html><body><h1>Login page</h1></body><html>'); setupTarget(harness, { assets: ['src/login'], optimization: { scripts: true, }, }); harness.useTarget('serve', { ...BASE_OPTIONS, }); const { result, response } = await executeOnceAndFetch(harness, 'login/new'); expect(result?.success).toBeTrue(); expect(await response?.status).toBe(200); expect(await response?.text()).toContain('<h1>Login page</h1>'); }); it(`should return a redirect when an asset directory is accessed without a trailing '/'`, async () => { await harness.writeFile( 'src/login/index.html', '<html><body><h1>Login page</h1></body><html>', ); setupTarget(harness, { assets: ['src/login'], optimization: { scripts: true, }, }); harness.useTarget('serve', { ...BASE_OPTIONS, }); const { result, response } = await executeOnceAndFetch(harness, 'login', { request: { redirect: 'manual' }, }); expect(result?.success).toBeTrue(); expect(await response?.status).toBe(301); expect(await response?.headers.get('Location')).toBe('/login/'); }); }); });
{ "end_byte": 4281, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/tests/behavior/build-assets_spec.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/tests/behavior/build_localize_replaced_watch_spec.ts_0_2476
/** * @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 */ /* eslint-disable max-len */ import { concatMap, count, take, timeout } from 'rxjs'; import { URL } from 'url'; import { executeDevServer } from '../../index'; import { describeServeBuilder } from '../jasmine-helpers'; import { BASE_OPTIONS, BUILD_TIMEOUT, DEV_SERVER_BUILDER_INFO } from '../setup'; describeServeBuilder( executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget, isViteRun) => { // TODO(fix-vite): currently this is broken in vite. (isViteRun ? xdescribe : describe)( 'Behavior: "i18n $localize calls are replaced during watching"', () => { beforeEach(() => { harness.useProject('test', { root: '.', sourceRoot: 'src', cli: { cache: { enabled: false, }, }, i18n: { sourceLocale: { 'code': 'fr', }, }, }); setupTarget(harness, { localize: ['fr'] }); }); it('$localize are replaced in watch', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, watch: true, }); await harness.writeFile( 'src/app/app.component.html', ` <p id="hello" i18n="An introduction header for this sample">Hello {{ title }}! </p> `, ); const buildCount = await harness .execute() .pipe( timeout(BUILD_TIMEOUT * 2), concatMap(async ({ result }, index) => { expect(result?.success).toBe(true); const response = await fetch(new URL('main.js', `${result?.baseUrl}`)); expect(await response?.text()).not.toContain('$localize`:'); switch (index) { case 0: { await harness.modifyFile('src/app/app.component.html', (content) => content.replace('introduction', 'intro'), ); break; } } }), take(2), count(), ) .toPromise(); expect(buildCount).toBe(2); }); }, ); }, );
{ "end_byte": 2476, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/tests/behavior/build_localize_replaced_watch_spec.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/tests/behavior/serve-live-reload-proxies_spec.ts_0_3491
/** * @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 */ /* eslint-disable import/no-extraneous-dependencies */ import { tags } from '@angular-devkit/core'; import { createServer } from 'http'; import { createProxyServer } from 'http-proxy'; import { AddressInfo } from 'net'; import puppeteer, { Browser, Page } from 'puppeteer'; import { count, debounceTime, finalize, switchMap, take, timeout } from 'rxjs'; import { executeDevServer } from '../../index'; import { describeServeBuilder } from '../jasmine-helpers'; import { BASE_OPTIONS, BUILD_TIMEOUT, DEV_SERVER_BUILDER_INFO } from '../setup'; // eslint-disable-next-line @typescript-eslint/no-explicit-any declare const document: any; interface ProxyInstance { server: typeof createProxyServer extends () => infer R ? R : never; url: string; } function findFreePort(): Promise<number> { return new Promise<number>((resolve, reject) => { const server = createServer(); server.once('listening', () => { const port = (server.address() as AddressInfo).port; server.close((e) => (e ? reject(e) : resolve(port))); }); server.once('error', (e) => server.close(() => reject(e))); server.listen(); }); } async function createProxy(target: string, secure: boolean, ws = true): Promise<ProxyInstance> { const proxyPort = await findFreePort(); const server = createProxyServer({ ws, target, secure, ssl: secure && { key: tags.stripIndents` -----BEGIN RSA PRIVATE KEY----- MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDEBRUsUz4rdcMt CQGLvG3SzUinsmgdgOyTNQNA0eOMyRSrmS8L+F/kSLUnqqu4mzdeqDzo2Xj553jK dRqMCRFGJuGnQ/VIbW2A+ywgrqILuDyF5i4PL1aQW4yJ7TnXfONKfpswQArlN6DF gBYJtoJlf8XD1sOeJpsv/O46/ix/wngQ+GwQQ2cfqxQT0fE9SBCY23VNt3SPUJ3k 9etJMvJ9U9GHSb1CFdNQe7Gyx7xdKf1TazB27ElNZEg2aF99if47uRskYjvvFivy 7nxGx/ccIwjwNMpk29AsKG++0sn1yTK7tD5Px6aCSVK0BKbdXZS2euJor8hASGBJ 3GpVGJvdAgMBAAECggEAapYo8TVCdPdP7ckb4hPP0/R0MVu9aW2VNmZ5ImH+zar5 ZmWhQ20HF2bBupP/VB5yeTIaDLNUKO9Iqy4KBWNY1UCHKyC023FFPgFV+V98FctU faqwGOmwtEZToRwxe48ZOISndhEc247oCPyg/x8SwIY9z0OUkwaDFBEAqWtUXxM3 /SPpCT5ilLgxnRgVB8Fj5Z0q7ThnxNVOmVC1OSIakEj46PzmMXn1pCKLOCUmAAOQ BnrOZuty2b8b2M/GHsktLZwojQQJmArnIBymTXQTVhaGgKSyOv1qvHLp9L1OJf0/ Xm+/TqT6ztzhzlftcObdfQZZ5JuoEwlvyrsGFlA3MQKBgQDiQC3KYMG8ViJkWrv6 XNAFEoAjVEKrtirGWJ66YfQ9KSJ7Zttrd1Y1V1OLtq3z4YMH39wdQ8rOD+yR8mWV 6Tnsxma6yJXAH8uan8iVbxjIZKF1hnvNCxUoxYmWOmTLcEQMzmxvTzAiR+s6R6Uj 9LgGqppt30nM4wnOhOJU6UxqbwKBgQDdy03KidbPZuycJSy1C9AIt0jlrxDsYm+U fZrB6mHEZcgoZS5GbLKinQCdGcgERa05BXvJmNbfZtT5a37YEnbjsTImIhDiBP5P nW36/9a3Vg1svd1KP2206/Bh3gfZbgTsQg4YogXgjf0Uzuvw18btgTtLVpVyeuqz TU3eeF30cwKBgQCN6lvOmapsDEs+T3uhqx4AUH53qp63PmjOSUAnANJGmsq6ROZV HmHAy6nn9Qpf85BRHCXhZWiMoIhvc3As/EINNtWxS6hC/q6jqp4SvcD50cVFBroY /16iWGXZCX+37A+DSOfTWgSDPEFcKRx41UOpStHbITgVgEPieo/NWxlHmQKBgQDX JOLs2RB6V0ilnpnjdPXzvncD9fHgmwvJap24BPeZX3HtXViqD76oZsu1mNCg9EW3 zk3pnEyyoDlvSIreZerVq4kN3HWsCVP3Pqr0kz9g0CRtmy8RWr28hjHDfXD3xPUZ iGnMEz7IOHOKv722/liFAprV1cNaLUmFbDNg3jmlaQKBgQDG5WwngPhOHmjTnSml amfEz9a4yEhQqpqgVNW5wwoXOf6DbjL2m/maJh01giThj7inMcbpkZlIclxD0Eu6 Lof+ctCeqSAJvaVPmd+nv8Yp26zsF1yM8ax9xXjrIvv9fSbycNveGTDCsNNTiYoW QyvMqmN1kGy20SZbQDD/fLfqBQ== -----END RSA PRIVATE KEY----- `,
{ "end_byte": 3491, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/tests/behavior/serve-live-reload-proxies_spec.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/tests/behavior/serve-live-reload-proxies_spec.ts_3498_6078
cert: tags.stripIndents` -----BEGIN CERTIFICATE----- MIIDXTCCAkWgAwIBAgIJALz8gD/gAt0OMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX aWRnaXRzIFB0eSBMdGQwHhcNMTgxMDIzMTgyMTQ5WhcNMTkxMDIzMTgyMTQ5WjBF MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50 ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB CgKCAQEAxAUVLFM+K3XDLQkBi7xt0s1Ip7JoHYDskzUDQNHjjMkUq5kvC/hf5Ei1 J6qruJs3Xqg86Nl4+ed4ynUajAkRRibhp0P1SG1tgPssIK6iC7g8heYuDy9WkFuM ie0513zjSn6bMEAK5TegxYAWCbaCZX/Fw9bDniabL/zuOv4sf8J4EPhsEENnH6sU E9HxPUgQmNt1Tbd0j1Cd5PXrSTLyfVPRh0m9QhXTUHuxsse8XSn9U2swduxJTWRI NmhffYn+O7kbJGI77xYr8u58Rsf3HCMI8DTKZNvQLChvvtLJ9ckyu7Q+T8emgklS tASm3V2UtnriaK/IQEhgSdxqVRib3QIDAQABo1AwTjAdBgNVHQ4EFgQUDZBhVKdb 3BRhLIhuuE522Vsul0IwHwYDVR0jBBgwFoAUDZBhVKdb3BRhLIhuuE522Vsul0Iw DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEABh9WWZwWLgb9/DcTxL72 6pI96t4jiF79Q+pPefkaIIi0mE6yodWrTAsBQu9I6bNRaEcCSoiXkP2bqskD/UGg LwUFgSrDOAA3UjdHw3QU5g2NocduG7mcFwA40TB98sOsxsUyYlzSyWzoiQWwPYwb hek1djuWkqPXsTjlj54PTPN/SjTFmo4p5Ip6nbRf2nOREl7v0rJpGbJvXiCMYyd+ Zv+j4mRjCGo8ysMR2HjCUGkYReLAgKyyz3M7i8vevJhKslyOmy6Txn4F0nPVumaU DDIy4xXPW1STWfsmSYJfYW3wa0wk+pJQ3j2cTzkPQQ8gwpvM3U9DJl43uwb37v6I 7Q== -----END CERTIFICATE----- `, }, }).listen(proxyPort); return { server, url: `${secure ? 'https' : 'http'}://localhost:${proxyPort}`, }; } async function goToPageAndWaitForWS(page: Page, url: string): Promise<void> { const baseUrl = url.replace(/^http/, 'ws'); const socksRequest = baseUrl[baseUrl.length - 1] === '/' ? `${baseUrl}ng-cli-ws` : `${baseUrl}/ng-cli-ws`; // Create a Chrome dev tools session so that we can capturing websocket request. // https://github.com/puppeteer/puppeteer/issues/2974 // We do this, to ensure that we make the right request with the expected host, port etc... const client = await page.target().createCDPSession(); await client.send('Network.enable'); await client.send('Page.enable'); await Promise.all([ new Promise<void>((resolve, reject) => { const timeout = setTimeout( () => reject(new Error(`A Websocket connected to ${socksRequest} was not established.`)), 2000, ); client.on('Network.webSocketCreated', ({ url }) => { if (url.startsWith(socksRequest)) { clearTimeout(timeout); resolve(); } }); }), page.goto(url), ]); await client.detach(); }
{ "end_byte": 6078, "start_byte": 3498, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/tests/behavior/serve-live-reload-proxies_spec.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/tests/behavior/serve-live-reload-proxies_spec.ts_6080_12248
describeServeBuilder( executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget, isViteRun) => { // TODO(fix-vite): currently this is broken in vite. (isViteRun ? xdescribe : describe)( 'Behavior: "Dev-server builder live-reload with proxies"', () => { let browser: Browser; let page: Page; const SERVE_OPTIONS = Object.freeze({ ...BASE_OPTIONS, hmr: false, watch: true, liveReload: true, }); beforeAll(async () => { browser = await puppeteer.launch({ // MacOSX users need to set the local binary manually because Chrome has lib files with // spaces in them which Bazel does not support in runfiles // See: https://github.com/angular/angular-cli/pull/17624 // eslint-disable-next-line max-len // executablePath: '/Users/<USERNAME>/git/angular-cli/node_modules/puppeteer/.local-chromium/mac-818858/chrome-mac/Chromium.app/Contents/MacOS/Chromium', ignoreHTTPSErrors: true, args: ['--no-sandbox', '--disable-gpu'], }); }); afterAll(async () => { await browser.close(); }); beforeEach(async () => { setupTarget(harness, { polyfills: ['src/polyfills.ts'], }); page = await browser.newPage(); }); afterEach(async () => { await page.close(); }); it('works without proxy', async () => { harness.useTarget('serve', { ...SERVE_OPTIONS, }); await harness.writeFile('src/app/app.component.html', '<p>{{ title }}</p>'); const buildCount = await harness .execute() .pipe( debounceTime(1000), timeout(BUILD_TIMEOUT * 2), switchMap(async ({ result }, index) => { expect(result?.success).toBeTrue(); if (typeof result?.baseUrl !== 'string') { throw new Error('Expected "baseUrl" to be a string.'); } switch (index) { case 0: await goToPageAndWaitForWS(page, result.baseUrl); await harness.modifyFile('src/app/app.component.ts', (content) => content.replace(`'app'`, `'app-live-reload'`), ); break; case 1: const innerText = await page.evaluate( () => document.querySelector('p').innerText, ); expect(innerText).toBe('app-live-reload'); break; } }), take(2), count(), ) .toPromise(); expect(buildCount).toBe(2); }); it('works without http -> http proxy', async () => { harness.useTarget('serve', { ...SERVE_OPTIONS, }); await harness.writeFile('src/app/app.component.html', '<p>{{ title }}</p>'); let proxy: ProxyInstance | undefined; const buildCount = await harness .execute() .pipe( debounceTime(1000), timeout(BUILD_TIMEOUT * 2), switchMap(async ({ result }, index) => { expect(result?.success).toBeTrue(); if (typeof result?.baseUrl !== 'string') { throw new Error('Expected "baseUrl" to be a string.'); } switch (index) { case 0: proxy = await createProxy(result.baseUrl, false); await goToPageAndWaitForWS(page, proxy.url); await harness.modifyFile('src/app/app.component.ts', (content) => content.replace(`'app'`, `'app-live-reload'`), ); break; case 1: const innerText = await page.evaluate( () => document.querySelector('p').innerText, ); expect(innerText).toBe('app-live-reload'); break; } }), take(2), count(), finalize(() => { proxy?.server.close(); }), ) .toPromise(); expect(buildCount).toBe(2); }); it('works without https -> http proxy', async () => { harness.useTarget('serve', { ...SERVE_OPTIONS, }); await harness.writeFile('src/app/app.component.html', '<p>{{ title }}</p>'); let proxy: ProxyInstance | undefined; const buildCount = await harness .execute() .pipe( debounceTime(1000), timeout(BUILD_TIMEOUT * 2), switchMap(async ({ result }, index) => { expect(result?.success).toBeTrue(); if (typeof result?.baseUrl !== 'string') { throw new Error('Expected "baseUrl" to be a string.'); } switch (index) { case 0: proxy = await createProxy(result.baseUrl, true); await goToPageAndWaitForWS(page, proxy.url); await harness.modifyFile('src/app/app.component.ts', (content) => content.replace(`'app'`, `'app-live-reload'`), ); break; case 1: const innerText = await page.evaluate( () => document.querySelector('p').innerText, ); expect(innerText).toBe('app-live-reload'); break; } }), take(2), count(), finalize(() => { proxy?.server.close(); }), ) .toPromise(); expect(buildCount).toBe(2); }); }, ); }, );
{ "end_byte": 12248, "start_byte": 6080, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/tests/behavior/serve-live-reload-proxies_spec.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/tests/behavior/build-conditions_spec.ts_0_2709
/** * @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 { setupConditionImport, setTargetMapping, } from '../../../../../../../../modules/testing/builder/src/dev_prod_mode'; import { executeDevServer } from '../../index'; import { executeOnceAndFetch } from '../execute-fetch'; import { describeServeBuilder } from '../jasmine-helpers'; import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup'; describeServeBuilder( executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget, isApplicationBuilder) => { describe('Behavior: "conditional imports"', () => { if (!isApplicationBuilder) { it('requires esbuild', () => { expect(true).toBeTrue(); }); return; } beforeEach(async () => { setupTarget(harness); await setupConditionImport(harness); }); interface ImportsTestCase { name: string; mapping: unknown; output?: string; } const GOOD_TARGET = './src/good.js'; const BAD_TARGET = './src/bad.js'; const testCases: ImportsTestCase[] = [ { name: 'simple string', mapping: GOOD_TARGET }, { name: 'default fallback without matching condition', mapping: { 'never': BAD_TARGET, 'default': GOOD_TARGET, }, }, { name: 'development condition', mapping: { 'development': GOOD_TARGET, 'default': BAD_TARGET, }, }, { name: 'production condition', mapping: { 'production': BAD_TARGET, 'default': GOOD_TARGET, }, }, { name: 'browser condition (in browser)', mapping: { 'browser': GOOD_TARGET, 'default': BAD_TARGET, }, }, ]; for (const testCase of testCases) { describe(testCase.name, () => { beforeEach(async () => { await setTargetMapping(harness, testCase.mapping); }); it('resolves to expected target', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, }); const { result, response } = await executeOnceAndFetch(harness, '/main.js'); expect(result?.success).toBeTrue(); const output = await response?.text(); expect(output).toContain('good-value'); expect(output).not.toContain('bad-value'); }); }); } }); }, );
{ "end_byte": 2709, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/tests/behavior/build-conditions_spec.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/tests/behavior/build-budgets_spec.ts_0_1224
/** * @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 { BudgetType } from '../../../../utils/bundle-calculator'; import { executeDevServer } from '../../index'; import { describeServeBuilder } from '../jasmine-helpers'; import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup'; describeServeBuilder( executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget, isViteRun) => { // TODO(fix-vite): currently this is broken in vite. (isViteRun ? xdescribe : describe)('Behavior: "browser builder budgets"', () => { beforeEach(() => { setupTarget(harness, { // Add a budget error for any file over 100 bytes budgets: [{ type: BudgetType.All, maximumError: '100b' }], optimization: true, }); }); it('should ignore budgets defined in the "buildTarget" options', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); }); }); }, );
{ "end_byte": 1224, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/tests/behavior/build-budgets_spec.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/tests/behavior/build_translation_watch_spec.ts_0_3446
/** * @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 */ /* eslint-disable max-len */ import { concatMap, count, take, timeout } from 'rxjs'; import { URL } from 'url'; import { executeDevServer } from '../../index'; import { describeServeBuilder } from '../jasmine-helpers'; import { BASE_OPTIONS, BUILD_TIMEOUT, DEV_SERVER_BUILDER_INFO } from '../setup'; describeServeBuilder( executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget, isViteRun) => { // TODO(fix-vite): currently this is broken in vite. (isViteRun ? xdescribe : describe)('Behavior: "i18n translation file watching"', () => { beforeEach(() => { harness.useProject('test', { root: '.', sourceRoot: 'src', cli: { cache: { enabled: false, }, }, i18n: { locales: { 'fr': 'src/locales/messages.fr.xlf', }, }, }); setupTarget(harness, { localize: ['fr'] }); }); it('watches i18n translation files by default', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, watch: 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); const mainUrl = new URL('main.js', `${result?.baseUrl}`); switch (index) { case 0: { const response = await fetch(mainUrl); expect(await response?.text()).toContain('Bonjour'); await harness.modifyFile('src/locales/messages.fr.xlf', (content) => content.replace('Bonjour', 'Salut'), ); break; } case 1: { const response = await fetch(mainUrl); expect(await response?.text()).toContain('Salut'); 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": 3446, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/tests/behavior/build_translation_watch_spec.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/tests/behavior/component-updates_spec.ts_0_1776
/** * @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 { executeDevServer } from '../../index'; import { executeOnceAndFetch } from '../execute-fetch'; import { describeServeBuilder } from '../jasmine-helpers'; import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup'; describeServeBuilder(executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget) => { describe('Behavior: "Component updates"', () => { beforeEach(async () => { setupTarget(harness, {}); // Application code is not needed for these tests await harness.writeFile('src/main.ts', 'console.log("foo");'); }); it('responds with a 400 status if no request component query is present', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, }); const { result, response } = await executeOnceAndFetch(harness, '/@ng/component'); expect(result?.success).toBeTrue(); expect(response?.status).toBe(400); }); it('responds with an empty JS file when no component update is available', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, }); const { result, response } = await executeOnceAndFetch( harness, '/@ng/component?c=src%2Fapp%2Fapp.component.ts%40AppComponent', ); expect(result?.success).toBeTrue(); expect(response?.status).toBe(200); const output = await response?.text(); expect(response?.headers.get('Content-Type')).toEqual('text/javascript'); expect(response?.headers.get('Cache-Control')).toEqual('no-cache'); expect(output).toBe(''); }); }); });
{ "end_byte": 1776, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/tests/behavior/component-updates_spec.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/tests/behavior/build-external-dependencies_spec.ts_0_2790
/** * @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 { executeDevServer } from '../../index'; import { executeOnceAndFetch } from '../execute-fetch'; import { describeServeBuilder } from '../jasmine-helpers'; import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup'; describeServeBuilder(executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget) => { describe('Behavior: "browser builder external dependencies"', () => { beforeEach(async () => { setupTarget(harness, { externalDependencies: ['rxjs', 'rxjs/operators'], }); await harness.writeFile( 'src/main.ts', ` import { BehaviorSubject } from 'rxjs'; import { map } from 'rxjs/operators'; const subject = new BehaviorSubject<string>('hello'); console.log(subject.value); subject.pipe(map((val) => val + ' there')).subscribe(console.log); `, ); }); it('respects import specifiers for externalized dependencies', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, }); const { result, response } = await executeOnceAndFetch(harness, 'main.js'); expect(result?.success).toBeTrue(); const text = await response?.text(); expect(text).toContain(`import { BehaviorSubject } from "rxjs";`); expect(text).toContain(`import { map } from "rxjs/operators";`); }); it('respects import specifiers when using baseHref with trailing slash', async () => { setupTarget(harness, { externalDependencies: ['rxjs', 'rxjs/operators'], baseHref: '/test/', }); harness.useTarget('serve', { ...BASE_OPTIONS, }); const { result, response } = await executeOnceAndFetch(harness, 'main.js'); expect(result?.success).toBeTrue(); const text = await response?.text(); expect(text).toContain(`import { BehaviorSubject } from "rxjs";`); expect(text).toContain(`import { map } from "rxjs/operators";`); }); it('respects import specifiers when using baseHref without trailing slash', async () => { setupTarget(harness, { externalDependencies: ['rxjs', 'rxjs/operators'], baseHref: '/test', }); harness.useTarget('serve', { ...BASE_OPTIONS, }); const { result, response } = await executeOnceAndFetch(harness, 'main.js'); expect(result?.success).toBeTrue(); const text = await response?.text(); expect(text).toContain(`import { BehaviorSubject } from "rxjs";`); expect(text).toContain(`import { map } from "rxjs/operators";`); }); }); });
{ "end_byte": 2790, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/tests/behavior/build-external-dependencies_spec.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/tests/behavior/build-base-href_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 { executeDevServer } from '../../index'; import { executeOnceAndFetch } from '../execute-fetch'; import { describeServeBuilder } from '../jasmine-helpers'; import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup'; describeServeBuilder(executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget) => { describe('Behavior: "buildTarget baseHref"', () => { beforeEach(async () => { setupTarget(harness, { baseHref: '/test/', }); // Application code is not needed for these tests await harness.writeFile('src/main.ts', 'console.log("foo");'); }); it('uses the baseHref defined in the "buildTarget" options as the serve path', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, }); const { result, response } = await executeOnceAndFetch(harness, '/test/main.js'); expect(result?.success).toBeTrue(); const baseUrl = new URL(`${result?.baseUrl}/`); expect(baseUrl.pathname).toBe('/test/'); expect(await response?.text()).toContain('console.log'); }); it('serves the application from baseHref location without trailing slash', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, }); const { result, response } = await executeOnceAndFetch(harness, '/test'); expect(result?.success).toBeTrue(); expect(await response?.text()).toContain('<script src="main.js" type="module">'); }); }); });
{ "end_byte": 1677, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/tests/behavior/build-base-href_spec.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/tests/behavior/build-inline-critical-css_spec.ts_0_1401
/** * @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 { executeDevServer } from '../../index'; import { executeOnceAndFetch } from '../execute-fetch'; import { describeServeBuilder } from '../jasmine-helpers'; import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup'; describeServeBuilder(executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget) => { describe('Behavior: "browser builder inline critical css"', () => { beforeEach(async () => { setupTarget(harness, { optimization: { styles: { minify: true, inlineCritical: true, }, }, styles: ['src/styles.css'], }); await harness.writeFiles({ 'src/styles.css': 'body { color: #000 }', }); // Application code is not needed for these tests await harness.writeFile('src/main.ts', ''); }); it('inlines critical css when enabled in the "buildTarget" options', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, }); const { result, response } = await executeOnceAndFetch(harness, '/'); expect(result?.success).toBeTrue(); expect(await response?.text()).toContain('body{color:#000}'); }); }); });
{ "end_byte": 1401, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/tests/behavior/build-inline-critical-css_spec.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/tests/options/proxy-config_spec.ts_0_8605
/** * @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 { createServer } from 'node:http'; import { executeDevServer } from '../../index'; import { executeOnceAndFetch } from '../execute-fetch'; import { describeServeBuilder } from '../jasmine-helpers'; import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO, BuilderHarness } from '../setup'; describeServeBuilder(executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget, isVite) => { describe('option: "proxyConfig"', () => { beforeEach(async () => { setupTarget(harness); // Application code is not needed for these tests await harness.writeFile('src/main.ts', ''); }); it('proxies requests based on the `.json` proxy configuration file provided in the option', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, proxyConfig: 'proxy.config.json', }); const proxyServer = await createProxyServer(); try { await harness.writeFiles({ 'proxy.config.json': `{ "/api/*": { "target": "http://127.0.0.1:${proxyServer.address.port}" } }`, }); const { result, response } = await executeOnceAndFetch(harness, '/api/test'); expect(result?.success).toBeTrue(); expect(await response?.text()).toContain('TEST_API_RETURN'); } finally { await proxyServer.close(); } }); it('proxies requests based on the `.json` (with comments) proxy configuration file provided in the option', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, proxyConfig: 'proxy.config.json', }); const proxyServer = await createProxyServer(); try { await harness.writeFiles({ 'proxy.config.json': ` // JSON file with comments { "/api/*": { "target": "http://127.0.0.1:${proxyServer.address.port}" } } `, }); const { result, response } = await executeOnceAndFetch(harness, '/api/test'); expect(result?.success).toBeTrue(); expect(await response?.text()).toContain('TEST_API_RETURN'); } finally { await proxyServer.close(); } }); it('proxies requests based on the `.js` (CommonJS) proxy configuration file provided in the option', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, proxyConfig: 'proxy.config.js', }); const proxyServer = await createProxyServer(); try { await harness.writeFiles({ 'proxy.config.js': `module.exports = { "/api/*": { "target": "http://127.0.0.1:${proxyServer.address.port}" } }`, }); const { result, response } = await executeOnceAndFetch(harness, '/api/test'); expect(result?.success).toBeTrue(); expect(await response?.text()).toContain('TEST_API_RETURN'); } finally { await proxyServer.close(); } }); it('proxies requests based on the `.js` (ESM) proxy configuration file provided in the option', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, proxyConfig: 'proxy.config.js', }); const proxyServer = await createProxyServer(); try { await harness.writeFiles({ 'proxy.config.js': `export default { "/api/*": { "target": "http://127.0.0.1:${proxyServer.address.port}" } }`, 'package.json': '{ "type": "module" }', }); const { result, response } = await executeOnceAndFetch(harness, '/api/test'); expect(result?.success).toBeTrue(); expect(await response?.text()).toContain('TEST_API_RETURN'); } finally { await proxyServer.close(); } }); it('proxies requests based on the `.cjs` proxy configuration file provided in the option', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, proxyConfig: 'proxy.config.cjs', }); const proxyServer = await createProxyServer(); try { const proxyAddress = proxyServer.address; await harness.writeFiles({ 'proxy.config.cjs': `module.exports = { "/api/*": { "target": "http://127.0.0.1:${proxyAddress.port}" } }`, }); const { result, response } = await executeOnceAndFetch(harness, '/api/test'); expect(result?.success).toBeTrue(); expect(await response?.text()).toContain('TEST_API_RETURN'); } finally { await proxyServer.close(); } }); it('proxies requests based on the `.mjs` proxy configuration file provided in the option', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, proxyConfig: 'proxy.config.mjs', }); const proxyServer = await createProxyServer(); try { await harness.writeFiles({ 'proxy.config.mjs': `export default { "/api/*": { "target": "http://127.0.0.1:${proxyServer.address.port}" } }`, }); const { result, response } = await executeOnceAndFetch(harness, '/api/test'); expect(result?.success).toBeTrue(); expect(await response?.text()).toContain('TEST_API_RETURN'); } finally { await proxyServer.close(); } }); it('supports the Webpack array form of the configuration file', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, proxyConfig: 'proxy.config.json', }); const proxyServer = await createProxyServer(); try { await harness.writeFiles({ 'proxy.config.json': `[ { "context": ["/api", "/abc"], "target": "http://127.0.0.1:${proxyServer.address.port}" } ]`, }); const { result, response } = await executeOnceAndFetch(harness, '/api/test'); expect(result?.success).toBeTrue(); expect(await response?.text()).toContain('TEST_API_RETURN'); } finally { await proxyServer.close(); } }); it('throws an error when proxy configuration file cannot be found', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, proxyConfig: 'INVALID.json', }); const { result, error } = await harness.executeOnce({ outputLogsOnException: false }); expect(result).toBeUndefined(); expect(error).toEqual( jasmine.objectContaining({ message: jasmine.stringMatching('INVALID\\.json does not exist'), }), ); }); it('throws an error when JSON proxy configuration file cannot be parsed', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, proxyConfig: 'proxy.config.json', }); // Create a JSON file with a parse error (target property has no value) await harness.writeFiles({ 'proxy.config.json': ` // JSON file with comments { "/api/*": { "target": } } `, }); const { result, error } = await harness.executeOnce({ outputLogsOnException: false }); expect(result).toBeUndefined(); expect(error).toEqual( jasmine.objectContaining({ message: jasmine.stringMatching('contains parse errors:\\n\\[3, 35\\] ValueExpected'), }), ); }); it('supports negation of globs', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, proxyConfig: 'proxy.config.json', }); const proxyServer = await createProxyServer(); try { await harness.writeFiles({ 'proxy.config.json': ` { "!something/**/*": { "target": "http://127.0.0.1:${proxyServer.address.port}" } } `, }); const { result, response } = await executeOnceAndFetch(harness, '/api/test'); expect(result?.success).toBeTrue(); expect(await response?.text()).toContain('TEST_API_RETURN'); } finally { await proxyServer.close(); } }); /** * **************************************************************************************************** * ********************************** Below only Vite specific tests ********************************** * **************************************************************************************************** */ if (isVite) { viteOnlyTests(harness); } }); }); /** * Creates an HTTP Server used for proxy testing that provides a `/test` endpoint * that returns a 200 response with a body of `TEST_API_RETURN`. All other requests * will return a 404 response. */
{ "end_byte": 8605, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/tests/options/proxy-config_spec.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/tests/options/proxy-config_spec.ts_8606_10582
async function createProxyServer() { const proxyServer = createServer((request, response) => { if (request.url?.endsWith('/test')) { response.writeHead(200); response.end('TEST_API_RETURN'); } else { response.writeHead(404); response.end(); } }); await new Promise<void>((resolve) => proxyServer.listen(0, '127.0.0.1', resolve)); return { address: proxyServer.address() as import('net').AddressInfo, close: () => new Promise<void>((resolve) => proxyServer.close(() => resolve())), }; } /** * Vite specific tests */ function viteOnlyTests(harness: BuilderHarness<unknown>): void { it('proxies support regexp as context', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, proxyConfig: 'proxy.config.json', }); const proxyServer = await createProxyServer(); try { await harness.writeFiles({ 'proxy.config.json': ` { "^/api/.*": { "target": "http://127.0.0.1:${proxyServer.address.port}" } } `, }); const { result, response } = await executeOnceAndFetch(harness, '/api/test'); expect(result?.success).toBeTrue(); expect(await response?.text()).toContain('TEST_API_RETURN'); } finally { await proxyServer.close(); } }); it('proxies support negated regexp as context', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, proxyConfig: 'proxy.config.json', }); const proxyServer = await createProxyServer(); try { await harness.writeFiles({ 'proxy.config.json': ` { "^\\/(?!something).*": { "target": "http://127.0.0.1:${proxyServer.address.port}" } } `, }); const { result, response } = await executeOnceAndFetch(harness, '/api/test'); expect(result?.success).toBeTrue(); expect(await response?.text()).toContain('TEST_API_RETURN'); } finally { await proxyServer.close(); } }); }
{ "end_byte": 10582, "start_byte": 8606, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/tests/options/proxy-config_spec.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/tests/options/port_spec.ts_0_3338
/** * @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 { URL } from 'url'; import { executeDevServer } from '../../index'; import { executeOnceAndFetch } from '../execute-fetch'; import { describeServeBuilder } from '../jasmine-helpers'; import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup'; function getResultPort(result: Record<string, unknown> | undefined): string | undefined { if (typeof result?.baseUrl !== 'string') { fail(`Expected builder result with a string 'baseUrl' property. Received: ${result?.baseUrl}`); return; } try { return new URL(result.baseUrl).port; } catch { fail(`Expected a valid URL in builder result 'baseUrl' property. Received: ${result.baseUrl}`); } } describeServeBuilder( executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget, isViteRun) => { describe('option: "port"', () => { beforeEach(async () => { setupTarget(harness); // Application code is not needed for these tests await harness.writeFile('src/main.ts', ''); }); it('uses default port (4200) when not present', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, // Base options set port to zero port: undefined, }); const { result, response, logs } = await executeOnceAndFetch(harness, '/'); expect(result?.success).toBeTrue(); expect(getResultPort(result)).toBe('4200'); expect(await response?.text()).toContain('<title>'); if (!isViteRun) { expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching(/:4200/), }), ); } }); it('uses a random free port when set to 0 (zero)', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, port: 0, }); const { result, response, logs } = await executeOnceAndFetch(harness, '/'); expect(result?.success).toBeTrue(); const port = getResultPort(result); expect(port).not.toBe('4200'); if (isViteRun) { // Should not be default Vite port either expect(port).not.toBe('5173'); } expect(port).toMatch(/\d{4,6}/); expect(await response?.text()).toContain('<title>'); if (!isViteRun) { expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching(':' + port), }), ); } }); it('uses specific port when a non-zero number is specified', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, port: 8000, }); const { result, response, logs } = await executeOnceAndFetch(harness, '/'); expect(result?.success).toBeTrue(); expect(getResultPort(result)).toBe('8000'); expect(await response?.text()).toContain('<title>'); if (!isViteRun) { expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching(':8000'), }), ); } }); }); }, );
{ "end_byte": 3338, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/tests/options/port_spec.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/tests/options/prebundle_spec.ts_0_3413
/** * @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 { executeDevServer } from '../../index'; import { executeOnceAndFetch } from '../execute-fetch'; import { describeServeBuilder } from '../jasmine-helpers'; import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup'; // TODO: Temporarily disabled pending investigation into test-only Vite not stopping when caching is enabled describeServeBuilder( executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget, isViteRun) => { // prebundling is not available in webpack (isViteRun ? xdescribe : xdescribe)('option: "prebundle"', () => { beforeEach(async () => { setupTarget(harness); harness.useProject('test', { cli: { cache: { enabled: true, }, }, }); // Application code is not needed for these tests await harness.writeFile( 'src/main.ts', ` import { VERSION as coreVersion } from '@angular/core'; import { VERSION as platformVersion } from '@angular/platform-browser'; console.log(coreVersion); console.log(platformVersion); `, ); }); it('should prebundle dependencies when option is not present', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, }); const { result, content } = await executeOnceAndFetch(harness, '/main.js'); expect(result?.success).toBeTrue(); expect(content).toContain('vite/deps/@angular_core.js'); expect(content).not.toContain('node_modules/@angular/core/'); }); it('should prebundle dependencies when option is set to true', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, prebundle: true, }); const { result, content } = await executeOnceAndFetch(harness, '/main.js'); expect(result?.success).toBeTrue(); expect(content).toContain('vite/deps/@angular_core.js'); expect(content).not.toContain('node_modules/@angular/core/'); }); it('should not prebundle dependencies when option is set to false', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, prebundle: false, }); const { result, content } = await executeOnceAndFetch(harness, '/main.js'); expect(result?.success).toBeTrue(); expect(content).not.toContain('vite/deps/@angular_core.js'); expect(content).toContain('node_modules/@angular/core/'); }); it('should not prebundle specified dependency if added to exclude list', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, prebundle: { exclude: ['@angular/platform-browser'] }, }); const { result, content } = await executeOnceAndFetch(harness, '/main.js'); expect(result?.success).toBeTrue(); expect(content).toContain('vite/deps/@angular_core.js'); expect(content).not.toContain('node_modules/@angular/core/'); expect(content).not.toContain('vite/deps/@angular_platform-browser.js'); expect(content).toContain('node_modules/@angular/platform-browser/'); }); }); }, );
{ "end_byte": 3413, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/tests/options/prebundle_spec.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/tests/options/watch_spec.ts_0_2861
/** * @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 { TimeoutError } from 'rxjs'; import { executeDevServer } from '../../index'; import { describeServeBuilder } from '../jasmine-helpers'; import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup'; describeServeBuilder(executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget) => { describe('Option: "watch"', () => { beforeEach(() => { setupTarget(harness); }); it('does not wait for file changes when false', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, watch: false, }); await harness .executeWithCases([ async ({ result }) => { // Initial build should succeed expect(result?.success).toBe(true); // Modify a file to attempt to trigger file watcher await harness.modifyFile( 'src/main.ts', (content) => content + 'console.log("abcd1234");', ); }, () => { fail('Expected files to not be watched.'); }, ]) .catch((error) => { // Timeout is expected if watching is disabled if (error instanceof TimeoutError) { return; } throw error; }); }); it('watches for file changes when not present', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, watch: undefined, }); await harness.executeWithCases([ async ({ result }) => { // Initial build should succeed expect(result?.success).toBe(true); // Modify a file to trigger file watcher await harness.modifyFile( 'src/main.ts', (content) => content + 'console.log("abcd1234");', ); }, async ({ result }) => { // Modifying a file should trigger a successful rebuild expect(result?.success).toBe(true); }, ]); }); it('watches for file changes when true', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, watch: true, }); await harness.executeWithCases([ async ({ result }) => { // Initial build should succeed expect(result?.success).toBe(true); // Modify a file to trigger file watcher await harness.modifyFile( 'src/main.ts', (content) => content + 'console.log("abcd1234");', ); }, async ({ result }) => { // Modifying a file should trigger a successful rebuild expect(result?.success).toBe(true); }, ]); }); }); });
{ "end_byte": 2861, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/tests/options/watch_spec.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/tests/options/headers_spec.ts_0_1981
/** * @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 { executeDevServer } from '../../index'; import { executeOnceAndFetch } from '../execute-fetch'; import { describeServeBuilder } from '../jasmine-helpers'; import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup'; describeServeBuilder(executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget) => { describe('option: "headers"', () => { beforeEach(async () => { setupTarget(harness, { styles: ['src/styles.css'], }); // Application code is not needed for these tests await harness.writeFile('src/main.ts', ''); await harness.writeFile('src/styles.css', ''); }); it('index response headers should include configured header', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, headers: { 'x-custom': 'foo', }, }); const { result, response } = await executeOnceAndFetch(harness, '/'); expect(result?.success).toBeTrue(); expect(await response?.headers.get('x-custom')).toBe('foo'); }); it('media resource response headers should include configured header', async () => { await harness.writeFiles({ 'src/styles.css': `h1 { background: url('./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>`, }); harness.useTarget('serve', { ...BASE_OPTIONS, headers: { 'x-custom': 'foo', }, }); const { result, response } = await executeOnceAndFetch(harness, '/media/test.svg'); expect(result?.success).toBeTrue(); expect(await response?.headers.get('x-custom')).toBe('foo'); }); }); });
{ "end_byte": 1981, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/tests/options/headers_spec.ts" }
angular-cli/packages/angular/build/src/builders/dev-server/tests/options/serve-path_spec.ts_0_4053
/** * @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 { URL } from 'url'; import { executeDevServer } from '../../index'; import { executeOnceAndFetch } from '../execute-fetch'; import { describeServeBuilder } from '../jasmine-helpers'; import { BASE_OPTIONS, DEV_SERVER_BUILDER_INFO } from '../setup'; describeServeBuilder( executeDevServer, DEV_SERVER_BUILDER_INFO, (harness, setupTarget, isViteRun) => { describe('option: "servePath"', () => { beforeEach(async () => { setupTarget(harness, { assets: ['src/assets'], }); // Application code is not needed for these tests await harness.writeFile('src/main.ts', 'console.log("foo");'); }); it('serves application at the root when option is not present', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, }); const { result, response } = await executeOnceAndFetch(harness, '/main.js'); expect(result?.success).toBeTrue(); const baseUrl = new URL(`${result?.baseUrl}`); expect(baseUrl.pathname).toBe('/'); expect(await response?.text()).toContain('console.log'); }); it('serves application at specified path when option is used', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, servePath: 'test', }); const { result, response } = await executeOnceAndFetch(harness, '/test/main.js'); expect(result?.success).toBeTrue(); const baseUrl = new URL(`${result?.baseUrl}/`); expect(baseUrl.pathname).toBe('/test/'); expect(await response?.text()).toContain('console.log'); }); // TODO(fix-vite): currently this is broken in vite. (isViteRun ? xit : it)('does not rewrite from root when option is used', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, servePath: 'test', }); const { result, response } = await executeOnceAndFetch(harness, '/', { // fallback processing requires an accept header request: { headers: { accept: 'text/html' } }, }); expect(result?.success).toBeTrue(); expect(response?.status).toBe(404); }); it('does not rewrite from path outside serve path when option is used', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, servePath: 'test', }); const { result, response } = await executeOnceAndFetch(harness, '/api/', { // fallback processing requires an accept header request: { headers: { accept: 'text/html' } }, }); expect(result?.success).toBeTrue(); expect(response?.status).toBe(404); }); it('rewrites from path inside serve path when option is used', async () => { harness.useTarget('serve', { ...BASE_OPTIONS, servePath: 'test', }); const { result, response } = await executeOnceAndFetch(harness, '/test/inside', { // fallback processing requires an accept header request: { headers: { accept: 'text/html' } }, }); expect(result?.success).toBeTrue(); expect(await response?.text()).toContain('<title>'); }); it('serves assets at specified path when option is used', async () => { await harness.writeFile('src/assets/test.txt', 'hello world!'); harness.useTarget('serve', { ...BASE_OPTIONS, servePath: 'test', }); const { result, response } = await executeOnceAndFetch(harness, '/test/assets/test.txt', { // fallback processing requires an accept header request: { headers: { accept: 'text/html' } }, }); expect(result?.success).toBeTrue(); expect(await response?.text()).toContain('hello world'); }); }); }, );
{ "end_byte": 4053, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/dev-server/tests/options/serve-path_spec.ts" }
angular-cli/packages/angular/build/src/builders/extract-i18n/builder.ts_0_6002
/** * @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 { Diagnostics } from '@angular/localize/tools'; import type { BuilderContext, BuilderOutput } from '@angular-devkit/architect'; import fs from 'node:fs'; import path from 'node:path'; import { loadEsmModule } from '../../utils/load-esm'; import { assertCompatibleAngularVersion } from '../../utils/version'; import type { ApplicationBuilderExtensions } from '../application/options'; 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, extensions?: ApplicationBuilderExtensions, ): 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 const { extractMessages } = await import('./application-extraction'); const extractionResult = await extractMessages( normalizedOptions, builderName, context, localizeToolsModule.MessageExtractor, extensions, ); if (!extractionResult.success) { return { success: false }; } // 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": 6002, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/extract-i18n/builder.ts" }
angular-cli/packages/angular/build/src/builders/extract-i18n/application-extraction.ts_0_5440
/** * @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 type { MessageExtractor } from '@angular/localize/tools'; import type { BuilderContext } from '@angular-devkit/architect'; import { readFileSync } from 'node:fs'; import nodePath from 'node:path'; import { buildApplicationInternal } from '../application'; import type { ApplicationBuilderExtensions, ApplicationBuilderInternalOptions, } from '../application/options'; import { ResultFile, ResultKind } from '../application/results'; import { OutputMode } from '../application/schema'; import type { NormalizedExtractI18nOptions } from './options'; export async function extractMessages( options: NormalizedExtractI18nOptions, builderName: string, context: BuilderContext, extractorConstructor: typeof MessageExtractor, extensions?: ApplicationBuilderExtensions, ): Promise<{ success: boolean; basePath: string; messages: LocalizeMessage[]; useLegacyIds: boolean; }> { const messages: LocalizeMessage[] = []; // Setup the build options for the application based on the buildTarget option const buildOptions = (await context.validateOptions( await context.getTargetOptions(options.buildTarget), builderName, )) as unknown as ApplicationBuilderInternalOptions; buildOptions.optimization = false; buildOptions.sourceMap = { scripts: true, vendor: true, styles: false }; buildOptions.localize = false; buildOptions.budgets = undefined; buildOptions.index = false; buildOptions.serviceWorker = false; buildOptions.outputMode = OutputMode.Static; buildOptions.server = undefined; // Build the application with the build options const builderResult = await first(buildApplicationInternal(buildOptions, context, extensions)); 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": 5440, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/extract-i18n/application-extraction.ts" }
angular-cli/packages/angular/build/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/build/src/builders/extract-i18n/index.ts" }
angular-cli/packages/angular/build/src/builders/extract-i18n/options.ts_0_2836
/** * @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, targetFromTargetString } from '@angular-devkit/architect'; import { fail } from 'node:assert'; import path from 'node:path'; import { createI18nOptions } from '../../utils/i18n-options'; 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": 2836, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/extract-i18n/options.ts" }
angular-cli/packages/angular/build/src/builders/application/build-action.ts_0_7560
/** * @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 { existsSync } from 'node:fs'; import path from 'node:path'; import { BuildOutputFileType } from '../../tools/esbuild/bundler-context'; import { ExecutionResult, RebuildState } from '../../tools/esbuild/bundler-execution-result'; import { shutdownSassWorkerPool } from '../../tools/esbuild/stylesheets/sass-language'; import { logMessages, withNoProgress, withSpinner } from '../../tools/esbuild/utils'; import { shouldWatchRoot } from '../../utils/environment-options'; import { NormalizedCachedOptions } from '../../utils/normalize-cache'; import { NormalizedApplicationBuildOptions, NormalizedOutputOptions } from './options'; import { FullResult, Result, ResultKind, ResultMessage } from './results'; // Watch workspace for package manager changes const packageWatchFiles = [ // manifest can affect module resolution 'package.json', // npm lock file 'package-lock.json', // pnpm lock file 'pnpm-lock.yaml', // yarn lock file including Yarn PnP manifest files (https://yarnpkg.com/advanced/pnp-spec/) 'yarn.lock', '.pnp.cjs', '.pnp.data.json', ]; export async function* runEsBuildBuildAction( action: (rebuildState?: RebuildState) => Promise<ExecutionResult>, options: { workspaceRoot: string; projectRoot: string; outputOptions: NormalizedOutputOptions; logger: BuilderContext['logger']; cacheOptions: NormalizedCachedOptions; watch?: boolean; verbose?: boolean; progress?: boolean; poll?: number; signal?: AbortSignal; preserveSymlinks?: boolean; clearScreen?: boolean; colors?: boolean; jsonLogs?: boolean; }, ): AsyncIterable<Result> { const { watch, poll, clearScreen, logger, cacheOptions, outputOptions, verbose, projectRoot, workspaceRoot, progress, preserveSymlinks, colors, jsonLogs, } = options; const withProgress: typeof withSpinner = progress ? withSpinner : withNoProgress; // Initial build let result: ExecutionResult; try { // Perform the build action result = await withProgress('Building...', () => action()); // Log all diagnostic (error/warning/logs) messages await logMessages(logger, result, colors, jsonLogs); } finally { // Ensure Sass workers are shutdown if not watching if (!watch) { shutdownSassWorkerPool(); } } // Setup watcher if watch mode enabled let watcher: import('../../tools/esbuild/watcher').BuildWatcher | undefined; if (watch) { if (progress) { logger.info('Watch mode enabled. Watching for file changes...'); } const ignored: string[] = [ // Ignore the output and cache paths to avoid infinite rebuild cycles outputOptions.base, cacheOptions.basePath, `${workspaceRoot.replace(/\\/g, '/')}/**/.*/**`, ]; // Setup a watcher const { createWatcher } = await import('../../tools/esbuild/watcher'); watcher = createWatcher({ polling: typeof poll === 'number', interval: poll, followSymlinks: preserveSymlinks, ignored, }); // Setup abort support options.signal?.addEventListener('abort', () => void watcher?.close()); // Watch the entire project root if 'NG_BUILD_WATCH_ROOT' environment variable is set if (shouldWatchRoot) { if (!preserveSymlinks) { // Ignore all node modules directories to avoid excessive file watchers. // Package changes are handled below by watching manifest and lock files. // NOTE: this is not enable when preserveSymlinks is true as this would break `npm link` usages. ignored.push('**/node_modules/**'); watcher.add( packageWatchFiles .map((file) => path.join(workspaceRoot, file)) .filter((file) => existsSync(file)), ); } watcher.add(projectRoot); } // Watch locations provided by the initial build result watcher.add(result.watchFiles); } // Output the first build results after setting up the watcher to ensure that any code executed // higher in the iterator call stack will trigger the watcher. This is particularly relevant for // unit tests which execute the builder and modify the file system programmatically. yield await emitOutputResult(result, outputOptions); // Finish if watch mode is not enabled if (!watcher) { return; } // Wait for changes and rebuild as needed const currentWatchFiles = new Set(result.watchFiles); try { for await (const changes of watcher) { if (options.signal?.aborted) { break; } if (clearScreen) { // eslint-disable-next-line no-console console.clear(); } if (verbose) { logger.info(changes.toDebugString()); } // Clear removed files from current watch files changes.removed.forEach((removedPath) => currentWatchFiles.delete(removedPath)); result = await withProgress('Changes detected. Rebuilding...', () => action(result.createRebuildState(changes)), ); // Log all diagnostic (error/warning/logs) messages await logMessages(logger, result, colors, jsonLogs); // Update watched locations provided by the new build result. // Keep watching all previous files if there are any errors; otherwise consider all // files stale until confirmed present in the new result's watch files. const staleWatchFiles = result.errors.length > 0 ? undefined : new Set(currentWatchFiles); for (const watchFile of result.watchFiles) { if (!currentWatchFiles.has(watchFile)) { // Add new watch location watcher.add(watchFile); currentWatchFiles.add(watchFile); } // Present so remove from stale locations staleWatchFiles?.delete(watchFile); } // Remove any stale locations if the build was successful if (staleWatchFiles?.size) { watcher.remove([...staleWatchFiles]); } yield await emitOutputResult(result, outputOptions); } } finally { // Stop the watcher and cleanup incremental rebuild state await Promise.allSettled([watcher.close(), result.dispose()]); shutdownSassWorkerPool(); } } async function emitOutputResult( { outputFiles, assetFiles, errors, warnings, externalMetadata, htmlIndexPath, htmlBaseHref, }: ExecutionResult, outputOptions: NormalizedApplicationBuildOptions['outputOptions'], ): Promise<Result> { if (errors.length > 0) { return { kind: ResultKind.Failure, errors: errors as ResultMessage[], warnings: warnings as ResultMessage[], detail: { outputOptions, }, }; } const result: FullResult = { kind: ResultKind.Full, warnings: warnings as ResultMessage[], files: {}, detail: { externalMetadata, htmlIndexPath, htmlBaseHref, outputOptions, }, }; for (const file of assetFiles) { result.files[file.destination] = { type: BuildOutputFileType.Browser, inputPath: file.source, origin: 'disk', }; } for (const file of outputFiles) { result.files[file.path] = { type: file.type, contents: file.contents, origin: 'memory', hash: file.hash, }; } return result; }
{ "end_byte": 7560, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/build-action.ts" }
angular-cli/packages/angular/build/src/builders/application/setup-bundling.ts_0_5668
/** * @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 { ComponentStylesheetBundler } from '../../tools/esbuild/angular/component-stylesheets'; import { SourceFileCache } from '../../tools/esbuild/angular/source-file-cache'; import { createBrowserCodeBundleOptions, createBrowserPolyfillBundleOptions, createServerMainCodeBundleOptions, createServerPolyfillBundleOptions, createSsrEntryCodeBundleOptions, } from '../../tools/esbuild/application-code-bundle'; import { BundlerContext } from '../../tools/esbuild/bundler-context'; import { createGlobalScriptsBundleOptions } from '../../tools/esbuild/global-scripts'; import { createGlobalStylesBundleOptions } from '../../tools/esbuild/global-styles'; import { getSupportedNodeTargets } from '../../tools/esbuild/utils'; import { NormalizedApplicationBuildOptions } from './options'; /** * Generates one or more BundlerContext instances based on the builder provided * configuration. * @param options The normalized application builder options to use. * @param browsers An string array of browserslist browsers to support. * @param codeBundleCache An instance of the TypeScript source file cache. * @returns An array of BundlerContext objects. */ export function setupBundlerContexts( options: NormalizedApplicationBuildOptions, target: string[], codeBundleCache: SourceFileCache, stylesheetBundler: ComponentStylesheetBundler, ): BundlerContext[] { const { outputMode, serverEntryPoint, appShellOptions, prerenderOptions, ssrOptions, workspaceRoot, watch = false, } = options; const bundlerContexts = []; // Browser application code bundlerContexts.push( new BundlerContext( workspaceRoot, watch, createBrowserCodeBundleOptions(options, target, codeBundleCache, stylesheetBundler), ), ); // Browser polyfills code const browserPolyfillBundleOptions = createBrowserPolyfillBundleOptions( options, target, codeBundleCache, stylesheetBundler, ); if (browserPolyfillBundleOptions) { bundlerContexts.push(new BundlerContext(workspaceRoot, watch, browserPolyfillBundleOptions)); } // Global Stylesheets if (options.globalStyles.length > 0) { for (const initial of [true, false]) { const bundleOptions = createGlobalStylesBundleOptions(options, target, initial); if (bundleOptions) { bundlerContexts.push( new BundlerContext(workspaceRoot, watch, bundleOptions, () => initial), ); } } } // Global Scripts if (options.globalScripts.length > 0) { for (const initial of [true, false]) { const bundleOptions = createGlobalScriptsBundleOptions(options, target, initial); if (bundleOptions) { bundlerContexts.push( new BundlerContext(workspaceRoot, watch, bundleOptions, () => initial), ); } } } // Skip server build when none of the features are enabled. if (serverEntryPoint && (outputMode || prerenderOptions || appShellOptions || ssrOptions)) { const nodeTargets = [...target, ...getSupportedNodeTargets()]; bundlerContexts.push( new BundlerContext( workspaceRoot, watch, createServerMainCodeBundleOptions(options, nodeTargets, codeBundleCache, stylesheetBundler), ), ); if (outputMode && ssrOptions?.entry) { // New behavior introduced: 'server.ts' is now bundled separately from 'main.server.ts'. bundlerContexts.push( new BundlerContext( workspaceRoot, watch, createSsrEntryCodeBundleOptions(options, nodeTargets, codeBundleCache, stylesheetBundler), ), ); } // Server polyfills code const serverPolyfillBundleOptions = createServerPolyfillBundleOptions( options, nodeTargets, codeBundleCache, ); if (serverPolyfillBundleOptions) { bundlerContexts.push(new BundlerContext(workspaceRoot, watch, serverPolyfillBundleOptions)); } } return bundlerContexts; } export function createComponentStyleBundler( options: NormalizedApplicationBuildOptions, target: string[], ): ComponentStylesheetBundler { const { workspaceRoot, optimizationOptions, sourcemapOptions, outputNames, externalDependencies, preserveSymlinks, stylePreprocessorOptions, inlineStyleLanguage, cacheOptions, tailwindConfiguration, postcssConfiguration, publicPath, } = options; const incremental = !!options.watch; return new ComponentStylesheetBundler( { workspaceRoot, inlineFonts: !!optimizationOptions.fonts.inline, optimization: !!optimizationOptions.styles.minify, sourcemap: // Hidden component stylesheet sourcemaps are inaccessible which is effectively // the same as being disabled. Disabling has the advantage of avoiding the overhead // of sourcemap processing. sourcemapOptions.styles && !sourcemapOptions.hidden ? 'linked' : false, outputNames, includePaths: stylePreprocessorOptions?.includePaths, // string[] | undefined' is not assignable to type '(Version | DeprecationOrId)[] | undefined'. // eslint-disable-next-line @typescript-eslint/no-explicit-any sass: stylePreprocessorOptions?.sass as any, externalDependencies, target, preserveSymlinks, tailwindConfiguration, postcssConfiguration, cacheOptions, publicPath, }, inlineStyleLanguage, incremental, ); }
{ "end_byte": 5668, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/setup-bundling.ts" }
angular-cli/packages/angular/build/src/builders/application/chunk-optimizer.ts_0_5650
/** * @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 assert from 'node:assert'; import { rollup } from 'rollup'; import { BuildOutputFile, BuildOutputFileType, BundleContextResult, InitialFileRecord, } from '../../tools/esbuild/bundler-context'; import { createOutputFile } from '../../tools/esbuild/utils'; import { assertIsError } from '../../utils/error'; export async function optimizeChunks( original: BundleContextResult, sourcemap: boolean | 'hidden', ): Promise<BundleContextResult> { // Failed builds cannot be optimized if (original.errors) { return original; } // Find the main browser entrypoint let mainFile; for (const [file, record] of original.initialFiles) { if ( record.name === 'main' && record.entrypoint && !record.serverFile && record.type === 'script' ) { mainFile = file; break; } } // No action required if no browser main entrypoint if (!mainFile) { return original; } const chunks: Record<string, BuildOutputFile> = {}; const maps: Record<string, BuildOutputFile> = {}; for (const originalFile of original.outputFiles) { if (originalFile.type !== BuildOutputFileType.Browser) { continue; } if (originalFile.path.endsWith('.js')) { chunks[originalFile.path] = originalFile; } else if (originalFile.path.endsWith('.js.map')) { // Create mapping of JS file to sourcemap content maps[originalFile.path.slice(0, -4)] = originalFile; } } const usedChunks = new Set<string>(); let bundle; let optimizedOutput; try { bundle = await rollup({ input: mainFile, plugins: [ { name: 'angular-bundle', resolveId(source) { // Remove leading `./` if present const file = source[0] === '.' && source[1] === '/' ? source.slice(2) : source; if (chunks[file]) { return file; } // All other identifiers are considered external to maintain behavior return { id: source, external: true }; }, load(id) { assert( chunks[id], `Angular chunk content should always be present in chunk optimizer [${id}].`, ); usedChunks.add(id); const result = { code: chunks[id].text, map: maps[id]?.text, }; return result; }, }, ], }); const result = await bundle.generate({ compact: true, sourcemap, chunkFileNames: (chunkInfo) => `${chunkInfo.name.replace(/-[a-zA-Z0-9]{8}$/, '')}-[hash].js`, }); optimizedOutput = result.output; } catch (e) { assertIsError(e); return { errors: [ // Most of these fields are not actually needed for printing the error { id: '', text: 'Chunk optimization failed', detail: undefined, pluginName: '', location: null, notes: [ { text: e.message, location: null, }, ], }, ], warnings: original.warnings, }; } finally { await bundle?.close(); } // Remove used chunks and associated sourcemaps from the original result original.outputFiles = original.outputFiles.filter( (file) => !usedChunks.has(file.path) && !(file.path.endsWith('.map') && usedChunks.has(file.path.slice(0, -4))), ); // Add new optimized chunks const importsPerFile: Record<string, string[]> = {}; for (const optimizedFile of optimizedOutput) { if (optimizedFile.type !== 'chunk') { continue; } importsPerFile[optimizedFile.fileName] = optimizedFile.imports; original.outputFiles.push( createOutputFile(optimizedFile.fileName, optimizedFile.code, BuildOutputFileType.Browser), ); if (optimizedFile.map && optimizedFile.sourcemapFileName) { original.outputFiles.push( createOutputFile( optimizedFile.sourcemapFileName, optimizedFile.map.toString(), BuildOutputFileType.Browser, ), ); } } // Update initial files to reflect optimized chunks const entriesToAnalyze: [string, InitialFileRecord][] = []; for (const usedFile of usedChunks) { // Leave the main file since its information did not change if (usedFile === mainFile) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion entriesToAnalyze.push([mainFile, original.initialFiles.get(mainFile)!]); continue; } // Remove all other used chunks original.initialFiles.delete(usedFile); } // Analyze for transitive initial files let currentEntry; while ((currentEntry = entriesToAnalyze.pop())) { const [entryPath, entryRecord] = currentEntry; for (const importPath of importsPerFile[entryPath]) { const existingRecord = original.initialFiles.get(importPath); if (existingRecord) { // Store the smallest value depth if (existingRecord.depth > entryRecord.depth + 1) { existingRecord.depth = entryRecord.depth + 1; } continue; } const record: InitialFileRecord = { type: 'script', entrypoint: false, external: false, serverFile: false, depth: entryRecord.depth + 1, }; entriesToAnalyze.push([importPath, record]); } } return original; }
{ "end_byte": 5650, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/chunk-optimizer.ts" }
angular-cli/packages/angular/build/src/builders/application/i18n.ts_0_5688
/** * @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 { join } from 'node:path'; import { BuildOutputFileType, InitialFileRecord } from '../../tools/esbuild/bundler-context'; import { ExecutionResult, PrerenderedRoutesRecord, } from '../../tools/esbuild/bundler-execution-result'; import { I18nInliner } from '../../tools/esbuild/i18n-inliner'; import { maxWorkers } from '../../utils/environment-options'; import { loadTranslations } from '../../utils/i18n-options'; import { createTranslationLoader } from '../../utils/load-translations'; import { executePostBundleSteps } from './execute-post-bundle'; import { NormalizedApplicationBuildOptions, getLocaleBaseHref } from './options'; /** * Inlines all active locales as specified by the application build options into all * application JavaScript files created during the build. * @param options The normalized application builder options used to create the build. * @param executionResult The result of an executed build. * @param initialFiles A map containing initial file information for the executed build. */ export async function inlineI18n( options: NormalizedApplicationBuildOptions, executionResult: ExecutionResult, initialFiles: Map<string, InitialFileRecord>, ): Promise<{ errors: string[]; warnings: string[]; prerenderedRoutes: PrerenderedRoutesRecord; }> { // Create the multi-threaded inliner with common options and the files generated from the build. const inliner = new I18nInliner( { missingTranslation: options.i18nOptions.missingTranslationBehavior ?? 'warning', outputFiles: executionResult.outputFiles, shouldOptimize: options.optimizationOptions.scripts, }, maxWorkers, ); const inlineResult: { errors: string[]; warnings: string[]; prerenderedRoutes: PrerenderedRoutesRecord; } = { errors: [], warnings: [], prerenderedRoutes: {}, }; // For each active locale, use the inliner to process the output files of the build. const updatedOutputFiles = []; const updatedAssetFiles = []; try { for (const locale of options.i18nOptions.inlineLocales) { // A locale specific set of files is returned from the inliner. const localeInlineResult = await inliner.inlineForLocale( locale, options.i18nOptions.locales[locale].translation, ); const localeOutputFiles = localeInlineResult.outputFiles; inlineResult.errors.push(...localeInlineResult.errors); inlineResult.warnings.push(...localeInlineResult.warnings); const baseHref = getLocaleBaseHref(options.baseHref, options.i18nOptions, locale) ?? options.baseHref; const { errors, warnings, additionalAssets, additionalOutputFiles, prerenderedRoutes: generatedRoutes, } = await executePostBundleSteps( { ...options, baseHref, }, localeOutputFiles, executionResult.assetFiles, initialFiles, locale, ); localeOutputFiles.push(...additionalOutputFiles); inlineResult.errors.push(...errors); inlineResult.warnings.push(...warnings); // Update directory with locale base if (options.i18nOptions.flatOutput !== true) { localeOutputFiles.forEach((file) => { file.path = join(locale, file.path); }); for (const assetFile of [...executionResult.assetFiles, ...additionalAssets]) { updatedAssetFiles.push({ source: assetFile.source, destination: join(locale, assetFile.destination), }); } } else { executionResult.assetFiles.push(...additionalAssets); } inlineResult.prerenderedRoutes = { ...inlineResult.prerenderedRoutes, ...generatedRoutes }; updatedOutputFiles.push(...localeOutputFiles); } } finally { await inliner.close(); } // Update the result with all localized files. executionResult.outputFiles = [ // Root and SSR entry files are not modified. ...executionResult.outputFiles.filter( ({ type }) => type === BuildOutputFileType.Root || type === BuildOutputFileType.ServerRoot, ), // Updated files for each locale. ...updatedOutputFiles, ]; // Assets are only changed if not using the flat output option if (options.i18nOptions.flatOutput !== true) { executionResult.assetFiles = updatedAssetFiles; } return inlineResult; } /** * Loads all active translations using the translation loaders from the `@angular/localize` package. * @param context The architect builder context for the current build. * @param i18n The normalized i18n options to use. */ export async function loadActiveTranslations( context: BuilderContext, i18n: NormalizedApplicationBuildOptions['i18nOptions'], ) { // Load locale data and translations (if present) let loader; for (const [locale, desc] of Object.entries(i18n.locales)) { if (!i18n.inlineLocales.has(locale) && locale !== i18n.sourceLocale) { continue; } if (!desc.files.length) { continue; } loader ??= await createTranslationLoader(); loadTranslations( locale, desc, context.workspaceRoot, loader, { warn(message) { context.logger.warn(message); }, error(message) { throw new Error(message); }, }, undefined, i18n.duplicateTranslationBehavior, ); } }
{ "end_byte": 5688, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/i18n.ts" }
angular-cli/packages/angular/build/src/builders/application/execute-post-bundle.ts_0_8125
/** * @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 assert from 'node:assert'; import { BuildOutputFile, BuildOutputFileType, InitialFileRecord, } from '../../tools/esbuild/bundler-context'; import { BuildOutputAsset, PrerenderedRoutesRecord, } from '../../tools/esbuild/bundler-execution-result'; import { generateIndexHtml } from '../../tools/esbuild/index-html-generator'; import { createOutputFile } from '../../tools/esbuild/utils'; import { maxWorkers } from '../../utils/environment-options'; import { SERVER_APP_MANIFEST_FILENAME, generateAngularServerAppManifest, } from '../../utils/server-rendering/manifest'; import { RouteRenderMode, WritableSerializableRouteTreeNode, } from '../../utils/server-rendering/models'; import { prerenderPages } from '../../utils/server-rendering/prerender'; import { augmentAppWithServiceWorkerEsbuild } from '../../utils/service-worker'; import { INDEX_HTML_CSR, INDEX_HTML_SERVER, NormalizedApplicationBuildOptions } from './options'; import { OutputMode } from './schema'; /** * Run additional builds steps including SSG, AppShell, Index HTML file and Service worker generation. * @param options The normalized application builder options used to create the build. * @param outputFiles The output files of an executed build. * @param assetFiles The assets of an executed build. * @param initialFiles A map containing initial file information for the executed build. * @param locale A language locale to insert in the index.html. */ export async function executePostBundleSteps( options: NormalizedApplicationBuildOptions, outputFiles: BuildOutputFile[], assetFiles: BuildOutputAsset[], initialFiles: Map<string, InitialFileRecord>, locale: string | undefined, ): Promise<{ errors: string[]; warnings: string[]; additionalOutputFiles: BuildOutputFile[]; additionalAssets: BuildOutputAsset[]; prerenderedRoutes: PrerenderedRoutesRecord; }> { const additionalAssets: BuildOutputAsset[] = []; const additionalOutputFiles: BuildOutputFile[] = []; const allErrors: string[] = []; const allWarnings: string[] = []; const prerenderedRoutes: PrerenderedRoutesRecord = {}; const { baseHref = '/', serviceWorker, indexHtmlOptions, optimizationOptions, sourcemapOptions, outputMode, serverEntryPoint, prerenderOptions, appShellOptions, workspaceRoot, partialSSRBuild, } = options; // Index HTML content without CSS inlining to be used for server rendering (AppShell, SSG and SSR). // NOTE: Critical CSS inlining is deliberately omitted here, as it will be handled during server rendering. // Additionally, when using prerendering or AppShell, the index HTML file may be regenerated. // To prevent generating duplicate files with the same filename, a `Map` is used to store and manage the files. const additionalHtmlOutputFiles = new Map<string, BuildOutputFile>(); // Generate index HTML file // If localization is enabled, index generation is handled in the inlining process. if (indexHtmlOptions) { const { csrContent, ssrContent, errors, warnings } = await generateIndexHtml( initialFiles, outputFiles, options, locale, ); allErrors.push(...errors); allWarnings.push(...warnings); additionalHtmlOutputFiles.set( indexHtmlOptions.output, createOutputFile(indexHtmlOptions.output, csrContent, BuildOutputFileType.Browser), ); if (ssrContent) { additionalHtmlOutputFiles.set( INDEX_HTML_SERVER, createOutputFile(INDEX_HTML_SERVER, ssrContent, BuildOutputFileType.ServerApplication), ); } } // Create server manifest if (serverEntryPoint) { additionalOutputFiles.push( createOutputFile( SERVER_APP_MANIFEST_FILENAME, generateAngularServerAppManifest( additionalHtmlOutputFiles, outputFiles, optimizationOptions.styles.inlineCritical ?? false, undefined, locale, ), BuildOutputFileType.ServerApplication, ), ); } // Pre-render (SSG) and App-shell // If localization is enabled, prerendering is handled in the inlining process. if ( !partialSSRBuild && (prerenderOptions || appShellOptions || (outputMode && serverEntryPoint)) && !allErrors.length ) { assert( indexHtmlOptions, 'The "index" option is required when using the "ssg" or "appShell" options.', ); const { output, warnings, errors, serializableRouteTreeNode } = await prerenderPages( workspaceRoot, baseHref, appShellOptions, prerenderOptions, [...outputFiles, ...additionalOutputFiles], assetFiles, outputMode, sourcemapOptions.scripts, maxWorkers, ); allErrors.push(...errors); allWarnings.push(...warnings); const indexHasBeenPrerendered = output[indexHtmlOptions.output]; for (const [path, { content, appShellRoute }] of Object.entries(output)) { // Update the index contents with the app shell under these conditions: // - Replace 'index.html' with the app shell only if it hasn't been prerendered yet. // - Always replace 'index.csr.html' with the app shell. let filePath = path; if (appShellRoute && !indexHasBeenPrerendered) { if (outputMode !== OutputMode.Server && indexHtmlOptions.output === INDEX_HTML_CSR) { filePath = 'index.html'; } else { filePath = indexHtmlOptions.output; } } additionalHtmlOutputFiles.set( filePath, createOutputFile(filePath, content, BuildOutputFileType.Browser), ); } const serializableRouteTreeNodeForManifest: WritableSerializableRouteTreeNode = []; for (const metadata of serializableRouteTreeNode) { switch (metadata.renderMode) { case RouteRenderMode.Prerender: case /* Legacy building mode */ undefined: { if (!metadata.redirectTo || outputMode === OutputMode.Static) { prerenderedRoutes[metadata.route] = { headers: metadata.headers }; } break; } case RouteRenderMode.Server: case RouteRenderMode.Client: serializableRouteTreeNodeForManifest.push(metadata); break; } } if (outputMode === OutputMode.Server) { // Regenerate the manifest to append route tree. This is only needed if SSR is enabled. const manifest = additionalOutputFiles.find((f) => f.path === SERVER_APP_MANIFEST_FILENAME); assert(manifest, `${SERVER_APP_MANIFEST_FILENAME} was not found in output files.`); manifest.contents = new TextEncoder().encode( generateAngularServerAppManifest( additionalHtmlOutputFiles, outputFiles, optimizationOptions.styles.inlineCritical ?? false, serializableRouteTreeNodeForManifest, locale, ), ); } } additionalOutputFiles.push(...additionalHtmlOutputFiles.values()); // Augment the application with service worker support // If localization is enabled, service worker is handled in the inlining process. if (serviceWorker) { try { const serviceWorkerResult = await augmentAppWithServiceWorkerEsbuild( workspaceRoot, serviceWorker, baseHref, options.indexHtmlOptions?.output, // Ensure additional files recently added are used [...outputFiles, ...additionalOutputFiles], assetFiles, ); additionalOutputFiles.push( createOutputFile('ngsw.json', serviceWorkerResult.manifest, BuildOutputFileType.Browser), ); additionalAssets.push(...serviceWorkerResult.assetFiles); } catch (error) { allErrors.push(error instanceof Error ? error.message : `${error}`); } } return { errors: allErrors, warnings: allWarnings, additionalAssets, prerenderedRoutes, additionalOutputFiles, }; }
{ "end_byte": 8125, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/execute-post-bundle.ts" }
angular-cli/packages/angular/build/src/builders/application/results.ts_0_1699
/** * @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 '../../tools/esbuild/bundler-context'; export enum ResultKind { Failure, Full, Incremental, ComponentUpdate, } export type Result = FailureResult | FullResult | IncrementalResult | ComponentUpdateResult; export interface BaseResult { kind: ResultKind; warnings?: ResultMessage[]; duration?: number; detail?: Record<string, unknown>; } export interface FailureResult extends BaseResult { kind: ResultKind.Failure; errors: ResultMessage[]; } export interface FullResult extends BaseResult { kind: ResultKind.Full; files: Record<string, ResultFile>; } export interface IncrementalResult extends BaseResult { kind: ResultKind.Incremental; added: string[]; removed: string[]; modified: string[]; files: Record<string, ResultFile>; } export type ResultFile = DiskFile | MemoryFile; export interface BaseResultFile { origin: 'memory' | 'disk'; type: BuildOutputFileType; } export interface DiskFile extends BaseResultFile { origin: 'disk'; inputPath: string; } export interface MemoryFile extends BaseResultFile { origin: 'memory'; hash: string; contents: Uint8Array; } export interface ResultMessage { text: string; location?: { file: string; line: number; column: number } | null; notes?: { text: string }[]; } export interface ComponentUpdateResult extends BaseResult { kind: ResultKind.ComponentUpdate; updates: { id: string; type: 'style' | 'template'; content: string; }[]; }
{ "end_byte": 1699, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/results.ts" }
angular-cli/packages/angular/build/src/builders/application/index.ts_0_9770
/** * @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, BuilderOutput, createBuilder } from '@angular-devkit/architect'; import type { Plugin } from 'esbuild'; import assert from 'node:assert'; import fs from 'node:fs/promises'; import path from 'node:path'; import { BuildOutputFile, BuildOutputFileType } from '../../tools/esbuild/bundler-context'; import { createJsonBuildManifest, emitFilesToDisk } from '../../tools/esbuild/utils'; import { colors as ansiColors } from '../../utils/color'; import { deleteOutputDir } from '../../utils/delete-output-dir'; import { useJSONBuildLogs } from '../../utils/environment-options'; import { purgeStaleBuildCache } from '../../utils/purge-cache'; import { assertCompatibleAngularVersion } from '../../utils/version'; import { runEsBuildBuildAction } from './build-action'; import { executeBuild } from './execute-build'; import { ApplicationBuilderExtensions, ApplicationBuilderInternalOptions, NormalizedOutputOptions, normalizeOptions, } from './options'; import { Result, ResultKind } from './results'; import { Schema as ApplicationBuilderOptions } from './schema'; export type { ApplicationBuilderOptions }; export async function* buildApplicationInternal( options: ApplicationBuilderInternalOptions, // TODO: Integrate abort signal support into builder system context: BuilderContext & { signal?: AbortSignal }, extensions?: ApplicationBuilderExtensions, ): AsyncIterable<Result> { const { workspaceRoot, logger, target } = context; // Check Angular version. assertCompatibleAngularVersion(workspaceRoot); // Purge old build disk cache. await purgeStaleBuildCache(context); // Determine project name from builder context target const projectName = target?.project; if (!projectName) { context.logger.error(`The 'application' builder requires a target to be specified.`); // Only the vite-based dev server current uses the errors value yield { kind: ResultKind.Failure, errors: [] }; return; } const normalizedOptions = await normalizeOptions(context, projectName, options, extensions); if (!normalizedOptions.outputOptions.ignoreServer) { const { browser, server } = normalizedOptions.outputOptions; if (browser === '') { context.logger.error( `'outputPath.browser' cannot be configured to an empty string when SSR is enabled.`, ); yield { kind: ResultKind.Failure, errors: [] }; return; } if (browser === server) { context.logger.error( `'outputPath.browser' and 'outputPath.server' cannot be configured to the same value.`, ); yield { kind: ResultKind.Failure, errors: [] }; return; } } // Setup an abort controller with a builder teardown if no signal is present let signal = context.signal; if (!signal) { const controller = new AbortController(); signal = controller.signal; context.addTeardown(() => controller.abort('builder-teardown')); } yield* runEsBuildBuildAction( async (rebuildState) => { const { serverEntryPoint, jsonLogs, partialSSRBuild } = normalizedOptions; const startTime = process.hrtime.bigint(); const result = await executeBuild(normalizedOptions, context, rebuildState); if (jsonLogs) { result.addLog(await createJsonBuildManifest(result, normalizedOptions)); } else { if (serverEntryPoint && !partialSSRBuild) { const prerenderedRoutesLength = Object.keys(result.prerenderedRoutes).length; let prerenderMsg = `Prerendered ${prerenderedRoutesLength} static route`; prerenderMsg += prerenderedRoutesLength !== 1 ? 's.' : '.'; result.addLog(ansiColors.magenta(prerenderMsg)); } const buildTime = Number(process.hrtime.bigint() - startTime) / 10 ** 9; const hasError = result.errors.length > 0; result.addLog( `Application bundle generation ${hasError ? 'failed' : 'complete'}. [${buildTime.toFixed(3)} seconds]\n`, ); } return result; }, { watch: normalizedOptions.watch, preserveSymlinks: normalizedOptions.preserveSymlinks, poll: normalizedOptions.poll, cacheOptions: normalizedOptions.cacheOptions, outputOptions: normalizedOptions.outputOptions, verbose: normalizedOptions.verbose, projectRoot: normalizedOptions.projectRoot, workspaceRoot: normalizedOptions.workspaceRoot, progress: normalizedOptions.progress, clearScreen: normalizedOptions.clearScreen, colors: normalizedOptions.colors, jsonLogs: normalizedOptions.jsonLogs, logger, signal, }, ); } export interface ApplicationBuilderOutput extends BuilderOutput { outputFiles?: BuildOutputFile[]; assetFiles?: { source: string; destination: string }[]; } /** * Builds an application using the `application` builder with the provided * options. * * Usage of the `plugins` parameter is NOT supported and may cause unexpected * build output or build failures. * * @experimental Direct usage of this function is considered experimental. * * @param options The options defined by the builder's schema to use. * @param context An Architect builder context instance. * @param plugins An array of plugins to apply to the main code bundling. * @returns The build output results of the build. */ export function buildApplication( options: ApplicationBuilderOptions, context: BuilderContext, plugins?: Plugin[], ): AsyncIterable<ApplicationBuilderOutput>; /** * Builds an application using the `application` builder with the provided * options. * * Usage of the `extensions` parameter is NOT supported and may cause unexpected * build output or build failures. * * @experimental Direct usage of this function is considered experimental. * * @param options The options defined by the builder's schema to use. * @param context An Architect builder context instance. * @param extensions An object contain extension points for the build. * @returns The build output results of the build. */ export function buildApplication( options: ApplicationBuilderOptions, context: BuilderContext, extensions?: ApplicationBuilderExtensions, ): AsyncIterable<ApplicationBuilderOutput>; export async function* buildApplication( options: ApplicationBuilderOptions, context: BuilderContext, pluginsOrExtensions?: Plugin[] | ApplicationBuilderExtensions, ): AsyncIterable<ApplicationBuilderOutput> { let extensions: ApplicationBuilderExtensions | undefined; if (pluginsOrExtensions && Array.isArray(pluginsOrExtensions)) { extensions = { codePlugins: pluginsOrExtensions, }; } else { extensions = pluginsOrExtensions; } let initial = true; for await (const result of buildApplicationInternal(options, context, extensions)) { const outputOptions = result.detail?.['outputOptions'] as NormalizedOutputOptions | undefined; if (initial) { initial = false; // Clean the output location if requested. // Output options may not be present if the build failed. if (outputOptions?.clean) { await deleteOutputDir(context.workspaceRoot, outputOptions.base, [ outputOptions.browser, outputOptions.server, ]); } } if (result.kind === ResultKind.Failure) { yield { success: false }; continue; } assert(outputOptions, 'Application output options are required for builder usage.'); assert(result.kind === ResultKind.Full, 'Application build did not provide a full output.'); // TODO: Restructure output logging to better handle stdout JSON piping if (!useJSONBuildLogs) { context.logger.info(`Output location: ${outputOptions.base}\n`); } // Writes the output files to disk and ensures the containing directories are present const directoryExists = new Set<string>(); await emitFilesToDisk(Object.entries(result.files), async ([filePath, file]) => { if ( outputOptions.ignoreServer && (file.type === BuildOutputFileType.ServerApplication || file.type === BuildOutputFileType.ServerRoot) ) { return; } let typeDirectory: string; switch (file.type) { case BuildOutputFileType.Browser: case BuildOutputFileType.Media: typeDirectory = outputOptions.browser; break; case BuildOutputFileType.ServerApplication: case BuildOutputFileType.ServerRoot: typeDirectory = outputOptions.server; break; case BuildOutputFileType.Root: typeDirectory = ''; break; default: throw new Error( `Unhandled write for file "${filePath}" with type "${BuildOutputFileType[file.type]}".`, ); } // NOTE: 'base' is a fully resolved path at this point const fullFilePath = path.join(outputOptions.base, typeDirectory, 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); } }); yield { success: true }; } } export default createBuilder(buildApplication);
{ "end_byte": 9770, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/index.ts" }
angular-cli/packages/angular/build/src/builders/application/options.ts_0_4975
/** * @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 { BuilderContext } from '@angular-devkit/architect'; import type { Plugin } from 'esbuild'; import { realpathSync } from 'node:fs'; import { access, constants } from 'node:fs/promises'; import { createRequire } from 'node:module'; import path from 'node:path'; import { normalizeAssetPatterns, normalizeOptimization, normalizeSourceMaps } from '../../utils'; import { supportColor } from '../../utils/color'; import { useJSONBuildLogs, usePartialSsrBuild } from '../../utils/environment-options'; import { I18nOptions, createI18nOptions } from '../../utils/i18n-options'; import { IndexHtmlTransform } from '../../utils/index-file/index-html-generator'; import { normalizeCacheOptions } from '../../utils/normalize-cache'; import { SearchDirectory, findTailwindConfiguration, generateSearchDirectories, loadPostcssConfiguration, } from '../../utils/postcss-configuration'; import { urlJoin } from '../../utils/url'; import { Schema as ApplicationBuilderOptions, ExperimentalPlatform, I18NTranslation, OutputHashing, OutputMode, OutputPathClass, } from './schema'; /** * The filename for the client-side rendered HTML template. * This template is used for client-side rendering (CSR) in a web application. */ export const INDEX_HTML_CSR = 'index.csr.html'; /** * The filename for the server-side rendered HTML template. * This template is used for server-side rendering (SSR) in a web application. */ export const INDEX_HTML_SERVER = 'index.server.html'; export type NormalizedOutputOptions = Required<OutputPathClass> & { clean: boolean; ignoreServer: boolean; }; export type NormalizedApplicationBuildOptions = Awaited<ReturnType<typeof normalizeOptions>>; export interface ApplicationBuilderExtensions { codePlugins?: Plugin[]; indexHtmlTransformer?: IndexHtmlTransform; } /** Internal options hidden from builder schema but available when invoked programmatically. */ interface InternalOptions { /** * Entry points to use for the compilation. Incompatible with `browser`, which must not be provided. May be relative or absolute paths. * If given a relative path, it is resolved relative to the current workspace and will generate an output at the same relative location * in the output directory. If given an absolute path, the output will be generated in the root of the output directory with the same base * name. */ entryPoints?: Set<string>; /** File extension to use for the generated output files. */ outExtension?: 'js' | 'mjs'; /** * Indicates whether all node packages should be marked as external. * Currently used by the dev-server to support prebundling. */ externalPackages?: boolean | { exclude: string[] }; /** * Forces the output from the localize post-processing to not create nested directories per locale output. * This is only used by the development server which currently only supports a single locale per build. */ forceI18nFlatOutput?: boolean; /** * When set to `true`, enables fast SSR in development mode by disabling the full manifest generation and prerendering. * * This option is intended to optimize performance during development by skipping prerendering and route extraction when not required. * @default false */ partialSSRBuild?: boolean; /** * Enables the use of AOT compiler emitted external runtime styles. * External runtime styles use `link` elements instead of embedded style content in the output JavaScript. * This option is only intended to be used with a development server that can process and serve component * styles. */ externalRuntimeStyles?: boolean; /** * Enables instrumentation to collect code coverage data for specific files. * * Used exclusively for tests and shouldn't be used for other kinds of builds. */ instrumentForCoverage?: (filename: string) => boolean; } /** Full set of options for `application` builder. */ export type ApplicationBuilderInternalOptions = Omit< ApplicationBuilderOptions & InternalOptions, 'browser' > & { // `browser` can be `undefined` if `entryPoints` is used. browser?: string; }; /** * 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. * @param plugins An optional array of programmatically supplied build plugins. * @returns An object containing normalized options required to perform the build. */ // eslint-disable-next-line max-lines-per-function
{ "end_byte": 4975, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/options.ts" }
angular-cli/packages/angular/build/src/builders/application/options.ts_4976_13619
export async function normalizeOptions( context: BuilderContext, projectName: string, options: ApplicationBuilderInternalOptions, extensions?: ApplicationBuilderExtensions, ) { // If not explicitly set, default to the Node.js process argument const preserveSymlinks = options.preserveSymlinks ?? process.execArgv.includes('--preserve-symlinks'); // Setup base paths based on workspace root and project information const workspaceRoot = preserveSymlinks ? context.workspaceRoot : // NOTE: promises.realpath should not be used here since it uses realpath.native which // can cause case conversion and other undesirable behavior on Windows systems. // ref: https://github.com/nodejs/node/issues/7726 realpathSync(context.workspaceRoot); const projectMetadata = await context.getProjectMetadata(projectName); const projectRoot = normalizeDirectoryPath( path.join(workspaceRoot, (projectMetadata.root as string | undefined) ?? ''), ); const projectSourceRoot = normalizeDirectoryPath( path.join(workspaceRoot, (projectMetadata.sourceRoot as string | undefined) ?? 'src'), ); // Gather persistent caching option and provide a project specific cache location const cacheOptions = normalizeCacheOptions(projectMetadata, workspaceRoot); cacheOptions.path = path.join(cacheOptions.path, projectName); const i18nOptions: I18nOptions & { duplicateTranslationBehavior?: I18NTranslation; missingTranslationBehavior?: I18NTranslation; } = createI18nOptions(projectMetadata, options.localize); i18nOptions.duplicateTranslationBehavior = options.i18nDuplicateTranslation; i18nOptions.missingTranslationBehavior = options.i18nMissingTranslation; if (options.forceI18nFlatOutput) { i18nOptions.flatOutput = true; } const entryPoints = normalizeEntryPoints(workspaceRoot, options.browser, options.entryPoints); const tsconfig = path.join(workspaceRoot, options.tsConfig); const optimizationOptions = normalizeOptimization(options.optimization); const sourcemapOptions = normalizeSourceMaps(options.sourceMap ?? false); const assets = options.assets?.length ? normalizeAssetPatterns(options.assets, workspaceRoot, projectRoot, projectSourceRoot) : undefined; let fileReplacements: Record<string, string> | undefined; if (options.fileReplacements) { for (const replacement of options.fileReplacements) { const fileReplaceWith = path.join(workspaceRoot, replacement.with); try { await access(fileReplaceWith, constants.F_OK); } catch { throw new Error(`The ${fileReplaceWith} path in file replacements does not exist.`); } fileReplacements ??= {}; fileReplacements[path.join(workspaceRoot, replacement.replace)] = fileReplaceWith; } } let loaderExtensions: Record<string, 'text' | 'binary' | 'file'> | undefined; if (options.loader) { for (const [extension, value] of Object.entries(options.loader)) { if (extension[0] !== '.' || /\.[cm]?[jt]sx?$/.test(extension)) { continue; } if (value !== 'text' && value !== 'binary' && value !== 'file' && value !== 'empty') { continue; } loaderExtensions ??= {}; loaderExtensions[extension] = value; } } // Validate prerender and ssr options when using the outputMode if (options.outputMode === OutputMode.Server) { if (!options.server) { throw new Error('The "server" option is required when "outputMode" is set to "server".'); } if (typeof options.ssr === 'boolean' || !options.ssr?.entry) { throw new Error('The "ssr.entry" option is required when "outputMode" is set to "server".'); } } if (options.outputMode) { if (!options.server) { options.ssr = false; } if (options.prerender !== undefined) { context.logger.warn( 'The "prerender" option is not considered when "outputMode" is specified.', ); } options.prerender = !!options.server; if (options.appShell !== undefined) { context.logger.warn( 'The "appShell" option is not considered when "outputMode" is specified.', ); } } // A configuration file can exist in the project or workspace root const searchDirectories = await generateSearchDirectories([projectRoot, workspaceRoot]); const postcssConfiguration = await loadPostcssConfiguration(searchDirectories); // Skip tailwind configuration if postcss is customized const tailwindConfiguration = postcssConfiguration ? undefined : await getTailwindConfig(searchDirectories, workspaceRoot, context); let serverEntryPoint: string | undefined; if (options.server) { serverEntryPoint = path.join(workspaceRoot, options.server); } else if (options.server === '') { throw new Error('The "server" option cannot be an empty string.'); } let prerenderOptions; if (options.prerender) { const { discoverRoutes = true, routesFile = undefined } = options.prerender === true ? {} : options.prerender; prerenderOptions = { discoverRoutes, routesFile: routesFile && path.join(workspaceRoot, routesFile), }; } let ssrOptions; if (options.ssr === true) { ssrOptions = {}; } else if (typeof options.ssr === 'object') { const { entry, experimentalPlatform = ExperimentalPlatform.Node } = options.ssr; ssrOptions = { entry: entry && path.join(workspaceRoot, entry), platform: experimentalPlatform, }; } let appShellOptions; if (options.appShell) { appShellOptions = { route: 'shell', }; } const outputPath = options.outputPath; const outputOptions: NormalizedOutputOptions = { browser: 'browser', server: 'server', media: 'media', ...(typeof outputPath === 'string' ? undefined : outputPath), base: normalizeDirectoryPath( path.resolve(workspaceRoot, typeof outputPath === 'string' ? outputPath : outputPath.base), ), clean: options.deleteOutputPath ?? true, // For app-shell and SSG server files are not required by users. // Omit these when SSR is not enabled. ignoreServer: ((ssrOptions === undefined || serverEntryPoint === undefined) && options.outputMode === undefined) || options.outputMode === OutputMode.Static, }; const outputNames = { bundles: options.outputHashing === OutputHashing.All || options.outputHashing === OutputHashing.Bundles ? '[name]-[hash]' : '[name]', media: outputOptions.media + (options.outputHashing === OutputHashing.All || options.outputHashing === OutputHashing.Media ? '/[name]-[hash]' : '/[name]'), }; const globalStyles = normalizeGlobalEntries(options.styles, 'styles'); const globalScripts = normalizeGlobalEntries(options.scripts, 'scripts'); let indexHtmlOptions; // index can never have a value of `true` but in the schema it's of type `boolean`. if (typeof options.index !== 'boolean') { let indexOutput: string; // The output file will be created within the configured output path if (typeof options.index === 'string') { /** * If SSR is activated, create a distinct entry file for the `index.html`. * This is necessary because numerous server/cloud providers automatically serve the `index.html` as a static file * if it exists (handling SSG). * * For instance, accessing `foo.com/` would lead to `foo.com/index.html` being served instead of hitting the server. * * This approach can also be applied to service workers, where the `index.csr.html` is served instead of the prerendered `index.html`. */ const indexBaseName = path.basename(options.index); indexOutput = (ssrOptions || prerenderOptions) && indexBaseName === 'index.html' ? INDEX_HTML_CSR : indexBaseName; } else { indexOutput = options.index.output || 'index.html'; } indexHtmlOptions = { input: path.join( workspaceRoot, typeof options.index === 'string' ? options.index : options.index.input, ), output: indexOutput, insertionOrder: [ ['polyfills', true], ...globalStyles.filter((s) => s.initial).map((s) => [s.name, false]), ...globalScripts.filter((s) => s.initial).map((s) => [s.name, false]), ['main', true], // [name, esm] ] as [string, boolean][], transformer: extensions?.indexHtmlTransformer, // Preload initial defaults to true preloadInitial: typeof options.index !== 'object' || (options.index.preloadInitial ?? true), }; }
{ "end_byte": 13619, "start_byte": 4976, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/options.ts" }
angular-cli/packages/angular/build/src/builders/application/options.ts_13623_22055
if (appShellOptions || ssrOptions || prerenderOptions) { if (!serverEntryPoint) { throw new Error( 'The "server" option is required when enabling "ssr", "prerender" or "app-shell".', ); } if (!indexHtmlOptions) { throw new Error( 'The "index" option cannot be set to false when enabling "ssr", "prerender" or "app-shell".', ); } } // Initial options to keep const { allowedCommonJsDependencies, aot, baseHref, crossOrigin, externalDependencies, extractLicenses, inlineStyleLanguage = 'css', outExtension, serviceWorker, poll, polyfills, statsJson, outputMode, stylePreprocessorOptions, subresourceIntegrity, verbose, watch, progress = true, externalPackages, namedChunks, budgets, deployUrl, clearScreen, define, partialSSRBuild = false, externalRuntimeStyles, instrumentForCoverage, security, } = options; // Return all the normalized options return { advancedOptimizations: !!aot && optimizationOptions.scripts, allowedCommonJsDependencies, baseHref, cacheOptions, crossOrigin, externalDependencies, extractLicenses, inlineStyleLanguage, jit: !aot, stats: !!statsJson, polyfills: polyfills === undefined || Array.isArray(polyfills) ? polyfills : [polyfills], poll, progress, externalPackages, preserveSymlinks, stylePreprocessorOptions, subresourceIntegrity, serverEntryPoint, prerenderOptions, appShellOptions, outputMode, ssrOptions, verbose, watch, workspaceRoot, entryPoints, optimizationOptions, outputOptions, outExtension, sourcemapOptions, tsconfig, projectRoot, assets, outputNames, fileReplacements, globalStyles, globalScripts, serviceWorker: serviceWorker ? path.join( workspaceRoot, typeof serviceWorker === 'string' ? serviceWorker : 'src/ngsw-config.json', ) : undefined, indexHtmlOptions, tailwindConfiguration, postcssConfiguration, i18nOptions, namedChunks, budgets: budgets?.length ? budgets : undefined, publicPath: deployUrl, plugins: extensions?.codePlugins?.length ? extensions?.codePlugins : undefined, loaderExtensions, jsonLogs: useJSONBuildLogs, colors: supportColor(), clearScreen, define, partialSSRBuild: usePartialSsrBuild || partialSSRBuild, externalRuntimeStyles, instrumentForCoverage, security, }; } async function getTailwindConfig( searchDirectories: SearchDirectory[], workspaceRoot: string, context: BuilderContext, ): Promise<{ file: string; package: string } | undefined> { const tailwindConfigurationPath = findTailwindConfiguration(searchDirectories); if (!tailwindConfigurationPath) { return undefined; } // Create a node resolver from the configuration file const resolver = createRequire(tailwindConfigurationPath); try { return { file: tailwindConfigurationPath, package: resolver.resolve('tailwindcss'), }; } catch { const relativeTailwindConfigPath = path.relative(workspaceRoot, tailwindConfigurationPath); context.logger.warn( `Tailwind CSS configuration file found (${relativeTailwindConfigPath})` + ` but the 'tailwindcss' package is not installed.` + ` To enable Tailwind CSS, please install the 'tailwindcss' package.`, ); } return undefined; } /** * Normalize entry point options. To maintain compatibility with the legacy browser builder, we need a single `browser` * option which defines a single entry point. However, we also want to support multiple entry points as an internal option. * The two options are mutually exclusive and if `browser` is provided it will be used as the sole entry point. * If `entryPoints` are provided, they will be used as the set of entry points. * * @param workspaceRoot Path to the root of the Angular workspace. * @param browser The `browser` option pointing at the application entry point. While required per the schema file, it may be omitted by * programmatic usages of `browser-esbuild`. * @param entryPoints Set of entry points to use if provided. * @returns An object mapping entry point names to their file paths. */ function normalizeEntryPoints( workspaceRoot: string, browser: string | undefined, entryPoints: Set<string> = new Set(), ): Record<string, string> { if (browser === '') { throw new Error('`browser` option cannot be an empty string.'); } // `browser` and `entryPoints` are mutually exclusive. if (browser && entryPoints.size > 0) { throw new Error('Only one of `browser` or `entryPoints` may be provided.'); } if (!browser && entryPoints.size === 0) { // Schema should normally reject this case, but programmatic usages of the builder might make this mistake. throw new Error('Either `browser` or at least one `entryPoints` value must be provided.'); } // Schema types force `browser` to always be provided, but it may be omitted when the builder is invoked programmatically. if (browser) { // Use `browser` alone. return { 'main': path.join(workspaceRoot, browser) }; } else { // Use `entryPoints` alone. const entryPointPaths: Record<string, string> = {}; for (const entryPoint of entryPoints) { const parsedEntryPoint = path.parse(entryPoint); // Use the input file path without an extension as the "name" of the entry point dictating its output location. // Relative entry points are generated at the same relative path in the output directory. // Absolute entry points are always generated with the same file name in the root of the output directory. This includes absolute // paths pointing at files actually within the workspace root. const entryPointName = path.isAbsolute(entryPoint) ? parsedEntryPoint.name : path.join(parsedEntryPoint.dir, parsedEntryPoint.name); // Get the full file path to a relative entry point input. Leave bare specifiers alone so they are resolved as modules. const isRelativePath = entryPoint.startsWith('.'); const entryPointPath = isRelativePath ? path.join(workspaceRoot, entryPoint) : entryPoint; // Check for conflicts with previous entry points. const existingEntryPointPath = entryPointPaths[entryPointName]; if (existingEntryPointPath) { throw new Error( `\`${existingEntryPointPath}\` and \`${entryPointPath}\` both output to the same location \`${entryPointName}\`.` + ' Rename or move one of the files to fix the conflict.', ); } entryPointPaths[entryPointName] = entryPointPath; } return entryPointPaths; } } /** * Normalize a directory path string. * Currently only removes a trailing slash if present. * @param path A path string. * @returns A normalized path string. */ function normalizeDirectoryPath(path: string): string { const last = path[path.length - 1]; if (last === '/' || last === '\\') { return path.slice(0, -1); } return path; } function normalizeGlobalEntries( rawEntries: ({ bundleName?: string; input: string; inject?: boolean } | string)[] | undefined, defaultName: string, ): { name: string; files: string[]; initial: boolean }[] { if (!rawEntries?.length) { return []; } const bundles = new Map<string, { name: string; files: string[]; initial: boolean }>(); for (const rawEntry of rawEntries) { let entry; if (typeof rawEntry === 'string') { // string entries use default bundle name and inject values entry = { input: rawEntry }; } else { entry = rawEntry; } const { bundleName, input, inject = true } = entry; // Non-injected entries default to the file name const name = bundleName || (inject ? defaultName : path.basename(input, path.extname(input))); const existing = bundles.get(name); if (!existing) { bundles.set(name, { name, files: [input], initial: inject }); continue; } if (existing.initial !== inject) { throw new Error( `The "${name}" bundle is mixing injected and non-injected entries. ` + 'Verify that the project options are correct.', ); } existing.files.push(input); } return [...bundles.values()]; }
{ "end_byte": 22055, "start_byte": 13623, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/options.ts" }
angular-cli/packages/angular/build/src/builders/application/options.ts_22057_22456
export function getLocaleBaseHref( baseHref: string | undefined, i18n: NormalizedApplicationBuildOptions['i18nOptions'], locale: string, ): string | undefined { if (i18n.flatOutput) { return undefined; } if (i18n.locales[locale] && i18n.locales[locale].baseHref !== '') { return urlJoin(baseHref || '', i18n.locales[locale].baseHref ?? `/${locale}/`); } return undefined; }
{ "end_byte": 22456, "start_byte": 22057, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/options.ts" }
angular-cli/packages/angular/build/src/builders/application/execute-build.ts_0_1827
/** * @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 assert from 'node:assert'; import { SourceFileCache } from '../../tools/esbuild/angular/source-file-cache'; import { generateBudgetStats } from '../../tools/esbuild/budget-stats'; import { BuildOutputFileType, BundlerContext } from '../../tools/esbuild/bundler-context'; import { ExecutionResult, RebuildState } from '../../tools/esbuild/bundler-execution-result'; import { checkCommonJSModules } from '../../tools/esbuild/commonjs-checker'; import { extractLicenses } from '../../tools/esbuild/license-extractor'; import { profileAsync } from '../../tools/esbuild/profiling'; import { calculateEstimatedTransferSizes, logBuildStats, transformSupportedBrowsersToTargets, } from '../../tools/esbuild/utils'; import { BudgetCalculatorResult, checkBudgets } from '../../utils/bundle-calculator'; import { shouldOptimizeChunks } from '../../utils/environment-options'; import { resolveAssets } from '../../utils/resolve-assets'; import { SERVER_APP_ENGINE_MANIFEST_FILENAME, generateAngularServerAppEngineManifest, } from '../../utils/server-rendering/manifest'; import { getSupportedBrowsers } from '../../utils/supported-browsers'; import { optimizeChunks } from './chunk-optimizer'; import { executePostBundleSteps } from './execute-post-bundle'; import { inlineI18n, loadActiveTranslations } from './i18n'; import { NormalizedApplicationBuildOptions } from './options'; import { OutputMode } from './schema'; import { createComponentStyleBundler, setupBundlerContexts } from './setup-bundling'; // eslint-disable-next-line max-lines-per-function
{ "end_byte": 1827, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/execute-build.ts" }
angular-cli/packages/angular/build/src/builders/application/execute-build.ts_1828_9526
export async function executeBuild( options: NormalizedApplicationBuildOptions, context: BuilderContext, rebuildState?: RebuildState, ): Promise<ExecutionResult> { const { projectRoot, workspaceRoot, i18nOptions, optimizationOptions, assets, outputMode, cacheOptions, serverEntryPoint, baseHref, ssrOptions, verbose, colors, jsonLogs, } = options; // TODO: Consider integrating into watch mode. Would require full rebuild on target changes. const browsers = getSupportedBrowsers(projectRoot, context.logger); // Load active translations if inlining // TODO: Integrate into watch mode and only load changed translations if (i18nOptions.shouldInline) { await loadActiveTranslations(context, i18nOptions); } // Reuse rebuild state or create new bundle contexts for code and global stylesheets let bundlerContexts; let componentStyleBundler; let codeBundleCache; if (rebuildState) { bundlerContexts = rebuildState.rebuildContexts; componentStyleBundler = rebuildState.componentStyleBundler; codeBundleCache = rebuildState.codeBundleCache; } else { const target = transformSupportedBrowsersToTargets(browsers); codeBundleCache = new SourceFileCache(cacheOptions.enabled ? cacheOptions.path : undefined); componentStyleBundler = createComponentStyleBundler(options, target); bundlerContexts = setupBundlerContexts(options, target, codeBundleCache, componentStyleBundler); } let bundlingResult = await BundlerContext.bundleAll( bundlerContexts, rebuildState?.fileChanges.all, ); if (options.optimizationOptions.scripts && shouldOptimizeChunks) { bundlingResult = await profileAsync('OPTIMIZE_CHUNKS', () => optimizeChunks( bundlingResult, options.sourcemapOptions.scripts ? !options.sourcemapOptions.hidden || 'hidden' : false, ), ); } const executionResult = new ExecutionResult( bundlerContexts, componentStyleBundler, codeBundleCache, ); executionResult.addWarnings(bundlingResult.warnings); // Return if the bundling has errors if (bundlingResult.errors) { executionResult.addErrors(bundlingResult.errors); return executionResult; } // Analyze external imports if external options are enabled if (options.externalPackages || bundlingResult.externalConfiguration) { const { externalConfiguration, externalImports: { browser, server }, } = bundlingResult; const implicitBrowser = browser ? [...browser] : []; const implicitServer = server ? [...server] : []; // TODO: Implement wildcard externalConfiguration filtering executionResult.setExternalMetadata( externalConfiguration ? implicitBrowser.filter((value) => !externalConfiguration.includes(value)) : implicitBrowser, externalConfiguration ? implicitServer.filter((value) => !externalConfiguration.includes(value)) : implicitServer, externalConfiguration, ); } const { metafile, initialFiles, outputFiles } = bundlingResult; executionResult.outputFiles.push(...outputFiles); const changedFiles = rebuildState && executionResult.findChangedFiles(rebuildState.previousOutputHashes); // Analyze files for bundle budget failures if present let budgetFailures: BudgetCalculatorResult[] | undefined; if (options.budgets) { const compatStats = generateBudgetStats(metafile, outputFiles, initialFiles); budgetFailures = [...checkBudgets(options.budgets, compatStats, true)]; for (const { message, severity } of budgetFailures) { if (severity === 'error') { executionResult.addError(message); } else { executionResult.addWarning(message); } } } // Calculate estimated transfer size if scripts are optimized let estimatedTransferSizes; if (optimizationOptions.scripts || optimizationOptions.styles.minify) { estimatedTransferSizes = await calculateEstimatedTransferSizes(executionResult.outputFiles); } // Check metafile for CommonJS module usage if optimizing scripts if (optimizationOptions.scripts) { const messages = checkCommonJSModules(metafile, options.allowedCommonJsDependencies); executionResult.addWarnings(messages); } // Copy assets if (assets) { executionResult.addAssets(await resolveAssets(assets, workspaceRoot)); } // Extract and write licenses for used packages if (options.extractLicenses) { executionResult.addOutputFile( '3rdpartylicenses.txt', await extractLicenses(metafile, workspaceRoot), BuildOutputFileType.Root, ); } // Watch input index HTML file if configured if (options.indexHtmlOptions) { executionResult.extraWatchFiles.push(options.indexHtmlOptions.input); executionResult.htmlIndexPath = options.indexHtmlOptions.output; executionResult.htmlBaseHref = options.baseHref; } // Create server app engine manifest if (serverEntryPoint) { executionResult.addOutputFile( SERVER_APP_ENGINE_MANIFEST_FILENAME, generateAngularServerAppEngineManifest(i18nOptions, baseHref, undefined), BuildOutputFileType.ServerRoot, ); } // Override auto-CSP settings if we are serving through Vite middleware. if (context.builder.builderName === 'dev-server' && options.security) { options.security.autoCsp = false; } // Perform i18n translation inlining if enabled if (i18nOptions.shouldInline) { const result = await inlineI18n(options, executionResult, initialFiles); executionResult.addErrors(result.errors); executionResult.addWarnings(result.warnings); executionResult.addPrerenderedRoutes(result.prerenderedRoutes); } else { const result = await executePostBundleSteps( options, executionResult.outputFiles, executionResult.assetFiles, initialFiles, // Set lang attribute to the defined source locale if present i18nOptions.hasDefinedSourceLocale ? i18nOptions.sourceLocale : undefined, ); executionResult.addErrors(result.errors); executionResult.addWarnings(result.warnings); executionResult.addPrerenderedRoutes(result.prerenderedRoutes); executionResult.outputFiles.push(...result.additionalOutputFiles); executionResult.assetFiles.push(...result.additionalAssets); } if (serverEntryPoint) { const prerenderedRoutes = executionResult.prerenderedRoutes; // Regenerate the manifest to append prerendered routes data. This is only needed if SSR is enabled. if (outputMode === OutputMode.Server && Object.keys(prerenderedRoutes).length) { const manifest = executionResult.outputFiles.find( (f) => f.path === SERVER_APP_ENGINE_MANIFEST_FILENAME, ); assert(manifest, `${SERVER_APP_ENGINE_MANIFEST_FILENAME} was not found in output files.`); manifest.contents = new TextEncoder().encode( generateAngularServerAppEngineManifest(i18nOptions, baseHref, prerenderedRoutes), ); } executionResult.addOutputFile( 'prerendered-routes.json', JSON.stringify({ routes: prerenderedRoutes }, null, 2), BuildOutputFileType.Root, ); } // Write metafile if stats option is enabled if (options.stats) { executionResult.addOutputFile( 'stats.json', JSON.stringify(metafile, null, 2), BuildOutputFileType.Root, ); } if (!jsonLogs) { executionResult.addLog( logBuildStats( metafile, outputFiles, initialFiles, budgetFailures, colors, changedFiles, estimatedTransferSizes, !!ssrOptions, verbose, ), ); } return executionResult; }
{ "end_byte": 9526, "start_byte": 1828, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/execute-build.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/setup.ts_0_1089
/** * @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'; // TODO: Consider using package.json imports field instead of relative path // after the switch to rules_js. export * from '../../../../../../../modules/testing/builder/src'; export const APPLICATION_BUILDER_INFO = Object.freeze({ name: '@angular-devkit/build-angular:application', 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', browser: 'src/main.ts', outputPath: 'dist', tsConfig: 'src/tsconfig.app.json', progress: false, // Disable optimizations optimization: false, // Enable polling (if a test enables watch mode). // This is a workaround for bazel isolation file watch not triggering in tests. poll: 100, });
{ "end_byte": 1089, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/setup.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/behavior/rebuild-index-html_spec.ts_0_2289
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; /** * Maximum time in milliseconds for single build/rebuild * This accounts for CI variability. */ export const BUILD_TIMEOUT = 30_000; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Behavior: "Rebuilds when input index HTML changes"', () => { beforeEach(async () => { // Application code is not needed for styles tests await harness.writeFile('src/main.ts', 'console.log("TEST");'); }); it('rebuilds output index HTML', async () => { harness.useTarget('build', { ...BASE_OPTIONS, watch: true, }); const buildCount = await harness .execute({ outputLogsOnFailure: false }) .pipe( timeout(30000), concatMap(async ({ result }, index) => { switch (index) { case 0: expect(result?.success).toBe(true); harness.expectFile('dist/browser/index.html').content.toContain('charset="utf-8"'); await harness.modifyFile('src/index.html', (content) => content.replace('charset="utf-8"', 'abc'), ); break; case 1: expect(result?.success).toBe(true); harness .expectFile('dist/browser/index.html') .content.not.toContain('charset="utf-8"'); await harness.modifyFile('src/index.html', (content) => content.replace('abc', 'charset="utf-8"'), ); break; case 2: expect(result?.success).toBe(true); harness.expectFile('dist/browser/index.html').content.toContain('charset="utf-8"'); break; } }), take(3), count(), ) .toPromise(); expect(buildCount).toBe(3); }); }); });
{ "end_byte": 2289, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/behavior/rebuild-index-html_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/behavior/typescript-path-mapping_spec.ts_0_3556
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Behavior: "TypeScript Path Mapping"', () => { it('should resolve TS files when imported with a path mapping', async () => { // Change main module import to use path mapping await harness.modifyFile('src/main.ts', (content) => content.replace(`'./app/app.module'`, `'@root/app.module'`), ); // Add a path mapping for `@root` await harness.modifyFile('tsconfig.json', (content) => { const tsconfig = JSON.parse(content); tsconfig.compilerOptions.paths = { '@root/*': ['./src/app/*'], }; return JSON.stringify(tsconfig); }); harness.useTarget('build', { ...BASE_OPTIONS, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); }); it('should fail to resolve if no path mapping for an import is present', async () => { // Change main module import to use path mapping await harness.modifyFile('src/main.ts', (content) => content.replace(`'./app/app.module'`, `'@root/app.module'`), ); // Add a path mapping for `@not-root` await harness.modifyFile('tsconfig.json', (content) => { const tsconfig = JSON.parse(content); tsconfig.compilerOptions.paths = { '@not-root/*': ['./src/app/*'], }; return JSON.stringify(tsconfig); }); harness.useTarget('build', { ...BASE_OPTIONS, }); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBe(false); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching('Could not resolve "@root/app.module"'), }), ); }); it('should resolve JS files when imported with a path mapping', async () => { // Change main module import to use path mapping await harness.modifyFile('src/main.ts', (content) => content.replace(`'./app/app.module'`, `'app-module'`), ); await harness.writeFiles({ 'a.js': `export * from './src/app/app.module';\n\nconsole.log('A');`, 'a.d.ts': `export * from './src/app/app.module';`, }); // Add a path mapping for `@root` await harness.modifyFile('tsconfig.json', (content) => { const tsconfig = JSON.parse(content); tsconfig.compilerOptions.paths = { 'app-module': ['a.js'], }; return JSON.stringify(tsconfig); }); // app.module needs to be manually included since it is not referenced via a TS file // with the test path mapping in place. await harness.modifyFile('src/tsconfig.app.json', (content) => { const tsconfig = JSON.parse(content); tsconfig.files.push('app/app.module.ts'); return JSON.stringify(tsconfig); }); harness.useTarget('build', { ...BASE_OPTIONS, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js').content.toContain(`console.log("A")`); }); }); });
{ "end_byte": 3556, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/behavior/typescript-path-mapping_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/behavior/typescript-rebuild-touch-file_spec.ts_0_1709
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Behavior: "Rebuilds when touching file"', () => { for (const aot of [true, false]) { it(`Rebuild correctly when file is touched with ${aot ? 'AOT' : 'JIT'}`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, watch: true, aot, }); const buildCount = await harness .execute({ outputLogsOnFailure: false }) .pipe( timeout(30_000), concatMap(async ({ result }, index) => { switch (index) { case 0: expect(result?.success).toBeTrue(); // Touch a file without doing any changes. await harness.modifyFile('src/app/app.component.ts', (content) => content); break; case 1: expect(result?.success).toBeTrue(); await harness.removeFile('src/app/app.component.ts'); break; case 2: expect(result?.success).toBeFalse(); break; } }), take(3), count(), ) .toPromise(); expect(buildCount).toBe(3); }); } }); });
{ "end_byte": 1709, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/behavior/typescript-rebuild-touch-file_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/behavior/rebuild-web-workers_spec.ts_0_4704
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; /** * Maximum time in milliseconds for single build/rebuild * This accounts for CI variability. */ export const BUILD_TIMEOUT = 30_000; /** * A regular expression used to check if a built worker is correctly referenced in application code. */ const REFERENCED_WORKER_REGEXP = /new Worker\(new URL\("worker-[A-Z0-9]{8}\.js", import\.meta\.url\)/; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Behavior: "Rebuilds when Web Worker files change"', () => { it('Recovers from error when directly referenced worker file is changed', async () => { harness.useTarget('build', { ...BASE_OPTIONS, watch: true, }); const workerCodeFile = ` console.log('WORKER FILE'); `; const errorText = `Expected ";" but found "~"`; // Create a worker file await harness.writeFile('src/app/worker.ts', workerCodeFile); // 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: '<h1>Worker Test</h1>', }) export class AppComponent { worker = new Worker(new URL('./worker', import.meta.url), { type: 'module' }); } `, ); const buildCount = await harness .execute({ outputLogsOnFailure: false }) .pipe( timeout(BUILD_TIMEOUT), concatMap(async ({ result, logs }, index) => { switch (index) { case 0: expect(result?.success).toBeTrue(); // Ensure built worker is referenced in the application code harness .expectFile('dist/browser/main.js') .content.toMatch(REFERENCED_WORKER_REGEXP); // Update the worker file to be invalid syntax await harness.writeFile('src/app/worker.ts', `asd;fj$3~kls;kd^(*fjlk;sdj---flk`); break; case 1: expect(result?.success).toBeFalse(); expect(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching(errorText), }), ); // 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(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching(errorText), }), ); // Revert the change that caused the error // Should remove the error await harness.writeFile('src/app/worker.ts', workerCodeFile); break; case 3: expect(result?.success).toBeTrue(); expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching(errorText), }), ); // 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(errorText), }), ); // Ensure built worker is referenced in the application code harness .expectFile('dist/browser/main.js') .content.toMatch(REFERENCED_WORKER_REGEXP); break; } }), take(5), count(), ) .toPromise(); expect(buildCount).toBe(5); }); }); });
{ "end_byte": 4704, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/behavior/rebuild-web-workers_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/behavior/browser-support_spec.ts_0_5339
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_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, polyfills: ['zone.js'], sourceMap: { scripts: true, }, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js').content.not.toMatch(/\sasync\s+function\s/); harness.expectFile('dist/browser/main.js.map').content.toContain('Promise<Void123>'); }); it('downlevels async functions when zone.js is included as a polyfill', async () => { // Add an async function to the project await harness.writeFile( 'src/main.ts', 'async function test(): Promise<void> { console.log("from-async-function"); }\ntest();', ); harness.useTarget('build', { ...BASE_OPTIONS, polyfills: ['zone.js'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js').content.not.toMatch(/\sasync\s/); harness.expectFile('dist/browser/main.js').content.toContain('"from-async-function"'); }); it('does not downlevels async functions when zone.js is not included as a polyfill', async () => { // Add an async function to the project await harness.writeFile( 'src/main.ts', 'async function test(): Promise<void> { console.log("from-async-function"); }\ntest();', ); harness.useTarget('build', { ...BASE_OPTIONS, polyfills: [], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js').content.toMatch(/\sasync\s/); harness.expectFile('dist/browser/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" when zone.js is included as a polyfill', 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, polyfills: ['zone.js'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js').content.not.toMatch(/\sawait\s/); harness.expectFile('dist/browser/main.js').content.toContain('"for await...of"'); }); it('does not downlevel "for await...of" when zone.js is not included as a polyfill', 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, polyfills: [], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js').content.toMatch(/\sawait\s/); harness.expectFile('dist/browser/main.js').content.toContain('"for await...of"'); }); }); });
{ "end_byte": 5339, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/behavior/browser-support_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/behavior/wasm-esm_spec.ts_0_1546
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; /** * Compiled and base64 encoded WASM file for the following WAT: * ``` * (module * (export "multiply" (func $multiply)) * (func $multiply (param i32 i32) (result i32) * local.get 0 * local.get 1 * i32.mul * ) * ) * ``` */ const exportWasmBase64 = 'AGFzbQEAAAABBwFgAn9/AX8DAgEABwwBCG11bHRpcGx5AAAKCQEHACAAIAFsCwAXBG5hbWUBCwEACG11bHRpcGx5AgMBAAA='; const exportWasmBytes = Buffer.from(exportWasmBase64, 'base64'); /** * Compiled and base64 encoded WASM file for the following WAT: * ``` * (module * (import "./values" "getValue" (func $getvalue (result i32))) * (export "multiply" (func $multiply)) * (export "subtract1" (func $subtract)) * (func $multiply (param i32 i32) (result i32) * local.get 0 * local.get 1 * i32.mul * ) * (func $subtract (param i32) (result i32) * call $getvalue * local.get 0 * i32.sub * ) * ) * ``` */ const importWasmBase64 = 'AGFzbQEAAAABEANgAAF/YAJ/fwF/YAF/AX8CFQEILi92YWx1ZXMIZ2V0VmFsdWUAAAMDAgECBxgCCG11bHRpcGx5AAEJc3VidHJhY3QxAAIKEQIHACAAIAFsCwcAEAAgAGsLAC8EbmFtZQEfAwAIZ2V0dmFsdWUBCG11bHRpcGx5AghzdWJ0cmFjdAIHAwAAAQACAA=='; const importWasmBytes = Buffer.from(importWasmBase64, 'base64');
{ "end_byte": 1546, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/behavior/wasm-esm_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/behavior/wasm-esm_spec.ts_1548_8650
describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Behavior: "Supports WASM/ES module integration"', () => { it('should inject initialization code and add an export', async () => { harness.useTarget('build', { ...BASE_OPTIONS, }); // Create WASM file await harness.writeFile('src/multiply.wasm', exportWasmBytes); // Create main file that uses the WASM file await harness.writeFile( 'src/main.ts', ` // @ts-ignore import { multiply } from './multiply.wasm'; console.log(multiply(4, 5)); `, ); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); // Ensure initialization code and export name is present in output code harness.expectFile('dist/browser/main.js').content.toContain('WebAssembly.instantiate'); harness.expectFile('dist/browser/main.js').content.toContain('multiply'); }); it('should compile successfully with a provided type definition file', async () => { harness.useTarget('build', { ...BASE_OPTIONS, }); // Create WASM file await harness.writeFile('src/multiply.wasm', exportWasmBytes); await harness.writeFile( 'src/multiply.wasm.d.ts', 'export declare function multiply(a: number, b: number): number;', ); // Create main file that uses the WASM file await harness.writeFile( 'src/main.ts', ` import { multiply } from './multiply.wasm'; console.log(multiply(4, 5)); `, ); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); // Ensure initialization code and export name is present in output code harness.expectFile('dist/browser/main.js').content.toContain('WebAssembly.instantiate'); harness.expectFile('dist/browser/main.js').content.toContain('multiply'); }); it('should add WASM defined imports and include resolved TS file for import', async () => { harness.useTarget('build', { ...BASE_OPTIONS, }); // Create WASM file await harness.writeFile('src/subtract.wasm', importWasmBytes); // Create TS file that is expect by WASM file await harness.writeFile( 'src/values.ts', ` export function getValue(): number { return 100; } `, ); // The file is not imported into any actual TS files so it needs to be manually added to the TypeScript program await harness.modifyFile('src/tsconfig.app.json', (content) => content.replace('"main.ts",', '"main.ts","values.ts",'), ); // Create main file that uses the WASM file await harness.writeFile( 'src/main.ts', ` // @ts-ignore import { subtract1 } from './subtract.wasm'; console.log(subtract1(5)); `, ); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); // Ensure initialization code and export name is present in output code harness.expectFile('dist/browser/main.js').content.toContain('WebAssembly.instantiate'); harness.expectFile('dist/browser/main.js').content.toContain('subtract1'); harness.expectFile('dist/browser/main.js').content.toContain('./values'); harness.expectFile('dist/browser/main.js').content.toContain('getValue'); }); it('should add WASM defined imports and include resolved JS file for import', async () => { harness.useTarget('build', { ...BASE_OPTIONS, }); // Create WASM file await harness.writeFile('src/subtract.wasm', importWasmBytes); // Create JS file that is expect by WASM file await harness.writeFile( 'src/values.js', ` export function getValue() { return 100; } `, ); // Create main file that uses the WASM file await harness.writeFile( 'src/main.ts', ` // @ts-ignore import { subtract1 } from './subtract.wasm'; console.log(subtract1(5)); `, ); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); // Ensure initialization code and export name is present in output code harness.expectFile('dist/browser/main.js').content.toContain('WebAssembly.instantiate'); harness.expectFile('dist/browser/main.js').content.toContain('subtract1'); harness.expectFile('dist/browser/main.js').content.toContain('./values'); harness.expectFile('dist/browser/main.js').content.toContain('getValue'); }); it('should inline WASM files less than 10kb', async () => { harness.useTarget('build', { ...BASE_OPTIONS, }); // Create WASM file await harness.writeFile('src/multiply.wasm', exportWasmBytes); // Create main file that uses the WASM file await harness.writeFile( 'src/main.ts', ` // @ts-ignore import { multiply } from './multiply.wasm'; console.log(multiply(4, 5)); `, ); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); // Ensure WASM is present in output code harness.expectFile('dist/browser/main.js').content.toContain(exportWasmBase64); }); it('should show an error on invalid WASM file', async () => { harness.useTarget('build', { ...BASE_OPTIONS, }); // Create WASM file await harness.writeFile('src/multiply.wasm', 'NOT_WASM'); // Create main file that uses the WASM file await harness.writeFile( 'src/main.ts', ` // @ts-ignore import { multiply } from './multiply.wasm'; console.log(multiply(4, 5)); `, ); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBeFalse(); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching('Unable to analyze WASM file'), }), ); }); it('should show an error if using Zone.js', async () => { harness.useTarget('build', { ...BASE_OPTIONS, polyfills: ['zone.js'], }); // Create WASM file await harness.writeFile('src/multiply.wasm', importWasmBytes); // Create main file that uses the WASM file await harness.writeFile( 'src/main.ts', ` // @ts-ignore import { multiply } from './multiply.wasm'; console.log(multiply(4, 5)); `, ); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBeFalse(); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching( 'WASM/ES module integration imports are not supported with Zone.js applications', ), }), ); }); }); });
{ "end_byte": 8650, "start_byte": 1548, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/behavior/wasm-esm_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/behavior/stylesheet_autoprefixer_spec.ts_0_6378
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; const styleBaseContent: Record<string, string> = Object.freeze({ 'css': ` @import url(imported-styles.css); div { hyphens: none; } `, }); const styleImportedContent: Record<string, string> = Object.freeze({ 'css': 'section { hyphens: none; }', }); describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Behavior: "Stylesheet autoprefixer"', () => { for (const ext of ['css'] /* ['css', 'sass', 'scss', 'less'] */) { it(`should add prefixes for listed browsers in global styles [${ext}]`, async () => { await harness.writeFile( '.browserslistrc', ` Safari 15.4 Edge 104 Firefox 91 `, ); await harness.writeFiles({ [`src/styles.${ext}`]: styleBaseContent[ext], [`src/imported-styles.${ext}`]: styleImportedContent[ext], }); harness.useTarget('build', { ...BASE_OPTIONS, styles: [`src/styles.${ext}`], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness .expectFile('dist/browser/styles.css') .content.toMatch(/section\s*{\s*-webkit-hyphens:\s*none;\s*hyphens:\s*none;\s*}/); harness .expectFile('dist/browser/styles.css') .content.toMatch(/div\s*{\s*-webkit-hyphens:\s*none;\s*hyphens:\s*none;\s*}/); }); it(`should not add prefixes if not required by browsers in global styles [${ext}]`, async () => { await harness.writeFile( '.browserslistrc', ` Edge 110 `, ); await harness.writeFiles({ [`src/styles.${ext}`]: styleBaseContent[ext], [`src/imported-styles.${ext}`]: styleImportedContent[ext], }); harness.useTarget('build', { ...BASE_OPTIONS, styles: [`src/styles.${ext}`], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness .expectFile('dist/browser/styles.css') .content.toMatch(/section\s*{\s*hyphens:\s*none;\s*}/); harness .expectFile('dist/browser/styles.css') .content.toMatch(/div\s*{\s*hyphens:\s*none;\s*}/); }); it(`should add prefixes for listed browsers in external component styles [${ext}]`, async () => { await harness.writeFile( '.browserslistrc', ` Safari 15.4 Edge 104 Firefox 91 `, ); await harness.writeFiles({ [`src/app/app.component.${ext}`]: styleBaseContent[ext], [`src/app/imported-styles.${ext}`]: styleImportedContent[ext], }); await harness.modifyFile('src/app/app.component.ts', (content) => content.replace('./app.component.css', `./app.component.${ext}`), ); harness.useTarget('build', { ...BASE_OPTIONS, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness .expectFile('dist/browser/main.js') .content.toMatch(/{\\n\s*-webkit-hyphens:\s*none;\\n\s*hyphens:\s*none;\\n\s*}/); harness .expectFile('dist/browser/main.js') .content.toMatch(/{\\n\s*-webkit-hyphens:\s*none;\\n\s*hyphens:\s*none;\\n\s*}/); }); it(`should not add prefixes if not required by browsers in external component styles [${ext}]`, async () => { await harness.writeFile( '.browserslistrc', ` Edge 110 `, ); await harness.writeFiles({ [`src/app/app.component.${ext}`]: styleBaseContent[ext], [`src/app/imported-styles.${ext}`]: styleImportedContent[ext], }); await harness.modifyFile('src/app/app.component.ts', (content) => content.replace('./app.component.css', `./app.component.${ext}`), ); harness.useTarget('build', { ...BASE_OPTIONS, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness .expectFile('dist/browser/main.js') .content.toMatch(/{\\n\s*hyphens:\s*none;\\n\s*}/); harness .expectFile('dist/browser/main.js') .content.toMatch(/{\\n\s*hyphens:\s*none;\\n\s*}/); }); } it('should add prefixes for listed browsers in inline component styles', async () => { await harness.writeFile( '.browserslistrc', ` Safari 15.4 Edge 104 Firefox 91 `, ); await harness.modifyFile('src/app/app.component.ts', (content) => { return content .replace('styleUrls', 'styles') .replace('./app.component.css', 'div { hyphens: none; }'); }); harness.useTarget('build', { ...BASE_OPTIONS, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness .expectFile('dist/browser/main.js') // div[_ngcontent-%COMP%] {\n -webkit-hyphens: none;\n hyphens: none;\n}\n .content.toMatch(/{\\n\s*-webkit-hyphens:\s*none;\\n\s*hyphens:\s*none;\\n\s*}/); }); it('should not add prefixes if not required by browsers in inline component styles', async () => { await harness.writeFile( '.browserslistrc', ` Edge 110 `, ); await harness.modifyFile('src/app/app.component.ts', (content) => { return content .replace('styleUrls', 'styles') .replace('./app.component.css', 'div { hyphens: none; }'); }); harness.useTarget('build', { ...BASE_OPTIONS, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/main.js').content.toMatch(/{\\n\s*hyphens:\s*none;\\n\s*}/); }); }); });
{ "end_byte": 6378, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/behavior/stylesheet_autoprefixer_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/behavior/stylesheet-url-resolution_spec.ts_0_9152
/** * @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 { buildApplication } from '../../index'; import { OutputHashing } from '../../schema'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Behavior: "Stylesheet url() Resolution"', () => { it('should show a note when using tilde prefix in a directly referenced stylesheet', async () => { await harness.writeFile( 'src/styles.css', ` .a { background-image: url("~/image.jpg") } `, ); harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.css'], }); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBe(false); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching('You can remove the tilde and'), }), ); expect(logs).not.toContain( jasmine.objectContaining({ message: jasmine.stringMatching('Preprocessor stylesheets may not show the exact'), }), ); }); it('should show a note when using tilde prefix in an imported CSS stylesheet', async () => { await harness.writeFile( 'src/styles.css', ` @import "a.css"; `, ); await harness.writeFile( 'src/a.css', ` .a { background-image: url("~/image.jpg") } `, ); harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.css'], }); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBe(false); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching('You can remove the tilde and'), }), ); }); it('should show a note when using tilde prefix in an imported Sass stylesheet', async () => { await harness.writeFile( 'src/styles.scss', ` @import "a"; `, ); await harness.writeFile( 'src/a.scss', ` .a { background-image: url("~/image.jpg") } `, ); harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.scss'], }); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBe(false); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching('You can remove the tilde and'), }), ); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching('Preprocessor stylesheets may not show the exact'), }), ); }); it('should show a note when using caret prefix in a directly referenced stylesheet', async () => { await harness.writeFile( 'src/styles.css', ` .a { background-image: url("^image.jpg") } `, ); harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.css'], }); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBe(false); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching('You can remove the caret and'), }), ); }); it('should show a note when using caret prefix in an imported Sass stylesheet', async () => { await harness.writeFile( 'src/styles.scss', ` @import "a"; `, ); await harness.writeFile( 'src/a.scss', ` .a { background-image: url("^image.jpg") } `, ); harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.scss'], }); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBe(false); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching('You can remove the caret and'), }), ); }); it('should not rebase a URL with a namespaced Sass variable reference that points to an absolute asset', async () => { await harness.writeFiles({ 'src/styles.scss': `@use 'theme/a';`, 'src/theme/a.scss': ` @use './b' as named; .a { background-image: url(named.$my-var) } `, 'src/theme/b.scss': `@forward './c.scss' show $my-var;`, 'src/theme/c.scss': `$my-var: "https://example.com/example.png";`, }); harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.scss'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness .expectFile('dist/browser/styles.css') .content.toContain('url(https://example.com/example.png)'); }); it('should not rebase a URL with a Sass variable reference that points to an absolute asset', async () => { await harness.writeFiles({ 'src/styles.scss': `@use 'theme/a';`, 'src/theme/a.scss': ` @import './b'; .a { background-image: url($my-var) } `, 'src/theme/b.scss': `$my-var: "https://example.com/example.png";`, }); harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.scss'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness .expectFile('dist/browser/styles.css') .content.toContain('url(https://example.com/example.png)'); }); it('should rebase a URL with a namespaced Sass variable referencing a local resource', async () => { await harness.writeFiles({ 'src/styles.scss': `@use 'theme/a';`, 'src/theme/a.scss': ` @use './b' as named; .a { background-image: url(named.$my-var) } `, 'src/theme/b.scss': `@forward './c.scss' show $my-var;`, 'src/theme/c.scss': `$my-var: "./images/logo.svg";`, 'src/theme/images/logo.svg': `<svg></svg>`, }); harness.useTarget('build', { ...BASE_OPTIONS, outputHashing: OutputHashing.None, styles: ['src/styles.scss'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/styles.css').content.toContain(`url("./media/logo.svg")`); harness.expectFile('dist/browser/media/logo.svg').toExist(); }); it('should rebase a URL with a Sass variable referencing a local resource', async () => { await harness.writeFiles({ 'src/styles.scss': `@use 'theme/a';`, 'src/theme/a.scss': ` @import './b'; .a { background-image: url($my-var) } `, 'src/theme/b.scss': `$my-var: "./images/logo.svg";`, 'src/theme/images/logo.svg': `<svg></svg>`, }); harness.useTarget('build', { ...BASE_OPTIONS, outputHashing: OutputHashing.None, styles: ['src/styles.scss'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/styles.css').content.toContain(`url("./media/logo.svg")`); harness.expectFile('dist/browser/media/logo.svg').toExist(); }); it('should rebase a URL with an leading interpolation referencing a local resource', async () => { await harness.writeFiles({ 'src/styles.scss': `@use 'theme/a';`, 'src/theme/a.scss': ` @import './b'; .a { background-image: url(#{$my-var}logo.svg) } `, 'src/theme/b.scss': `$my-var: "./images/";`, 'src/theme/images/logo.svg': `<svg></svg>`, }); harness.useTarget('build', { ...BASE_OPTIONS, outputHashing: OutputHashing.None, styles: ['src/styles.scss'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/styles.css').content.toContain(`url("./media/logo.svg")`); harness.expectFile('dist/browser/media/logo.svg').toExist(); });
{ "end_byte": 9152, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/behavior/stylesheet-url-resolution_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/behavior/stylesheet-url-resolution_spec.ts_9158_12939
it('should rebase a URL with interpolation using concatenation referencing a local resource', async () => { await harness.writeFiles({ 'src/styles.scss': `@use 'theme/a';`, 'src/theme/a.scss': ` @import './b'; $extra-var: "2"; $postfix-var: "xyz"; .a { background-image: url("#{$my-var}logo#{$extra-var+ "-" + $postfix-var}.svg") } `, 'src/theme/b.scss': `$my-var: "./images/";`, 'src/theme/images/logo2-xyz.svg': `<svg></svg>`, }); harness.useTarget('build', { ...BASE_OPTIONS, outputHashing: OutputHashing.None, styles: ['src/styles.scss'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness .expectFile('dist/browser/styles.css') .content.toContain(`url("./media/logo2-xyz.svg")`); harness.expectFile('dist/browser/media/logo2-xyz.svg').toExist(); }); it('should rebase a URL with an non-leading interpolation referencing a local resource', async () => { await harness.writeFiles({ 'src/styles.scss': `@use 'theme/a';`, 'src/theme/a.scss': ` @import './b'; .a { background-image: url(./#{$my-var}logo.svg) } `, 'src/theme/b.scss': `$my-var: "./images/";`, 'src/theme/images/logo.svg': `<svg></svg>`, }); harness.useTarget('build', { ...BASE_OPTIONS, outputHashing: OutputHashing.None, styles: ['src/styles.scss'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/styles.css').content.toContain(`url("./media/logo.svg")`); harness.expectFile('dist/browser/media/logo.svg').toExist(); }); it('should not rebase Sass function definition with name ending in "url"', async () => { await harness.writeFiles({ 'src/styles.scss': `@use 'theme/a';`, 'src/theme/a.scss': ` @import './b'; .a { $asset: my-function-url('logo'); background-image: url($asset) } `, 'src/theme/b.scss': `@function my-function-url($name) { @return "./images/" + $name + ".svg"; }`, 'src/theme/images/logo.svg': `<svg></svg>`, }); harness.useTarget('build', { ...BASE_OPTIONS, outputHashing: OutputHashing.None, styles: ['src/styles.scss'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/styles.css').content.toContain(`url("./media/logo.svg")`); harness.expectFile('dist/browser/media/logo.svg').toExist(); }); it('should not process a URL that has been marked as external', async () => { await harness.writeFiles({ 'src/styles.scss': `@use 'theme/a';`, 'src/theme/a.scss': ` .a { background-image: url("assets/logo.svg") } `, }); harness.useTarget('build', { ...BASE_OPTIONS, outputHashing: OutputHashing.None, externalDependencies: ['assets/*'], styles: ['src/styles.scss'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/styles.css').content.toContain(`url(assets/logo.svg)`); }); }); });
{ "end_byte": 12939, "start_byte": 9158, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/behavior/stylesheet-url-resolution_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/behavior/build-conditions_spec.ts_0_3198
/** * @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 { setupConditionImport, setTargetMapping, } from '../../../../../../../../modules/testing/builder/src/dev_prod_mode'; import { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Behavior: "conditional imports"', () => { beforeEach(async () => { await setupConditionImport(harness); }); interface ImportsTestCase { name: string; mapping: unknown; output?: string; } const GOOD_TARGET = './src/good.js'; const BAD_TARGET = './src/bad.js'; const testCases: ImportsTestCase[] = [ { name: 'simple string', mapping: GOOD_TARGET }, { name: 'default fallback without matching condition', mapping: { 'never': BAD_TARGET, 'default': GOOD_TARGET, }, }, { name: 'development condition', mapping: { 'development': BAD_TARGET, 'default': GOOD_TARGET, }, }, { name: 'production condition', mapping: { 'production': GOOD_TARGET, 'default': BAD_TARGET, }, }, { name: 'browser condition (in browser)', mapping: { 'browser': GOOD_TARGET, 'default': BAD_TARGET, }, }, { name: 'browser condition (in server)', output: 'server/main.server.mjs', mapping: { 'browser': BAD_TARGET, 'default': GOOD_TARGET, }, }, ]; for (const testCase of testCases) { describe(testCase.name, () => { beforeEach(async () => { await setTargetMapping(harness, testCase.mapping); }); it('resolves to expected target', async () => { harness.useTarget('build', { ...BASE_OPTIONS, optimization: true, ssr: true, server: 'src/main.ts', }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); const outputFile = `dist/${testCase.output ?? 'browser/main.js'}`; harness.expectFile(outputFile).content.toContain('"good-value"'); harness.expectFile(outputFile).content.not.toContain('"bad-value"'); }); }); } it('fails type-checking when import contains differing type', async () => { await setTargetMapping(harness, { 'development': './src/wrong.ts', 'default': './src/good.ts', }); harness.useTarget('build', { ...BASE_OPTIONS, optimization: false, }); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBeFalse(); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching('TS2339'), }), ); }); }); });
{ "end_byte": 3198, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/behavior/build-conditions_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/behavior/typescript-isolated-modules_spec.ts_0_2684
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Behavior: "TypeScript isolated modules direct transpilation"', () => { it('should successfully build with isolated modules enabled and disabled optimizations', async () => { // Enable tsconfig isolatedModules option in tsconfig await harness.modifyFile('tsconfig.json', (content) => { const tsconfig = JSON.parse(content); tsconfig.compilerOptions.isolatedModules = true; return JSON.stringify(tsconfig); }); harness.useTarget('build', { ...BASE_OPTIONS, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); }); it('should successfully build with isolated modules enabled and enabled optimizations', async () => { // Enable tsconfig isolatedModules option in tsconfig await harness.modifyFile('tsconfig.json', (content) => { const tsconfig = JSON.parse(content); tsconfig.compilerOptions.isolatedModules = true; return JSON.stringify(tsconfig); }); harness.useTarget('build', { ...BASE_OPTIONS, optimization: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); }); it('supports TSX files with isolated modules enabled and enabled optimizations', async () => { // Enable tsconfig isolatedModules option in tsconfig await harness.modifyFile('tsconfig.json', (content) => { const tsconfig = JSON.parse(content); tsconfig.compilerOptions.isolatedModules = true; tsconfig.compilerOptions.jsx = 'react-jsx'; return JSON.stringify(tsconfig); }); await harness.writeFile('src/types.d.ts', `declare module 'react/jsx-runtime' { jsx: any }`); await harness.writeFile('src/abc.tsx', `export function hello() { return <h1>Hello</h1>; }`); await harness.modifyFile( 'src/main.ts', (content) => content + `import { hello } from './abc'; console.log(hello());`, ); harness.useTarget('build', { ...BASE_OPTIONS, optimization: true, externalDependencies: ['react'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); }); }); });
{ "end_byte": 2684, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/behavior/typescript-isolated-modules_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/behavior/component-stylesheets_spec.ts_0_1710
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Behavior: "Component Stylesheets"', () => { it('should successfuly compile with an empty inline style', async () => { await harness.modifyFile('src/app/app.component.ts', (content) => { return content.replace('styleUrls', 'styles').replace('./app.component.css', ''); }); harness.useTarget('build', { ...BASE_OPTIONS, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); }); it('should maintain optimized empty Sass stylesheet when original has content', async () => { await harness.modifyFile('src/app/app.component.ts', (content) => { return content.replace('./app.component.css', './app.component.scss'); }); await harness.removeFile('src/app/app.component.css'); await harness.writeFile('src/app/app.component.scss', '@import "variables";'); await harness.writeFile('src/app/_variables.scss', '$value: blue;'); harness.useTarget('build', { ...BASE_OPTIONS, optimization: { styles: true, }, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/main.js').content.not.toContain('variables'); }); }); });
{ "end_byte": 1710, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/behavior/component-stylesheets_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/behavior/rebuild-general_spec.ts_0_3475
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; /** * Maximum time in milliseconds for single build/rebuild * This accounts for CI variability. */ export const BUILD_TIMEOUT = 30_000; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Behavior: "Rebuild updates in general cases"', () => { it('detects changes after a file was deleted and recreated', async () => { harness.useTarget('build', { ...BASE_OPTIONS, watch: true, }); const fileAContent = ` console.log('FILE-A'); export {}; `; // Create a file and add to application await harness.writeFile('src/app/file-a.ts', fileAContent); await harness.writeFile( 'src/app/app.component.ts', ` import { Component } from '@angular/core'; import './file-a'; @Component({ selector: 'app-root', standalone: false, template: 'App component', }) 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(); harness.expectFile('dist/browser/main.js').content.toContain('FILE-A'); // Delete the imported file await harness.removeFile('src/app/file-a.ts'); break; case 1: // Should fail from missing import expect(result?.success).toBeFalse(); // Remove the failing import await harness.modifyFile('src/app/app.component.ts', (content) => content.replace(`import './file-a';`, ''), ); break; case 2: expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/main.js').content.not.toContain('FILE-A'); // Recreate the file and the import await harness.writeFile('src/app/file-a.ts', fileAContent); await harness.modifyFile( 'src/app/app.component.ts', (content) => `import './file-a';\n` + content, ); break; case 3: expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/main.js').content.toContain('FILE-A'); // Change the imported file await harness.modifyFile('src/app/file-a.ts', (content) => content.replace('FILE-A', 'FILE-B'), ); break; case 4: expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/main.js').content.toContain('FILE-B'); break; } }), take(5), count(), ) .toPromise(); expect(buildCount).toBe(5); }); }); });
{ "end_byte": 3475, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/behavior/rebuild-general_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/behavior/angular-aot-metadata_spec.ts_0_1221
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Behavior: "Angular metadata"', () => { it('should not emit any AOT class metadata functions', async () => { harness.useTarget('build', { ...BASE_OPTIONS, optimization: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js').content.not.toContain('setClassMetadata'); }); it('should not emit any AOT NgModule scope metadata functions', async () => { harness.useTarget('build', { ...BASE_OPTIONS, optimization: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js').content.not.toContain('setNgModuleScope'); }); }); });
{ "end_byte": 1221, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/behavior/angular-aot-metadata_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/behavior/typescript-resolve-json_spec.ts_0_3000
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Behavior: "TypeScript JSON module resolution"', () => { it('should resolve JSON files when imported with resolveJsonModule enabled', async () => { await harness.writeFiles({ 'src/x.json': `{"a": 1}`, 'src/main.ts': `import * as x from './x.json'; console.log(x);`, }); // Enable tsconfig resolveJsonModule option in tsconfig await harness.modifyFile('tsconfig.json', (content) => { const tsconfig = JSON.parse(content); tsconfig.compilerOptions.resolveJsonModule = true; return JSON.stringify(tsconfig); }); harness.useTarget('build', { ...BASE_OPTIONS, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); }); it('should fail to resolve with TS if resolveJsonModule is not present', async () => { await harness.writeFiles({ 'src/x.json': `{"a": 1}`, 'src/main.ts': `import * as x from './x.json'; console.log(x);`, }); // Enable tsconfig resolveJsonModule option in tsconfig await harness.modifyFile('tsconfig.json', (content) => { const tsconfig = JSON.parse(content); tsconfig.compilerOptions.resolveJsonModule = undefined; return JSON.stringify(tsconfig); }); harness.useTarget('build', { ...BASE_OPTIONS, }); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBe(false); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching(`Cannot find module './x.json'`), }), ); }); it('should fail to resolve with TS if resolveJsonModule is disabled', async () => { await harness.writeFiles({ 'src/x.json': `{"a": 1}`, 'src/main.ts': `import * as x from './x.json'; console.log(x);`, }); // Enable tsconfig resolveJsonModule option in tsconfig await harness.modifyFile('tsconfig.json', (content) => { const tsconfig = JSON.parse(content); tsconfig.compilerOptions.resolveJsonModule = false; return JSON.stringify(tsconfig); }); harness.useTarget('build', { ...BASE_OPTIONS, }); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBe(false); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching(`Cannot find module './x.json'`), }), ); }); }); });
{ "end_byte": 3000, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/behavior/typescript-resolve-json_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/behavior/index-preload-hints_spec.ts_0_1995
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Behavior: "Preload hints"', () => { it('should add preload hints for transitive global style imports', async () => { await harness.writeFile( 'src/styles.css', ` @import url('https://fonts.googleapis.com/css2?family=Roboto+Mono&family=Roboto:wght@300;400;500;700&display=swap'); `, ); harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.css'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/browser/index.html') .content.toContain( '<link rel="preload" href="https://fonts.googleapis.com/css2?family=Roboto+Mono&family=Roboto:wght@300;400;500;700&display=swap" as="style">', ); }); it('should not add preload hints for ssr files', async () => { await harness.modifyFile('src/tsconfig.app.json', (content) => { const tsConfig = JSON.parse(content); tsConfig.files ??= []; tsConfig.files.push('main.server.ts'); return JSON.stringify(tsConfig); }); harness.useTarget('build', { ...BASE_OPTIONS, server: 'src/main.server.ts', ssr: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/server/main.server.mjs').toExist(); harness .expectFile('dist/browser/index.csr.html') .content.not.toMatch(/<link rel="modulepreload" href="chunk-\.+\.mjs">/); }); }); });
{ "end_byte": 1995, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/behavior/index-preload-hints_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/behavior/web-workers-application_spec.ts_0_2037
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; /** * A regular expression used to check if a built worker is correctly referenced in application code. */ const REFERENCED_WORKER_REGEXP = /new Worker\(new URL\("worker-[A-Z0-9]{8}\.js", import\.meta\.url\)/; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Behavior: "Bundles web worker files within application code"', () => { it('should use the worker entry point when worker lazy chunks are present', async () => { harness.useTarget('build', { ...BASE_OPTIONS, }); const workerCodeFile = ` addEventListener('message', () => { import('./extra').then((m) => console.log(m.default)); }); `; const extraWorkerCodeFile = ` export default 'WORKER FILE'; `; // Create a worker file await harness.writeFile('src/app/worker.ts', workerCodeFile); await harness.writeFile('src/app/extra.ts', extraWorkerCodeFile); // 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: '<h1>Worker Test</h1>', }) export class AppComponent { worker = new Worker(new URL('./worker', import.meta.url), { type: 'module' }); } `, ); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); // Ensure built worker is referenced in the application code harness.expectFile('dist/browser/main.js').content.toMatch(REFERENCED_WORKER_REGEXP); }); }); });
{ "end_byte": 2037, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/behavior/web-workers-application_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/behavior/rebuild-errors_spec.ts_0_10281
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; /** * Maximum time in milliseconds for single build/rebuild * This accounts for CI variability. */ export const BUILD_TIMEOUT = 30_000; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Behavior: "Rebuild Error Detection"', () => { it('detects template errors with no AOT codegen or TS emit differences', async () => { harness.useTarget('build', { ...BASE_OPTIONS, 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 cumulative block syntax errors', async () => { harness.useTarget('build', { ...BASE_OPTIONS, watch: true, }); const buildCount = await harness .execute({ outputLogsOnFailure: false }) .pipe( timeout(BUILD_TIMEOUT), concatMap(async ({ logs }, index) => { switch (index) { case 0: // Add invalid block syntax await harness.appendToFile('src/app/app.component.html', '@one'); break; case 1: expect(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringContaining('@one'), }), ); // 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(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringContaining('@one'), }), ); // Add more invalid block syntax await harness.appendToFile('src/app/app.component.html', '@two'); break; case 3: expect(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringContaining('@one'), }), ); expect(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringContaining('@two'), }), ); // Add more invalid block syntax await harness.appendToFile('src/app/app.component.html', '@three'); break; case 4: expect(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringContaining('@one'), }), ); expect(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringContaining('@two'), }), ); expect(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringContaining('@three'), }), ); // Revert the changes that caused the error // Should remove the error await harness.writeFile('src/app/app.component.html', '<p>GOOD</p>'); break; case 5: expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringContaining('@one'), }), ); expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringContaining('@two'), }), ); expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringContaining('@three'), }), ); break; } }), take(6), count(), ) .toPromise(); expect(buildCount).toBe(6); }); 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: await harness.writeFile('src/app/app.component.css', 'invalid-css-content'); break; case 1: 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(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching('invalid-css-content'), }), ); harness .expectFile('dist/browser/main.js') .content.toContain('p {\\n color: green;\\n}'); break; } }), take(3), count(), ) .toPromise(); expect(buildCount).toBe(3); });
{ "end_byte": 10281, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/behavior/rebuild-errors_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/behavior/rebuild-errors_spec.ts_10287_12398
it('recovers from component template error', async () => { harness.useTarget('build', { ...BASE_OPTIONS, watch: true, }); const buildCount = await harness .execute({ outputLogsOnFailure: false }) .pipe( timeout(BUILD_TIMEOUT), concatMap(async ({ result, logs }, index) => { switch (index) { case 0: // Missing ending `>` on the div will cause an error await harness.appendToFile('src/app/app.component.html', '<div>Hello, world!</div'); break; case 1: expect(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching('Unexpected character "EOF"'), }), ); await harness.appendToFile('src/app/app.component.html', '>'); break; case 2: expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching('Unexpected character "EOF"'), }), ); harness.expectFile('dist/browser/main.js').content.toContain('Hello, world!'); // Make an additional valid change to ensure that rebuilds still trigger await harness.appendToFile('src/app/app.component.html', '<div>Guten Tag</div>'); break; case 3: expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching('invalid-css-content'), }), ); harness.expectFile('dist/browser/main.js').content.toContain('Hello, world!'); harness.expectFile('dist/browser/main.js').content.toContain('Guten Tag'); break; } }), take(4), count(), ) .toPromise(); expect(buildCount).toBe(4); }); }); });
{ "end_byte": 12398, "start_byte": 10287, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/behavior/rebuild-errors_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/behavior/rebuild-global_styles_spec.ts_0_6570
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; /** * Maximum time in milliseconds for single build/rebuild * This accounts for CI variability. */ export const BUILD_TIMEOUT = 30_000; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Behavior: "Rebuilds when global stylesheets change"', () => { beforeEach(async () => { // Application code is not needed for styles tests await harness.writeFile('src/main.ts', 'console.log("TEST");'); }); it('rebuilds Sass stylesheet after error on rebuild from import', async () => { harness.useTarget('build', { ...BASE_OPTIONS, watch: true, styles: ['src/styles.scss'], }); await harness.writeFile('src/styles.scss', "@import './a';"); await harness.writeFile('src/a.scss', '$primary: aqua;\\nh1 { color: $primary; }'); const buildCount = await harness .execute({ outputLogsOnFailure: false }) .pipe( timeout(30000), concatMap(async ({ result }, index) => { switch (index) { case 0: expect(result?.success).toBe(true); harness.expectFile('dist/browser/styles.css').content.toContain('color: aqua'); harness.expectFile('dist/browser/styles.css').content.not.toContain('color: blue'); await harness.writeFile( 'src/a.scss', 'invalid-invalid-invalid\\nh1 { color: $primary; }', ); break; case 1: expect(result?.success).toBe(false); await harness.writeFile('src/a.scss', '$primary: blue;\\nh1 { color: $primary; }'); break; case 2: expect(result?.success).toBe(true); harness.expectFile('dist/browser/styles.css').content.not.toContain('color: aqua'); harness.expectFile('dist/browser/styles.css').content.toContain('color: blue'); break; } }), take(3), count(), ) .toPromise(); expect(buildCount).toBe(3); }); it('rebuilds Sass stylesheet after error on initial build from import', async () => { harness.useTarget('build', { ...BASE_OPTIONS, watch: true, styles: ['src/styles.scss'], }); await harness.writeFile('src/styles.scss', "@import './a';"); await harness.writeFile('src/a.scss', 'invalid-invalid-invalid\\nh1 { color: $primary; }'); const buildCount = await harness .execute({ outputLogsOnFailure: false }) .pipe( timeout(30000), concatMap(async ({ result }, index) => { switch (index) { case 0: expect(result?.success).toBe(false); await harness.writeFile('src/a.scss', '$primary: aqua;\\nh1 { color: $primary; }'); break; case 1: expect(result?.success).toBe(true); harness.expectFile('dist/browser/styles.css').content.toContain('color: aqua'); harness.expectFile('dist/browser/styles.css').content.not.toContain('color: blue'); await harness.writeFile('src/a.scss', '$primary: blue;\\nh1 { color: $primary; }'); break; case 2: expect(result?.success).toBe(true); harness.expectFile('dist/browser/styles.css').content.not.toContain('color: aqua'); harness.expectFile('dist/browser/styles.css').content.toContain('color: blue'); break; } }), take(3), count(), ) .toPromise(); expect(buildCount).toBe(3); }); it('rebuilds dependent Sass stylesheets after error on initial build from import', async () => { harness.useTarget('build', { ...BASE_OPTIONS, watch: true, styles: [ { bundleName: 'styles', input: 'src/styles.scss' }, { bundleName: 'other', input: 'src/other.scss' }, ], }); await harness.writeFile('src/styles.scss', "@import './a';"); await harness.writeFile('src/other.scss', "@import './a'; h1 { color: green; }"); await harness.writeFile('src/a.scss', 'invalid-invalid-invalid\\nh1 { color: $primary; }'); const buildCount = await harness .execute({ outputLogsOnFailure: false }) .pipe( timeout(30000), concatMap(async ({ result }, index) => { switch (index) { case 0: expect(result?.success).toBe(false); await harness.writeFile('src/a.scss', '$primary: aqua;\\nh1 { color: $primary; }'); break; case 1: expect(result?.success).toBe(true); harness.expectFile('dist/browser/styles.css').content.toContain('color: aqua'); harness.expectFile('dist/browser/styles.css').content.not.toContain('color: blue'); harness.expectFile('dist/browser/other.css').content.toContain('color: green'); harness.expectFile('dist/browser/other.css').content.toContain('color: aqua'); harness.expectFile('dist/browser/other.css').content.not.toContain('color: blue'); await harness.writeFile('src/a.scss', '$primary: blue;\\nh1 { color: $primary; }'); break; case 2: expect(result?.success).toBe(true); harness.expectFile('dist/browser/styles.css').content.not.toContain('color: aqua'); harness.expectFile('dist/browser/styles.css').content.toContain('color: blue'); harness.expectFile('dist/browser/other.css').content.toContain('color: green'); harness.expectFile('dist/browser/other.css').content.not.toContain('color: aqua'); harness.expectFile('dist/browser/other.css').content.toContain('color: blue'); break; } }), take(3), count(), ) .toPromise(); expect(buildCount).toBe(3); }); }); });
{ "end_byte": 6570, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/behavior/rebuild-global_styles_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/behavior/csp-nonce_spec.ts_0_1208
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Behavior: "CSP Nonce"', () => { it('should add CSP nonce to scripts when optimization is disabled', async () => { await harness.modifyFile('src/index.html', (content) => content.replace(/<app-root/g, '<app-root ngCspNonce="{% nonce %}" '), ); harness.useTarget('build', { ...BASE_OPTIONS, polyfills: [], optimization: false, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); const indexFileContent = harness.expectFile('dist/browser/index.html').content; indexFileContent.toContain( '<script src="main.js" type="module" nonce="{% nonce %}"></script>', ); indexFileContent.toContain('<app-root ngcspnonce="{% nonce %}"'); }); }); });
{ "end_byte": 1208, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/behavior/csp-nonce_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/behavior/loader-import-attribute_spec.ts_0_5501
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Behavior: "loader import attribute"', () => { beforeEach(async () => { await harness.modifyFile('tsconfig.json', (content) => { return content.replace('"module": "ES2022"', '"module": "esnext"'); }); }); it('should inline text content for loader attribute set to "text"', async () => { harness.useTarget('build', { ...BASE_OPTIONS, }); await harness.writeFile('./src/a.unknown', 'ABC'); await harness.writeFile( 'src/main.ts', '// @ts-expect-error\nimport contents from "./a.unknown" with { loader: "text" };\n console.log(contents);', ); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js').content.toContain('ABC'); }); it('should inline binary content for loader attribute set to "binary"', async () => { harness.useTarget('build', { ...BASE_OPTIONS, }); await harness.writeFile('./src/a.unknown', 'ABC'); await harness.writeFile( 'src/main.ts', '// @ts-expect-error\nimport contents from "./a.unknown" with { loader: "binary" };\n console.log(contents);', ); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); // Should contain the binary encoding used esbuild and not the text content harness.expectFile('dist/browser/main.js').content.toContain('__toBinary("QUJD")'); harness.expectFile('dist/browser/main.js').content.not.toContain('ABC'); }); it('should emit an output file for loader attribute set to "file"', async () => { harness.useTarget('build', { ...BASE_OPTIONS, }); await harness.writeFile('./src/a.unknown', 'ABC'); await harness.writeFile( 'src/main.ts', '// @ts-expect-error\nimport contents from "./a.unknown" with { loader: "file" };\n console.log(contents);', ); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js').content.toContain('a.unknown'); harness.expectFile('dist/browser/media/a.unknown').toExist(); }); it('should emit an output file with hashing when enabled for loader attribute set to "file"', async () => { harness.useTarget('build', { ...BASE_OPTIONS, // eslint-disable-next-line @typescript-eslint/no-explicit-any outputHashing: 'media' as any, }); await harness.writeFile('./src/a.unknown', 'ABC'); await harness.writeFile( 'src/main.ts', '// @ts-expect-error\nimport contents from "./a.unknown" with { loader: "file" };\n console.log(contents);', ); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js').content.toContain('a.unknown'); expect(harness.hasFileMatch('dist/browser/media', /a-[0-9A-Z]{8}\.unknown$/)).toBeTrue(); }); it('should allow overriding default `.txt` extension behavior', async () => { harness.useTarget('build', { ...BASE_OPTIONS, }); await harness.writeFile('./src/a.txt', 'ABC'); await harness.writeFile( 'src/main.ts', '// @ts-expect-error\nimport contents from "./a.txt" with { loader: "file" };\n console.log(contents);', ); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js').content.toContain('a.txt'); harness.expectFile('dist/browser/media/a.txt').toExist(); }); it('should allow overriding default `.js` extension behavior', async () => { harness.useTarget('build', { ...BASE_OPTIONS, }); await harness.writeFile('./src/a.js', 'ABC'); await harness.writeFile( 'src/main.ts', '// @ts-expect-error\nimport contents from "./a.js" with { loader: "file" };\n console.log(contents);', ); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js').content.toContain('a.js'); harness.expectFile('dist/browser/media/a.js').toExist(); }); it('should fail with an error if an invalid loader attribute value is used', async () => { harness.useTarget('build', { ...BASE_OPTIONS, }); harness.useTarget('build', { ...BASE_OPTIONS, }); await harness.writeFile('./src/a.unknown', 'ABC'); await harness.writeFile( 'src/main.ts', '// @ts-expect-error\nimport contents from "./a.unknown" with { loader: "invalid" };\n console.log(contents);', ); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBe(false); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching('Unsupported loader import attribute'), }), ); }); }); });
{ "end_byte": 5501, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/behavior/loader-import-attribute_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/behavior/typescript-rebuild-lazy_spec.ts_0_2960
/** * @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 { logging } from '@angular-devkit/core'; import { concatMap, count, firstValueFrom, take, timeout } from 'rxjs'; import { buildApplication } from '../../index'; import { OutputHashing } from '../../schema'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { beforeEach(async () => { await harness.modifyFile('src/tsconfig.app.json', (content) => { const tsConfig = JSON.parse(content); tsConfig.files = ['main.server.ts', 'main.ts']; return JSON.stringify(tsConfig); }); await harness.writeFiles({ 'src/lazy.ts': `export const foo: number = 1;`, 'src/main.ts': `export async function fn () { const lazy = await import('./lazy'); return lazy.foo; }`, 'src/main.server.ts': `export { fn as default } from './main';`, }); }); describe('Behavior: "Rebuild both server and browser bundles when using lazy loading"', () => { it('detect changes and errors when expected', async () => { harness.useTarget('build', { ...BASE_OPTIONS, watch: true, namedChunks: true, outputHashing: OutputHashing.None, server: 'src/main.server.ts', ssr: true, }); const buildCount = await firstValueFrom( harness.execute({ outputLogsOnFailure: false }).pipe( timeout(30_000), concatMap(async ({ result, logs }, index) => { switch (index) { case 0: expect(result?.success).toBeTrue(); // Add valid code await harness.appendToFile('src/lazy.ts', `console.log('foo');`); break; case 1: expect(result?.success).toBeTrue(); // Update type of 'foo' to invalid (number -> string) await harness.writeFile('src/lazy.ts', `export const foo: string = 1;`); break; case 2: expect(result?.success).toBeFalse(); expect(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching( `Type 'number' is not assignable to type 'string'.`, ), }), ); // Fix TS error await harness.writeFile('src/lazy.ts', `export const foo: string = "1";`); break; case 3: expect(result?.success).toBeTrue(); break; } }), take(4), count(), ), ); expect(buildCount).toBe(4); }); }); });
{ "end_byte": 2960, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/behavior/typescript-rebuild-lazy_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/behavior/rebuild-component_styles_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 { concatMap, count, take, timeout } from 'rxjs'; import { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; /** * Maximum time in milliseconds for single build/rebuild * This accounts for CI variability. */ export const BUILD_TIMEOUT = 30_000; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Behavior: "Rebuilds when component stylesheets change"', () => { for (const aot of [true, false]) { it(`updates component when imported sass changes with ${aot ? 'AOT' : 'JIT'}`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, watch: true, aot, }); await harness.modifyFile('src/app/app.component.ts', (content) => content.replace('app.component.css', 'app.component.scss'), ); await harness.writeFile('src/app/app.component.scss', "@import './a';"); await harness.writeFile('src/app/a.scss', '$primary: aqua;\\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/browser/main.js').content.toContain('color: aqua'); harness.expectFile('dist/browser/main.js').content.not.toContain('color: blue'); await harness.writeFile( 'src/app/a.scss', '$primary: blue;\\nh1 { color: $primary; }', ); break; case 1: harness.expectFile('dist/browser/main.js').content.not.toContain('color: aqua'); harness.expectFile('dist/browser/main.js').content.toContain('color: blue'); await harness.writeFile( 'src/app/a.scss', '$primary: green;\\nh1 { color: $primary; }', ); break; case 2: harness.expectFile('dist/browser/main.js').content.not.toContain('color: aqua'); harness.expectFile('dist/browser/main.js').content.not.toContain('color: blue'); harness.expectFile('dist/browser/main.js').content.toContain('color: green'); break; } }), take(3), count(), ) .toPromise(); expect(buildCount).toBe(3); }); } }); });
{ "end_byte": 2853, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/behavior/rebuild-component_styles_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/behavior/typescript-incremental_spec.ts_0_1025
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Behavior: "TypeScript explicit incremental option usage"', () => { it('should successfully build with incremental disabled', async () => { // Disable tsconfig incremental option in tsconfig await harness.modifyFile('tsconfig.json', (content) => { const tsconfig = JSON.parse(content); tsconfig.compilerOptions.incremental = false; return JSON.stringify(tsconfig); }); harness.useTarget('build', { ...BASE_OPTIONS, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); }); }); });
{ "end_byte": 1025, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/behavior/typescript-incremental_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/assets_spec.ts_0_4062
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Option: "assets"', () => { beforeEach(async () => { // Application code is not needed for asset tests await harness.writeFile('src/main.ts', 'console.log("TEST");'); }); 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/browser/extra.file').content.toBe('extra file'); harness.expectFile('dist/browser/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/browser/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/browser/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/browser/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/browser/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/browser/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/browser/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 { error } = await harness.executeOnce({ outputLogsOnException: false }); expect(error?.message).toMatch('path must start with the project source root'); harness.expectFile('dist/browser/test.svg').toNotExist(); }); });
{ "end_byte": 4062, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/assets_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/assets_spec.ts_4068_12973
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/browser/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/browser/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/browser/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/browser/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/browser/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/browser/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/browser/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/browser/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/browser/another.file').content.toBe('asset file'); harness.expectFile('dist/browser/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/browser/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/browser/another.file').toNotExist(); harness.expectFile('dist/browser/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/browser/test.svg').content.toBe('<svg></svg>'); harness.expectFile('dist/browser/another.file').toNotExist(); harness.expectFile('dist/browser/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/browser/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/browser/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/browser/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/browser/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/browser/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/browser/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 { error } = await harness.executeOnce({ outputLogsOnException: false }); expect(error?.message).toMatch( 'An asset cannot be written to a location outside of the output path', ); harness.expectFile('dist/browser/test.svg').toNotExist(); }); }); }); });
{ "end_byte": 12973, "start_byte": 4068, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/assets_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/app-shell_spec.ts_0_5851
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; const appShellRouteFiles: Record<string, string> = { 'src/styles.css': `p { color: #000 }`, 'src/app/app-shell/app-shell.component.ts': ` import { Component } from '@angular/core'; @Component({ selector: 'app-app-shell', standalone: false, styles: ['div { color: #fff; }'], template: '<p>app-shell works!</p>', }) export class AppShellComponent {}`, 'src/main.server.ts': ` import { AppServerModule } from './app/app.module.server'; export default AppServerModule; `, 'src/app/app.module.ts': ` import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { RouterModule } from '@angular/router'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, RouterModule ], bootstrap: [AppComponent] }) export class AppModule { } `, 'src/app/app.module.server.ts': ` import { NgModule } from '@angular/core'; import { ServerModule } from '@angular/platform-server'; import { AppModule } from './app.module'; import { AppComponent } from './app.component'; import { Routes, RouterModule } from '@angular/router'; import { AppShellComponent } from './app-shell/app-shell.component'; const routes: Routes = [ { path: 'shell', component: AppShellComponent }]; @NgModule({ imports: [ AppModule, ServerModule, RouterModule.forRoot(routes), ], bootstrap: [AppComponent], declarations: [AppShellComponent], }) export class AppServerModule {} `, 'src/main.ts': ` import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; platformBrowserDynamic().bootstrapModule(AppModule).catch(err => console.log(err)); `, 'src/app/app-routing.module.ts': ` import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; const routes: Routes = []; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } `, 'src/app/app.component.html': `<router-outlet></router-outlet>`, }; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { beforeEach(async () => { await harness.modifyFile('src/tsconfig.app.json', (content) => { const tsConfig = JSON.parse(content); tsConfig.files ??= []; tsConfig.files.push('main.server.ts'); return JSON.stringify(tsConfig); }); await harness.writeFiles(appShellRouteFiles); }); describe('Option: "appShell"', () => { it('renders the application shell', async () => { harness.useTarget('build', { ...BASE_OPTIONS, server: 'src/main.server.ts', polyfills: ['zone.js'], appShell: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/main.js').toExist(); const indexFileContent = harness.expectFile('dist/browser/index.html').content; indexFileContent.toContain('app-shell works!'); // TODO(alanagius): enable once integration of routes in complete. // indexFileContent.toContain('ng-server-context="app-shell"'); }); it('critical CSS is inlined', async () => { harness.useTarget('build', { ...BASE_OPTIONS, server: 'src/main.server.ts', polyfills: ['zone.js'], appShell: true, styles: ['src/styles.css'], optimization: { styles: { minify: true, inlineCritical: true, }, }, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); const indexFileContent = harness.expectFile('dist/browser/index.html').content; indexFileContent.toContain('app-shell works!'); indexFileContent.toContain('p{color:#000}'); indexFileContent.toContain( `<link rel="stylesheet" href="styles.css" media="print" onload="this.media='all'">`, ); }); it('applies CSP nonce to critical CSS', async () => { await harness.modifyFile('src/index.html', (content) => content.replace(/<app-root/g, '<app-root ngCspNonce="{% nonce %}" '), ); harness.useTarget('build', { ...BASE_OPTIONS, server: 'src/main.server.ts', polyfills: ['zone.js'], appShell: true, styles: ['src/styles.css'], optimization: { styles: { minify: true, inlineCritical: true, }, }, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); const indexFileContent = harness.expectFile('dist/browser/index.html').content; indexFileContent.toContain('app-shell works!'); indexFileContent.toContain('p{color:#000}'); indexFileContent.toContain( `<link rel="stylesheet" href="styles.css" media="print" ngCspMedia="all">`, ); indexFileContent.toContain('<style nonce="{% nonce %}">p{color:#000}'); indexFileContent.toContain('<style nonce="{% nonce %}" ng-app-id="ng">'); indexFileContent.toContain('<app-root ngcspnonce="{% nonce %}"'); }); }); });
{ "end_byte": 5851, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/app-shell_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/optimization-inline-critical_spec.ts_0_4407
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_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/browser/index.html') .content.toContain( `<link rel="stylesheet" href="styles.css" media="print" onload="this.media='all'">`, ); harness.expectFile('dist/browser/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/browser/index.html') .content.toContain( `<link rel="stylesheet" href="styles.css" media="print" onload="this.media='all'">`, ); harness.expectFile('dist/browser/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/browser/index.html') .content.toContain( `<link rel="stylesheet" href="styles.css" media="print" onload="this.media='all'">`, ); harness.expectFile('dist/browser/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/browser/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/browser/index.html').content.not.toContain(`<style`); }); 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/browser/index.html') .content.toContain( `<link rel="stylesheet" href="styles.css" media="print" onload="this.media='all'">`, ); harness.expectFile('dist/browser/index.html').content.toContain(`body{color:#000}`); }); }); });
{ "end_byte": 4407, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/optimization-inline-critical_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/inline-style-language_spec.ts_0_5439
/** * @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 { buildApplication } from '../../index'; import { InlineStyleLanguage } from '../../schema'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_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/browser/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/browser/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/browser/main.js').content.toContain('color: indianred'); }); it('updates produced stylesheet in watch mode', async () => { harness.useTarget('build', { ...BASE_OPTIONS, 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/browser/main.js') .content.toContain('color: indianred'); harness.expectFile('dist/browser/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/browser/main.js') .content.not.toContain('color: indianred'); harness.expectFile('dist/browser/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/browser/main.js') .content.not.toContain('color: indianred'); harness.expectFile('dist/browser/main.js').content.not.toContain('color: aqua'); harness.expectFile('dist/browser/main.js').content.toContain('color: blue'); break; } }), take(3), count(), ) .toPromise(); expect(buildCount).toBe(3); }); }); } }); });
{ "end_byte": 5439, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/inline-style-language_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/bundle-budgets_spec.ts_0_7811
/** * @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 { buildApplication } from '../../index'; import { Type } from '../../schema'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder, lazyModuleFiles, lazyModuleFnImport, } from '../setup'; describeBuilder(buildApplication, APPLICATION_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).toBeFalse(); 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-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-module exceeded maximum budget'), }), ); }); it(`should not warn when non-injected style is not within the baseline threshold`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, optimization: false, styles: [ { input: 'src/lazy-styles.css', inject: false, bundleName: 'lazy-styles', }, ], budgets: [ { type: Type.Bundle, name: 'lazy-styles', warning: '1kb', error: '1kb', baseline: '2kb' }, ], }); await harness.writeFile( 'src/lazy-styles.css', ` .foo { color: green; padding: 1px; } `.repeat(24), ); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBeTrue(); expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ level: 'warn', message: jasmine.stringMatching('lazy-styles failed to meet minimum 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(`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": 7811, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/bundle-budgets_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/loader_spec.ts_0_8770
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Option: "loader"', () => { it('should error for an unknown file extension', async () => { harness.useTarget('build', { ...BASE_OPTIONS, }); await harness.writeFile( './src/types.d.ts', 'declare module "*.unknown" { const content: string; export default content; }', ); await harness.writeFile('./src/a.unknown', 'ABC'); await harness.writeFile( 'src/main.ts', 'import contents from "./a.unknown";\n console.log(contents);', ); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBe(false); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching( 'No loader is configured for ".unknown" files: src/a.unknown', ), }), ); }); it('should not include content for file extension set to "empty"', async () => { harness.useTarget('build', { ...BASE_OPTIONS, loader: { '.unknown': 'empty', }, }); await harness.writeFile( './src/types.d.ts', 'declare module "*.unknown" { const content: string; export default content; }', ); await harness.writeFile('./src/a.unknown', 'ABC'); await harness.writeFile( 'src/main.ts', 'import contents from "./a.unknown";\n console.log(contents);', ); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js').content.not.toContain('ABC'); }); it('should inline text content for file extension set to "text"', async () => { harness.useTarget('build', { ...BASE_OPTIONS, loader: { '.unknown': 'text', }, }); await harness.writeFile( './src/types.d.ts', 'declare module "*.unknown" { const content: string; export default content; }', ); await harness.writeFile('./src/a.unknown', 'ABC'); await harness.writeFile( 'src/main.ts', 'import contents from "./a.unknown";\n console.log(contents);', ); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js').content.toContain('ABC'); }); it('should inline binary content for file extension set to "binary"', async () => { harness.useTarget('build', { ...BASE_OPTIONS, loader: { '.unknown': 'binary', }, }); await harness.writeFile( './src/types.d.ts', 'declare module "*.unknown" { const content: Uint8Array; export default content; }', ); await harness.writeFile('./src/a.unknown', 'ABC'); await harness.writeFile( 'src/main.ts', 'import contents from "./a.unknown";\n console.log(contents);', ); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); // Should contain the binary encoding used esbuild and not the text content harness.expectFile('dist/browser/main.js').content.toContain('__toBinary("QUJD")'); harness.expectFile('dist/browser/main.js').content.not.toContain('ABC'); }); it('should emit an output file for file extension set to "file"', async () => { harness.useTarget('build', { ...BASE_OPTIONS, loader: { '.unknown': 'file', }, }); await harness.writeFile( './src/types.d.ts', 'declare module "*.unknown" { const location: string; export default location; }', ); await harness.writeFile('./src/a.unknown', 'ABC'); await harness.writeFile( 'src/main.ts', 'import contents from "./a.unknown";\n console.log(contents);', ); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js').content.toContain('a.unknown'); harness.expectFile('dist/browser/media/a.unknown').toExist(); }); it('should emit an output file with hashing when enabled for file extension set to "file"', async () => { harness.useTarget('build', { ...BASE_OPTIONS, // eslint-disable-next-line @typescript-eslint/no-explicit-any outputHashing: 'media' as any, loader: { '.unknown': 'file', }, }); await harness.writeFile( './src/types.d.ts', 'declare module "*.unknown" { const location: string; export default location; }', ); await harness.writeFile('./src/a.unknown', 'ABC'); await harness.writeFile( 'src/main.ts', 'import contents from "./a.unknown";\n console.log(contents);', ); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js').content.toContain('a.unknown'); expect(harness.hasFileMatch('dist/browser/media', /a-[0-9A-Z]{8}\.unknown$/)).toBeTrue(); }); it('should inline text content for `.txt` by default', async () => { harness.useTarget('build', { ...BASE_OPTIONS, loader: undefined, }); await harness.writeFile( './src/types.d.ts', 'declare module "*.txt" { const content: string; export default content; }', ); await harness.writeFile('./src/a.txt', 'ABC'); await harness.writeFile( 'src/main.ts', 'import contents from "./a.txt";\n console.log(contents);', ); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js').content.toContain('ABC'); }); it('should inline text content for `.txt` by default when other extensions are defined', async () => { harness.useTarget('build', { ...BASE_OPTIONS, loader: { '.unknown': 'binary', }, }); await harness.writeFile( './src/types.d.ts', 'declare module "*.txt" { const content: string; export default content; }', ); await harness.writeFile('./src/a.txt', 'ABC'); await harness.writeFile( 'src/main.ts', 'import contents from "./a.txt";\n console.log(contents);', ); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js').content.toContain('ABC'); }); it('should allow overriding default `.txt` extension behavior', async () => { harness.useTarget('build', { ...BASE_OPTIONS, loader: { '.txt': 'file', }, }); await harness.writeFile( './src/types.d.ts', 'declare module "*.txt" { const location: string; export default location; }', ); await harness.writeFile('./src/a.txt', 'ABC'); await harness.writeFile( 'src/main.ts', 'import contents from "./a.txt";\n console.log(contents);', ); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js').content.toContain('a.txt'); harness.expectFile('dist/browser/media/a.txt').toExist(); }); // Schema validation will prevent this from happening for supported use-cases. // This will only happen if used programmatically and the option value is set incorrectly. it('should ignore entry if an invalid loader name is used', async () => { harness.useTarget('build', { ...BASE_OPTIONS, loader: { '.unknown': 'invalid', }, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); }); // Schema validation will prevent this from happening for supported use-cases. // This will only happen if used programmatically and the option value is set incorrectly. it('should ignore entry if an extension does not start with a period', async () => { harness.useTarget('build', { ...BASE_OPTIONS, loader: { 'unknown': 'text', }, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); }); }); });
{ "end_byte": 8770, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/loader_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/server_spec.ts_0_3151
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { beforeEach(async () => { await harness.modifyFile('src/tsconfig.app.json', (content) => { const tsConfig = JSON.parse(content); tsConfig.files ??= []; tsConfig.files.push('main.server.ts'); return JSON.stringify(tsConfig); }); }); describe('Option: "server"', () => { it('uses a provided TypeScript file', async () => { harness.useTarget('build', { ...BASE_OPTIONS, ssr: true, server: 'src/main.server.ts', }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/main.js').toExist(); }); it('does not write file to disk when "ssr" is "false"', async () => { harness.useTarget('build', { ...BASE_OPTIONS, ssr: true, server: 'src/main.server.ts', }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/main.js').toExist(); }); it('uses a provided JavaScript file', async () => { await harness.writeFile('src/server.js', `console.log('server'); export default {};`); harness.useTarget('build', { ...BASE_OPTIONS, ssr: true, server: 'src/server.js', }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); }); it('fails and shows an error when file does not exist', async () => { harness.useTarget('build', { ...BASE_OPTIONS, ssr: true, server: 'src/missing.ts', }); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBeFalse(); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching('Could not resolve "') }), ); harness.expectFile('dist/browser/main.js').toNotExist(); }); it('throws an error when given an empty string', async () => { harness.useTarget('build', { ...BASE_OPTIONS, ssr: true, server: '', }); const { result, error } = await harness.executeOnce({ outputLogsOnException: false }); expect(result).toBeUndefined(); expect(error?.message).toContain('cannot be an empty string'); }); it('resolves an absolute path as relative inside the workspace root', async () => { await harness.writeFile('file.mjs', `console.log('Hello!'); export default {};`); harness.useTarget('build', { ...BASE_OPTIONS, ssr: true, server: '/file.mjs', }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); }); }); });
{ "end_byte": 3151, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/server_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/i18n-missing-translation_spec.ts_0_7242
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Option: "i18nMissingTranslation"', () => { beforeEach(() => { harness.useProject('test', { root: '.', sourceRoot: 'src', cli: { cache: { enabled: false, }, }, i18n: { locales: { 'fr': 'src/locales/messages.fr.xlf', }, }, }); }); it('should warn when i18nMissingTranslation is undefined (default)', async () => { harness.useTarget('build', { ...BASE_OPTIONS, localize: true, i18nMissingTranslation: undefined, }); 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', MISSING_TRANSLATION_FILE_CONTENT); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBeTrue(); expect(logs).toContain( jasmine.objectContaining({ level: 'warn', message: jasmine.stringMatching('No translation found for'), }), ); }); it('should warn when i18nMissingTranslation is set to warning', async () => { harness.useTarget('build', { ...BASE_OPTIONS, localize: true, // eslint-disable-next-line @typescript-eslint/no-explicit-any i18nMissingTranslation: 'warning' as any, }); 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', MISSING_TRANSLATION_FILE_CONTENT); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBeTrue(); expect(logs).toContain( jasmine.objectContaining({ level: 'warn', message: jasmine.stringMatching('No translation found for'), }), ); }); it('should error when i18nMissingTranslation is set to error', async () => { harness.useTarget('build', { ...BASE_OPTIONS, localize: true, // eslint-disable-next-line @typescript-eslint/no-explicit-any i18nMissingTranslation: 'error' as any, }); 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', MISSING_TRANSLATION_FILE_CONTENT); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBeFalse(); expect(logs).toContain( jasmine.objectContaining({ level: 'error', message: jasmine.stringMatching('No translation found for'), }), ); }); it('should not error or warn when i18nMissingTranslation is set to ignore', async () => { harness.useTarget('build', { ...BASE_OPTIONS, localize: true, // eslint-disable-next-line @typescript-eslint/no-explicit-any i18nMissingTranslation: 'ignore' as any, }); 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', MISSING_TRANSLATION_FILE_CONTENT); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBeTrue(); expect(logs).not.toContain( jasmine.objectContaining({ message: jasmine.stringMatching('No translation found for'), }), ); }); it('should not error or warn when i18nMissingTranslation is set to error and all found', async () => { harness.useTarget('build', { ...BASE_OPTIONS, localize: true, // eslint-disable-next-line @typescript-eslint/no-explicit-any i18nMissingTranslation: 'error' as any, }); 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', GOOD_TRANSLATION_FILE_CONTENT); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBeTrue(); expect(logs).not.toContain( jasmine.objectContaining({ message: jasmine.stringMatching('No translation found for'), }), ); }); it('should not error or warn when i18nMissingTranslation is set to warning and all found', async () => { harness.useTarget('build', { ...BASE_OPTIONS, localize: true, // eslint-disable-next-line @typescript-eslint/no-explicit-any i18nMissingTranslation: 'warning' as any, }); 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', GOOD_TRANSLATION_FILE_CONTENT); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBeTrue(); expect(logs).not.toContain( jasmine.objectContaining({ message: jasmine.stringMatching('No translation found for'), }), ); }); }); }); const GOOD_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="fr" 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> `; const MISSING_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="fr" datatype="plaintext" original="ng2.template"> <body> </body> </file> </xliff> `;
{ "end_byte": 7242, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/i18n-missing-translation_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/base-href_spec.ts_0_3428
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Option: "baseHref"', () => { beforeEach(async () => { // Application code is not needed for asset tests await harness.writeFile('src/main.ts', 'console.log("TEST");'); }); it('should update the base element href attribute when option is set', async () => { harness.useTarget('build', { ...BASE_OPTIONS, baseHref: '/abc', }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/index.html').content.toContain('<base href="/abc">'); }); it('should update the base element with no href attribute when option is set', async () => { await harness.writeFile( 'src/index.html', ` <html> <head><base></head> <body></body> </html> `, ); harness.useTarget('build', { ...BASE_OPTIONS, baseHref: '/abc', }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/index.html').content.toContain('<base href="/abc">'); }); it('should add the base element href attribute when option is set', async () => { await harness.writeFile( 'src/index.html', ` <html> <head></head> <body></body> </html> `, ); harness.useTarget('build', { ...BASE_OPTIONS, baseHref: '/abc', }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/index.html').content.toContain('<base href="/abc">'); }); it('should update the base element href attribute when option is set to an empty string', async () => { harness.useTarget('build', { ...BASE_OPTIONS, baseHref: '', }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/index.html').content.toContain('<base href="">'); }); it('should not update the base element href attribute when option is not present', async () => { harness.useTarget('build', { ...BASE_OPTIONS, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/index.html').content.toContain('<base href="/">'); }); it('should not change the base element href attribute when option is not present', async () => { await harness.writeFile( 'src/index.html', ` <html> <head><base href="."></head> <body></body> </html> `, ); harness.useTarget('build', { ...BASE_OPTIONS, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/index.html').content.toContain('<base href=".">'); }); }); });
{ "end_byte": 3428, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/base-href_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/subresource-integrity_spec.ts_0_2324
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_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/browser/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/browser/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/browser/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/browser/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": 2324, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/subresource-integrity_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/sourcemap_spec.ts_0_7974
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Option: "sourceMap"', () => { it('should not generate script sourcemap files by default', async () => { harness.useTarget('build', { ...BASE_OPTIONS, sourceMap: undefined, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js.map').toNotExist(); }); it('should not generate script sourcemap files when false', async () => { harness.useTarget('build', { ...BASE_OPTIONS, sourceMap: false, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js.map').toNotExist(); }); it('should not generate script sourcemap files when scripts suboption is false', async () => { harness.useTarget('build', { ...BASE_OPTIONS, sourceMap: { scripts: false }, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js.map').toNotExist(); }); it('should generate script sourcemap files when true', async () => { harness.useTarget('build', { ...BASE_OPTIONS, sourceMap: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js.map').toExist(); }); it('should generate script sourcemap files when scripts suboption is true', async () => { harness.useTarget('build', { ...BASE_OPTIONS, sourceMap: { scripts: true }, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js.map').toExist(); }); it('should not include third-party sourcemaps when true', async () => { await harness.writeFile('src/polyfills.js', `console.log('main');`); harness.useTarget('build', { ...BASE_OPTIONS, sourceMap: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js.map').content.not.toContain('/core/index.ts'); harness.expectFile('dist/browser/main.js.map').content.not.toContain('/common/index.ts'); }); it('should not include third-party sourcemaps when vendor suboption is false', async () => { await harness.writeFile('src/polyfills.js', `console.log('main');`); harness.useTarget('build', { ...BASE_OPTIONS, sourceMap: { scripts: true, vendor: false }, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js.map').content.not.toContain('/core/index.ts'); harness.expectFile('dist/browser/main.js.map').content.not.toContain('/common/index.ts'); }); it('should include third-party sourcemaps when vendor suboption is true', async () => { await harness.writeFile('src/polyfills.js', `console.log('main');`); harness.useTarget('build', { ...BASE_OPTIONS, sourceMap: { scripts: true, vendor: true }, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js.map').content.toContain('/core/index.ts'); harness.expectFile('dist/browser/main.js.map').content.toContain('/common/index.ts'); }); it(`should not include 'sourceMappingURL' sourcemaps when hidden suboption is true`, async () => { await harness.writeFile('src/styles.css', `div { flex: 1 }`); harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.css'], sourceMap: { scripts: true, styles: true, hidden: true }, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/main.js.map').toExist(); harness .expectFile('dist/browser/main.js') .content.not.toContain('sourceMappingURL=main.js.map'); harness.expectFile('dist/browser/styles.css.map').toExist(); harness .expectFile('dist/browser/styles.css') .content.not.toContain('sourceMappingURL=styles.css.map'); }); it(`should include 'sourceMappingURL' sourcemaps when hidden suboption is false`, async () => { await harness.writeFile('src/styles.css', `div { flex: 1 }`); harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.css'], sourceMap: { scripts: true, styles: true, hidden: false }, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/main.js.map').toExist(); harness.expectFile('dist/browser/main.js').content.toContain('sourceMappingURL=main.js.map'); harness.expectFile('dist/browser/styles.css.map').toExist(); harness .expectFile('dist/browser/styles.css') .content.toContain('sourceMappingURL=styles.css.map'); }); it(`should include 'sourceMappingURL' sourcemaps when hidden suboption is not set`, async () => { await harness.writeFile('src/styles.css', `div { flex: 1 }`); harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.css'], sourceMap: { scripts: true, styles: true }, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/main.js.map').toExist(); harness.expectFile('dist/browser/main.js').content.toContain('sourceMappingURL=main.js.map'); harness.expectFile('dist/browser/styles.css.map').toExist(); harness .expectFile('dist/browser/styles.css') .content.toContain('sourceMappingURL=styles.css.map'); }); it('should add "x_google_ignoreList" extension to script sourcemap files when true', async () => { harness.useTarget('build', { ...BASE_OPTIONS, sourceMap: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js.map').content.toContain('"x_google_ignoreList"'); }); it('should generate component sourcemaps when sourcemaps when true', async () => { await harness.writeFile('src/app/app.component.css', `* { color: red}`); harness.useTarget('build', { ...BASE_OPTIONS, sourceMap: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness .expectFile('dist/browser/main.js') .content.toContain('sourceMappingURL=app.component.css.map'); harness.expectFile('dist/browser/app.component.css.map').toExist(); }); it('should not generate component sourcemaps when sourcemaps when false', async () => { await harness.writeFile('src/app/app.component.css', `* { color: red}`); harness.useTarget('build', { ...BASE_OPTIONS, sourceMap: false, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness .expectFile('dist/browser/main.js') .content.not.toContain('sourceMappingURL=app.component.css.map'); harness.expectFile('dist/browser/app.component.css.map').toNotExist(); }); }); });
{ "end_byte": 7974, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/sourcemap_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/allowed-common-js-dependencies_spec.ts_0_6363
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_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 'buffer';`); harness.useTarget('build', { ...BASE_OPTIONS, allowedCommonJsDependencies: [], optimization: true, aot, }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching( /Module 'buffer' used by 'src\/app\/app\.component\.ts' is not ESM/, ), }), ); expect(logs).toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching(/CommonJS or AMD dependencies/), }), ); expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching('base64-js'), }), '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 'buffer'; `, ); harness.useTarget('build', { ...BASE_OPTIONS, allowedCommonJsDependencies: ['buffer', 'base64-js', 'ieee754'], optimization: true, }); 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 'buffer'; `, ); harness.useTarget('build', { ...BASE_OPTIONS, allowedCommonJsDependencies: ['*'], optimization: true, }); 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 depending on zone.js', async () => { // Add a Common JS dependency await harness.appendToFile( 'src/app/app.component.ts', ` import 'zone.js'; `, ); harness.useTarget('build', { ...BASE_OPTIONS, allowedCommonJsDependencies: [], optimization: true, }); 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: [], optimization: true, }); 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: [], optimization: true, 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/), }), ); }); it('should not show warning for relative imports', async () => { await harness.appendToFile('src/main.ts', `import './abc';`); await harness.writeFile('src/abc.ts', 'console.log("abc");'); harness.useTarget('build', { ...BASE_OPTIONS, allowedCommonJsDependencies: [], optimization: true, }); 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": 6363, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/allowed-common-js-dependencies_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/output-path_spec.ts_0_2497
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { beforeEach(async () => { // Add a global stylesheet media file await harness.writeFile('src/styles.css', `h1 { background: url('./spectrum.png')}`); // Add a component stylesheet media file await harness.writeFile('src/app/abc.svg', ''); await harness.writeFile('src/app/app.component.css', `h2 { background: url('./abc.svg')}`); // Enable SSR await harness.modifyFile('src/tsconfig.app.json', (content) => { const tsConfig = JSON.parse(content); tsConfig.files ??= []; tsConfig.files.push('main.server.ts', 'server.ts'); return JSON.stringify(tsConfig); }); // Application server code is not needed in this test await harness.writeFile('src/main.server.ts', `console.log('Hello!');`); await harness.writeFile('src/server.ts', `console.log('Hello!');`); }); describe('Option: "outputPath"', () => { describe(`when option value is is a string`, () => { beforeEach(() => { harness.useTarget('build', { ...BASE_OPTIONS, polyfills: [], outputPath: 'dist', styles: ['src/styles.css'], server: 'src/main.server.ts', ssr: { entry: 'src/server.ts', }, }); }); it(`should emit browser bundles in 'browser' directory`, async () => { const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/main.js').toExist(); }); it(`should emit media files in 'browser/media' directory`, async () => { const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/media/spectrum.png').toExist(); harness.expectFile('dist/browser/media/abc.svg').toExist(); }); it(`should emit server bundles in 'server' directory`, async () => { const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/server/server.mjs').toExist(); }); });
{ "end_byte": 2497, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/output-path_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/output-path_spec.ts_2503_12190
describe(`when option value is an object`, () => { describe(`'media' is set to 'resources'`, () => { beforeEach(() => { harness.useTarget('build', { ...BASE_OPTIONS, polyfills: [], styles: ['src/styles.css'], server: 'src/main.server.ts', outputPath: { base: 'dist', media: 'resource', }, ssr: { entry: 'src/server.ts', }, }); }); it(`should emit browser bundles in 'browser' directory`, async () => { const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/main.js').toExist(); }); it(`should emit media files in 'browser/resource' directory`, async () => { const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/resource/spectrum.png').toExist(); harness.expectFile('dist/browser/resource/abc.svg').toExist(); }); it(`should emit server bundles in 'server' directory`, async () => { const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/server/server.mjs').toExist(); }); }); describe(`'media' is set to ''`, () => { beforeEach(() => { harness.useTarget('build', { ...BASE_OPTIONS, polyfills: [], styles: ['src/styles.css'], server: 'src/main.server.ts', outputPath: { base: 'dist', media: '', }, ssr: { entry: 'src/server.ts', }, }); }); it(`should emit browser bundles in 'browser' directory`, async () => { const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/main.js').toExist(); }); it(`should emit media files in 'browser' directory`, async () => { const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/spectrum.png').toExist(); harness.expectFile('dist/browser/abc.svg').toExist(); // Component CSS should not be considered media harness.expectFile('dist/browser/app.component.css').toNotExist(); }); it(`should emit server bundles in 'server' directory`, async () => { const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/server/server.mjs').toExist(); }); }); describe(`'server' is set to 'node-server'`, () => { beforeEach(() => { harness.useTarget('build', { ...BASE_OPTIONS, polyfills: [], styles: ['src/styles.css'], server: 'src/main.server.ts', outputPath: { base: 'dist', server: 'node-server', }, ssr: { entry: 'src/server.ts', }, }); }); it(`should emit browser bundles in 'browser' directory`, async () => { const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/main.js').toExist(); }); it(`should emit media files in 'browser/media' directory`, async () => { const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/media/spectrum.png').toExist(); harness.expectFile('dist/browser/media/abc.svg').toExist(); }); it(`should emit server bundles in 'node-server' directory`, async () => { const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/node-server/server.mjs').toExist(); }); }); describe(`'browser' is set to 'public'`, () => { beforeEach(() => { harness.useTarget('build', { ...BASE_OPTIONS, polyfills: [], styles: ['src/styles.css'], server: 'src/main.server.ts', outputPath: { base: 'dist', browser: 'public', }, ssr: { entry: 'src/server.ts', }, }); }); it(`should emit browser bundles in 'public' directory`, async () => { const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/public/main.js').toExist(); }); it(`should emit media files in 'public/media' directory`, async () => { const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/public/media/spectrum.png').toExist(); harness.expectFile('dist/public/media/abc.svg').toExist(); }); it(`should emit server bundles in 'server' directory`, async () => { const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/server/server.mjs').toExist(); }); }); describe(`'browser' is set to ''`, () => { it(`should emit browser bundles in '' directory`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, polyfills: [], server: 'src/main.server.ts', outputPath: { base: 'dist', browser: '', }, ssr: false, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/main.js').toExist(); }); it(`should emit media files in 'media' directory`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, polyfills: [], styles: ['src/styles.css'], server: 'src/main.server.ts', outputPath: { base: 'dist', browser: '', }, ssr: false, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/media/spectrum.png').toExist(); harness.expectFile('dist/media/abc.svg').toExist(); }); it(`should error when ssr is enabled`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, polyfills: [], server: 'src/main.server.ts', outputPath: { base: 'dist', browser: '', }, ssr: { entry: 'src/server.ts', }, }); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBeFalse(); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching( `'outputPath.browser' cannot be configured to an empty string when SSR is enabled`, ), }), ); }); }); describe(`'server' is set ''`, () => { beforeEach(() => { harness.useTarget('build', { ...BASE_OPTIONS, polyfills: [], styles: ['src/styles.css'], server: 'src/main.server.ts', outputPath: { base: 'dist', server: '', }, ssr: { entry: 'src/server.ts', }, }); }); it(`should emit browser bundles in 'browser' directory`, async () => { const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/main.js').toExist(); }); it(`should emit media files in 'browser/media' directory`, async () => { const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/media/spectrum.png').toExist(); harness.expectFile('dist/browser/media/abc.svg').toExist(); }); it(`should emit server bundles in '' directory`, async () => { const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/server.mjs').toExist(); }); }); it(`should error when ssr is enabled and 'browser' and 'server' are identical`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, polyfills: [], server: 'src/main.server.ts', outputPath: { base: 'dist', browser: 'public', server: 'public', }, ssr: { entry: 'src/server.ts', }, }); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBeFalse(); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching( `'outputPath.browser' and 'outputPath.server' cannot be configured to the same value`, ), }), ); }); }); }); });
{ "end_byte": 12190, "start_byte": 2503, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/output-path_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/ssr_spec.ts_0_3051
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { beforeEach(async () => { await harness.modifyFile('src/tsconfig.app.json', (content) => { const tsConfig = JSON.parse(content); tsConfig.files ??= []; tsConfig.files.push('main.server.ts', 'server.ts'); return JSON.stringify(tsConfig); }); await harness.writeFile('src/server.ts', `console.log('Hello!');`); }); describe('Option: "ssr"', () => { it('uses a provided TypeScript file', async () => { harness.useTarget('build', { ...BASE_OPTIONS, server: 'src/main.server.ts', ssr: { entry: 'src/server.ts' }, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/server/main.server.mjs').toExist(); harness.expectFile('dist/server/server.mjs').toExist(); }); it('resolves an absolute path as relative inside the workspace root', async () => { await harness.writeFile('file.mjs', `console.log('Hello!');`); harness.useTarget('build', { ...BASE_OPTIONS, server: 'src/main.server.ts', ssr: { entry: '/file.mjs' }, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/server/server.mjs').toExist(); }); it(`should emit 'server' directory when 'ssr' is 'true'`, async () => { await harness.writeFile('file.mjs', `console.log('Hello!');`); harness.useTarget('build', { ...BASE_OPTIONS, server: 'src/main.server.ts', ssr: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectDirectory('dist/server').toExist(); }); it(`should not emit 'server' directory when 'ssr' is 'false'`, async () => { await harness.writeFile('file.mjs', `console.log('Hello!');`); harness.useTarget('build', { ...BASE_OPTIONS, server: 'src/main.server.ts', ssr: false, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectDirectory('dist/server').toNotExist(); }); it(`should not emit 'server' directory when 'ssr' is not set`, async () => { await harness.writeFile('file.mjs', `console.log('Hello!');`); harness.useTarget('build', { ...BASE_OPTIONS, server: 'src/main.server.ts', ssr: undefined, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectDirectory('dist/server').toNotExist(); }); }); });
{ "end_byte": 3051, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/ssr_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/optimization-fonts-inline_spec.ts_0_3209
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Option: "fonts.inline"', () => { beforeEach(async () => { await harness.modifyFile('/src/index.html', (content) => content.replace( '<head>', `<head><link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet">`, ), ); await harness.writeFile( 'src/styles.css', '@import url(https://fonts.googleapis.com/css?family=Roboto:300,400,500);', ); await harness.writeFile( 'src/app/app.component.css', '@import url(https://fonts.googleapis.com/css?family=Roboto:300,400,500);', ); }); it(`should not inline fonts when fonts optimization is set to false`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, optimization: { scripts: true, styles: true, fonts: false, }, styles: ['src/styles.css'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); for (const file of ['styles.css', 'index.html', 'main.js']) { harness .expectFile(`dist/browser/${file}`) .content.toContain(`https://fonts.googleapis.com/css?family=Roboto:300,400,500`); } }); it(`should inline fonts when fonts optimization is unset`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, optimization: { scripts: true, styles: true, fonts: undefined, }, styles: ['src/styles.css'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); for (const file of ['styles.css', 'index.html', 'main.js']) { harness .expectFile(`dist/browser/${file}`) .content.not.toContain(`https://fonts.googleapis.com/css?family=Roboto:300,400,500`); harness .expectFile(`dist/browser/${file}`) .content.toMatch(/@font-face{font-family:'?Roboto/); } }); it(`should inline fonts when fonts optimization is true`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, optimization: { scripts: true, styles: true, fonts: true, }, styles: ['src/styles.css'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); for (const file of ['styles.css', 'index.html', 'main.js']) { harness .expectFile(`dist/browser/${file}`) .content.not.toContain(`https://fonts.googleapis.com/css?family=Roboto:300,400,500`); harness .expectFile(`dist/browser/${file}`) .content.toMatch(/@font-face{font-family:'?Roboto/); } }); }); });
{ "end_byte": 3209, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/optimization-fonts-inline_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/output-hashing_spec.ts_0_6693
/** * @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 { buildApplication } from '../../index'; import { OutputHashing } from '../../schema'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Option: "outputHashing"', () => { beforeEach(async () => { // Application code is not needed for asset tests await harness.writeFile('src/main.ts', 'console.log("TEST");'); await harness.writeFile('src/polyfills.ts', 'console.log("TEST-POLYFILLS");'); }); 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/browser', /main-[0-9A-Z]{8}\.js$/)).toBeTrue(); expect(harness.hasFileMatch('dist/browser', /polyfills-[0-9A-Z]{8}\.js$/)).toBeTrue(); expect(harness.hasFileMatch('dist/browser', /styles-[0-9A-Z]{8}\.css$/)).toBeTrue(); expect(harness.hasFileMatch('dist/browser/media', /spectrum-[0-9A-Z]{8}\.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/browser', /main-[0-9A-Z]{8}\.js$/)).toBeFalse(); expect(harness.hasFileMatch('dist/browser', /polyfills-[0-9A-Z]{8}\.js$/)).toBeFalse(); expect(harness.hasFileMatch('dist/browser', /styles-[0-9A-Z]{8}\.css$/)).toBeFalse(); expect(harness.hasFileMatch('dist/browser/media', /spectrum-[0-9A-Z]{8}\.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/browser', /main-[0-9A-Z]{8}\.js$/)).toBeFalse(); expect(harness.hasFileMatch('dist/browser', /polyfills-[0-9A-Z]{8}\.js$/)).toBeFalse(); expect(harness.hasFileMatch('dist/browser', /styles-[0-9A-Z]{8}\.css$/)).toBeFalse(); expect(harness.hasFileMatch('dist/browser/media', /spectrum-[0-9A-Z]{8}\.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/browser', /main-[0-9A-Z]{8}\.js$/)).toBeFalse(); expect(harness.hasFileMatch('dist/browser', /polyfills-[0-9A-Z]{8}\.js$/)).toBeFalse(); expect(harness.hasFileMatch('dist/browser', /styles-[0-9A-Z]{8}\.css$/)).toBeFalse(); expect(harness.hasFileMatch('dist/browser/media', /spectrum-[0-9A-Z]{8}\.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/browser', /main-[0-9A-Z]{8}\.js$/)).toBeTrue(); expect(harness.hasFileMatch('dist/browser', /polyfills-[0-9A-Z]{8}\.js$/)).toBeTrue(); expect(harness.hasFileMatch('dist/browser', /styles-[0-9A-Z]{8}\.css$/)).toBeTrue(); expect(harness.hasFileMatch('dist/browser/media', /spectrum-[0-9A-Z]{8}\.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/browser', /styles-[0-9A-Z]{8}\.css$/)).toBeFalse(); expect(harness.hasFileMatch('dist/browser', /styles-[0-9A-Z]{8}\.css.map$/)).toBeFalse(); harness.expectFile('dist/browser/styles.css').toExist(); harness.expectFile('dist/browser/styles.css.map').toExist(); }); // TODO: Re-enable once implemented in the esbuild builder xit('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/browser/media/test.svg').toExist(); harness.expectFile('dist/browser/media/small-test.svg').toExist(); }); }); });
{ "end_byte": 6693, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/output-hashing_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/scripts_spec.ts_0_5111
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Option: "scripts"', () => { beforeEach(async () => { // Application code is not needed for scripts tests await harness.writeFile('src/main.ts', 'console.log("TESTING");'); }); 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/browser/scripts.js').toExist(); harness .expectFile('dist/browser/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/browser/scripts.js').content.toContain('console.log("a")'); harness .expectFile('dist/browser/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/browser/scripts.js').content.toContain('console.log("a")'); harness.expectFile('dist/browser/scripts.js').content.toContain('console.log("b")'); harness .expectFile('dist/browser/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/browser/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({ outputLogsOnFailure: false }); expect(result?.success).toBeFalse(); expect(logs).toContain( jasmine.objectContaining({ level: 'error', message: jasmine.stringMatching(`Could not resolve "src/test-script-a.js"`), }), ); harness.expectFile('dist/browser/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": 5111, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/scripts_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/scripts_spec.ts_5117_13672
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/browser/scripts.js').content.toContain('console.log("a")'); harness .expectFile('dist/browser/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/browser/extra.js').content.toContain('console.log("a")'); harness .expectFile('dist/browser/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/browser/scripts.js').content.toContain('console.log("a")'); harness .expectFile('dist/browser/index.html') .content.toContain('<script src="scripts.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/browser/extra.js').content.toContain('console.log("a")'); harness.expectFile('dist/browser/other.js').content.toContain('console.log("b")'); harness .expectFile('dist/browser/index.html') .content.toContain('<script src="extra.js" defer></script>'); harness .expectFile('dist/browser/index.html') .content.toContain('<script src="other.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/browser/scripts.js').content.toContain('console.log("a")'); harness.expectFile('dist/browser/scripts.js').content.toContain('console.log("b")'); harness .expectFile('dist/browser/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/browser/extra.js').content.toContain('console.log("a")'); harness.expectFile('dist/browser/extra.js').content.toContain('console.log("b")'); harness .expectFile('dist/browser/index.html') .content.toContain('<script src="extra.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/browser/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/browser/other.js') .content.toMatch(/console\.log\("c"\)[;\s]+console\.log\("a"\)/); harness .expectFile('dist/browser/extra.js') .content.toMatch(/console\.log\("d"\)[;\s]+console\.log\("b"\)/); harness .expectFile('dist/browser/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/browser/scripts.js').content.toContain('console.log("a")'); harness .expectFile('dist/browser/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/browser/test-script-a.js').content.toContain('console.log("a")'); harness .expectFile('dist/browser/index.html') .content.not.toContain('<script src="test-script-a.js" defer></script>'); });
{ "end_byte": 13672, "start_byte": 5117, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/scripts_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/scripts_spec.ts_13680_15542
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/browser/extra.js').content.toContain('console.log("a")'); harness .expectFile('dist/browser/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": 15542, "start_byte": 13680, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/scripts_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/deploy-url_spec.ts_0_2960
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Option: "deployUrl"', () => { beforeEach(async () => { // Add a global stylesheet to test link elements await harness.writeFile('src/styles.css', '/* Global styles */'); // Reduce the input index HTML to a single line to simplify comparing await harness.writeFile( 'src/index.html', '<html><head><base href="/"></head><body><app-root></app-root></body></html>', ); }); it('should update script src and link href attributes when option is set to relative URL', async () => { harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.css'], deployUrl: 'deployUrl/', }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/browser/index.html') .content.toEqual( `<html><head><base href="/"><link rel="stylesheet" href="deployUrl/styles.css"></head>` + `<body><app-root></app-root>` + `<script src="deployUrl/main.js" type="module"></script></body></html>`, ); }); it('should update script src and link href attributes when option is set to absolute URL', async () => { harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.css'], deployUrl: 'https://example.com/some/path/', }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/browser/index.html') .content.toEqual( `<html><head><base href="/"><link rel="stylesheet" href="https://example.com/some/path/styles.css"></head>` + `<body><app-root></app-root>` + `<script src="https://example.com/some/path/main.js" type="module"></script></body></html>`, ); }); it('should update resources component stylesheets to reference deployURL', async () => { await harness.writeFile('src/app/test.svg', '<svg></svg>'); await harness.writeFile( 'src/app/app.component.css', `* { background-image: url('./test.svg'); }`, ); harness.useTarget('build', { ...BASE_OPTIONS, deployUrl: 'https://example.com/some/path/', }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness .expectFile('dist/browser/main.js') .content.toContain('background-image: url("https://example.com/some/path/media/test.svg")'); }); }); });
{ "end_byte": 2960, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/deploy-url_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/external-dependencies_spec.ts_0_2666
/** * @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 { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Option: "externalDependencies"', () => { it('should not externalize any dependency when option is not set', async () => { harness.useTarget('build', { ...BASE_OPTIONS, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/main.js').content.not.toMatch(/from ['"]@angular\/core['"]/); harness .expectFile('dist/browser/main.js') .content.not.toMatch(/from ['"]@angular\/common['"]/); }); it('should only externalize the listed depedencies when option is set', async () => { harness.useTarget('build', { ...BASE_OPTIONS, externalDependencies: ['@angular/core'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/main.js').content.toMatch(/from ['"]@angular\/core['"]/); harness .expectFile('dist/browser/main.js') .content.not.toMatch(/from ['"]@angular\/common['"]/); }); it('should externalize the listed depedencies in Web Workers when option is set', async () => { harness.useTarget('build', { ...BASE_OPTIONS, externalDependencies: ['path'], }); // The `path` Node.js builtin is used to cause a failure if not externalized const workerCodeFile = ` import path from "path"; console.log(path); `; // Create a worker file await harness.writeFile('src/app/worker.ts', workerCodeFile); // 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: '<h1>Worker Test</h1>', }) export class AppComponent { worker = new Worker(new URL('./worker', import.meta.url), { type: 'module' }); } `, ); const { result } = await harness.executeOnce(); // If not externalized, build will fail with a Node.js platform builtin error expect(result?.success).toBeTrue(); }); }); });
{ "end_byte": 2666, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/external-dependencies_spec.ts" }