_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular-cli/tests/legacy-cli/e2e/tests/build/config-file-fallback.ts_0_262
import { ng } from '../../utils/process'; import { moveFile } from '../../utils/fs'; export default function () { return Promise.resolve() .then(() => ng('build')) .then(() => moveFile('angular.json', '.angular.json')) .then(() => ng('build')); }
{ "end_byte": 262, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/config-file-fallback.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/lazy-load-syntax.ts_0_2018
/** * @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 { setTimeout } from 'node:timers/promises'; import { replaceInFile, writeFile } from '../../utils/fs'; import { ng } from '../../utils/process'; import { updateJsonFile } from '../../utils/project'; export default async function () { // Add lazy route. await ng('generate', 'component', 'lazy-comp'); await replaceInFile( 'src/app/app.routes.ts', 'routes: Routes = [];', `routes: Routes = [{ path: 'lazy', loadComponent: () => import('./lazy-comp/lazy-comp.component').then(c => c.LazyCompComponent), }];`, ); // Add lazy route e2e await writeFile( 'e2e/src/app.e2e-spec.ts', ` import { browser, logging, element, by } from 'protractor'; describe('workspace-project App', () => { it('should display lazy route', async () => { await browser.get(browser.baseUrl + '/lazy'); expect(await element(by.css('app-lazy-comp p')).getText()).toEqual('lazy-comp works!'); }); afterEach(async () => { // Assert that there are no errors emitted from the browser const logs = await browser.manage().logs().get(logging.Type.BROWSER); expect(logs).not.toContain(jasmine.objectContaining({ level: logging.Level.SEVERE, })); }); }); `, ); // Convert the default config to use JIT and prod to just do AOT. // This way we can use `ng e2e` to test JIT and `ng e2e --configuration=production` to test AOT. await updateJsonFile('angular.json', (json) => { const buildTarget = json['projects']['test-project']['architect']['build']; buildTarget['options']['aot'] = true; buildTarget['configurations']['development']['aot'] = false; }); await ng('e2e'); await setTimeout(500); await ng('e2e', '--configuration=production'); }
{ "end_byte": 2018, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/lazy-load-syntax.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/wasm-esm.ts_0_3498
/** * @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 { readFile, writeFile } from 'node:fs/promises'; import assert from 'node:assert/strict'; import { ng } from '../../utils/process'; import { prependToFile, replaceInFile } from '../../utils/fs'; import { updateJsonFile, useSha } from '../../utils/project'; import { installWorkspacePackages } from '../../utils/packages'; /** * 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'); export default async function () { // Add WASM file to project await writeFile('src/app/multiply.wasm', importWasmBytes); await writeFile( 'src/app/multiply.wasm.d.ts', 'export declare function multiply(a: number, b: number): number; export declare function subtract1(a: number): number;', ); // Add requested WASM import file await writeFile('src/app/values.js', 'export function getValue() { return 100; }'); // Use WASM file in project await prependToFile( 'src/app/app.component.ts', ` import { multiply, subtract1 } from './multiply.wasm'; `, ); await replaceInFile( 'src/app/app.component.ts', "'test-project'", 'multiply(4, 5) + subtract1(88)', ); // Remove Zone.js from polyfills and make zoneless await updateJsonFile('angular.json', (json) => { // Remove bundle budgets to avoid a build error due to the expected increased output size // of a JIT production build. json.projects['test-project'].architect.build.options.polyfills = []; }); await replaceInFile( 'src/app/app.config.ts', 'provideZoneChangeDetection', 'provideExperimentalZonelessChangeDetection', ); await replaceInFile( 'src/app/app.config.ts', 'provideZoneChangeDetection({ eventCoalescing: true })', 'provideExperimentalZonelessChangeDetection()', ); await ng('build'); // Update E2E test to check for WASM execution await writeFile( 'e2e/src/app.e2e-spec.ts', ` import { AppPage } from './app.po'; import { browser, logging } from 'protractor'; describe('WASM execution', () => { it('should log WASM result messages', async () => { const page = new AppPage(); await page.navigateTo(); expect(await page.getTitleText()).toEqual('Hello, 32'); }); }); `, ); await ng('e2e'); // Setup prerendering and build to test Node.js functionality await ng('add', '@angular/ssr', '--skip-confirmation'); await useSha(); await installWorkspacePackages(); await ng('build', '--configuration', 'development', '--prerender'); const content = await readFile('dist/test-project/browser/index.html', 'utf-8'); assert.match(content, /Hello, 32/); }
{ "end_byte": 3498, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/wasm-esm.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/bundle-budgets.ts_0_1502
/** * @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 { ng } from '../../utils/process'; import { updateJsonFile } from '../../utils/project'; import { expectToFail } from '../../utils/utils'; export default async function () { // Error await updateJsonFile('angular.json', (json) => { json.projects['test-project'].architect.build.configurations.production.budgets = [ { type: 'all', maximumError: '100b' }, ]; }); const { message: errorMessage } = await expectToFail(() => ng('build')); if (!/Error.+budget/i.test(errorMessage)) { throw new Error('Budget error: all, max error.'); } // Warning await updateJsonFile('angular.json', (json) => { json.projects['test-project'].architect.build.configurations.production.budgets = [ { type: 'all', minimumWarning: '100mb' }, ]; }); const { stderr } = await ng('build'); if (!/Warning.+budget/i.test(stderr)) { throw new Error('Budget warning: all, min warning'); } // Pass await updateJsonFile('angular.json', (json) => { json.projects['test-project'].architect.build.configurations.production.budgets = [ { type: 'allScript', maximumError: '100mb' }, ]; }); const { stderr: stderr2 } = await ng('build'); if (/(Warning|Error)/i.test(stderr2)) { throw new Error('BIG max for all, should not error'); } }
{ "end_byte": 1502, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/bundle-budgets.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/prod-build.ts_0_2049
import { statSync } from 'fs'; import { join } from 'path'; import { getGlobalVariable } from '../../utils/env'; import { expectFileToExist, expectFileToMatch, readFile } from '../../utils/fs'; import { noSilentNg } from '../../utils/process'; function verifySize(bundle: string, baselineBytes: number) { const size = statSync(`dist/test-project/browser/${bundle}`).size; const percentageBaseline = (baselineBytes * 10) / 100; const maxSize = baselineBytes + percentageBaseline; const minSize = baselineBytes - percentageBaseline; if (size >= maxSize) { throw new Error( `Expected ${bundle} size to be less than ${maxSize / 1024}Kb but it was ${size / 1024}Kb.`, ); } if (size <= minSize) { throw new Error( `Expected ${bundle} size to be greater than ${minSize / 1024}Kb but it was ${size / 1024}Kb.`, ); } } export default async function () { await noSilentNg('build'); await expectFileToExist(join(process.cwd(), 'dist')); // Check for cache busting hash script src if (getGlobalVariable('argv')['esbuild']) { // esbuild uses an 8 character hash and a dash as separator await expectFileToMatch('dist/test-project/browser/index.html', /main-[0-9a-zA-Z]{8}\.js/); await expectFileToMatch('dist/test-project/browser/index.html', /styles-[0-9a-zA-Z]{8}\.css/); await expectFileToMatch('dist/test-project/3rdpartylicenses.txt', /MIT/); } else { await expectFileToMatch('dist/test-project/browser/index.html', /main\.[0-9a-zA-Z]{16}\.js/); await expectFileToMatch('dist/test-project/browser/index.html', /styles\.[0-9a-zA-Z]{16}\.css/); await expectFileToMatch('dist/test-project/browser/3rdpartylicenses.txt', /MIT/); } const indexContent = await readFile('dist/test-project/browser/index.html'); const mainSrcRegExp = getGlobalVariable('argv')['esbuild'] ? /src="(main-[0-9a-zA-Z]{8}\.js)"/ : /src="(main\.[0-9a-zA-Z]{16}\.js)"/; const mainPath = indexContent.match(mainSrcRegExp)![1]; // Size checks in bytes verifySize(mainPath, 210000); }
{ "end_byte": 2049, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/prod-build.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/progress-and-stats.ts_0_1274
import assert from 'node:assert/strict'; import { getGlobalVariable } from '../../utils/env'; import { ng } from '../../utils/process'; export default async function () { const { stderr: stderrProgress, stdout } = await ng('build', '--progress'); if (!stdout.includes('Initial total')) { throw new Error(`Expected stdout to contain 'Initial total' but it did not.\n${stdout}`); } if (!stdout.includes('Estimated transfer size')) { throw new Error( `Expected stdout to contain 'Estimated transfer size' but it did not.\n${stdout}`, ); } let logs; if (getGlobalVariable('argv')['esbuild']) { assert.match(stdout, /Building\.\.\./); return; } else { logs = [ 'Browser application bundle generation complete', 'Copying assets complete', 'Index html generation complete', ]; } for (const log of logs) { if (!stderrProgress.includes(log)) { throw new Error(`Expected stderr to contain '${log}' but didn't.\n${stderrProgress}`); } } const { stderr: stderrNoProgress } = await ng('build', '--no-progress'); for (const log of logs) { if (stderrNoProgress.includes(log)) { throw new Error(`Expected stderr not to contain '${log}' but it did.\n${stderrProgress}`); } } }
{ "end_byte": 1274, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/progress-and-stats.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/multiple-configs.ts_0_2430
import { getGlobalVariable } from '../../utils/env'; import { expectFileToExist } from '../../utils/fs'; import { ng } from '../../utils/process'; import { updateJsonFile } from '../../utils/project'; import { expectToFail } from '../../utils/utils'; export default async function () { // TODO: Restructure to support application builder option // This only needs to be tested once since it is really testing the CLI itself and not the builders if (getGlobalVariable('argv')['esbuild']) { return; } await updateJsonFile('angular.json', (workspaceJson) => { const appArchitect = workspaceJson.projects['test-project'].architect; // These are the default options, that we'll overwrite in subsequent configs. // sourceMap defaults to true appArchitect['build'] = { ...appArchitect['build'], defaultConfiguration: undefined, options: { ...appArchitect['build'].options, optimization: false, sourceMap: true, outputHashing: 'none', vendorChunk: true, styles: ['src/styles.css'], scripts: [], budgets: [], }, configurations: { development: { sourceMap: true, }, one: { assets: [], }, two: { sourceMap: false, }, }, }; return workspaceJson; }); // Test the base configuration. await ng('build', '--configuration=development'); await expectFileToExist('dist/test-project/browser/favicon.ico'); await expectFileToExist('dist/test-project/browser/main.js.map'); await expectFileToExist('dist/test-project/browser/vendor.js'); await ng('build'); await expectFileToExist('dist/test-project/browser/styles.css'); // Use two configurations. await ng('build', '--configuration=one,two', '--vendor-chunk=false'); await expectToFail(() => expectFileToExist('dist/test-project/browser/favicon.ico')); await expectToFail(() => expectFileToExist('dist/test-project/browser/main.js.map')); // Use two configurations and two overrides, one of which overrides a config. await ng('build', '--configuration=one,two', '--vendor-chunk=false', '--source-map=true'); await expectToFail(() => expectFileToExist('dist/test-project/browser/favicon.ico')); await expectFileToExist('dist/test-project/browser/main.js.map'); await expectToFail(() => expectFileToExist('dist/test-project/browser/vendor.js')); }
{ "end_byte": 2430, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/multiple-configs.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/scripts-output-hashing.ts_0_1995
import { getGlobalVariable } from '../../utils/env'; import { expectFileMatchToExist, expectFileToMatch, writeFile, writeMultipleFiles, } from '../../utils/fs'; import { ng } from '../../utils/process'; import { updateJsonFile } from '../../utils/project'; function getScriptsFilename(): Promise<string> { if (getGlobalVariable('argv')['esbuild']) { return expectFileMatchToExist('dist/test-project/browser/', /external-module-[0-9A-Z]{8}\.js/); } else { return expectFileMatchToExist( 'dist/test-project/browser/', /external-module\.[0-9a-f]{16}\.js/, ); } } export default async function () { // verify content hash is based on code after optimizations await writeMultipleFiles({ 'src/script.js': 'try { console.log(); } catch {}', }); await updateJsonFile('angular.json', (configJson) => { const build = configJson.projects['test-project'].architect.build; build.options['scripts'] = [ { input: 'src/script.js', inject: true, bundleName: 'external-module', }, ]; build.configurations['production'].outputHashing = 'all'; configJson['cli'] = { cache: { enabled: 'false' } }; }); // Chrome 65 does not support optional catch in try/catch blocks. await writeFile('.browserslistrc', 'Chrome 65'); await ng('build', '--configuration=production'); const filenameBuild1 = await getScriptsFilename(); await expectFileToMatch( `dist/test-project/browser/${filenameBuild1}`, 'try{console.log()}catch(c){}', ); await writeFile('.browserslistrc', 'last 1 Chrome version'); await ng('build', '--configuration=production'); const filenameBuild2 = await getScriptsFilename(); await expectFileToMatch( `dist/test-project/browser/${filenameBuild2}`, 'try{console.log()}catch{}', ); if (filenameBuild1 === filenameBuild2) { throw new Error( 'Contents of the built file changed between builds, but the content hash stayed the same!', ); } }
{ "end_byte": 1995, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/scripts-output-hashing.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/jit-prod.ts_0_613
import { getGlobalVariable } from '../../utils/env'; import { ng } from '../../utils/process'; import { updateJsonFile } from '../../utils/project'; export default async function () { // Make prod use JIT. await updateJsonFile('angular.json', (configJson) => { const appArchitect = configJson.projects['test-project'].architect; appArchitect.build.configurations['production'].aot = false; if (!getGlobalVariable('argv')['esbuild']) { appArchitect.build.configurations['production'].buildOptimizer = false; } }); // Test it works await ng('e2e', '--configuration=production'); }
{ "end_byte": 613, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/jit-prod.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/rebuild-dot-dirname.ts_0_1920
import { setTimeout } from 'node:timers/promises'; import { getGlobalVariable } from '../../utils/env'; import { appendToFile, createDir, rimraf } from '../../utils/fs'; import { installWorkspacePackages } from '../../utils/packages'; import { killAllProcesses, ng, waitForAnyProcessOutputToMatch } from '../../utils/process'; import { ngServe, updateJsonFile, useSha } from '../../utils/project'; const goodRegEx = getGlobalVariable('argv')['esbuild'] ? /Application bundle generation complete\./ : / Compiled successfully\./; export default async function () { const originalCwd = process.cwd(); // Delete angular.json so that we can create a new app. await rimraf('angular.json'); await createDir('./.subdirectory'); try { process.chdir('./.subdirectory'); await ng('new', 'subdirectory-test-project', '--skip-install'); process.chdir('./subdirectory-test-project'); await useSha(); await installWorkspacePackages(); const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; if (useWebpackBuilder) { await updateJsonFile('angular.json', (json) => { const build = json['projects']['subdirectory-test-project']['architect']['build']; build.builder = '@angular-devkit/build-angular:browser'; build.options = { ...build.options, main: build.options.browser, browser: undefined, }; build.configurations.development = { ...build.configurations.development, vendorChunk: true, namedChunks: true, buildOptimizer: false, }; }); } await ngServe(); // Wait before editing a file. await setTimeout(1000); await appendToFile('src/main.ts', 'console.log(1);'); await waitForAnyProcessOutputToMatch(goodRegEx); } finally { process.chdir(originalCwd); await killAllProcesses(); await setTimeout(100); } }
{ "end_byte": 1920, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/rebuild-dot-dirname.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/relative-sourcemap.ts_0_2120
import * as fs from 'fs'; import { isAbsolute } from 'path'; import { getGlobalVariable } from '../../utils/env'; import { ng } from '../../utils/process'; import { updateJsonFile } from '../../utils/project'; export default async function () { // General secondary application project await ng('generate', 'application', 'secondary-project', '--skip-install'); // Setup webpack builder if esbuild is not requested on the commandline const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; if (useWebpackBuilder) { await updateJsonFile('angular.json', (json) => { const build = json['projects']['secondary-project']['architect']['build']; build.builder = '@angular-devkit/build-angular:browser'; build.options = { ...build.options, main: build.options.browser, browser: undefined, }; build.configurations.development = { ...build.configurations.development, vendorChunk: true, namedChunks: true, buildOptimizer: false, }; }); } await ng('build', 'secondary-project', '--configuration=development'); await ng('build', '--output-hashing=none', '--source-map', '--configuration=development'); const sourceMapPath = getGlobalVariable('argv')['esbuild'] ? './dist/secondary-project/browser/main.js.map' : './dist/secondary-project/main.js.map'; const content = fs.readFileSync(sourceMapPath, 'utf8'); const { sources } = JSON.parse(content) as { sources: string[] }; let mainFileFound = false; for (const source of sources) { if (isAbsolute(source)) { throw new Error(`Expected ${source} to be relative.`); } if (source.endsWith('main.ts')) { mainFileFound = true; if ( source !== 'projects/secondary-project/src/main.ts' && source !== './projects/secondary-project/src/main.ts' ) { throw new Error(`Expected main file ${source} to be relative to the workspace root.`); } } } if (!mainFileFound) { throw new Error('Could not find the main file in the application sourcemap sources array.'); } }
{ "end_byte": 2120, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/relative-sourcemap.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/rebuild-deps-type-check.ts_0_3489
import { waitForAnyProcessOutputToMatch, execAndWaitForOutputToMatch } from '../../utils/process'; import { writeFile, prependToFile, appendToFile } from '../../utils/fs'; import { getGlobalVariable } from '../../utils/env'; const doneRe = getGlobalVariable('argv')['esbuild'] ? /Application bundle generation complete\./ : / Compiled successfully\.|: Failed to compile\./; const errorRe = /Error/i; export default function () { // TODO(architect): Delete this test. It is now in devkit/build-angular. if (process.platform.startsWith('win')) { return Promise.resolve(); } return ( Promise.resolve() // Create and import files. .then(() => writeFile( 'src/funky2.ts', ` export function funky2(value: string): string { return value + 'hello'; } `, ), ) .then(() => writeFile( 'src/funky.ts', ` export * from './funky2'; `, ), ) .then(() => prependToFile( 'src/main.ts', ` import { funky2 } from './funky'; `, ), ) .then(() => appendToFile( 'src/main.ts', ` console.log(funky2('town')); `, ), ) // Should trigger a rebuild, no error expected. .then(() => execAndWaitForOutputToMatch('ng', ['serve'], doneRe)) // Make an invalid version of the file. // Should trigger a rebuild, this time an error is expected. .then(() => Promise.all([ waitForAnyProcessOutputToMatch(errorRe, 20000), writeFile( 'src/funky2.ts', ` export function funky2(value: number): number { return value + 1; } `, ), ]), ) .then((results) => { const stderr = results[0].stderr; if ( !stderr.includes( "Argument of type 'string' is not assignable to parameter of type 'number'", ) ) { throw new Error('Expected an error but none happened.'); } }) // Change an UNRELATED file and the error should still happen. // Should trigger a rebuild, this time an error is also expected. .then(() => Promise.all([ waitForAnyProcessOutputToMatch(errorRe, 20000), appendToFile( 'src/app/app.config.ts', ` function anything(): number { return 1; } `, ), ]), ) .then((results) => { const stderr = results[0].stderr; if ( !stderr.includes( "Argument of type 'string' is not assignable to parameter of type 'number'", ) ) { throw new Error('Expected an error to still be there but none was.'); } }) // Fix the error! .then(() => Promise.all([ waitForAnyProcessOutputToMatch(doneRe, 20000), writeFile( 'src/funky2.ts', ` export function funky2(value: string): string { return value + 'hello'; } `, ), ]), ) .then((results) => { const stderr = results[0].stderr; if ( stderr.includes( "Argument of type 'string' is not assignable to parameter of type 'number'", ) ) { throw new Error('Expected no error but an error was shown.'); } }) ); }
{ "end_byte": 3489, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/rebuild-deps-type-check.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/jit-ngmodule.ts_0_1435
import { getGlobalVariable } from '../../utils/env'; import { ng } from '../../utils/process'; import { updateJsonFile, useCIChrome, useCIDefaults } from '../../utils/project'; export default async function () { await ng('generate', 'app', 'test-project-two', '--no-standalone', '--skip-install'); await ng('generate', 'private-e2e', '--related-app-name=test-project-two'); // Setup testing to use CI Chrome. await useCIChrome('test-project-two', './projects/test-project-two/e2e'); await useCIDefaults('test-project-two'); // Make prod use JIT. const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; // Setup webpack builder if esbuild is not requested on the commandline await updateJsonFile('angular.json', (json) => { const build = json['projects']['test-project-two']['architect']['build']; if (useWebpackBuilder) { build.builder = '@angular-devkit/build-angular:browser'; build.options = { ...build.options, main: build.options.browser, browser: undefined, buildOptimizer: false, }; build.configurations.development = { ...build.configurations.development, vendorChunk: true, namedChunks: true, }; } build.options.aot = false; }); // Test it works await ng('e2e', 'test-project-two', '--configuration=production'); await ng('e2e', 'test-project-two', '--configuration=development'); }
{ "end_byte": 1435, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/jit-ngmodule.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/material.ts_0_3496
import assert from 'node:assert/strict'; import { appendFile, readdir } from 'node:fs/promises'; import { getGlobalVariable } from '../../utils/env'; import { readFile, replaceInFile } from '../../utils/fs'; import { getActivePackageManager, installPackage, installWorkspacePackages, } from '../../utils/packages'; import { execWithEnv, ng } from '../../utils/process'; import { isPrereleaseCli, updateJsonFile } from '../../utils/project'; const snapshots = require('../../ng-snapshot/package.json'); export default async function () { const isPrerelease = await isPrereleaseCli(); let tag = isPrerelease ? '@next' : ''; if (getActivePackageManager() === 'npm') { await appendFile('.npmrc', '\nlegacy-peer-deps=true'); } await ng('add', `@angular/material${tag}`, '--skip-confirmation'); const isSnapshotBuild = getGlobalVariable('argv')['ng-snapshots']; if (isSnapshotBuild) { await updateJsonFile('package.json', (packageJson) => { const dependencies = packageJson['dependencies']; // Angular material adds dependencies on other Angular packages // Iterate over all of the packages to update them to the snapshot version. for (const [name, version] of Object.entries(snapshots.dependencies)) { if (name in dependencies) { dependencies[name] = version; } } dependencies['@angular/material-moment-adapter'] = snapshots.dependencies['@angular/material-moment-adapter']; }); await installWorkspacePackages(); } else { if (!tag) { const installedMaterialVersion = JSON.parse(await readFile('package.json'))['dependencies'][ '@angular/material' ]; tag = `@${installedMaterialVersion}`; } await installPackage(`@angular/material-moment-adapter${tag}`); } await installPackage('moment'); await ng('build'); // Ensure moment adapter works (uses unique importing mechanism for moment) // Issue: https://github.com/angular/angular-cli/issues/17320 await replaceInFile( 'src/app/app.config.ts', `import { ApplicationConfig } from '@angular/core';`, ` import { ApplicationConfig } from '@angular/core'; import { MomentDateAdapter, MAT_MOMENT_DATE_FORMATS } from '@angular/material-moment-adapter'; import { DateAdapter, MAT_DATE_LOCALE, MAT_DATE_FORMATS } from '@angular/material/core'; `, ); await replaceInFile( 'src/app/app.config.ts', `providers: [provideRouter(routes) ]`, ` providers: [ provideRouter(routes), { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] }, { provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS } ] `, ); await ng('e2e', '--configuration=production'); const usingApplicationBuilder = getGlobalVariable('argv')['esbuild']; if (usingApplicationBuilder) { // Test with chunk optimizations to reduce async animations chunk file count await execWithEnv('ng', ['build'], { ...process.env, NG_BUILD_OPTIMIZE_CHUNKS: '1', }); const distFiles = await readdir('dist/test-project/browser'); const jsCount = distFiles.filter((file) => file.endsWith('.js')).length; // 3 = polyfills, main, and one lazy chunk assert.equal(jsCount, 3); await execWithEnv('ng', ['e2e', '--configuration=production'], { ...process.env, NG_BUILD_OPTIMIZE_CHUNKS: '1', }); } }
{ "end_byte": 3496, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/material.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/project-name.ts_0_371
import { silentNg } from '../../utils/process'; export default async function () { // Named Development build await silentNg('build', 'test-project', '--configuration=development'); await silentNg('build', '--configuration=development', 'test-project', '--no-progress'); await silentNg('build', '--configuration=development', '--no-progress', 'test-project'); }
{ "end_byte": 371, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/project-name.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/polyfills.ts_0_937
import { expectFileSizeToBeUnder, expectFileToExist, expectFileToMatch, getFileSize, } from '../../utils/fs'; import { ng } from '../../utils/process'; import { expectToFail } from '../../utils/utils'; export default async function () { await ng('build', '--aot=false', '--configuration=development'); // files were created successfully await expectFileToMatch('dist/test-project/browser/polyfills.js', 'zone.js'); await expectFileToMatch( 'dist/test-project/browser/index.html', '<script src="polyfills.js" type="module">', ); await ng('build', '--aot=true', '--configuration=development'); // files were created successfully await expectFileToExist('dist/test-project/browser/polyfills.js'); await expectFileToMatch('dist/test-project/browser/polyfills.js', 'zone.js'); await expectFileToMatch( 'dist/test-project/browser/index.html', '<script src="polyfills.js" type="module">', ); }
{ "end_byte": 937, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/polyfills.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/worker.ts_0_3371
/** * @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 { readdir } from 'fs/promises'; import { expectFileToExist, expectFileToMatch, replaceInFile, writeFile } from '../../utils/fs'; import { ng } from '../../utils/process'; import { getGlobalVariable } from '../../utils/env'; import { expectToFail } from '../../utils/utils'; export default async function () { const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; const workerPath = 'src/app/app.worker.ts'; const snippetPath = 'src/app/app.component.ts'; const projectTsConfig = 'tsconfig.json'; const workerTsConfig = 'tsconfig.worker.json'; await ng('generate', 'web-worker', 'app'); await expectFileToExist(workerPath); await expectFileToExist(projectTsConfig); await expectFileToExist(workerTsConfig); await expectFileToMatch(snippetPath, `new Worker(new URL('./app.worker', import.meta.url)`); await ng('build', '--configuration=development'); if (useWebpackBuilder) { await expectFileToExist('dist/test-project/browser/src_app_app_worker_ts.js'); await expectFileToMatch('dist/test-project/browser/main.js', 'src_app_app_worker_ts'); } else { const workerOutputFile = await getWorkerOutputFile(false); await expectFileToExist(`dist/test-project/browser/${workerOutputFile}`); await expectFileToMatch('dist/test-project/browser/main.js', workerOutputFile); await expectToFail(() => expectFileToMatch('dist/test-project/browser/main.js', workerOutputFile + '.map'), ); } await ng('build', '--output-hashing=none'); const workerOutputFile = await getWorkerOutputFile(useWebpackBuilder); await expectFileToExist(`dist/test-project/browser/${workerOutputFile}`); if (useWebpackBuilder) { // Check Webpack builds for the numeric chunk identifier await expectFileToMatch('dist/test-project/browser/main.js', workerOutputFile.substring(0, 3)); } else { await expectFileToMatch('dist/test-project/browser/main.js', workerOutputFile); } // console.warn has to be used because chrome only captures warnings and errors by default // https://github.com/angular/protractor/issues/2207 await replaceInFile('src/app/app.component.ts', 'console.log', 'console.warn'); await writeFile( 'e2e/app.e2e-spec.ts', ` import { AppPage } from './app.po'; import { browser, logging } from 'protractor'; describe('worker bundle', () => { it('should log worker messages', async () => { const page = new AppPage();; page.navigateTo(); const logs = await browser.manage().logs().get(logging.Type.BROWSER); expect(logs.length).toEqual(1); expect(logs[0].message).toContain('page got message: worker response to hello'); }); }); `, ); await ng('e2e'); } async function getWorkerOutputFile(useWebpackBuilder: boolean): Promise<string> { const files = await readdir('dist/test-project/browser'); let fileName; if (useWebpackBuilder) { fileName = files.find((f) => /^\d{3}\.js$/.test(f)); } else { fileName = files.find((f) => /worker-[\dA-Z]{8}\.js/.test(f)); } if (!fileName) { throw new Error('Cannot determine worker output file name.'); } return fileName; }
{ "end_byte": 3371, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/worker.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/extract-licenses.ts_0_1236
import { getGlobalVariable } from '../../utils/env'; import { expectFileToExist, expectFileToMatch } from '../../utils/fs'; import { ng } from '../../utils/process'; import { expectToFail } from '../../utils/utils'; export default async function () { const usingWebpack = !getGlobalVariable('argv')['esbuild']; // Licenses should be left intact if extraction is disabled await ng('build', '--extract-licenses=false', '--output-hashing=none'); if (usingWebpack) { await expectToFail(() => expectFileToExist('dist/test-project/browser/3rdpartylicenses.txt')); } else { // Application builder puts the licenses at the output path root await expectToFail(() => expectFileToExist('dist/test-project/3rdpartylicenses.txt')); } await expectFileToMatch('dist/test-project/browser/main.js', '@license'); // Licenses should be removed if extraction is enabled await ng('build', '--extract-licenses', '--output-hashing=none'); if (usingWebpack) { await expectFileToExist('dist/test-project/browser/3rdpartylicenses.txt'); } else { await expectFileToExist('dist/test-project/3rdpartylicenses.txt'); } await expectToFail(() => expectFileToMatch('dist/test-project/browser/main.js', '@license')); }
{ "end_byte": 1236, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/extract-licenses.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/library/lib-consumption-partial-jit.ts_0_916
import { setTimeout } from 'node:timers/promises'; import { updateJsonFile } from '../../../utils/project'; import { ng } from '../../../utils/process'; import { libraryConsumptionSetup } from './setup'; import { getGlobalVariable } from '../../../utils/env'; export default async function () { await libraryConsumptionSetup(); // Build library in partial mode (production) await ng('build', 'my-lib', '--configuration=production'); // JIT linking await updateJsonFile('angular.json', (config) => { const build = config.projects['test-project'].architect.build; build.options.aot = false; if (!getGlobalVariable('argv')['esbuild']) { build.configurations.production.buildOptimizer = false; } }); // Check that the e2e succeeds prod and non prod mode await ng('e2e', '--configuration=production'); await setTimeout(500); await ng('e2e', '--configuration=development'); }
{ "end_byte": 916, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/library/lib-consumption-partial-jit.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/library/lib-consumption-full-jit.ts_0_1205
import { setTimeout } from 'node:timers/promises'; import { updateJsonFile } from '../../../utils/project'; import { expectFileToMatch } from '../../../utils/fs'; import { ng } from '../../../utils/process'; import { libraryConsumptionSetup } from './setup'; import { getGlobalVariable } from '../../../utils/env'; export default async function () { await libraryConsumptionSetup(); // Build library in full mode (development) await ng('build', 'my-lib', '--configuration=development'); // JIT linking await updateJsonFile('angular.json', (config) => { const build = config.projects['test-project'].architect.build; build.options.aot = false; if (!getGlobalVariable('argv')['esbuild']) { build.configurations.production.buildOptimizer = false; } }); // Check that the e2e succeeds prod and non prod mode await ng('e2e', '--configuration=production'); await setTimeout(500); await ng('e2e', '--configuration=development'); // Validate that sourcemaps for the library exists. await ng('build', '--configuration=development'); await expectFileToMatch( 'dist/test-project/browser/main.js.map', 'projects/my-lib/src/lib/my-lib.component.ts', ); }
{ "end_byte": 1205, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/library/lib-consumption-full-jit.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/library/lib-consumption-sourcemaps.ts_0_568
import { expectFileToMatch } from '../../../utils/fs'; import { ng } from '../../../utils/process'; import { libraryConsumptionSetup } from './setup'; export default async function () { await libraryConsumptionSetup(); // Build library in full mode (development) await ng('build', 'my-lib', '--configuration=development'); // Validate that sourcemaps for the library exists. await ng('build', '--configuration=development'); await expectFileToMatch( 'dist/test-project/browser/main.js.map', 'projects/my-lib/src/lib/my-lib.component.ts', ); }
{ "end_byte": 568, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/library/lib-consumption-sourcemaps.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/library/lib-consumption-full-aot.ts_0_510
import { setTimeout } from 'node:timers/promises'; import { ng } from '../../../utils/process'; import { libraryConsumptionSetup } from './setup'; export default async function () { await libraryConsumptionSetup(); // Build library in full mode (development) await ng('build', 'my-lib', '--configuration=development'); // Check that the e2e succeeds prod and non prod mode await ng('e2e', '--configuration=production'); await setTimeout(500); await ng('e2e', '--configuration=development'); }
{ "end_byte": 510, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/library/lib-consumption-full-aot.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/library/lib-consumption-partial-aot.ts_0_511
import { setTimeout } from 'node:timers/promises'; import { ng } from '../../../utils/process'; import { libraryConsumptionSetup } from './setup'; export default async function () { await libraryConsumptionSetup(); // Build library in partial mode (production) await ng('build', 'my-lib', '--configuration=production'); // Check that the e2e succeeds prod and non prod mode await ng('e2e', '--configuration=production'); await setTimeout(500); await ng('e2e', '--configuration=development'); }
{ "end_byte": 511, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/library/lib-consumption-partial-aot.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/library/setup.ts_0_1842
import { writeMultipleFiles } from '../../../utils/fs'; import { silentNg } from '../../../utils/process'; export async function libraryConsumptionSetup(): Promise<void> { await silentNg('generate', 'library', 'my-lib'); // Force an external template await writeMultipleFiles({ 'projects/my-lib/src/lib/my-lib.component.html': `<p>my-lib works!</p>`, 'projects/my-lib/src/lib/my-lib.component.ts': `import { Component } from '@angular/core'; @Component({ standalone: true, selector: 'lib-my-lib', templateUrl: './my-lib.component.html', }) export class MyLibComponent {}`, './src/app/app.component.ts': ` import { Component } from '@angular/core'; import { MyLibService, MyLibComponent } from 'my-lib'; @Component({ standalone: true, selector: 'app-root', template: '<lib-my-lib></lib-my-lib>', imports: [MyLibComponent], }) export class AppComponent { title = 'test-project'; constructor(myLibService: MyLibService) { console.log(myLibService); } } `, 'e2e/src/app.e2e-spec.ts': ` import { browser, logging, element, by } from 'protractor'; import { AppPage } from './app.po'; describe('workspace-project App', () => { let page: AppPage; beforeEach(() => { page = new AppPage(); }); it('should display text from library component', async () => { await page.navigateTo(); expect(await element(by.css('lib-my-lib p')).getText()).toEqual('my-lib works!'); }); afterEach(async () => { // Assert that there are no errors emitted from the browser const logs = await browser.manage().logs().get(logging.Type.BROWSER); expect(logs).not.toContain(jasmine.objectContaining({ level: logging.Level.SEVERE, })); }); }); `, }); }
{ "end_byte": 1842, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/library/setup.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/library/lib-unused-decorated-class-treeshake.ts_0_1829
import assert from 'assert'; import { appendToFile, expectFileToExist, expectFileToMatch, readFile } from '../../../utils/fs'; import { ng } from '../../../utils/process'; import { libraryConsumptionSetup } from './setup'; import { updateJsonFile } from '../../../utils/project'; import { expectToFail } from '../../../utils/utils'; export default async function () { await ng('cache', 'off'); await libraryConsumptionSetup(); // Add an unused class as part of the public api. await appendToFile( 'projects/my-lib/src/lib/my-lib.component.ts', ` function something() { return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) { console.log("someDecorator"); }; } export class ExampleClass { @something() method() {} } `, ); // build the lib await ng('build', 'my-lib', '--configuration=production'); const packageJson = JSON.parse(await readFile('dist/my-lib/package.json')); assert.equal(packageJson.sideEffects, false); // build the app await ng('build', 'test-project', '--configuration=production', '--output-hashing=none'); // Output should not contain `ExampleClass` as the library is marked as side-effect free. await expectFileToExist('dist/test-project/browser/main.js'); await expectToFail(() => expectFileToMatch('dist/test-project/browser/main.js', 'someDecorator')); // Mark library as side-effectful. await updateJsonFile('dist/my-lib/package.json', (packageJson) => { packageJson.sideEffects = true; }); // build the app await ng('build', 'test-project', '--configuration=production', '--output-hashing=none'); // Output should contain `ExampleClass` as the library is marked as side-effectful. await expectFileToMatch('dist/test-project/browser/main.js', 'someDecorator'); }
{ "end_byte": 1829, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/library/lib-unused-decorated-class-treeshake.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/styles/tailwind-v2.ts_0_2698
import { deleteFile, expectFileToMatch, writeFile } from '../../../utils/fs'; import { installPackage, uninstallPackage } from '../../../utils/packages'; import { ng, silentExec } from '../../../utils/process'; import { expectToFail } from '../../../utils/utils'; export default async function () { // Temporarily turn off caching until the build cache accounts for the presence of tailwind // and its configuration file. Otherwise cached builds without tailwind will cause test failures. await ng('cache', 'off'); // Create configuration file await silentExec('npx', 'tailwindcss@2', 'init'); // Add Tailwind directives to a component style await writeFile('src/app/app.component.css', '@tailwind base; @tailwind components;'); // Add Tailwind directives to a global style await writeFile('src/styles.css', '@tailwind base; @tailwind components;'); // Ensure installation warning is present const { stderr } = await ng('build', '--configuration=development'); if (!stderr.includes("To enable Tailwind CSS, please install the 'tailwindcss' package.")) { throw new Error(`Expected tailwind installation warning. STDERR:\n${stderr}`); } // Tailwind directives should be unprocessed with missing package await expectFileToMatch( 'dist/test-project/browser/styles.css', /@tailwind base;\s+@tailwind components;/, ); await expectFileToMatch( 'dist/test-project/browser/main.js', /@tailwind base;(?:\\n|\s*)@tailwind components;/, ); // Install Tailwind await installPackage('tailwindcss@2'); // Build should succeed and process Tailwind directives await ng('build', '--configuration=development'); // Check for Tailwind output await expectFileToMatch('dist/test-project/browser/styles.css', /::placeholder/); await expectFileToMatch('dist/test-project/browser/main.js', /::placeholder/); await expectToFail(() => expectFileToMatch( 'dist/test-project/browser/styles.css', /@tailwind base;\s+@tailwind components;/, ), ); await expectToFail(() => expectFileToMatch( 'dist/test-project/browser/main.js', /@tailwind base;(?:\\n|\s*)@tailwind components;/, ), ); // Remove configuration file await deleteFile('tailwind.config.js'); // Ensure Tailwind is disabled when no configuration file is present await ng('build', '--configuration=development'); await expectFileToMatch( 'dist/test-project/browser/styles.css', /@tailwind base;\s+@tailwind components;/, ); await expectFileToMatch( 'dist/test-project/browser/main.js', /@tailwind base;(?:\\n|\s*)@tailwind components;/, ); // Uninstall Tailwind await uninstallPackage('tailwindcss'); }
{ "end_byte": 2698, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/styles/tailwind-v2.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/styles/include-paths.ts_0_2336
import { writeMultipleFiles, expectFileToMatch, replaceInFile, createDir } from '../../../utils/fs'; import { ng } from '../../../utils/process'; import { updateJsonFile } from '../../../utils/project'; export default async function () { await createDir('src/style-paths'); await writeMultipleFiles({ 'src/style-paths/_variables.scss': '$primary-color: red;', 'src/styles.scss': ` @import 'variables'; h1 { color: $primary-color; } `, 'src/app/app.component.scss': ` @import 'variables'; h2 { color: $primary-color; } `, 'src/style-paths/variables.less': '@primary-color: #ADDADD;', 'src/styles.less': ` @import 'variables'; h5 { color: @primary-color; } `, 'src/app/app.component.less': ` @import 'variables'; h6 { color: @primary-color; } `, }); await replaceInFile( 'src/app/app.component.ts', `styleUrl: './app.component.css\'`, `styleUrls: ['./app.component.scss', './app.component.less']`, ); await updateJsonFile('angular.json', (workspaceJson) => { const appArchitect = workspaceJson.projects['test-project'].architect; appArchitect.build.options.styles = [ { input: 'src/styles.scss' }, { input: 'src/styles.less' }, ]; appArchitect.build.options.stylePreprocessorOptions = { includePaths: ['src/style-paths'], }; }); await ng('build', '--configuration=development'); await expectFileToMatch('dist/test-project/browser/styles.css', /h1\s*{\s*color: red;\s*}/); await expectFileToMatch('dist/test-project/browser/main.js', /h2.*{.*color: red;.*}/); // These checks are for the less files await expectFileToMatch('dist/test-project/browser/styles.css', /h5\s*{\s*color: #ADDADD;\s*}/); await expectFileToMatch('dist/test-project/browser/main.js', /h6.*{.*color: #ADDADD;.*}/); await ng('build', '--no-aot', '--configuration=development'); await expectFileToMatch('dist/test-project/browser/styles.css', /h1\s*{\s*color: red;\s*}/); await expectFileToMatch('dist/test-project/browser/main.js', /h2.*{[\S\s]*color: red;[\S\s]*}/); await expectFileToMatch('dist/test-project/browser/styles.css', /h5\s*{\s*color: #ADDADD;\s*}/); await expectFileToMatch( 'dist/test-project/browser/main.js', /h6.*{[\S\s]*color: #ADDADD;[\S\s]*}/, ); }
{ "end_byte": 2336, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/styles/include-paths.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/styles/less.ts_0_1807
import { writeMultipleFiles, deleteFile, expectFileToMatch, replaceInFile, } from '../../../utils/fs'; import { expectToFail } from '../../../utils/utils'; import { ng } from '../../../utils/process'; import { updateJsonFile } from '../../../utils/project'; export default function () { // TODO(architect): Delete this test. It is now in devkit/build-angular. return writeMultipleFiles({ 'src/styles.less': ` @import './imported-styles.less'; body { background-color: blue; } `, 'src/imported-styles.less': 'p { background-color: red; }', 'src/app/app.component.less': ` .outer { .inner { background: #fff; } } `, }) .then(() => deleteFile('src/app/app.component.css')) .then(() => updateJsonFile('angular.json', (workspaceJson) => { const appArchitect = workspaceJson.projects['test-project'].architect; appArchitect.build.options.styles = [{ input: 'src/styles.less' }]; }), ) .then(() => replaceInFile('src/app/app.component.ts', './app.component.css', './app.component.less'), ) .then(() => ng('build', '--source-map', '--configuration=development')) .then(() => expectFileToMatch( 'dist/test-project/browser/styles.css', /body\s*{\s*background-color: blue;\s*}/, ), ) .then(() => expectFileToMatch( 'dist/test-project/browser/styles.css', /p\s*{\s*background-color: red;\s*}/, ), ) .then(() => expectToFail(() => expectFileToMatch('dist/test-project/browser/styles.css', '"mappings":""'), ), ) .then(() => expectFileToMatch( 'dist/test-project/browser/main.js', /.outer.*.inner.*background:\s*#[fF]+/, ), ); }
{ "end_byte": 1807, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/styles/less.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/styles/tailwind-v3.ts_0_3613
import { deleteFile, expectFileToMatch, writeFile } from '../../../utils/fs'; import { installPackage, uninstallPackage } from '../../../utils/packages'; import { ng, silentExec } from '../../../utils/process'; import { expectToFail } from '../../../utils/utils'; export default async function () { // Temporarily turn off caching until the build cache accounts for the presence of tailwind // and its configuration file. Otherwise cached builds without tailwind will cause test failures. await ng('cache', 'off'); // Create configuration file await silentExec('npx', 'tailwindcss@3', 'init'); // Add Tailwind directives to a component style await writeFile('src/app/app.component.css', '@tailwind base; @tailwind components;'); // Add Tailwind directives to a global style await writeFile( 'src/styles.css', ` @import url(https://fonts.googleapis.com/css?family=Roboto:400); @tailwind base; @tailwind components; `, ); // Ensure installation warning is present const { stderr } = await ng('build', '--configuration=development'); if (!stderr.includes("To enable Tailwind CSS, please install the 'tailwindcss' package.")) { throw new Error('Expected tailwind installation warning'); } // Tailwind directives should be unprocessed with missing package await expectFileToMatch( 'dist/test-project/browser/styles.css', /@tailwind base;\s+@tailwind components;/, ); await expectFileToMatch( 'dist/test-project/browser/main.js', /@tailwind base;(?:\\n|\s*)@tailwind components;/, ); // Install Tailwind await installPackage('tailwindcss@3'); // Build should succeed and process Tailwind directives await ng('build', '--configuration=development'); // Check for Tailwind output await expectFileToMatch('dist/test-project/browser/styles.css', /::placeholder/); await expectFileToMatch('dist/test-project/browser/main.js', /::placeholder/); await expectToFail(() => expectFileToMatch( 'dist/test-project/browser/styles.css', /@tailwind base;\s+@tailwind components;/, ), ); await expectToFail(() => expectFileToMatch( 'dist/test-project/browser/main.js', /@tailwind base;(?:\\n|\s*)@tailwind components;/, ), ); // Add Tailwind directives to an imported global style await writeFile('src/tailwind.scss', '@tailwind base; @tailwind components;'); await writeFile('src/styles.css', '@import "./tailwind.scss";'); // Build should succeed and process Tailwind directives await ng('build', '--configuration=development'); // Check for Tailwind output await expectFileToMatch('dist/test-project/browser/styles.css', /::placeholder/); await expectFileToMatch('dist/test-project/browser/main.js', /::placeholder/); await expectToFail(() => expectFileToMatch( 'dist/test-project/browser/styles.css', /@tailwind base;\s+@tailwind components;/, ), ); await expectToFail(() => expectFileToMatch( 'dist/test-project/browser/main.js', /@tailwind base;(?:\\n|\s*)@tailwind components;/, ), ); // Remove configuration file await deleteFile('tailwind.config.js'); // Ensure Tailwind is disabled when no configuration file is present await ng('build', '--configuration=development'); await expectFileToMatch( 'dist/test-project/browser/styles.css', /@tailwind base;\s+@tailwind components;/, ); await expectFileToMatch( 'dist/test-project/browser/main.js', /@tailwind base;(?:\\n|\s*)@tailwind components;/, ); // Uninstall Tailwind await uninstallPackage('tailwindcss'); }
{ "end_byte": 3613, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/styles/tailwind-v3.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/styles/tailwind-v3-cjs.ts_0_1416
import { expectFileToMatch, writeFile } from '../../../utils/fs'; import { installPackage, uninstallPackage } from '../../../utils/packages'; import { ng, silentExec } from '../../../utils/process'; import { updateJsonFile } from '../../../utils/project'; import { expectToFail } from '../../../utils/utils'; export default async function () { // Temporarily turn off caching until the build cache accounts for the presence of tailwind // and its configuration file. Otherwise cached builds without tailwind will cause test failures. await ng('cache', 'off'); // Add type module in package.json. await updateJsonFile('package.json', (json) => { json['type'] = 'module'; }); // Install Tailwind await installPackage('tailwindcss@3'); // Create configuration file await silentExec('npx', 'tailwindcss', 'init'); // Add Tailwind directives to a global style await writeFile('src/styles.css', '@tailwind base; @tailwind components;'); // Build should succeed and process Tailwind directives await ng('build', '--configuration=development'); // Check for Tailwind output await expectFileToMatch('dist/test-project/browser/styles.css', /::placeholder/); await expectToFail(() => expectFileToMatch( 'dist/test-project/browser/styles.css', /@tailwind base;\s+@tailwind components;/, ), ); // Uninstall Tailwind await uninstallPackage('tailwindcss'); }
{ "end_byte": 1416, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/styles/tailwind-v3-cjs.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/styles/scss.ts_0_1548
import { writeMultipleFiles, deleteFile, expectFileToMatch, replaceInFile, } from '../../../utils/fs'; import { expectToFail } from '../../../utils/utils'; import { ng } from '../../../utils/process'; import { updateJsonFile } from '../../../utils/project'; export default async function () { await writeMultipleFiles({ 'src/styles.scss': ` @import './imported-styles.scss'; body { background-color: blue; } `, 'src/imported-styles.scss': 'p { background-color: red; }', 'src/app/app.component.scss': ` .outer { .inner { background: #fff; } } `, }); await updateJsonFile('angular.json', (workspaceJson) => { const appArchitect = workspaceJson.projects['test-project'].architect; appArchitect.build.options.styles = [{ input: 'src/styles.scss' }]; }); await deleteFile('src/app/app.component.css'); await replaceInFile('src/app/app.component.ts', './app.component.css', './app.component.scss'); await ng('build', '--source-map', '--configuration=development'); await expectFileToMatch( 'dist/test-project/browser/styles.css', /body\s*{\s*background-color: blue;\s*}/, ); await expectFileToMatch( 'dist/test-project/browser/styles.css', /p\s*{\s*background-color: red;\s*}/, ); await expectToFail(() => expectFileToMatch('dist/test-project/browser/styles.css', '"mappings":""'), ); await expectFileToMatch( 'dist/test-project/browser/main.js', /.outer.*.inner.*background:\s*#[fF]+/, ); }
{ "end_byte": 1548, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/styles/scss.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/styles/scss-partial-resolution.ts_0_1225
import { installPackage } from '../../../utils/packages'; import { writeMultipleFiles, deleteFile, replaceInFile } from '../../../utils/fs'; import { ng } from '../../../utils/process'; import { updateJsonFile } from '../../../utils/project'; export default async function () { // Supports resolving node_modules with are pointing to partial files partial files. // @material/button/button below points to @material/button/_button.scss // https://unpkg.com/browse/@material/[email protected]/_button.scss await installPackage('@material/[email protected]'); await writeMultipleFiles({ 'src/styles.scss': ` @use '@material/button/button'; @include button.core-styles; `, 'src/app/app.component.scss': ` @use '@material/button/button'; @include button.core-styles; `, }); await updateJsonFile('angular.json', (workspaceJson) => { const appArchitect = workspaceJson.projects['test-project'].architect; appArchitect.build.options.styles = ['src/styles.scss']; }); await deleteFile('src/app/app.component.css'); await replaceInFile('src/app/app.component.ts', './app.component.css', './app.component.scss'); await ng('build', '--configuration=development'); }
{ "end_byte": 1225, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/styles/scss-partial-resolution.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/styles/symlinked-global.ts_0_1156
import { symlinkSync } from 'fs'; import { resolve } from 'path'; import { expectFileToMatch, writeMultipleFiles } from '../../../utils/fs'; import { ng } from '../../../utils/process'; import { updateJsonFile } from '../../../utils/project'; export default async function () { await writeMultipleFiles({ 'src/styles.scss': `p { color: red }`, 'src/styles-for-link.scss': `p { color: blue }`, }); symlinkSync(resolve('src/styles-for-link.scss'), resolve('src/styles-linked.scss')); await updateJsonFile('angular.json', (workspaceJson) => { const appArchitect = workspaceJson.projects['test-project'].architect; appArchitect.build.options.styles = ['src/styles.scss', 'src/styles-linked.scss']; }); await ng('build', '--configuration=development'); await expectFileToMatch('dist/test-project/browser/styles.css', 'red'); await expectFileToMatch('dist/test-project/browser/styles.css', 'blue'); await ng('build', '--preserve-symlinks', '--configuration=development'); await expectFileToMatch('dist/test-project/browser/styles.css', 'red'); await expectFileToMatch('dist/test-project/browser/styles.css', 'blue'); }
{ "end_byte": 1156, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/styles/symlinked-global.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/styles/sass.ts_0_1532
import { writeMultipleFiles, deleteFile, expectFileToMatch, replaceInFile, } from '../../../utils/fs'; import { expectToFail } from '../../../utils/utils'; import { ng } from '../../../utils/process'; import { updateJsonFile } from '../../../utils/project'; export default async function () { await writeMultipleFiles({ 'src/styles.sass': ` @import './imported-styles.sass' body background-color: blue `, 'src/imported-styles.sass': ` p background-color: red `, 'src/app/app.component.sass': ` .outer .inner background: #fff `, }); await updateJsonFile('angular.json', (workspaceJson) => { const appArchitect = workspaceJson.projects['test-project'].architect; appArchitect.build.options.styles = [{ input: 'src/styles.sass' }]; }); await deleteFile('src/app/app.component.css'); await replaceInFile('src/app/app.component.ts', './app.component.css', './app.component.sass'); await ng('build', '--source-map', '--configuration=development'); await expectFileToMatch( 'dist/test-project/browser/styles.css', /body\s*{\s*background-color: blue;\s*}/, ); await expectFileToMatch( 'dist/test-project/browser/styles.css', /p\s*{\s*background-color: red;\s*}/, ); await expectToFail(() => expectFileToMatch('dist/test-project/browser/styles.css', '"mappings":""'), ); await expectFileToMatch( 'dist/test-project/browser/main.js', /.outer.*.inner.*background:\s*#[fF]+/, ); }
{ "end_byte": 1532, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/styles/sass.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/styles/loaders.ts_0_1303
import { writeMultipleFiles, deleteFile, expectFileToMatch, replaceInFile, } from '../../../utils/fs'; import { ng } from '../../../utils/process'; import { updateJsonFile } from '../../../utils/project'; import { expectToFail } from '../../../utils/utils'; export default async function () { await writeMultipleFiles({ 'src/styles.scss': ` @import './imported-styles.scss'; body { background-color: blue; } `, 'src/imported-styles.scss': 'p { background-color: red; }', 'src/app/app.component.scss': ` .outer { .inner { background: #fff; } } `, }); await deleteFile('src/app/app.component.css'); await updateJsonFile('angular.json', (workspaceJson) => { const appArchitect = workspaceJson.projects['test-project'].architect; appArchitect.build.options.styles = [{ input: 'src/styles.scss' }]; }); await replaceInFile('src/app/app.component.ts', './app.component.css', './app.component.scss'); await ng('build', '--configuration=development'); await expectToFail(() => expectFileToMatch('dist/test-project/browser/styles.css', /exports/)); await expectToFail(() => expectFileToMatch( 'dist/test-project/browser/main.js', /".*module\.exports.*\.outer.*background:/, ), ); }
{ "end_byte": 1303, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/styles/loaders.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/styles/bootstrap.ts_0_662
import { writeMultipleFiles } from '../../../utils/fs'; import { installPackage } from '../../../utils/packages'; import { ng } from '../../../utils/process'; import { updateJsonFile } from '../../../utils/project'; export default async function () { // Install bootstrap await installPackage('bootstrap@5'); await writeMultipleFiles({ 'src/styles.scss': ` @import 'bootstrap/scss/bootstrap'; `, }); await updateJsonFile('angular.json', (workspaceJson) => { const appArchitect = workspaceJson.projects['test-project'].architect; appArchitect.build.options.styles = [{ input: 'src/styles.scss' }]; }); await ng('build'); }
{ "end_byte": 662, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/styles/bootstrap.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-static.ts_0_3609
import { join } from 'node:path'; import { existsSync } from 'node:fs'; import assert from 'node:assert'; import { expectFileNotToExist, expectFileToMatch, replaceInFile, writeFile, } from '../../../utils/fs'; import { ng, noSilentNg, silentNg } from '../../../utils/process'; import { installWorkspacePackages, uninstallPackage } from '../../../utils/packages'; import { useSha } from '../../../utils/project'; import { getGlobalVariable } from '../../../utils/env'; import { expectToFail } from '../../../utils/utils'; export default async function () { assert( getGlobalVariable('argv')['esbuild'], 'This test should not be called in the Webpack suite.', ); // Forcibly remove in case another test doesn't clean itself up. await uninstallPackage('@angular/ssr'); await ng('add', '@angular/ssr', '--server-routing', '--skip-confirmation', '--skip-install'); await useSha(); await installWorkspacePackages(); // Add routes await writeFile( 'src/app/app.routes.ts', ` import { Routes } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { SsgComponent } from './ssg/ssg.component'; import { SsgWithParamsComponent } from './ssg-with-params/ssg-with-params.component'; export const routes: Routes = [ { path: '', component: HomeComponent, }, { path: 'ssg', component: SsgComponent, }, { path: 'ssg-redirect', redirectTo: 'ssg' }, { path: 'ssg/:id', component: SsgWithParamsComponent, }, { path: '**', component: HomeComponent, }, ]; `, ); // Add server routing await writeFile( 'src/app/app.routes.server.ts', ` import { RenderMode, ServerRoute } from '@angular/ssr'; export const serverRoutes: ServerRoute[] = [ { path: 'ssg/:id', renderMode: RenderMode.Prerender, getPrerenderParams: async() => [{id: 'one'}, {id: 'two'}], }, { path: '**', renderMode: RenderMode.Server, }, ]; `, ); // Generate components for the above routes const componentNames: string[] = ['home', 'ssg', 'ssg-with-params']; for (const componentName of componentNames) { await silentNg('generate', 'component', componentName); } // Should error as above we set `RenderMode.Server` const { message: errorMessage } = await expectToFail(() => noSilentNg('build', '--output-mode=static'), ); assert.match( errorMessage, new RegExp( `Route '/' is configured with server render mode, but the build 'outputMode' is set to 'static'.`, ), ); // Fix the error await replaceInFile('src/app/app.routes.server.ts', 'RenderMode.Server', 'RenderMode.Prerender'); await noSilentNg('build', '--output-mode=static'); const expects: Record<string, string> = { 'index.html': 'home works!', 'ssg/index.html': 'ssg works!', 'ssg/one/index.html': 'ssg-with-params works!', 'ssg/two/index.html': 'ssg-with-params works!', // When static redirects as generated as meta tags. 'ssg-redirect/index.html': '<meta http-equiv="refresh" content="0; url=/ssg">', }; for (const [filePath, fileMatch] of Object.entries(expects)) { await expectFileToMatch(join('dist/test-project/browser', filePath), fileMatch); } // Check that server directory does not exist assert( !existsSync('dist/test-project/server'), 'Server directory should not exist when output-mode is static', ); // Should not prerender the catch all await expectFileNotToExist(join('dist/test-project/browser/**/index.html')); }
{ "end_byte": 3609, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-static.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/server-rendering/express-engine-standalone.ts_0_4727
import { getGlobalVariable } from '../../../utils/env'; import { rimraf, writeMultipleFiles } from '../../../utils/fs'; import { findFreePort } from '../../../utils/network'; import { installWorkspacePackages } from '../../../utils/packages'; import { execAndWaitForOutputToMatch, ng } from '../../../utils/process'; import { updateJsonFile, updateServerFileForWebpack, useSha } from '../../../utils/project'; export default async function () { // forcibly remove in case another test doesn't clean itself up await rimraf('node_modules/@angular/ssr'); await ng('add', '@angular/ssr', '--server-routing', '--skip-confirmation', '--skip-install'); const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; if (!useWebpackBuilder) { // Disable prerendering await updateJsonFile('angular.json', (json) => { const build = json['projects']['test-project']['architect']['build']; build.options.outputMode = undefined; }); await updateServerFileForWebpack('src/server.ts'); } await useSha(); await installWorkspacePackages(); await writeMultipleFiles({ 'src/app/app.component.css': `div { color: #000 }`, 'src/styles.css': `* { color: #000 }`, 'src/main.ts': `import { bootstrapApplication } from '@angular/platform-browser'; import { AppComponent } from './app/app.component'; import { appConfig } from './app/app.config'; (window as any)['doBootstrap'] = () => { bootstrapApplication(AppComponent, appConfig).catch((err) => console.error(err)); }; `, 'e2e/src/app.e2e-spec.ts': ` import { browser, by, element } from 'protractor'; import * as webdriver from 'selenium-webdriver'; function verifyNoBrowserErrors() { return browser .manage() .logs() .get('browser') .then(function (browserLog: any[]) { const errors: any[] = []; browserLog.filter((logEntry) => { const msg = logEntry.message; console.log('>> ' + msg); if (logEntry.level.value >= webdriver.logging.Level.INFO.value) { errors.push(msg); } }); expect(errors).toEqual([]); }); } describe('Hello world E2E Tests', () => { beforeAll(async () => { await browser.waitForAngularEnabled(false); }); it('should display: Welcome', async () => { // Load the page without waiting for Angular since it is not bootstrapped automatically. await browser.driver.get(browser.baseUrl); const style = await browser.driver.findElement(by.css('style[ng-app-id="ng"]')); expect(await style.getText()).not.toBeNull(); // Test the contents from the server. const serverDiv = await browser.driver.findElement(by.css('h1')); expect(await serverDiv.getText()).toMatch('Hello'); // Bootstrap the client side app. await browser.executeScript('doBootstrap()'); // Retest the contents after the client bootstraps. expect(await element(by.css('h1')).getText()).toMatch('Hello'); // Make sure the server styles got replaced by client side ones. expect(await element(by.css('style[ng-app-id="ng"]')).isPresent()).toBeFalsy(); expect(await element(by.css('style')).getText()).toMatch(''); // Make sure there were no client side errors. await verifyNoBrowserErrors(); }); it('stylesheets should be configured to load asynchronously', async () => { // Load the page without waiting for Angular since it is not bootstrapped automatically. await browser.driver.get(browser.baseUrl); // Test the contents from the server. const styleTag = await browser.driver.findElement(by.css('link[rel="stylesheet"]')); expect(await styleTag.getAttribute('media')).toMatch('all'); // Make sure there were no client side errors. await verifyNoBrowserErrors(); }); }); `, }); async function spawnServer(): Promise<number> { const port = await findFreePort(); const runCommand = useWebpackBuilder ? 'serve:ssr' : 'serve:ssr:test-project'; await execAndWaitForOutputToMatch( 'npm', ['run', runCommand], /Node Express server listening on/, { 'PORT': String(port), }, ); return port; } await ng('build'); if (useWebpackBuilder) { // Build server code await ng('run', `test-project:server`); } const port = await spawnServer(); await ng('e2e', `--base-url=http://localhost:${port}`, '--dev-server-target='); }
{ "end_byte": 4727, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/server-rendering/express-engine-standalone.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/server-rendering/express-engine-ngmodule.ts_0_5926
import { getGlobalVariable } from '../../../utils/env'; import { rimraf, writeMultipleFiles } from '../../../utils/fs'; import { findFreePort } from '../../../utils/network'; import { installWorkspacePackages } from '../../../utils/packages'; import { execAndWaitForOutputToMatch, ng } from '../../../utils/process'; import { updateJsonFile, updateServerFileForWebpack, useCIChrome, useCIDefaults, useSha, } from '../../../utils/project'; export default async function () { // forcibly remove in case another test doesn't clean itself up await rimraf('node_modules/@angular/ssr'); await ng('generate', 'app', 'test-project-two', '--no-standalone', '--skip-install'); await ng('generate', 'private-e2e', '--related-app-name=test-project-two'); // Setup testing to use CI Chrome. await useCIChrome('test-project-two', 'projects/test-project-two/e2e/'); await useCIDefaults('test-project-two'); const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; if (useWebpackBuilder) { await updateJsonFile('angular.json', (json) => { const build = json['projects']['test-project-two']['architect']['build']; build.builder = '@angular-devkit/build-angular:browser'; build.options = { ...build.options, main: build.options.browser, browser: undefined, }; build.configurations.development = { ...build.configurations.development, vendorChunk: true, namedChunks: true, buildOptimizer: false, }; }); } await ng( 'add', '@angular/ssr', '--skip-confirmation', '--skip-install', '--project=test-project-two', ); await useSha(); await installWorkspacePackages(); if (!useWebpackBuilder) { // Disable prerendering await updateJsonFile('angular.json', (json) => { const build = json['projects']['test-project-two']['architect']['build']; build.configurations.production.prerender = false; build.options.outputMode = undefined; }); await updateServerFileForWebpack('projects/test-project-two/src/server.ts'); } await writeMultipleFiles({ 'projects/test-project-two/src/app/app.component.css': `div { color: #000 }`, 'projects/test-project-two/src/styles.css': `* { color: #000 }`, 'projects/test-project-two/src/main.ts': ` import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; (window as any)['doBootstrap'] = () => { platformBrowserDynamic() .bootstrapModule(AppModule) .catch((err) => console.error(err)); }; `, 'projects/test-project-two/e2e/src/app.e2e-spec.ts': ` import { browser, by, element } from 'protractor'; import * as webdriver from 'selenium-webdriver'; function verifyNoBrowserErrors() { return browser .manage() .logs() .get('browser') .then(function (browserLog: any[]) { const errors: any[] = []; browserLog.filter((logEntry) => { const msg = logEntry.message; console.log('>> ' + msg); if (logEntry.level.value >= webdriver.logging.Level.INFO.value) { errors.push(msg); } }); expect(errors).toEqual([]); }); } describe('Hello world E2E Tests', () => { beforeAll(async () => { await browser.waitForAngularEnabled(false); }); it('should display: Welcome', async () => { // Load the page without waiting for Angular since it is not bootstrapped automatically. await browser.driver.get(browser.baseUrl); const style = await browser.driver.findElement(by.css('style[ng-app-id="ng"]')); expect(await style.getText()).not.toBeNull(); // Test the contents from the server. const serverDiv = await browser.driver.findElement(by.css('h1')); expect(await serverDiv.getText()).toMatch('Hello'); // Bootstrap the client side app. await browser.executeScript('doBootstrap()'); // Retest the contents after the client bootstraps. expect(await element(by.css('h1')).getText()).toMatch('Hello'); // Make sure the server styles got replaced by client side ones. expect(await element(by.css('style[ng-app-id="ng"]')).isPresent()).toBeFalsy(); expect(await element(by.css('style')).getText()).toMatch(''); // Make sure there were no client side errors. await verifyNoBrowserErrors(); }); it('stylesheets should be configured to load asynchronously', async () => { // Load the page without waiting for Angular since it is not bootstrapped automatically. await browser.driver.get(browser.baseUrl); // Test the contents from the server. const styleTag = await browser.driver.findElement(by.css('link[rel="stylesheet"]')); expect(await styleTag.getAttribute('media')).toMatch('all'); // Make sure there were no client side errors. await verifyNoBrowserErrors(); }); }); `, }); async function spawnServer(): Promise<number> { const port = await findFreePort(); const runCommand = useWebpackBuilder ? 'serve:ssr' : `serve:ssr:test-project-two`; await execAndWaitForOutputToMatch( 'npm', ['run', runCommand], /Node Express server listening on/, { 'PORT': String(port), }, ); return port; } await ng('build', 'test-project-two'); if (useWebpackBuilder) { // Build server code await ng('run', `test-project-two:server`); } const port = await spawnServer(); await ng( 'e2e', '--project=test-project-two', `--base-url=http://localhost:${port}`, '--dev-server-target=', ); }
{ "end_byte": 5926, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/server-rendering/express-engine-ngmodule.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/server-rendering/express-engine-csp-nonce.ts_0_5642
import { getGlobalVariable } from '../../../utils/env'; import { rimraf, writeMultipleFiles } from '../../../utils/fs'; import { findFreePort } from '../../../utils/network'; import { installWorkspacePackages } from '../../../utils/packages'; import { execAndWaitForOutputToMatch, ng } from '../../../utils/process'; import { updateJsonFile, updateServerFileForWebpack, useSha } from '../../../utils/project'; export default async function () { const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; // forcibly remove in case another test doesn't clean itself up await rimraf('node_modules/@angular/ssr'); await ng('add', '@angular/ssr', '--server-routing', '--skip-confirmation', '--skip-install'); await useSha(); await installWorkspacePackages(); if (!useWebpackBuilder) { await updateJsonFile('angular.json', (json) => { const build = json['projects']['test-project']['architect']['build']; build.options.outputMode = undefined; build.configurations.production.prerender = false; }); await updateServerFileForWebpack('src/server.ts'); } await writeMultipleFiles({ 'src/app/app.component.css': `div { color: #000 }`, 'src/styles.css': `* { color: #000 }`, 'src/main.ts': `import { bootstrapApplication } from '@angular/platform-browser'; import { AppComponent } from './app/app.component'; import { appConfig } from './app/app.config'; (window as any)['doBootstrap'] = () => { bootstrapApplication(AppComponent, appConfig).catch((err) => console.error(err)); }; `, 'src/index.html': ` <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <base href="/"> </head> <body> <app-root ngCspNonce="{% nonce %}"></app-root> </body> </html> `, 'e2e/src/app.e2e-spec.ts': ` import { browser, by, element } from 'protractor'; import * as webdriver from 'selenium-webdriver'; function verifyNoBrowserErrors() { return browser .manage() .logs() .get('browser') .then(function (browserLog: any[]) { const errors: any[] = []; browserLog.filter((logEntry) => { const msg = logEntry.message; console.log('>> ' + msg); if (logEntry.level.value >= webdriver.logging.Level.INFO.value) { errors.push(msg); } }); expect(errors).toEqual([]); }); } describe('Hello world E2E Tests', () => { beforeAll(async () => { await browser.waitForAngularEnabled(false); }); it('should display: Welcome', async () => { // Load the page without waiting for Angular since it is not bootstrapped automatically. await browser.driver.get(browser.baseUrl); expect( await element(by.css('style[ng-app-id="ng"]')).getText() ).not.toBeNull(); // Test the contents from the server. expect(await element(by.css('h1')).getText()).toMatch('Hello'); // Bootstrap the client side app. await browser.executeScript('doBootstrap()'); // Retest the contents after the client bootstraps. expect(await element(by.css('h1')).getText()).toMatch('Hello'); // Make sure the server styles got replaced by client side ones. expect( await element(by.css('style[ng-app-id="ng"]')).isPresent() ).toBeFalsy(); expect(await element(by.css('style')).getText()).toMatch(''); // Make sure there were no client side errors. await verifyNoBrowserErrors(); }); it('stylesheets should be configured to load asynchronously', async () => { // Load the page without waiting for Angular since it is not bootstrapped automatically. await browser.driver.get(browser.baseUrl); // Test the contents from the server. const linkTag = await browser.driver.findElement( by.css('link[rel="stylesheet"]') ); expect(await linkTag.getAttribute('media')).toMatch('all'); expect(await linkTag.getAttribute('ngCspMedia')).toBeNull(); expect(await linkTag.getAttribute('onload')).toBeNull(); // Make sure there were no client side errors. await verifyNoBrowserErrors(); }); it('style tags all have a nonce attribute', async () => { // Load the page without waiting for Angular since it is not bootstrapped automatically. await browser.driver.get(browser.baseUrl); // Test the contents from the server. for (const s of await browser.driver.findElements(by.css('style'))) { expect(await s.getAttribute('nonce')).toBe('{% nonce %}'); } // Make sure there were no client side errors. await verifyNoBrowserErrors(); }); }); `, }); async function spawnServer(): Promise<number> { const port = await findFreePort(); const runCommand = useWebpackBuilder ? 'serve:ssr' : 'serve:ssr:test-project'; await execAndWaitForOutputToMatch( 'npm', ['run', runCommand], /Node Express server listening on/, { 'PORT': String(port), }, ); return port; } await ng('build'); if (useWebpackBuilder) { // Build server code await ng('run', 'test-project:server'); } const port = await spawnServer(); await ng('e2e', `--base-url=http://localhost:${port}`, '--dev-server-target='); }
{ "end_byte": 5642, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/server-rendering/express-engine-csp-nonce.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-static-http-calls.ts_0_4255
import assert, { match } from 'node:assert'; import { readFile, writeMultipleFiles } from '../../../utils/fs'; import { ng, noSilentNg, silentNg } from '../../../utils/process'; import { getGlobalVariable } from '../../../utils/env'; import { installWorkspacePackages, uninstallPackage } from '../../../utils/packages'; import { useSha } from '../../../utils/project'; export default async function () { assert( getGlobalVariable('argv')['esbuild'], 'This test should not be called in the Webpack suite.', ); // Forcibly remove in case another test doesn't clean itself up. await uninstallPackage('@angular/ssr'); await ng('add', '@angular/ssr', '--server-routing', '--skip-confirmation', '--skip-install'); await useSha(); await installWorkspacePackages(); await writeMultipleFiles({ // Add asset 'public/media.json': JSON.stringify({ dataFromAssets: true }), // Update component to do an HTTP call to asset and API. 'src/app/app.component.ts': ` import { Component, inject } from '@angular/core'; import { JsonPipe } from '@angular/common'; import { RouterOutlet } from '@angular/router'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-root', standalone: true, imports: [JsonPipe, RouterOutlet], template: \` <p>{{ assetsData | json }}</p> <p>{{ apiData | json }}</p> <router-outlet></router-outlet> \`, }) export class AppComponent { assetsData: any; apiData: any; constructor() { const http = inject(HttpClient); http.get('/media.json').toPromise().then((d) => { this.assetsData = d; }); http.get('/api').toPromise().then((d) => { this.apiData = d; }); } } `, // Add http client and route 'src/app/app.config.ts': ` import { ApplicationConfig } from '@angular/core'; import { provideRouter } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { provideClientHydration } from '@angular/platform-browser'; import { provideHttpClient, withFetch } from '@angular/common/http'; export const appConfig: ApplicationConfig = { providers: [ provideRouter([{ path: 'home', component: HomeComponent, }]), provideClientHydration(), provideHttpClient(withFetch()), ], }; `, 'src/server.ts': ` import { AngularNodeAppEngine, writeResponseToNodeResponse, isMainModule, createNodeRequestHandler } from '@angular/ssr/node'; import express from 'express'; import { fileURLToPath } from 'node:url'; import { dirname, resolve } from 'node:path'; export function app(): express.Express { const server = express(); const serverDistFolder = dirname(fileURLToPath(import.meta.url)); const browserDistFolder = resolve(serverDistFolder, '../browser'); const angularNodeAppEngine = new AngularNodeAppEngine(); server.get('/api', (req, res) => res.json({ dataFromAPI: true })); server.get('**', express.static(browserDistFolder, { maxAge: '1y', index: 'index.html' })); server.get('**', (req, res, next) => { angularNodeAppEngine.render(req) .then((response) => response ? writeResponseToNodeResponse(response, res) : next()) .catch(next); }); return server; } const server = app(); if (isMainModule(import.meta.url)) { const port = process.env['PORT'] || 4000; server.listen(port, () => { console.log(\`Node Express server listening on http://localhost:\${port}\`); }); } export const reqHandler = createNodeRequestHandler(server); `, }); await silentNg('generate', 'component', 'home'); await noSilentNg('build', '--output-mode=static'); const contents = await readFile('dist/test-project/browser/home/index.html'); match(contents, /<p>{[\S\s]*"dataFromAssets":[\s\S]*true[\S\s]*}<\/p>/); match(contents, /<p>{[\S\s]*"dataFromAPI":[\s\S]*true[\S\s]*}<\/p>/); match(contents, /home works!/); }
{ "end_byte": 4255, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-static-http-calls.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-server-platform-neutral.ts_0_4372
import { join } from 'node:path'; import { existsSync } from 'node:fs'; import assert from 'node:assert'; import { expectFileToMatch, writeMultipleFiles } from '../../../utils/fs'; import { execAndWaitForOutputToMatch, ng, noSilentNg, silentNg } from '../../../utils/process'; import { installPackage, installWorkspacePackages, uninstallPackage, } from '../../../utils/packages'; import { updateJsonFile, useSha } from '../../../utils/project'; import { getGlobalVariable } from '../../../utils/env'; import { findFreePort } from '../../../utils/network'; export default async function () { assert( getGlobalVariable('argv')['esbuild'], 'This test should not be called in the Webpack suite.', ); // Forcibly remove in case another test doesn't clean itself up. await uninstallPackage('@angular/ssr'); await ng('add', '@angular/ssr', '--server-routing', '--skip-confirmation', '--skip-install'); await useSha(); await installWorkspacePackages(); await installPackage('h3@1'); await writeMultipleFiles({ // Replace the template of app.component.html as it makes it harder to debug 'src/app/app.component.html': '<router-outlet />', 'src/app/app.routes.ts': ` import { Routes } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { SsrComponent } from './ssr/ssr.component'; import { SsgWithParamsComponent } from './ssg-with-params/ssg-with-params.component'; export const routes: Routes = [ { path: '', component: HomeComponent, }, { path: 'ssr', component: SsrComponent, }, { path: 'ssg/:id', component: SsgWithParamsComponent, }, ]; `, 'src/app/app.routes.server.ts': ` import { RenderMode, ServerRoute } from '@angular/ssr'; export const serverRoutes: ServerRoute[] = [ { path: 'ssg/:id', renderMode: RenderMode.Prerender, getPrerenderParams: async() => [{id: 'one'}, {id: 'two'}], }, { path: 'ssr', renderMode: RenderMode.Server, }, { path: '**', renderMode: RenderMode.Prerender, }, ]; `, 'src/server.ts': ` import { AngularAppEngine, createRequestHandler } from '@angular/ssr'; import { createApp, createRouter, toWebHandler, defineEventHandler, toWebRequest } from 'h3'; export const app = createApp(); const router = createRouter(); const angularAppEngine = new AngularAppEngine(); router.use( '/**', defineEventHandler((event) => angularAppEngine.render(toWebRequest(event))), ); app.use(router); export const reqHandler = createRequestHandler(toWebHandler(app)); `, }); // Generate components for the above routes const componentNames: string[] = ['home', 'ssr', 'ssg-with-params']; for (const componentName of componentNames) { await silentNg('generate', 'component', componentName); } await updateJsonFile('angular.json', (json) => { const buildTarget = json['projects']['test-project']['architect']['build']; const options = buildTarget['options']; options['ssr']['experimentalPlatform'] = 'neutral'; options['outputMode'] = 'server'; }); await noSilentNg('build'); // Valid SSG pages work const expects: Record<string, string> = { 'index.html': 'home works!', 'ssg/one/index.html': 'ssg-with-params works!', 'ssg/two/index.html': 'ssg-with-params works!', }; for (const [filePath, fileMatch] of Object.entries(expects)) { await expectFileToMatch(join('dist/test-project/browser', filePath), fileMatch); } const filesDoNotExist: string[] = ['csr/index.html', 'ssr/index.html', 'redirect/index.html']; for (const filePath of filesDoNotExist) { const file = join('dist/test-project/browser', filePath); assert.equal(existsSync(file), false, `Expected '${file}' to not exist.`); } const port = await findFreePort(); await execAndWaitForOutputToMatch( 'npx', ['-y', 'listhen@1', './dist/test-project/server/server.mjs', `--port=${port}`], /Server initialized/, ); const res = await fetch(`http://localhost:${port}/ssr`); const text = await res.text(); assert.match(text, new RegExp('ssr works!')); }
{ "end_byte": 4372, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-server-platform-neutral.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-server.ts_0_5519
import { join } from 'node:path'; import { existsSync } from 'node:fs'; import assert from 'node:assert'; import { expectFileToMatch, writeFile } from '../../../utils/fs'; import { execAndWaitForOutputToMatch, ng, noSilentNg, silentNg } from '../../../utils/process'; import { installWorkspacePackages, uninstallPackage } from '../../../utils/packages'; import { useSha } from '../../../utils/project'; import { getGlobalVariable } from '../../../utils/env'; import { findFreePort } from '../../../utils/network'; export default async function () { assert( getGlobalVariable('argv')['esbuild'], 'This test should not be called in the Webpack suite.', ); // Forcibly remove in case another test doesn't clean itself up. await uninstallPackage('@angular/ssr'); await ng('add', '@angular/ssr', '--server-routing', '--skip-confirmation', '--skip-install'); await useSha(); await installWorkspacePackages(); // Add routes await writeFile( 'src/app/app.routes.ts', ` import { Routes } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { CsrComponent } from './csr/csr.component'; import { SsrComponent } from './ssr/ssr.component'; import { SsgComponent } from './ssg/ssg.component'; import { AppShellComponent } from './app-shell/app-shell.component'; import { SsgWithParamsComponent } from './ssg-with-params/ssg-with-params.component'; export const routes: Routes = [ { path: 'app-shell', component: AppShellComponent }, { path: '', component: HomeComponent, }, { path: 'ssg', component: SsgComponent, }, { path: 'ssr', component: SsrComponent, }, { path: 'csr', component: CsrComponent, }, { path: 'redirect', redirectTo: 'ssg' }, { path: 'ssg/:id', component: SsgWithParamsComponent, }, ]; `, ); // Add server routing await writeFile( 'src/app/app.routes.server.ts', ` import { RenderMode, ServerRoute } from '@angular/ssr'; export const serverRoutes: ServerRoute[] = [ { path: 'ssg/:id', renderMode: RenderMode.Prerender, headers: { 'x-custom': 'ssg-with-params' }, getPrerenderParams: async() => [{id: 'one'}, {id: 'two'}], }, { path: 'ssr', renderMode: RenderMode.Server, headers: { 'x-custom': 'ssr' }, }, { path: 'csr', renderMode: RenderMode.Client, headers: { 'x-custom': 'csr' }, }, { path: 'app-shell', renderMode: RenderMode.AppShell, }, { path: '**', renderMode: RenderMode.Prerender, headers: { 'x-custom': 'ssg' }, }, ]; `, ); // Generate components for the above routes const componentNames: string[] = ['home', 'ssg', 'ssg-with-params', 'csr', 'ssr', 'app-shell']; for (const componentName of componentNames) { await silentNg('generate', 'component', componentName); } await noSilentNg('build', '--output-mode=server'); const expects: Record<string, string> = { 'index.html': 'home works!', 'ssg/index.html': 'ssg works!', 'ssg/one/index.html': 'ssg-with-params works!', 'ssg/two/index.html': 'ssg-with-params works!', }; for (const [filePath, fileMatch] of Object.entries(expects)) { await expectFileToMatch(join('dist/test-project/browser', filePath), fileMatch); } const filesDoNotExist: string[] = ['csr/index.html', 'ssr/index.html', 'redirect/index.html']; for (const filePath of filesDoNotExist) { const file = join('dist/test-project/browser', filePath); assert.equal(existsSync(file), false, `Expected '${file}' to not exist.`); } // Tests responses const responseExpects: Record< string, { headers: Record<string, string>; content: string; serverContext: string } > = { '/': { content: 'home works', serverContext: 'ng-server-context="ssg"', headers: { 'x-custom': 'ssg', }, }, '/ssg': { content: 'ssg works!', serverContext: 'ng-server-context="ssg"', headers: { 'x-custom': 'ssg', }, }, '/ssr': { content: 'ssr works!', serverContext: 'ng-server-context="ssr"', headers: { 'x-custom': 'ssr', }, }, '/csr': { content: 'app-shell works', serverContext: 'ng-server-context="app-shell"', headers: { 'x-custom': 'csr', }, }, }; const port = await spawnServer(); for (const [pathname, { content, headers, serverContext }] of Object.entries(responseExpects)) { const res = await fetch(`http://localhost:${port}${pathname}`); const text = await res.text(); assert.match( text, new RegExp(content), `Response for '${pathname}': ${content} was not matched in content.`, ); assert.match( text, new RegExp(serverContext), `Response for '${pathname}': ${serverContext} was not matched in content.`, ); for (const [name, value] of Object.entries(headers)) { assert.equal( res.headers.get(name), value, `Response for '${pathname}': ${name} header value did not match expected.`, ); } } } async function spawnServer(): Promise<number> { const port = await findFreePort(); await execAndWaitForOutputToMatch( 'npm', ['run', 'serve:ssr:test-project'], /Node Express server listening on/, { 'PORT': String(port), }, ); return port; }
{ "end_byte": 5519, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-server.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-server-i18n.ts_0_3584
import { join } from 'node:path'; import assert from 'node:assert'; import { expectFileToMatch, writeFile } from '../../../utils/fs'; import { execAndWaitForOutputToMatch, ng, noSilentNg, silentNg } from '../../../utils/process'; import { langTranslations, setupI18nConfig } from '../../i18n/setup'; import { findFreePort } from '../../../utils/network'; import { getGlobalVariable } from '../../../utils/env'; import { installWorkspacePackages, uninstallPackage } from '../../../utils/packages'; import { useSha } from '../../../utils/project'; export default async function () { assert( getGlobalVariable('argv')['esbuild'], 'This test should not be called in the Webpack suite.', ); // Setup project await setupI18nConfig(); // Forcibly remove in case another test doesn't clean itself up. await uninstallPackage('@angular/ssr'); await ng('add', '@angular/ssr', '--server-routing', '--skip-confirmation', '--skip-install'); await useSha(); await installWorkspacePackages(); // Add routes await writeFile( 'src/app/app.routes.ts', ` import { Routes } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { SsrComponent } from './ssr/ssr.component'; import { SsgComponent } from './ssg/ssg.component'; export const routes: Routes = [ { path: '', component: HomeComponent, }, { path: 'ssg', component: SsgComponent, }, { path: 'ssr', component: SsrComponent, }, ]; `, ); // Add server routing await writeFile( 'src/app/app.routes.server.ts', ` import { RenderMode, ServerRoute } from '@angular/ssr'; export const serverRoutes: ServerRoute[] = [ { path: '', renderMode: RenderMode.Prerender, }, { path: 'ssg', renderMode: RenderMode.Prerender, }, { path: '**', renderMode: RenderMode.Server, }, ]; `, ); // Generate components for the above routes const componentNames: string[] = ['home', 'ssg', 'ssr']; for (const componentName of componentNames) { await silentNg('generate', 'component', componentName); } await noSilentNg('build', '--output-mode=server'); const expects: Record<string, string> = { 'index.html': 'home works!', 'ssg/index.html': 'ssg works!', }; for (const { lang, outputPath } of langTranslations) { for (const [filePath, fileMatch] of Object.entries(expects)) { await expectFileToMatch(join(outputPath, filePath), `<p id="locale">${lang}</p>`); await expectFileToMatch(join(outputPath, filePath), fileMatch); } } // Tests responses const port = await spawnServer(); const pathname = '/ssr'; // We run the tests twice to ensure that the locale ID is set correctly. for (const iteration of [1, 2]) { for (const { lang, translation } of langTranslations) { const res = await fetch(`http://localhost:${port}/${lang}${pathname}`); const text = await res.text(); for (const match of [`<p id="date">${translation.date}</p>`, `<p id="locale">${lang}</p>`]) { assert.match( text, new RegExp(match), `Response for '${lang}${pathname}': '${match}' was not matched in content. Iteration: ${iteration}.`, ); } } } } async function spawnServer(): Promise<number> { const port = await findFreePort(); await execAndWaitForOutputToMatch( 'npm', ['run', 'serve:ssr:test-project'], /Node Express server listening on/, { 'PORT': String(port), }, ); return port; }
{ "end_byte": 3584, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-server-i18n.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-server-i18n-base-href.ts_0_3205
import { join } from 'node:path'; import assert from 'node:assert'; import { expectFileToMatch, writeFile } from '../../../utils/fs'; import { execAndWaitForOutputToMatch, ng, noSilentNg, silentNg } from '../../../utils/process'; import { langTranslations, setupI18nConfig } from '../../i18n/setup'; import { findFreePort } from '../../../utils/network'; import { getGlobalVariable } from '../../../utils/env'; import { installWorkspacePackages, uninstallPackage } from '../../../utils/packages'; import { useSha } from '../../../utils/project'; export default async function () { assert( getGlobalVariable('argv')['esbuild'], 'This test should not be called in the Webpack suite.', ); // Setup project await setupI18nConfig(); // Forcibly remove in case another test doesn't clean itself up. await uninstallPackage('@angular/ssr'); await ng('add', '@angular/ssr', '--server-routing', '--skip-confirmation', '--skip-install'); await useSha(); await installWorkspacePackages(); // Add routes await writeFile( 'src/app/app.routes.ts', ` import { Routes } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { SsrComponent } from './ssr/ssr.component'; import { SsgComponent } from './ssg/ssg.component'; export const routes: Routes = [ { path: '', component: HomeComponent, }, { path: 'ssg', component: SsgComponent, }, { path: 'ssr', component: SsrComponent, }, ]; `, ); // Add server routing await writeFile( 'src/app/app.routes.server.ts', ` import { RenderMode, ServerRoute } from '@angular/ssr'; export const serverRoutes: ServerRoute[] = [ { path: '', renderMode: RenderMode.Prerender, }, { path: 'ssg', renderMode: RenderMode.Prerender, }, { path: '**', renderMode: RenderMode.Server, }, ]; `, ); // Generate components for the above routes const componentNames: string[] = ['home', 'ssg', 'csr', 'ssr']; for (const componentName of componentNames) { await silentNg('generate', 'component', componentName); } await noSilentNg('build', '--output-mode=server', '--base-href=/base/'); for (const { lang, outputPath } of langTranslations) { await expectFileToMatch(join(outputPath, 'index.html'), `<p id="locale">${lang}</p>`); await expectFileToMatch(join(outputPath, 'ssg/index.html'), `<p id="locale">${lang}</p>`); } // Tests responses const port = await spawnServer(); const pathname = '/ssr'; for (const { lang } of langTranslations) { const res = await fetch(`http://localhost:${port}/base/${lang}${pathname}`); const text = await res.text(); assert.match( text, new RegExp(`<p id="locale">${lang}</p>`), `Response for '${lang}${pathname}': '<p id="locale">${lang}</p>' was not matched in content.`, ); } } async function spawnServer(): Promise<number> { const port = await findFreePort(); await execAndWaitForOutputToMatch( 'npm', ['run', 'serve:ssr:test-project'], /Node Express server listening on/, { 'PORT': String(port), }, ); return port; }
{ "end_byte": 3205, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/server-rendering/server-routes-output-mode-server-i18n-base-href.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/app-shell/app-shell-with-service-worker.ts_0_2042
import { getGlobalVariable } from '../../../utils/env'; import { appendToFile, expectFileToMatch, writeFile } from '../../../utils/fs'; import { installPackage } from '../../../utils/packages'; import { ng } from '../../../utils/process'; import { updateJsonFile } from '../../../utils/project'; const snapshots = require('../../../ng-snapshot/package.json'); export default async function () { await appendToFile('src/app/app.component.html', '<router-outlet></router-outlet>'); await ng('generate', 'service-worker', '--project', 'test-project'); await ng('generate', 'app-shell', '--project', 'test-project'); const isSnapshotBuild = getGlobalVariable('argv')['ng-snapshots']; if (isSnapshotBuild) { const packagesToInstall: string[] = []; await updateJsonFile('package.json', (packageJson) => { const dependencies = packageJson['dependencies']; // Iterate over all of the packages to update them to the snapshot version. for (const [name, version] of Object.entries( snapshots.dependencies as { [p: string]: string }, )) { if (name in dependencies && dependencies[name] !== version) { packagesToInstall.push(version); } } }); for (const pkg of packagesToInstall) { await installPackage(pkg); } } await writeFile( 'e2e/app.e2e-spec.ts', ` import { browser, by, element } from 'protractor'; it('should have ngsw in normal state', () => { browser.get('/'); // Wait for service worker to load. browser.sleep(2000); browser.waitForAngularEnabled(false); browser.get('/ngsw/state'); // Should have updated, and be in normal state. expect(element(by.css('pre')).getText()).not.toContain('Last update check: never'); expect(element(by.css('pre')).getText()).toContain('Driver state: NORMAL'); }); `, ); await ng('build'); await expectFileToMatch('dist/test-project/browser/index.html', /app-shell works!/); await ng('e2e', '--configuration=production'); }
{ "end_byte": 2042, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/app-shell/app-shell-with-service-worker.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/app-shell/app-shell-with-schematic.ts_0_1334
import { getGlobalVariable } from '../../../utils/env'; import { appendToFile, expectFileToMatch } from '../../../utils/fs'; import { installPackage } from '../../../utils/packages'; import { ng } from '../../../utils/process'; import { updateJsonFile } from '../../../utils/project'; const snapshots = require('../../../ng-snapshot/package.json'); export default async function () { await appendToFile('src/app/app.component.html', '<router-outlet></router-outlet>'); await ng('generate', 'app-shell', '--project', 'test-project'); const isSnapshotBuild = getGlobalVariable('argv')['ng-snapshots']; if (isSnapshotBuild) { const packagesToInstall: string[] = []; await updateJsonFile('package.json', (packageJson) => { const dependencies = packageJson['dependencies']; // Iterate over all of the packages to update them to the snapshot version. for (const [name, version] of Object.entries( snapshots.dependencies as { [p: string]: string }, )) { if (name in dependencies && dependencies[name] !== version) { packagesToInstall.push(version); } } }); for (const pkg of packagesToInstall) { await installPackage(pkg); } } await ng('build'); await expectFileToMatch('dist/test-project/browser/index.html', 'app-shell works!'); }
{ "end_byte": 1334, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/app-shell/app-shell-with-schematic.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/app-shell/app-shell-ngmodule.ts_0_1363
import { getGlobalVariable } from '../../../utils/env'; import { expectFileToMatch } from '../../../utils/fs'; import { installPackage } from '../../../utils/packages'; import { ng } from '../../../utils/process'; import { updateJsonFile } from '../../../utils/project'; const snapshots = require('../../../ng-snapshot/package.json'); export default async function () { await ng('generate', 'app', 'test-project-two', '--routing', '--no-standalone', '--skip-install'); await ng('generate', 'app-shell', '--project', 'test-project-two'); const isSnapshotBuild = getGlobalVariable('argv')['ng-snapshots']; if (isSnapshotBuild) { const packagesToInstall: string[] = []; await updateJsonFile('package.json', (packageJson) => { const dependencies = packageJson['dependencies']; // Iterate over all of the packages to update them to the snapshot version. for (const [name, version] of Object.entries( snapshots.dependencies as { [p: string]: string }, )) { if (name in dependencies && dependencies[name] !== version) { packagesToInstall.push(version); } } }); for (const pkg of packagesToInstall) { await installPackage(pkg); } } await ng('build', 'test-project-two'); await expectFileToMatch('dist/test-project-two/browser/index.html', 'app-shell works!'); }
{ "end_byte": 1363, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/app-shell/app-shell-ngmodule.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/prerender/discover-routes-ngmodule.ts_0_4240
import { join } from 'path'; import { getGlobalVariable } from '../../../utils/env'; import { expectFileToMatch, rimraf, writeFile } from '../../../utils/fs'; import { installWorkspacePackages } from '../../../utils/packages'; import { ng } from '../../../utils/process'; import { updateJsonFile, useSha } from '../../../utils/project'; export default async function () { const projectName = 'test-project-two'; await ng('generate', 'application', projectName, '--no-standalone', '--skip-install'); const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; if (useWebpackBuilder) { // Setup webpack builder if esbuild is not requested on the commandline await updateJsonFile('angular.json', (json) => { const build = json['projects'][projectName]['architect']['build']; build.builder = '@angular-devkit/build-angular:browser'; build.options = { ...build.options, main: build.options.browser, browser: undefined, }; build.configurations.development = { ...build.configurations.development, vendorChunk: true, namedChunks: true, buildOptimizer: false, }; }); } // Forcibly remove in case another test doesn't clean itself up. await rimraf('node_modules/@angular/ssr'); await ng( 'add', '@angular/ssr', '--project', projectName, '--skip-confirmation', '--skip-install', '--server-routing', ); await useSha(); await installWorkspacePackages(); // Add routes await writeFile( `projects/${projectName}/src/app/app-routing.module.ts`, ` import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { OneComponent } from './one/one.component'; import { TwoChildOneComponent } from './two-child-one/two-child-one.component'; import { TwoChildTwoComponent } from './two-child-two/two-child-two.component'; const routes: Routes = [ { path: '', component: OneComponent, }, { path: 'two', children: [ { path: 'two-child-one', component: TwoChildOneComponent, }, { path: 'two-child-two', component: TwoChildTwoComponent, }, ], }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], }) export class AppRoutingModule {} `, ); // Generate components for the above routes const componentNames: string[] = ['one', 'two-child-one', 'two-child-two']; for (const componentName of componentNames) { await ng('generate', 'component', componentName, '--project', projectName); } // Generate lazy routes const lazyModules: [route: string, moduleName: string][] = [ ['lazy-one', 'app.module'], ['lazy-one-child', 'lazy-one/lazy-one.module'], ['lazy-two', 'app.module'], ]; for (const [route, moduleName] of lazyModules) { await ng( 'generate', 'module', route, '--route', route, '--module', moduleName, '--project', projectName, ); } // Prerender pages if (useWebpackBuilder) { await ng('run', `${projectName}:prerender:production`); await runExpects(); return; } await ng('build', projectName, '--configuration=production'); await runExpects(); // Test also JIT mode. await ng('build', projectName, '--configuration=development', '--no-aot'); await runExpects(); async function runExpects(): Promise<void> { const expects: Record<string, string> = { 'index.html': 'one works!', 'two/index.html': 'router-outlet', 'two/two-child-one/index.html': 'two-child-one works!', 'two/two-child-two/index.html': 'two-child-two works!', 'lazy-one/index.html': 'lazy-one works!', 'lazy-one/lazy-one-child/index.html': 'lazy-one-child works!', 'lazy-two/index.html': 'lazy-two works!', }; if (!useWebpackBuilder) { expects['index.csr.html'] = '<app-root></app-root>'; } const distPath = 'dist/' + projectName + '/browser'; for (const [filePath, fileMatch] of Object.entries(expects)) { await expectFileToMatch(join(distPath, filePath), fileMatch); } } }
{ "end_byte": 4240, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/prerender/discover-routes-ngmodule.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/prerender/discover-routes-standalone.ts_0_3750
import { join } from 'path'; import { getGlobalVariable } from '../../../utils/env'; import { expectFileToMatch, readFile, rimraf, writeFile } from '../../../utils/fs'; import { installWorkspacePackages } from '../../../utils/packages'; import { ng } from '../../../utils/process'; import { useSha } from '../../../utils/project'; import { deepStrictEqual } from 'node:assert'; export default async function () { const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; // Forcibly remove in case another test doesn't clean itself up. await rimraf('node_modules/@angular/ssr'); await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); await useSha(); await installWorkspacePackages(); // Add routes await writeFile( 'src/app/app.routes.ts', ` import { Routes } from '@angular/router'; import { OneComponent } from './one/one.component'; import { TwoChildOneComponent } from './two-child-one/two-child-one.component'; import { TwoChildTwoComponent } from './two-child-two/two-child-two.component'; export const routes: Routes = [ { path: '', component: OneComponent, }, { path: 'two', children: [ { path: 'two-child-one', component: TwoChildOneComponent, }, { path: 'two-child-two', component: TwoChildTwoComponent, }, ], }, { path: 'lazy-one', children: [ { path: '', loadComponent: () => import('./lazy-one/lazy-one.component').then(c => c.LazyOneComponent), }, { path: 'lazy-one-child', loadComponent: () => import('./lazy-one-child/lazy-one-child.component').then(c => c.LazyOneChildComponent), }, ], }, { path: 'lazy-two', loadComponent: () => import('./lazy-two/lazy-two.component').then(c => c.LazyTwoComponent), }, ]; `, ); // Generate components for the above routes const componentNames: string[] = [ 'one', 'two-child-one', 'two-child-two', 'lazy-one', 'lazy-one-child', 'lazy-two', ]; for (const componentName of componentNames) { await ng('generate', 'component', componentName); } // Prerender pages if (useWebpackBuilder) { await ng('run', 'test-project:prerender:production'); await runExpects(); return; } await ng('build', '--configuration=production', '--prerender'); await runExpects(); // Test also JIT mode. await ng('build', '--configuration=development', '--prerender', '--no-aot'); await runExpects(); async function runExpects(): Promise<void> { const expects: Record<string, string> = { 'index.html': 'one works!', 'two/index.html': 'router-outlet', 'two/two-child-one/index.html': 'two-child-one works!', 'two/two-child-two/index.html': 'two-child-two works!', 'lazy-one/index.html': 'lazy-one works!', 'lazy-one/lazy-one-child/index.html': 'lazy-one-child works!', 'lazy-two/index.html': 'lazy-two works!', }; for (const [filePath, fileMatch] of Object.entries(expects)) { await expectFileToMatch(join('dist/test-project/browser', filePath), fileMatch); } if (!useWebpackBuilder) { // prerendered-routes.json file is only generated when using esbuild. const generatedRoutesStats = await readFile('dist/test-project/prerendered-routes.json'); deepStrictEqual(JSON.parse(generatedRoutesStats), { routes: { '/': {}, '/lazy-one': {}, '/lazy-one/lazy-one-child': {}, '/lazy-two': {}, '/two': {}, '/two/two-child-one': {}, '/two/two-child-two': {}, }, }); } } }
{ "end_byte": 3750, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/prerender/discover-routes-standalone.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/prerender/http-requests-assets.ts_0_2939
import { ng } from '../../../utils/process'; import { getGlobalVariable } from '../../../utils/env'; import { expectFileToMatch, rimraf, writeMultipleFiles } from '../../../utils/fs'; import { installWorkspacePackages } from '../../../utils/packages'; import { useSha } from '../../../utils/project'; export default async function () { const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; if (useWebpackBuilder) { // Not supported by the webpack based builder. return; } // Forcibly remove in case another test doesn't clean itself up. await rimraf('node_modules/@angular/ssr'); await ng('add', '@angular/ssr', '--server-routing', '--skip-confirmation'); await useSha(); await installWorkspacePackages(); await writeMultipleFiles({ // Add http client and route 'src/app/app.config.ts': ` import { ApplicationConfig } from '@angular/core'; import { provideRouter } from '@angular/router'; import {HomeComponent} from './home/home.component'; import { provideClientHydration } from '@angular/platform-browser'; import { provideHttpClient, withFetch } from '@angular/common/http'; export const appConfig: ApplicationConfig = { providers: [ provideRouter([{ path: '', component: HomeComponent, }]), provideClientHydration(), provideHttpClient(withFetch()), ], }; `, // Add asset 'public/media.json': JSON.stringify({ dataFromAssets: true }), 'public/media with-space.json': JSON.stringify({ dataFromAssetsWithSpace: true }), // Update component to do an HTTP call to asset. 'src/app/app.component.ts': ` import { Component, inject } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterOutlet } from '@angular/router'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-root', standalone: true, imports: [CommonModule, RouterOutlet], template: \` <p>{{ data | json }}</p> <p>{{ dataWithSpace | json }}</p> <router-outlet></router-outlet> \`, }) export class AppComponent { data: any; dataWithSpace: any; constructor() { const http = inject(HttpClient); http.get('/media.json').subscribe((d) => { this.data = d; }); http.get('/media%20with-space.json').subscribe((d) => { this.dataWithSpace = d; }); } } `, }); await ng('generate', 'component', 'home'); await ng('build', '--configuration=production', '--prerender'); await expectFileToMatch( 'dist/test-project/browser/index.html', /<p>{[\S\s]*"dataFromAssets":[\s\S]*true[\S\s]*}<\/p>/, ); await expectFileToMatch( 'dist/test-project/browser/index.html', /<p>{[\S\s]*"dataFromAssetsWithSpace":[\s\S]*true[\S\s]*}<\/p>/, ); }
{ "end_byte": 2939, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/prerender/http-requests-assets.ts" }
angular-cli/tests/legacy-cli/e2e/tests/build/prerender/error-with-sourcemaps.ts_0_1797
import { ng } from '../../../utils/process'; import { getGlobalVariable } from '../../../utils/env'; import { rimraf, writeMultipleFiles } from '../../../utils/fs'; import { match } from 'node:assert'; import { expectToFail } from '../../../utils/utils'; import { useSha } from '../../../utils/project'; import { installWorkspacePackages } from '../../../utils/packages'; export default async function () { const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; if (useWebpackBuilder) { return; } // Forcibly remove in case another test doesn't clean itself up. await rimraf('node_modules/@angular/ssr'); await ng('add', '@angular/ssr', '--skip-confirmation'); await useSha(); await installWorkspacePackages(); await writeMultipleFiles({ 'src/app/app.component.ts': ` import { Component } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterOutlet } from '@angular/router'; @Component({ selector: 'app-root', standalone: true, imports: [CommonModule, RouterOutlet], templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'test-ssr'; constructor() { console.log(window) } } `, }); const { message } = await expectToFail(() => ng('build', '--configuration', 'development', '--prerender'), ); match( message, // When babel is used it will add names to the sourcemap and `constructor` will be used in the stack trace. // This will currently only happen if AOT and script optimizations are set which enables advanced optimizations. /window is not defined[.\s\S]*(?:constructor|_AppComponent) \(.*app\.component\.ts\:\d+:\d+\)/, ); }
{ "end_byte": 1797, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/build/prerender/error-with-sourcemaps.ts" }
angular-cli/tests/legacy-cli/e2e/tests/i18n/ivy-localize-sourcelocale.ts_0_1914
/** * @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 { getGlobalVariable } from '../../utils/env'; import { expectFileToMatch } from '../../utils/fs'; import { ng } from '../../utils/process'; import { updateJsonFile } from '../../utils/project'; import { langTranslations, setupI18nConfig } from './setup'; export default async function () { // Setup i18n tests and config. await setupI18nConfig(); // Update angular.json await updateJsonFile('angular.json', (workspaceJson) => { const appProject = workspaceJson.projects['test-project']; // tslint:disable-next-line: no-any const i18n: Record<string, any> = appProject.i18n; i18n.sourceLocale = 'fr'; delete i18n.locales['fr']; }); // Build each locale and verify the output. await ng('build', '--configuration=development'); for (const { lang, outputPath } of langTranslations) { // does not exist in this test due to the source locale change if (lang === 'en-US') { continue; } const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; if (useWebpackBuilder) { // The only reference in a new application with Webpack is in @angular/core await expectFileToMatch(`${outputPath}/vendor.js`, lang); // Verify the locale data is registered using the global files await expectFileToMatch(`${outputPath}/vendor.js`, '.ng.common.locales'); } else { await expectFileToMatch(`${outputPath}/polyfills.js`, lang); // Verify the locale data is registered using the global files await expectFileToMatch(`${outputPath}/polyfills.js`, '.ng.common.locales'); } // Verify the HTML lang attribute is present await expectFileToMatch(`${outputPath}/index.html`, `lang="${lang}"`); } }
{ "end_byte": 1914, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/i18n/ivy-localize-sourcelocale.ts" }
angular-cli/tests/legacy-cli/e2e/tests/i18n/ivy-localize-app-shell-service-worker.ts_0_2996
import { getGlobalVariable } from '../../utils/env'; import { appendToFile, createDir, expectFileToMatch, writeFile } from '../../utils/fs'; import { installWorkspacePackages } from '../../utils/packages'; import { ng, silentNg } from '../../utils/process'; import { updateJsonFile } from '../../utils/project'; import { readNgVersion } from '../../utils/version'; const snapshots = require('../../ng-snapshot/package.json'); export default async function () { const isSnapshotBuild = getGlobalVariable('argv')['ng-snapshots']; await updateJsonFile('package.json', (packageJson) => { const dependencies = packageJson['dependencies']; dependencies['@angular/localize'] = isSnapshotBuild ? snapshots.dependencies['@angular/localize'] : readNgVersion(); }); await appendToFile('src/app/app.component.html', '<router-outlet></router-outlet>'); // Add app-shell and service-worker await silentNg('generate', 'app-shell'); await silentNg('generate', 'service-worker'); if (isSnapshotBuild) { await updateJsonFile('package.json', (packageJson) => { const dependencies = packageJson['dependencies']; dependencies['@angular/platform-server'] = snapshots.dependencies['@angular/platform-server']; dependencies['@angular/service-worker'] = snapshots.dependencies['@angular/service-worker']; dependencies['@angular/router'] = snapshots.dependencies['@angular/router']; }); } await installWorkspacePackages(); // Set configurations for each locale. const langTranslations = [ { lang: 'en-US', translation: 'Hello i18n!' }, { lang: 'fr', translation: 'Bonjour i18n!' }, ]; await updateJsonFile('angular.json', (workspaceJson) => { const appProject = workspaceJson.projects['test-project']; const appArchitect = appProject.architect; const buildOptions = appArchitect['build'].options; // Enable localization for all locales buildOptions.localize = true; // Add locale definitions to the project const i18n: Record<string, any> = (appProject.i18n = { locales: {} }); for (const { lang } of langTranslations) { if (lang == 'en-US') { i18n.sourceLocale = lang; } else { i18n.locales[lang] = `src/locale/messages.${lang}.xlf`; } } }); await createDir('src/locale'); for (const { lang } of langTranslations) { // dummy translation file. await writeFile( `src/locale/messages.${lang}.xlf`, ` <?xml version='1.0' encoding='utf-8'?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" version="1.2"> </xliff> `, ); } // Build each locale and verify the SW output. await ng('build', '--output-hashing=none'); for (const { lang } of langTranslations) { await Promise.all([ expectFileToMatch(`dist/test-project/browser/${lang}/ngsw.json`, `/${lang}/main.js`), expectFileToMatch(`dist/test-project/browser/${lang}/ngsw.json`, `/${lang}/index.html`), ]); } }
{ "end_byte": 2996, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/i18n/ivy-localize-app-shell-service-worker.ts" }
angular-cli/tests/legacy-cli/e2e/tests/i18n/ivy-localize-merging.ts_0_1644
/** * @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 { ng } from '../../utils/process'; import { updateJsonFile } from '../../utils/project'; import { expectToFail } from '../../utils/utils'; import { setupI18nConfig } from './setup'; export default async function () { // Setup i18n tests and config. await setupI18nConfig(); // Update angular.json await updateJsonFile('angular.json', (workspaceJson) => { const appProject = workspaceJson.projects['test-project']; const i18n: Record<string, any> = appProject.i18n; i18n.locales['fr'] = [i18n.locales['fr'], i18n.locales['fr']]; appProject.architect['build'].options.localize = ['fr']; }); const { stderr: err1 } = await ng('build'); if (!err1.includes('Duplicate translations for message')) { throw new Error('duplicate translations warning not shown'); } await updateJsonFile('angular.json', (workspaceJson) => { const appProject = workspaceJson.projects['test-project']; appProject.architect['build'].options.i18nDuplicateTranslation = 'error'; }); await expectToFail(() => ng('build')); await updateJsonFile('angular.json', (workspaceJson) => { const appProject = workspaceJson.projects['test-project']; appProject.architect['build'].options.i18nDuplicateTranslation = 'ignore'; }); const { stderr: err2 } = await ng('build'); if (err2.includes('Duplicate translations for message')) { throw new Error('duplicate translations message not ignore'); } }
{ "end_byte": 1644, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/i18n/ivy-localize-merging.ts" }
angular-cli/tests/legacy-cli/e2e/tests/i18n/extract-ivy-libraries.ts_0_1743
import { getGlobalVariable } from '../../utils/env'; import { expectFileToMatch, prependToFile, replaceInFile, writeFile } from '../../utils/fs'; import { installPackage, uninstallPackage } from '../../utils/packages'; import { ng } from '../../utils/process'; import { readNgVersion } from '../../utils/version'; export default async function () { // Setup a library await ng('generate', 'library', 'i18n-lib-test'); await replaceInFile( 'projects/i18n-lib-test/src/lib/i18n-lib-test.component.ts', '<p>', '<p i18n>', ); // Build library await ng('build', 'i18n-lib-test', '--configuration=development'); // Consume library in application await replaceInFile('src/app/app.component.ts', 'imports: [', 'imports: [I18nLibTestComponent,'); await prependToFile( 'src/app/app.component.ts', `import { I18nLibTestComponent } from 'i18n-lib-test';`, ); await writeFile( 'src/app/app.component.html', ` <p i18n>Hello world</p> <lib-i18n-lib-test></lib-i18n-lib-test> `, ); // Install correct version let localizeVersion = '@angular/localize@' + readNgVersion(); if (getGlobalVariable('argv')['ng-snapshots']) { localizeVersion = require('../../ng-snapshot/package.json').dependencies['@angular/localize']; } await installPackage(localizeVersion); // Extract messages await ng('extract-i18n'); await expectFileToMatch('messages.xlf', 'Hello world'); await expectFileToMatch('messages.xlf', 'i18n-lib-test works!'); await expectFileToMatch('messages.xlf', 'src/app/app.component.html'); await expectFileToMatch( 'messages.xlf', 'projects/i18n-lib-test/src/lib/i18n-lib-test.component.ts', ); await uninstallPackage('@angular/localize'); }
{ "end_byte": 1743, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/i18n/extract-ivy-libraries.ts" }
angular-cli/tests/legacy-cli/e2e/tests/i18n/ivy-localize-locale-data-augment.ts_0_1780
import { getGlobalVariable } from '../../utils/env'; import { expectFileToMatch, prependToFile, readFile, replaceInFile, writeFile, } from '../../utils/fs'; import { ng } from '../../utils/process'; import { updateJsonFile } from '../../utils/project'; import { langTranslations, setupI18nConfig } from './setup'; export default async function () { // Setup i18n tests and config. await setupI18nConfig(); // Update angular.json to only localize one locale await updateJsonFile('angular.json', (workspaceJson) => { const appProject = workspaceJson.projects['test-project']; appProject.architect['build'].options.localize = ['fr']; }); // Update E2E test to look for augmented locale data await replaceInFile('./e2e/src/app.fr.e2e-spec.ts', 'janvier', 'changed-janvier'); // Augment the locale data and import into the main application file const localeData = await readFile('node_modules/@angular/common/locales/global/fr.js'); await writeFile('src/fr-changed.js', localeData.replace('janvier', 'changed-janvier')); await prependToFile('src/main.ts', "import './fr-changed.js';\n"); // Run a build and test await ng('build'); for (const { lang, outputPath } of langTranslations) { // Only the fr locale was built for this test if (lang !== 'fr') { continue; } const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; if (useWebpackBuilder) { // The only reference in a new application with Webpack is in @angular/core await expectFileToMatch(`${outputPath}/vendor.js`, lang); } else { await expectFileToMatch(`${outputPath}/polyfills.js`, lang); } // Execute Application E2E tests with dev server await ng('e2e', `--configuration=${lang}`, '--port=0'); } }
{ "end_byte": 1780, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/i18n/ivy-localize-locale-data-augment.ts" }
angular-cli/tests/legacy-cli/e2e/tests/i18n/extract-ivy.ts_0_2185
import { join } from 'path'; import { getGlobalVariable } from '../../utils/env'; import { expectFileToMatch, writeFile } from '../../utils/fs'; import { uninstallPackage } from '../../utils/packages'; import { ng } from '../../utils/process'; import { expectToFail } from '../../utils/utils'; import { readNgVersion } from '../../utils/version'; export default async function () { // Setup an i18n enabled component await ng('generate', 'component', 'i18n-test'); await writeFile(join('src/app/i18n-test', 'i18n-test.component.html'), '<p i18n>Hello world</p>'); // Actually use the generated component to ensure it is present in the application output await writeFile( 'src/app/app.component.ts', ` import { Component } from '@angular/core'; import { I18nTestComponent } from './i18n-test/i18n-test.component'; @Component({ standalone: true, selector: 'app-root', imports: [I18nTestComponent], template: '<app-i18n-test />' }) export class AppComponent {} `, ); // Ensure localize package is not present initially await uninstallPackage('@angular/localize'); // Should fail if `@angular/localize` is missing const { message: message1 } = await expectToFail(() => ng('extract-i18n')); if (!message1.includes(`i18n extraction requires the '@angular/localize' package.`)) { throw new Error('Expected localize package error message when missing'); } // Install correct version let localizeVersion = '@angular/localize@' + readNgVersion(); if (getGlobalVariable('argv')['ng-snapshots']) { // The snapshots job won't work correctly because 'ng add' doesn't support github URLs // localizeVersion = require('../../ng-snapshot/package.json').dependencies['@angular/localize']; return; } await ng('add', localizeVersion, '--skip-confirmation'); // Should not show any warnings when extracting const { stderr: message5 } = await ng('extract-i18n'); if (message5.includes('WARNING')) { throw new Error('Expected no warnings to be shown. STDERR:\n' + message5); } await expectFileToMatch('messages.xlf', 'Hello world'); await uninstallPackage('@angular/localize'); }
{ "end_byte": 2185, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/i18n/extract-ivy.ts" }
angular-cli/tests/legacy-cli/e2e/tests/i18n/ivy-localize-basehref-absolute.ts_0_1515
/** * @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 { expectFileToMatch } from '../../utils/fs'; import { ng } from '../../utils/process'; import { updateJsonFile } from '../../utils/project'; import { langTranslations, setupI18nConfig } from './setup'; const baseHrefs: { [l: string]: string } = { 'en-US': '/en/', fr: '/fr-FR/', de: '', }; export default async function () { // Setup i18n tests and config. await setupI18nConfig(); // Update angular.json await updateJsonFile('angular.json', (workspaceJson) => { const appProject = workspaceJson.projects['test-project']; // tslint:disable-next-line: no-any const i18n: Record<string, any> = appProject.i18n; i18n.sourceLocale = { baseHref: baseHrefs['en-US'], }; i18n.locales['fr'] = { translation: i18n.locales['fr'], baseHref: baseHrefs['fr'], }; i18n.locales['de'] = { translation: i18n.locales['de'], baseHref: baseHrefs['de'], }; }); // Test absolute base href. await ng('build', '--base-href', 'http://www.example.com/', '--configuration=development'); for (const { lang, outputPath } of langTranslations) { // Verify the HTML base HREF attribute is present await expectFileToMatch( `${outputPath}/index.html`, `href="http://www.example.com${baseHrefs[lang] || '/'}"`, ); } }
{ "end_byte": 1515, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/i18n/ivy-localize-basehref-absolute.ts" }
angular-cli/tests/legacy-cli/e2e/tests/i18n/ivy-localize-hashes.ts_0_2102
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import * as fs from 'fs'; import { appendToFile } from '../../utils/fs'; import { ng } from '../../utils/process'; import { langTranslations, setupI18nConfig } from './setup'; const OUTPUT_RE = /^(?<name>(?:main|vendor|\d+))(?:\.|-)(?<hash>[a-z0-9]+)\.js$/i; export default async function () { // Setup i18n tests and config. await setupI18nConfig(); // Build each locale and record output file hashes const hashes = new Map<string, string>(); await ng('build', '--output-hashing=all', '--configuration=development'); for (const { lang, outputPath } of langTranslations) { for (const entry of fs.readdirSync(outputPath)) { const match = entry.match(OUTPUT_RE); if (!match?.groups) { continue; } hashes.set(`${lang}/${match.groups.name}`, match.groups.hash); } } // Ensure hashes for output files were recorded if (hashes.size === 0) { throw new Error('No output entries found.'); } // Alter content of a used translation file await appendToFile('src/locale/messages.fr.xlf', '\n'); // Build each locale and ensure hashes are different await ng('build', '--output-hashing=all', '--configuration=development'); for (const { lang, outputPath } of langTranslations) { for (const entry of fs.readdirSync(outputPath)) { const match = entry.match(OUTPUT_RE); if (!match?.groups) { continue; } const id = `${lang}/${match.groups.name}`; const hash = hashes.get(id); if (!hash) { throw new Error('Unexpected output entry: ' + id); } if (hash === match.groups!.hash) { throw new Error('Hash value did not change for entry: ' + id); } hashes.delete(id); } } // Check for missing entries in second build if (hashes.size > 0) { throw new Error('Missing output entries: ' + JSON.stringify(Array.from(hashes.values()))); } }
{ "end_byte": 2102, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/i18n/ivy-localize-hashes.ts" }
angular-cli/tests/legacy-cli/e2e/tests/i18n/ivy-localize-locale-data.ts_0_2200
/** * @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 { ng } from '../../utils/process'; import { updateJsonFile } from '../../utils/project'; import { setupI18nConfig } from './setup'; export default async function () { // Setup i18n tests and config. await setupI18nConfig(); // Update angular.json await updateJsonFile('angular.json', (workspaceJson) => { const appProject = workspaceJson.projects['test-project']; // tslint:disable-next-line: no-any const i18n: Record<string, any> = appProject.i18n; i18n.sourceLocale = 'fr-Abcd'; appProject.architect['build'].options.localize = ['fr-Abcd']; }); const { stderr: err1 } = await ng('build'); if (!err1.includes(`Locale data for 'fr-Abcd' cannot be found. Using locale data for 'fr'.`)) { throw new Error('locale data fallback warning not shown'); } // Update angular.json await updateJsonFile('angular.json', (workspaceJson) => { const appProject = workspaceJson.projects['test-project']; // tslint:disable-next-line: no-any const i18n: Record<string, any> = appProject.i18n; i18n.sourceLocale = 'en-US'; appProject.architect['build'].options.localize = ['en-US']; }); const { stderr: err2 } = await ng('build'); if ( err2.includes( `Locale data for 'en-US' cannot be found. No locale data will be included for this locale.`, ) ) { throw new Error('locale data not found warning shown'); } // Update angular.json await updateJsonFile('angular.json', (workspaceJson) => { const appProject = workspaceJson.projects['test-project']; const i18n: Record<string, any> = appProject.i18n; i18n.sourceLocale = 'en-x-abc'; appProject.architect['build'].options.localize = ['en-x-abc']; }); const { stderr: err3 } = await ng('build', '--configuration=development'); if ( err3.includes( `Locale data for 'en-x-abc' cannot be found. No locale data will be included for this locale.`, ) ) { throw new Error('locale data not found warning shown'); } }
{ "end_byte": 2200, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/i18n/ivy-localize-locale-data.ts" }
angular-cli/tests/legacy-cli/e2e/tests/i18n/extract-ivy-disk-cache.ts_0_1709
import { join } from 'path'; import { getGlobalVariable } from '../../utils/env'; import { expectFileToMatch, rimraf, writeFile } from '../../utils/fs'; import { installPackage, uninstallPackage } from '../../utils/packages'; import { ng } from '../../utils/process'; import { updateJsonFile } from '../../utils/project'; import { readNgVersion } from '../../utils/version'; export default async function () { // Enable disk cache await updateJsonFile('angular.json', (config) => { config.cli ??= {}; config.cli.cache = { environment: 'all' }; }); // Setup an i18n enabled component await ng('generate', 'component', 'i18n-test'); await writeFile(join('src/app/i18n-test', 'i18n-test.component.html'), '<p i18n>Hello world</p>'); await writeFile( 'src/app/app.component.ts', ` import { Component } from '@angular/core'; import { I18nTestComponent } from './i18n-test/i18n-test.component'; @Component({ standalone: true, selector: 'app-root', imports: [I18nTestComponent], template: '<app-i18n-test />' }) export class AppComponent {} `, ); // Install correct version let localizeVersion = '@angular/localize@' + readNgVersion(); if (getGlobalVariable('argv')['ng-snapshots']) { localizeVersion = require('../../ng-snapshot/package.json').dependencies['@angular/localize']; } await installPackage(localizeVersion); for (let i = 0; i < 2; i++) { // Run the extraction twice and make sure the second time round works with cache. await rimraf('messages.xlf'); await ng('extract-i18n'); await expectFileToMatch('messages.xlf', 'Hello world'); } await uninstallPackage('@angular/localize'); }
{ "end_byte": 1709, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/i18n/extract-ivy-disk-cache.ts" }
angular-cli/tests/legacy-cli/e2e/tests/i18n/ivy-localize-basehref.ts_0_2971
/** * @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 { expectFileToMatch } from '../../utils/fs'; import { ng } from '../../utils/process'; import { updateJsonFile } from '../../utils/project'; import { baseHrefs, externalServer, langTranslations, setupI18nConfig } from './setup'; export default async function () { // Setup i18n tests and config. await setupI18nConfig(); // Update angular.json await updateJsonFile('angular.json', (workspaceJson) => { const appProject = workspaceJson.projects['test-project']; // tslint:disable-next-line: no-any const i18n: Record<string, any> = appProject.i18n; i18n.sourceLocale = { baseHref: baseHrefs['en-US'], }; i18n.locales['fr'] = { translation: i18n.locales['fr'], baseHref: baseHrefs['fr'], }; i18n.locales['de'] = { translation: i18n.locales['de'], baseHref: baseHrefs['de'], }; }); // Build each locale and verify the output. await ng('build'); for (const { lang, outputPath } of langTranslations) { if (baseHrefs[lang] === undefined) { throw new Error('Invalid E2E test setup: unexpected locale ' + lang); } // Verify the HTML lang attribute is present await expectFileToMatch(`${outputPath}/index.html`, `lang="${lang}"`); // Verify the HTML base HREF attribute is present await expectFileToMatch(`${outputPath}/index.html`, `href="${baseHrefs[lang] || '/'}"`); // Execute Application E2E tests for a production build without dev server const { server, port, url } = await externalServer( outputPath, (baseHrefs[lang] as string) || '/', ); try { await ng( 'e2e', `--port=${port}`, `--configuration=${lang}`, '--dev-server-target=', `--base-url=${url}`, ); } finally { server.close(); } } // Update angular.json await updateJsonFile('angular.json', (workspaceJson) => { const appArchitect = workspaceJson.projects['test-project'].architect; appArchitect['build'].options.baseHref = '/test/'; }); // Build each locale and verify the output. await ng('build', '--configuration=development'); for (const { lang, outputPath } of langTranslations) { // Verify the HTML base HREF attribute is present await expectFileToMatch(`${outputPath}/index.html`, `href="/test${baseHrefs[lang] || '/'}"`); // Execute Application E2E tests for a production build without dev server const { server, port, url } = await externalServer( outputPath, '/test' + (baseHrefs[lang] || '/'), ); try { await ng( 'e2e', `--port=${port}`, `--configuration=${lang}`, '--dev-server-target=', `--base-url=${url}`, ); } finally { server.close(); } } }
{ "end_byte": 2971, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/i18n/ivy-localize-basehref.ts" }
angular-cli/tests/legacy-cli/e2e/tests/i18n/ivy-localize-es2015-e2e.ts_0_418
import { getGlobalVariable } from '../../utils/env'; import { ng } from '../../utils/process'; import { langTranslations, setupI18nConfig } from './setup'; export default async function () { // Setup i18n tests and config. await setupI18nConfig(); for (const { lang } of langTranslations) { // Execute Application E2E tests with dev server await ng('e2e', `--configuration=${lang}`, '--port=0'); } }
{ "end_byte": 418, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/i18n/ivy-localize-es2015-e2e.ts" }
angular-cli/tests/legacy-cli/e2e/tests/i18n/setup.ts_0_2624
import express from 'express'; import { dirname, resolve } from 'path'; import { getGlobalVariable } from '../../utils/env'; import { appendToFile, copyFile, createDir, replaceInFile, writeFile } from '../../utils/fs'; import { installPackage } from '../../utils/packages'; import { updateJsonFile } from '../../utils/project'; import { readNgVersion } from '../../utils/version'; import { Server } from 'http'; import { AddressInfo } from 'net'; // Configurations for each locale. const translationFile = 'src/locale/messages.xlf'; export const baseDir = 'dist/test-project/browser'; export const langTranslations = [ { lang: 'en-US', outputPath: `${baseDir}/en-US`, translation: { helloPartial: 'Hello', hello: 'Hello i18n!', plural: 'Updated 3 minutes ago', date: 'January', }, }, { lang: 'fr', outputPath: `${baseDir}/fr`, translation: { helloPartial: 'Bonjour', hello: 'Bonjour i18n!', plural: 'Mis à jour il y a 3 minutes', date: 'janvier', }, translationReplacements: [ ['Hello', 'Bonjour'], ['Updated', 'Mis à jour'], ['just now', 'juste maintenant'], ['one minute ago', 'il y a une minute'], [/other {/g, 'other {il y a '], ['minutes ago', 'minutes'], ], }, { lang: 'de', outputPath: `${baseDir}/de`, translation: { helloPartial: 'Hallo', hello: 'Hallo i18n!', plural: 'Aktualisiert vor 3 Minuten', date: 'Januar', }, translationReplacements: [ ['Hello', 'Hallo'], ['Updated', 'Aktualisiert'], ['just now', 'gerade jetzt'], ['one minute ago', 'vor einer Minute'], [/other {/g, 'other {vor '], ['minutes ago', 'Minuten'], ], }, ]; export const sourceLocale = langTranslations[0].lang; export interface ExternalServer { readonly server: Server; readonly port: number; readonly url: string; } /** * Create an `express` `http.Server` listening on a random port. * * Call .close() on the server return value to close the server. */ export async function externalServer(outputPath: string, baseUrl = '/'): Promise<ExternalServer> { const app = express(); app.use(baseUrl, express.static(resolve(outputPath))); return new Promise((resolve) => { const server = app.listen(0, 'localhost', () => { const { port } = server.address() as AddressInfo; resolve({ server, port, url: `http://localhost:${port}${baseUrl}`, }); }); }); } export const baseHrefs: { [l: string]: string } = { 'en-US': '/en/', fr: '/fr-FR/', de: '', };
{ "end_byte": 2624, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/i18n/setup.ts" }
angular-cli/tests/legacy-cli/e2e/tests/i18n/setup.ts_2626_9958
port async function setupI18nConfig() { // Add component with i18n content, both translations and localeData (plural, dates). await writeFile( 'src/app/app.component.ts', ` import { Component, Inject, LOCALE_ID } from '@angular/core'; import { DatePipe } from '@angular/common'; import { RouterOutlet } from '@angular/router'; @Component({ selector: 'app-root', imports: [DatePipe, RouterOutlet], standalone: true, templateUrl: './app.component.html' }) export class AppComponent { constructor(@Inject(LOCALE_ID) public locale: string) { } title = 'i18n'; jan = new Date(2000, 0, 1); minutes = 3; } `, ); await writeFile( `src/app/app.component.html`, ` <p id="hello" i18n="An introduction header for this sample">Hello {{ title }}! </p> <p id="locale">{{ locale }}</p> <p id="date">{{ jan | date : 'LLLL' }}</p> <p id="plural" i18n>Updated {minutes, plural, =0 {just now} =1 {one minute ago} other {{{minutes}} minutes ago}}</p> <router-outlet></router-outlet> `, ); await createDir(dirname(translationFile)); await writeFile( translationFile, ` <?xml version="1.0" encoding="UTF-8" ?> <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"> <file source-language="en-US" datatype="plaintext" original="ng2.template"> <body> <trans-unit id="4286451273117902052" datatype="html"> <source>Hello <x id="INTERPOLATION" equiv-text="{{ title }}"/>! </source> <context-group purpose="location"> <context context-type="sourcefile">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> <trans-unit id="4606963464835766483" datatype="html"> <source>Updated <x id="ICU" equiv-text="{minutes, plural, =0 {just now} =1 {one minute ago} other {{{minutes}} minutes ago}}" xid="1887283401472369100"/></source> <context-group purpose="location"> <context context-type="sourcefile">src/app/app.component.html</context> <context context-type="linenumber">5,6</context> </context-group> </trans-unit> <trans-unit id="2002272803511843863" datatype="html"> <source>{VAR_PLURAL, plural, =0 {just now} =1 {one minute ago} other {<x id="INTERPOLATION"/> minutes ago}}</source> <context-group purpose="location"> <context context-type="sourcefile">src/app/app.component.html</context> <context context-type="linenumber">5,6</context> </context-group> </trans-unit> </body> </file> </xliff>`, ); // Add a dynamic import to ensure syntax is supported // ng serve support: https://github.com/angular/angular-cli/issues/16248 await writeFile('src/app/dynamic.ts', `export const abc = 5;`); await appendToFile( 'src/app/app.component.ts', ` (async () => { await import('./dynamic'); })(); `, ); // Add e2e specs for each lang. for (const { lang, translation } of langTranslations) { await writeFile( `./e2e/src/app.${lang}.e2e-spec.ts`, ` import { browser, logging, element, by } from 'protractor'; describe('workspace-project App', () => { const getParagraph = async (name: string) => element(by.css('app-root p#' + name)).getText(); beforeEach(() => browser.get(browser.baseUrl)); afterEach(async () => { // Assert that there are no errors emitted from the browser const logs = await browser.manage().logs().get(logging.Type.BROWSER); expect(logs).not.toContain(jasmine.objectContaining({ level: logging.Level.SEVERE, } as logging.Entry)); }); it('should display welcome message', async () => expect(await getParagraph('hello')).toEqual('${translation.hello}')); it('should display locale', async () => expect(await getParagraph('locale')).toEqual('${lang}')); it('should display localized date', async () => expect(await getParagraph('date')).toEqual('${translation.date}')); it('should display pluralized message', async () => expect(await getParagraph('plural')).toEqual('${translation.plural}')); }); `, ); } // Update angular.json to build, serve, and test each locale. await updateJsonFile('angular.json', (workspaceJson) => { const appProject = workspaceJson.projects['test-project']; const appArchitect = workspaceJson.projects['test-project'].architect; const buildConfigs = appArchitect['build'].configurations; const serveConfigs = appArchitect['serve'].configurations; const e2eConfigs = appArchitect['e2e'].configurations; appArchitect['build'].defaultConfiguration = undefined; // Always error on missing translations. appArchitect['build'].options.optimization = true; appArchitect['build'].options.aot = true; appArchitect['build'].options.i18nMissingTranslation = 'error'; appArchitect['build'].options.sourceMap = true; appArchitect['build'].options.outputHashing = 'none'; const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; if (useWebpackBuilder) { appArchitect['build'].options.buildOptimizer = true; appArchitect['build'].options.vendorChunk = true; } // Enable localization for all locales appArchitect['build'].options.localize = true; // Add i18n config items (app, build, serve, e2e). // tslint:disable-next-line: no-any const i18n: Record<string, any> = (appProject.i18n = { locales: {} }); for (const { lang } of langTranslations) { if (lang === sourceLocale) { i18n.sourceLocale = lang; } else { i18n.locales[lang] = `src/locale/messages.${lang}.xlf`; } buildConfigs[lang] = { localize: [lang] }; serveConfigs[lang] = { buildTarget: `test-project:build:${lang}` }; e2eConfigs[lang] = { specs: [`./src/app.${lang}.e2e-spec.ts`], devServerTarget: `test-project:serve:${lang}`, }; } }); // Install the localize package if using ivy let localizeVersion = '@angular/localize@' + readNgVersion(); if (getGlobalVariable('argv')['ng-snapshots']) { localizeVersion = require('../../ng-snapshot/package.json').dependencies['@angular/localize']; } await installPackage(localizeVersion); // Make translations for each language. for (const { lang, translationReplacements } of langTranslations) { if (lang != sourceLocale) { await copyFile(translationFile, `src/locale/messages.${lang}.xlf`); for (const replacements of translationReplacements!) { await replaceInFile( `src/locale/messages.${lang}.xlf`, new RegExp(replacements[0], 'g'), replacements[1] as string, ); } for (const replacement of [[/source/g, 'target']]) { await replaceInFile( `src/locale/messages.${lang}.xlf`, new RegExp(replacement[0], 'g'), replacement[1] as string, ); } } } }
{ "end_byte": 9958, "start_byte": 2626, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/i18n/setup.ts" }
angular-cli/tests/legacy-cli/e2e/tests/i18n/ivy-localize-app-shell.ts_0_3868
import { getGlobalVariable } from '../../utils/env'; import { appendToFile, copyFile, expectFileToMatch, replaceInFile, writeFile, } from '../../utils/fs'; import { installWorkspacePackages } from '../../utils/packages'; import { ng } from '../../utils/process'; import { updateJsonFile } from '../../utils/project'; import { readNgVersion } from '../../utils/version'; const snapshots = require('../../ng-snapshot/package.json'); export default async function () { const isSnapshotBuild = getGlobalVariable('argv')['ng-snapshots']; await updateJsonFile('package.json', (packageJson) => { const dependencies = packageJson['dependencies']; dependencies['@angular/localize'] = isSnapshotBuild ? snapshots.dependencies['@angular/localize'] : readNgVersion(); }); await appendToFile('src/app/app.component.html', '<router-outlet></router-outlet>'); await ng('generate', 'app-shell', '--project', 'test-project'); if (isSnapshotBuild) { await updateJsonFile('package.json', (packageJson) => { const dependencies = packageJson['dependencies']; dependencies['@angular/platform-server'] = snapshots.dependencies['@angular/platform-server']; dependencies['@angular/router'] = snapshots.dependencies['@angular/router']; }); } await installWorkspacePackages(); // Set configurations for each locale. const langTranslations = [ { lang: 'en-US', translation: 'Hello i18n!' }, { lang: 'fr', translation: 'Bonjour i18n!' }, ]; await updateJsonFile('angular.json', (workspaceJson) => { const appProject = workspaceJson.projects['test-project']; const appArchitect = appProject.architect || appProject.targets; const buildOptions = appArchitect['build'].options; // Enable localization for all locales buildOptions.localize = true; // Add locale definitions to the project const i18n: Record<string, any> = (appProject.i18n = { locales: {} }); for (const { lang } of langTranslations) { if (lang == 'en-US') { i18n.sourceLocale = lang; } else { i18n.locales[lang] = `src/locale/messages.${lang}.xlf`; } } }); await writeFile( 'src/app/app-shell/app-shell.component.html', '<h1 i18n="An introduction header for this sample">Hello i18n!</h1>', ); // Add a translatable element // Extraction of i18n only works on browser targets. // Let's add the same translation that there is in the app-shell await writeFile( 'src/app/app.component.html', '<h1 i18n="An introduction header for this sample">Hello i18n!</h1>', ); // Extract the translation messages and copy them for each language. await ng('extract-i18n', '--output-path=src/locale'); await expectFileToMatch('src/locale/messages.xlf', `source-language="en-US"`); await expectFileToMatch('src/locale/messages.xlf', `An introduction header for this sample`); // Clean up app.component.html so that we can easily // find the translation text await writeFile('src/app/app.component.html', '<router-outlet></router-outlet>'); for (const { lang, translation } of langTranslations) { if (lang != 'en-US') { await copyFile('src/locale/messages.xlf', `src/locale/messages.${lang}.xlf`); await replaceInFile( `src/locale/messages.${lang}.xlf`, 'source-language="en-US"', `source-language="en-US" target-language="${lang}"`, ); await replaceInFile( `src/locale/messages.${lang}.xlf`, '<source>Hello i18n!</source>', `<source>Hello i18n!</source>\n<target>${translation}</target>`, ); } } // Build each locale and verify the output. await ng('build', '--output-mode=static'); for (const { lang, translation } of langTranslations) { await expectFileToMatch(`dist/test-project/browser/${lang}/index.html`, translation); } }
{ "end_byte": 3868, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/i18n/ivy-localize-app-shell.ts" }
angular-cli/tests/legacy-cli/e2e/tests/i18n/ivy-localize-es2015.ts_0_1779
import { getGlobalVariable } from '../../utils/env'; import { expectFileToMatch } from '../../utils/fs'; import { ng } from '../../utils/process'; import { expectToFail } from '../../utils/utils'; import { externalServer, langTranslations, setupI18nConfig } from './setup'; export default async function () { // Setup i18n tests and config. await setupI18nConfig(); const { stderr } = await ng('build'); if (/Locale data for .+ cannot be found/.test(stderr)) { throw new Error( `A warning for a locale not found was shown. This should not happen.\n\nSTDERR:\n${stderr}\n`, ); } for (const { lang, outputPath, translation } of langTranslations) { await expectFileToMatch(`${outputPath}/main.js`, translation.helloPartial); await expectToFail(() => expectFileToMatch(`${outputPath}/main.js`, '$localize`')); // Ensure locale is inlined (@angular/localize plugin inlines `$localize.locale` references) const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; if (useWebpackBuilder) { // The only reference in a new application with Webpack is in @angular/core await expectFileToMatch(`${outputPath}/vendor.js`, lang); } else { await expectFileToMatch(`${outputPath}/polyfills.js`, lang); } // Verify the HTML lang attribute is present await expectFileToMatch(`${outputPath}/index.html`, `lang="${lang}"`); // Execute Application E2E tests for a production build without dev server const { server, port, url } = await externalServer(outputPath, `/${lang}/`); try { await ng( 'e2e', `--port=${port}`, `--configuration=${lang}`, '--dev-server-target=', `--base-url=${url}`, ); } finally { server.close(); } } }
{ "end_byte": 1779, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/i18n/ivy-localize-es2015.ts" }
angular-cli/tests/legacy-cli/e2e/tests/i18n/ivy-localize-ssr.ts_0_2438
import { readFileSync, readdirSync } from 'node:fs'; import { getGlobalVariable } from '../../utils/env'; import { installWorkspacePackages, uninstallPackage } from '../../utils/packages'; import { ng } from '../../utils/process'; import { updateJsonFile, useSha } from '../../utils/project'; import { langTranslations, setupI18nConfig } from './setup'; export default async function () { const useWebpackBuilder = !getGlobalVariable('argv')['esbuild']; if (useWebpackBuilder) { // This test is for the `application` builder only return; } // Setup i18n tests and config. await setupI18nConfig(); // Update angular.json await updateJsonFile('angular.json', (workspaceJson) => { const appProject = workspaceJson.projects['test-project']; // tslint:disable-next-line: no-any const i18n: Record<string, any> = appProject.i18n; i18n.sourceLocale = { baseHref: '', }; i18n.locales['fr'] = { translation: i18n.locales['fr'], baseHref: '', }; i18n.locales['de'] = { translation: i18n.locales['de'], baseHref: '', }; }); // forcibly remove in case another test doesn't clean itself up await uninstallPackage('@angular/ssr'); await ng('add', '@angular/ssr', '--skip-confirmation', '--skip-install'); await useSha(); await installWorkspacePackages(); // Build each locale and verify the output. await ng('build', '--output-hashing=none'); for (const { lang, translation } of langTranslations) { let foundTranslation = false; let foundLocaleData = false; // The translation may be in any of the lazy-loaded generated chunks for (const entry of readdirSync(`dist/test-project/server/${lang}/`)) { if (!entry.endsWith('.mjs')) { continue; } const contents = readFileSync(`dist/test-project/server/${lang}/${entry}`, 'utf-8'); // Check for translated content foundTranslation ||= contents.includes(translation.helloPartial); // Check for the locale data month name to be present foundLocaleData ||= contents.includes(translation.date); if (foundTranslation && foundLocaleData) { break; } } if (!foundTranslation) { throw new Error(`Translation not found in 'dist/test-project/server/${lang}/'`); } if (!foundLocaleData) { throw new Error(`Locale data not found in 'dist/test-project/server/${lang}/'`); } } }
{ "end_byte": 2438, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/i18n/ivy-localize-ssr.ts" }
angular-cli/tests/legacy-cli/e2e/tests/i18n/ivy-localize-sourcemaps.ts_0_703
import { readFile } from '../../utils/fs'; import { ng } from '../../utils/process'; import { langTranslations, setupI18nConfig } from './setup'; export default async function () { // Setup i18n tests and config. await setupI18nConfig(); await ng('build', '--source-map'); for (const { outputPath } of langTranslations) { // Ensure sourcemap for modified file contains content const mainSourceMap = JSON.parse(await readFile(`${outputPath}/main.js.map`)); if ( mainSourceMap.version !== 3 || !Array.isArray(mainSourceMap.sources) || typeof mainSourceMap.mappings !== 'string' ) { throw new Error('invalid localized sourcemap for main.js'); } } }
{ "end_byte": 703, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/i18n/ivy-localize-sourcemaps.ts" }
angular-cli/tests/legacy-cli/e2e/tests/jest/custom-config.ts_0_1748
import { deleteFile, writeFile } from '../../utils/fs'; import { applyJestBuilder } from '../../utils/jest'; import { ng } from '../../utils/process'; import { updateJsonFile } from '../../utils/project'; export default async function (): Promise<void> { await applyJestBuilder(); { // Users may incorrectly write a Jest config believing it to be used by Angular. await writeFile( 'jest.config.mjs', ` export default { runner: 'does-not-exist', }; `.trim(), ); // Should not fail from the above (broken) configuration. Shouldn't use it at all. const { stderr } = await ng('test'); // Should warn that a Jest configuration was found but not used. if (!stderr.includes('A custom Jest config was found')) { throw new Error(`No warning about custom Jest config:\nSTDERR:\n\n${stderr}`); } if (!stderr.includes('jest.config.mjs')) { throw new Error(`Warning did not call out 'jest.config.mjs':\nSTDERR:\n\n${stderr}`); } await deleteFile('jest.config.mjs'); } { // Use `package.json` configuration instead of a `jest.config` file. await updateJsonFile('package.json', (json) => { json['jest'] = { runner: 'does-not-exist', }; }); // Should not fail from the above (broken) configuration. Shouldn't use it at all. const { stderr } = await ng('test'); // Should warn that a Jest configuration was found but not used. if (!stderr.includes('A custom Jest config was found')) { throw new Error(`No warning about custom Jest config:\nSTDERR:\n\n${stderr}`); } if (!stderr.includes('package.json')) { throw new Error(`Warning did not call out 'package.json':\nSTDERR:\n\n${stderr}`); } } }
{ "end_byte": 1748, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/jest/custom-config.ts" }
angular-cli/tests/legacy-cli/e2e/tests/jest/basic.ts_0_369
import { applyJestBuilder } from '../../utils/jest'; import { ng } from '../../utils/process'; export default async function (): Promise<void> { await applyJestBuilder(); const { stderr } = await ng('test'); if (!stderr.includes('Jest builder is currently EXPERIMENTAL')) { throw new Error(`No experimental notice in stderr.\nSTDERR:\n\n${stderr}`); } }
{ "end_byte": 369, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/tests/jest/basic.ts" }
angular-cli/tests/legacy-cli/e2e/ng-snapshot/BUILD.bazel_0_174
load("@build_bazel_rules_nodejs//:index.bzl", "copy_to_bin") copy_to_bin( name = "ng-snapshot", srcs = ["package.json"], visibility = ["//visibility:public"], )
{ "end_byte": 174, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/ng-snapshot/BUILD.bazel" }
angular-cli/tests/legacy-cli/e2e/utils/project.ts_0_7119
import * as fs from 'fs'; import * as path from 'path'; import { prerelease, SemVer } from 'semver'; import { getGlobalVariable } from './env'; import { readFile, replaceInFile, writeFile } from './fs'; import { gitCommit } from './git'; import { findFreePort } from './network'; import { installWorkspacePackages, PkgInfo } from './packages'; import { execAndWaitForOutputToMatch, git, ng } from './process'; export function updateJsonFile(filePath: string, fn: (json: any) => any | void) { return readFile(filePath).then((tsConfigJson) => { // Remove single and multiline comments const tsConfig = JSON.parse(tsConfigJson.replace(/\/\*\s(.|\n|\r)*\s\*\/|\/\/.*/g, '')) as any; const result = fn(tsConfig) || tsConfig; return writeFile(filePath, JSON.stringify(result, null, 2)); }); } export function updateTsConfig(fn: (json: any) => any | void) { return updateJsonFile('tsconfig.json', fn); } export async function ngServe(...args: string[]) { const port = await findFreePort(); const esbuild = getGlobalVariable('argv')['esbuild']; const validBundleRegEx = esbuild ? /complete\./ : /Compiled successfully\./; await execAndWaitForOutputToMatch( 'ng', ['serve', '--port', String(port), ...args], validBundleRegEx, ); return port; } export async function prepareProjectForE2e(name: string) { const argv: Record<string, unknown> = getGlobalVariable('argv'); await git('config', 'user.email', '[email protected]'); await git('config', 'user.name', 'Angular CLI E2E'); await git('config', 'commit.gpgSign', 'false'); await git('config', 'core.longpaths', 'true'); if (argv['ng-snapshots'] || argv['ng-tag']) { await useSha(); } console.log(`Project ${name} created... Installing packages.`); await installWorkspacePackages(); await ng('generate', 'private-e2e', '--related-app-name', name); await useCIChrome(name, 'e2e'); await useCIChrome(name, ''); await useCIDefaults(name); // Force sourcemaps to be from the root of the filesystem. await updateJsonFile('tsconfig.json', (json) => { json['compilerOptions']['sourceRoot'] = '/'; }); await gitCommit('prepare-project-for-e2e'); } export function useBuiltPackagesVersions(): Promise<void> { const packages: { [name: string]: PkgInfo } = getGlobalVariable('package-tars'); return updateJsonFile('package.json', (json) => { json['dependencies'] ??= {}; json['devDependencies'] ??= {}; for (const packageName of Object.keys(packages)) { if (packageName in json['dependencies']) { json['dependencies'][packageName] = packages[packageName].version; } else if (packageName in json['devDependencies']) { json['devDependencies'][packageName] = packages[packageName].version; } } }); } export async function useSha(): Promise<void> { const argv = getGlobalVariable('argv'); if (!argv['ng-snapshots'] && !argv['ng-tag']) { return; } // We need more than the sha here, version is also needed. Examples of latest tags: // 7.0.0-beta.4+dd2a650 // 6.1.6+4a8d56a const label = argv['ng-tag'] || ''; const ngSnapshotVersions = require('../ng-snapshot/package.json'); return updateJsonFile('package.json', (json) => { // Install over the project with snapshot builds. function replaceDependencies(key: string) { const missingSnapshots: string[] = []; Object.keys(json[key] || {}) .filter((name) => name.startsWith('@angular/')) .forEach((name) => { const pkgName = name.split(/\//)[1]; if (pkgName === 'cli' || pkgName === 'ssr' || pkgName === 'build') { return; } if (label) { json[key][`@angular/${pkgName}`] = `github:angular/${pkgName}-builds${label}`; } else { const replacement = ngSnapshotVersions.dependencies[`@angular/${pkgName}`]; if (!replacement) { missingSnapshots.push(`missing @angular/${pkgName}`); } json[key][`@angular/${pkgName}`] = replacement; } }); if (missingSnapshots.length > 0) { throw new Error( 'e2e test with --ng-snapshots requires all angular packages be ' + 'listed in tests/legacy-cli/e2e/ng-snapshot/package.json.\nErrors:\n' + missingSnapshots.join('\n '), ); } } replaceDependencies('dependencies'); replaceDependencies('devDependencies'); }); } export function useCIDefaults(projectName = 'test-project'): Promise<void> { return updateJsonFile('angular.json', (workspaceJson) => { // Disable progress reporting on CI to reduce spam. const project = workspaceJson.projects[projectName]; const appTargets = project.targets || project.architect; appTargets.build.options.progress = false; appTargets.test.options.progress = false; if (appTargets.e2e) { // Disable auto-updating webdriver in e2e. appTargets.e2e.options.webdriverUpdate = false; // Use a random port in e2e. appTargets.e2e.options.port = 0; } if (appTargets.serve) { // Use a random port in serve. appTargets.serve.options ??= {}; appTargets.serve.options.port = 0; } }); } export async function useCIChrome(projectName: string, projectDir = ''): Promise<void> { const protractorConf = path.join(projectDir, 'protractor.conf.js'); if (fs.existsSync(protractorConf)) { // Ensure the headless sandboxed chrome is configured in the protractor config await replaceInFile( protractorConf, `browserName: 'chrome'`, `browserName: 'chrome', chromeOptions: { args: ['--headless', '--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage'], binary: String.raw\`${process.env.CHROME_BIN}\`, }`, ); await replaceInFile( protractorConf, 'directConnect: true,', `directConnect: true, chromeDriver: String.raw\`${process.env.CHROMEDRIVER_BIN}\`,`, ); } const karmaConf = path.join(projectDir, 'karma.conf.js'); if (fs.existsSync(karmaConf)) { // Ensure the headless sandboxed chrome is configured in the karma config await replaceInFile( karmaConf, `browsers: ['Chrome'],`, `browsers: ['ChromeHeadlessNoSandbox'], customLaunchers: { ChromeHeadlessNoSandbox: { base: 'ChromeHeadless', flags: ['--no-sandbox', '--headless', '--disable-gpu', '--disable-dev-shm-usage'], }, },`, ); } // Update to use the headless sandboxed chrome return updateJsonFile('angular.json', (workspaceJson) => { const project = workspaceJson.projects[projectName]; const appTargets = project.targets || project.architect; appTargets.test.options.browsers = 'ChromeHeadlessNoSandbox'; }); } export function getNgCLIVersion(): SemVer { const packages: { [name: string]: PkgInfo } = getGlobalVariable('package-tars'); return new SemVer(packages['@angular/cli'].version); } export function isPrereleaseCli(): boolean { return (prerelease(getNgCLIVersion())?.length ?? 0) > 0; }
{ "end_byte": 7119, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/utils/project.ts" }
angular-cli/tests/legacy-cli/e2e/utils/project.ts_7121_9006
export function updateServerFileForWebpack(filepath: string): Promise<void> { return writeFile( filepath, ` import { APP_BASE_HREF } from '@angular/common'; import { CommonEngine } from '@angular/ssr/node'; import express from 'express'; import { fileURLToPath } from 'node:url'; import { dirname, join, resolve } from 'node:path'; import bootstrap from './main.server'; // The Express app is exported so that it can be used by serverless Functions. export function app(): express.Express { const server = express(); const serverDistFolder = dirname(fileURLToPath(import.meta.url)); const browserDistFolder = resolve(serverDistFolder, '../browser'); const indexHtml = join(serverDistFolder, 'index.server.html'); const commonEngine = new CommonEngine(); server.set('view engine', 'html'); server.set('views', browserDistFolder); server.get('**', express.static(browserDistFolder, { maxAge: '1y', index: 'index.html', })); // All regular routes use the Angular engine server.get('**', (req, res, next) => { const { protocol, originalUrl, baseUrl, headers } = req; commonEngine .render({ bootstrap, documentFilePath: indexHtml, url: \`\${protocol}://\${headers.host}\${originalUrl}\`, publicPath: browserDistFolder, providers: [{ provide: APP_BASE_HREF, useValue: baseUrl }], }) .then((html) => res.send(html)) .catch((err) => next(err)); }); return server; } function run(): void { const port = process.env['PORT'] || 4000; const server = app(); server.listen(port, () => { console.log(\`Node Express server listening on http://localhost:\${port}\`); }); } run(); `, ); }
{ "end_byte": 9006, "start_byte": 7121, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/utils/project.ts" }
angular-cli/tests/legacy-cli/e2e/utils/process.ts_0_7830
import * as ansiColors from 'ansi-colors'; import { spawn, SpawnOptions } from 'child_process'; import * as child_process from 'child_process'; import { concat, defer, EMPTY, from, lastValueFrom, catchError, repeat } from 'rxjs'; import { getGlobalVariable, getGlobalVariablesEnv } from './env'; import treeKill from 'tree-kill'; import { delimiter, join, resolve } from 'path'; interface ExecOptions { silent?: boolean; waitForMatch?: RegExp; env?: NodeJS.ProcessEnv; stdin?: string; cwd?: string; } /** * While `NPM_CONFIG_` and `YARN_` are case insensitive we filter based on case. * This is because when invoking a command using `yarn` it will add a bunch of these variables in lower case. * This causes problems when we try to update the variables during the test setup. */ const NPM_CONFIG_RE = /^(NPM_CONFIG_|YARN_|NO_UPDATE_NOTIFIER)/; let _processes: child_process.ChildProcess[] = []; export type ProcessOutput = { stdout: string; stderr: string; }; function _exec(options: ExecOptions, cmd: string, args: string[]): Promise<ProcessOutput> { // Create a separate instance to prevent unintended global changes to the color configuration const colors = ansiColors.create(); const cwd = options.cwd ?? process.cwd(); const env = options.env ?? process.env; console.log( `==========================================================================================`, ); // Ensure the custom npm and yarn global bin is on the PATH // https://docs.npmjs.com/cli/v8/configuring-npm/folders#executables const paths = [ join(getGlobalVariable('yarn-global'), 'bin'), join(getGlobalVariable('npm-global'), process.platform.startsWith('win') ? '' : 'bin'), env.PATH || process.env['PATH'], ].join(delimiter); args = args.filter((x) => x !== undefined); const flags = [ options.silent && 'silent', options.waitForMatch && `matching(${options.waitForMatch})`, ] .filter((x) => !!x) // Remove false and undefined. .join(', ') .replace(/^(.+)$/, ' [$1]'); // Proper formatting. console.log(colors.blue(`Running \`${cmd} ${args.map((x) => `"${x}"`).join(' ')}\`${flags}...`)); console.log(colors.blue(`CWD: ${cwd}`)); const spawnOptions: SpawnOptions = { cwd, env: { ...env, PATH: paths }, }; if (process.platform.startsWith('win')) { args.unshift('/c', cmd); cmd = 'cmd.exe'; spawnOptions['stdio'] = 'pipe'; } const childProcess = child_process.spawn(cmd, args, spawnOptions); _processes.push(childProcess); // Create the error here so the stack shows who called this function. const error = new Error(); return new Promise<ProcessOutput>((resolve, reject) => { let stdout = ''; let stderr = ''; let matched = false; // Return log info about the current process status function envDump() { return `STDOUT:\n${stdout}\n\nSTDERR:\n${stderr}`; } childProcess.stdout!.on('data', (data: Buffer) => { stdout += data.toString('utf-8'); if (options.waitForMatch && stdout.match(options.waitForMatch)) { resolve({ stdout, stderr }); matched = true; } if (options.silent) { return; } data .toString('utf-8') .split(/[\n\r]+/) .filter((line) => line !== '') .forEach((line) => console.log(' ' + line)); }); childProcess.stderr!.on('data', (data: Buffer) => { stderr += data.toString('utf-8'); if (options.waitForMatch && stderr.match(options.waitForMatch)) { resolve({ stdout, stderr }); matched = true; } if (options.silent) { return; } data .toString('utf-8') .split(/[\n\r]+/) .filter((line) => line !== '') .forEach((line) => console.error(colors.yellow(' ' + line))); }); childProcess.on('close', (code) => { _processes = _processes.filter((p) => p !== childProcess); if (options.waitForMatch && !matched) { reject( `Process output didn't match - "${cmd} ${args.join(' ')}": '${ options.waitForMatch }': ${code}...\n\n${envDump()}\n`, ); return; } if (!code) { resolve({ stdout, stderr }); return; } reject(`Process exit error - "${cmd} ${args.join(' ')}": ${code}...\n\n${envDump()}\n`); }); childProcess.on('error', (err) => { reject(`Process error - "${cmd} ${args.join(' ')}": ${err}...\n\n${envDump()}\n`); }); // Provide input to stdin if given. if (options.stdin) { childProcess.stdin!.write(options.stdin); childProcess.stdin!.end(); } }).catch((err) => { error.message = err.toString(); return Promise.reject(error); }); } export function extractNpmEnv() { return Object.keys(process.env) .filter((v) => NPM_CONFIG_RE.test(v)) .reduce<NodeJS.ProcessEnv>((vars, n) => { vars[n] = process.env[n]; return vars; }, {}); } function extractCIEnv(): NodeJS.ProcessEnv { return Object.keys(process.env) .filter( (v) => v.startsWith('SAUCE_') || v === 'CI' || v === 'CIRCLECI' || v === 'CHROME_BIN' || v === 'CHROME_PATH' || v === 'CHROMEDRIVER_BIN', ) .reduce<NodeJS.ProcessEnv>((vars, n) => { vars[n] = process.env[n]; return vars; }, {}); } function extractNgEnv() { return Object.keys(process.env) .filter((v) => v.startsWith('NG_')) .reduce<NodeJS.ProcessEnv>((vars, n) => { vars[n] = process.env[n]; return vars; }, {}); } export function waitForAnyProcessOutputToMatch( match: RegExp, timeout = 30000, ): Promise<ProcessOutput> { // Race between _all_ processes, and the timeout. First one to resolve/reject wins. const timeoutPromise: Promise<ProcessOutput> = new Promise((_resolve, reject) => { // Wait for 30 seconds and timeout. setTimeout(() => { reject(new Error(`Waiting for ${match} timed out (timeout: ${timeout}msec)...`)); }, timeout); }); const matchPromises: Promise<ProcessOutput>[] = _processes.map( (childProcess) => new Promise((resolve) => { let stdout = ''; let stderr = ''; childProcess.stdout!.on('data', (data: Buffer) => { stdout += data.toString(); if (stdout.match(match)) { resolve({ stdout, stderr }); } }); childProcess.stderr!.on('data', (data: Buffer) => { stderr += data.toString(); if (stderr.match(match)) { resolve({ stdout, stderr }); } }); }), ); return Promise.race(matchPromises.concat([timeoutPromise])); } export async function killAllProcesses(signal = 'SIGTERM'): Promise<void> { const processesToKill: Promise<void>[] = []; while (_processes.length) { const childProc = _processes.pop(); if (!childProc || childProc.pid === undefined) { continue; } processesToKill.push( new Promise<void>((resolve) => { treeKill(childProc.pid!, signal, () => { // Ignore all errors. // This is due to a race condition with the `waitForMatch` logic. // where promises are resolved on matches and not when the process terminates. // Also in some cases in windows we get `The operation attempted is not supported`. resolve(); }); }), ); } await Promise.all(processesToKill); } export function exec(cmd: string, ...args: string[]) { return _exec({}, cmd, args); } export function silentExec(cmd: string, ...args: string[]) { return _exec({ silent: true }, cmd, args); } export function execWithEnv(cmd: string, args: string[], env: NodeJS.ProcessEnv, stdin?: string) { return _exec({ env, stdin }, cmd, args); }
{ "end_byte": 7830, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/utils/process.ts" }
angular-cli/tests/legacy-cli/e2e/utils/process.ts_7832_13343
export async function execAndCaptureError( cmd: string, args: string[], env?: NodeJS.ProcessEnv, stdin?: string, ): Promise<Error> { try { await _exec({ env, stdin }, cmd, args); throw new Error('Tried to capture subprocess exception, but it completed successfully.'); } catch (err) { if (err instanceof Error) { return err; } throw new Error('Subprocess exception was not an Error instance'); } } export function execAndWaitForOutputToMatch( cmd: string, args: string[], match: RegExp, env?: NodeJS.ProcessEnv, ) { if (cmd === 'ng' && args[0] === 'serve') { // Accept matches up to 20 times after the initial match. // Useful because the Webpack watcher can rebuild a few times due to files changes that // happened just before the build (e.g. `git clean`). // This seems to be due to host file system differences, see // https://nodejs.org/docs/latest/api/fs.html#fs_caveats return lastValueFrom( concat( from(_exec({ waitForMatch: match, env }, cmd, args)), defer(() => waitForAnyProcessOutputToMatch(match, 2500)).pipe( repeat(20), catchError(() => EMPTY), ), ), ); } else { return _exec({ waitForMatch: match, env }, cmd, args); } } export function ng(...args: string[]) { const argv = getGlobalVariable('argv'); const maybeSilentNg = argv['nosilent'] ? noSilentNg : silentNg; if (['build', 'serve', 'test', 'e2e', 'extract-i18n'].indexOf(args[0]) != -1) { if (args[0] == 'e2e') { // Wait 1 second before running any end-to-end test. return new Promise((resolve) => setTimeout(resolve, 1000)).then(() => maybeSilentNg(...args)); } return maybeSilentNg(...args); } else { return noSilentNg(...args); } } export function noSilentNg(...args: string[]) { return _exec({}, 'ng', args); } export function silentNg(...args: string[]) { return _exec({ silent: true }, 'ng', args); } export function silentNpm(...args: string[]): Promise<ProcessOutput>; export function silentNpm(args: string[], options?: { cwd?: string }): Promise<ProcessOutput>; export function silentNpm( ...args: string[] | [args: string[], options?: { cwd?: string }] ): Promise<ProcessOutput> { if (Array.isArray(args[0])) { const [params, options] = args; return _exec( { silent: true, cwd: (options as { cwd?: string } | undefined)?.cwd, }, 'npm', params, ); } else { return _exec({ silent: true }, 'npm', args as string[]); } } export function silentYarn(...args: string[]) { return _exec({ silent: true }, 'yarn', args); } export function silentPnpm(...args: string[]) { return _exec({ silent: true }, 'pnpm', args); } export function silentBun(...args: string[]) { return _exec({ silent: true }, 'bun', args); } export function globalNpm(args: string[], env?: NodeJS.ProcessEnv) { if (!process.env.LEGACY_CLI_RUNNER) { throw new Error( 'The global npm cli should only be executed from the primary e2e runner process', ); } return _exec({ silent: true, env }, process.execPath, [require.resolve('npm'), ...args]); } export function node(...args: string[]) { return _exec({}, process.execPath, args); } export function git(...args: string[]) { return _exec({}, process.env.GIT_BIN || 'git', args); } export function silentGit(...args: string[]) { return _exec({ silent: true }, process.env.GIT_BIN || 'git', args); } /** * Launch the given entry in an child process isolated to the test environment. * * The test environment includes the local NPM registry, isolated NPM globals, * the PATH variable only referencing the local node_modules and local NPM * registry (not the test runner or standard global node_modules). */ export async function launchTestProcess(entry: string, ...args: any[]): Promise<void> { // NOTE: do NOT use the bazel TEST_TMPDIR. When sandboxing is not enabled the // TEST_TMPDIR is not sandboxed and has symlinks into the src dir in a // parent directory. Symlinks into the src dir will include package.json, // .git and other files/folders that may effect e2e tests. const tempRoot: string = getGlobalVariable('tmp-root'); const TEMP = process.env.TEMP ?? process.env.TMPDIR ?? tempRoot; // Extract explicit environment variables for the test process. const env: NodeJS.ProcessEnv = { TEMP, TMPDIR: TEMP, HOME: TEMP, // Use BAZEL_TARGET as a metadata variable to show it is a // process managed by bazel BAZEL_TARGET: process.env.BAZEL_TARGET, ...extractNpmEnv(), ...extractCIEnv(), ...extractNgEnv(), ...getGlobalVariablesEnv(), }; // Only include paths within the sandboxed test environment or external // non angular-cli paths such as /usr/bin for generic commands. env.PATH = process.env .PATH!.split(delimiter) .filter((p) => p.startsWith(tempRoot) || p.startsWith(TEMP) || !p.includes('angular-cli')) .join(delimiter); const testProcessArgs = [resolve(__dirname, 'test_process'), entry, ...args]; return new Promise<void>((resolve, reject) => { spawn(process.execPath, testProcessArgs, { stdio: 'inherit', env, }) .on('close', (code) => { if (!code) { resolve(); return; } reject(`Process error - "${testProcessArgs}`); }) .on('error', (err) => { reject(`Process exit error - "${testProcessArgs}]\n\n${err}`); }); }); }
{ "end_byte": 13343, "start_byte": 7832, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/utils/process.ts" }
angular-cli/tests/legacy-cli/e2e/utils/network.ts_0_423
import { AddressInfo, createServer } from 'net'; export function findFreePort(): Promise<number> { return new Promise<number>((resolve, reject) => { const srv = createServer(); srv.once('listening', () => { const port = (srv.address() as AddressInfo).port; srv.close((e) => (e ? reject(e) : resolve(port))); }); srv.once('error', (e) => srv.close(() => reject(e))); srv.listen(); }); }
{ "end_byte": 423, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/utils/network.ts" }
angular-cli/tests/legacy-cli/e2e/utils/web-test-runner.ts_0_847
import { silentNpm } from './process'; import { updateJsonFile } from './project'; /** Updates the `test` builder in the current workspace to use Web Test Runner with the given options. */ export async function applyWtrBuilder(): Promise<void> { await silentNpm('install', '@web/test-runner', '--save-dev'); await updateJsonFile('angular.json', (json) => { const projects = Object.values(json['projects']); if (projects.length !== 1) { throw new Error( `Expected exactly one project but found ${projects.length} projects named ${Object.keys( json['projects'], ).join(', ')}`, ); } const project = projects[0]! as any; // Update to Web Test Runner builder. const test = project['architect']['test']; test['builder'] = '@angular-devkit/build-angular:web-test-runner'; }); }
{ "end_byte": 847, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/utils/web-test-runner.ts" }
angular-cli/tests/legacy-cli/e2e/utils/assets.ts_0_2057
import { join } from 'path'; import { chmod } from 'fs/promises'; import glob from 'fast-glob'; import { getGlobalVariable } from './env'; import { resolve } from 'path'; import { copyFile } from './fs'; import { installWorkspacePackages, setRegistry } from './packages'; import { useBuiltPackagesVersions } from './project'; export function assetDir(assetName: string) { return join(__dirname, '../assets', assetName); } export function copyProjectAsset(assetName: string, to?: string) { const tempRoot = join(getGlobalVariable('projects-root'), 'test-project'); const sourcePath = assetDir(assetName); const targetPath = join(tempRoot, to || assetName); return copyFile(sourcePath, targetPath); } export function copyAssets(assetName: string, to?: string) { const seed = +Date.now(); const tempRoot = join(getGlobalVariable('projects-root'), 'assets', assetName + '-' + seed); const root = assetDir(assetName); return Promise.resolve() .then(() => { const allFiles = glob.sync('**/*', { dot: true, cwd: root }); return allFiles.reduce((promise, filePath) => { const toPath = to !== undefined ? resolve(getGlobalVariable('projects-root'), 'test-project', to, filePath) : join(tempRoot, filePath); return promise .then(() => copyFile(join(root, filePath), toPath)) .then(() => chmod(toPath, 0o777)); }, Promise.resolve()); }) .then(() => tempRoot); } /** * @returns a method that once called will restore the environment * to use the local NPM registry. * */ export async function createProjectFromAsset( assetName: string, useNpmPackages = false, skipInstall = false, ): Promise<() => Promise<void>> { const dir = await copyAssets(assetName); process.chdir(dir); await setRegistry(!useNpmPackages /** useTestRegistry */); if (!useNpmPackages) { await useBuiltPackagesVersions(); } if (!skipInstall) { await installWorkspacePackages(); } return () => setRegistry(true /** useTestRegistry */); }
{ "end_byte": 2057, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/utils/assets.ts" }
angular-cli/tests/legacy-cli/e2e/utils/fs.ts_0_3847
import { promises as fs, constants } from 'fs'; import { dirname, join } from 'path'; export function readFile(fileName: string): Promise<string> { return fs.readFile(fileName, 'utf-8'); } export function writeFile(fileName: string, content: string, options?: any): Promise<void> { return fs.writeFile(fileName, content, options); } export function deleteFile(path: string): Promise<void> { return fs.unlink(path); } export function rimraf(path: string): Promise<void> { return fs.rm(path, { force: true, recursive: true, maxRetries: 3, }); } export function moveFile(from: string, to: string): Promise<void> { return fs.rename(from, to); } export function symlinkFile(from: string, to: string, type?: string): Promise<void> { return fs.symlink(from, to, type); } export function createDir(path: string): Promise<string | undefined> { return fs.mkdir(path, { recursive: true }); } export async function copyFile(from: string, to: string): Promise<void> { await createDir(dirname(to)); return fs.copyFile(from, to, constants.COPYFILE_FICLONE); } export async function moveDirectory(from: string, to: string): Promise<void> { await rimraf(to); await createDir(to); for (const entry of await fs.readdir(from)) { const fromEntry = join(from, entry); const toEntry = join(to, entry); if ((await fs.stat(fromEntry)).isFile()) { await copyFile(fromEntry, toEntry); } else { await moveDirectory(fromEntry, toEntry); } } } export function writeMultipleFiles(fs: { [path: string]: string }) { return Promise.all(Object.keys(fs).map((fileName) => writeFile(fileName, fs[fileName]))); } export function replaceInFile(filePath: string, match: RegExp | string, replacement: string) { return readFile(filePath).then((content: string) => writeFile(filePath, content.replace(match, replacement)), ); } export function appendToFile(filePath: string, text: string, options?: any) { return readFile(filePath).then((content: string) => writeFile(filePath, content.concat(text), options), ); } export function prependToFile(filePath: string, text: string, options?: any) { return readFile(filePath).then((content: string) => writeFile(filePath, text.concat(content), options), ); } export async function expectFileMatchToExist(dir: string, regex: RegExp): Promise<string> { const files = await fs.readdir(dir); const fileName = files.find((name) => regex.test(name)); if (!fileName) { throw new Error(`File ${regex} was expected to exist but not found...`); } return fileName; } export async function expectFileNotToExist(fileName: string): Promise<void> { try { await fs.access(fileName, constants.F_OK); } catch { return; } throw new Error(`File ${fileName} was expected not to exist but found...`); } export async function expectFileToExist(fileName: string): Promise<void> { try { await fs.access(fileName, constants.F_OK); } catch { throw new Error(`File ${fileName} was expected to exist but not found...`); } } export async function expectFileToMatch(fileName: string, regEx: RegExp | string): Promise<void> { const content = await readFile(fileName); const found = typeof regEx === 'string' ? content.includes(regEx) : content.match(regEx); if (!found) { throw new Error( `File "${fileName}" did not contain "${regEx}"...\nContent:\n${content}\n------`, ); } } export async function getFileSize(fileName: string) { const stats = await fs.stat(fileName); return stats.size; } export async function expectFileSizeToBeUnder(fileName: string, sizeInBytes: number) { const fileSize = await getFileSize(fileName); if (fileSize > sizeInBytes) { throw new Error( `File "${fileName}" exceeded file size of "${sizeInBytes}". Size is ${fileSize}.`, ); } }
{ "end_byte": 3847, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/utils/fs.ts" }
angular-cli/tests/legacy-cli/e2e/utils/test_process.ts_0_516
const testScript: string = process.argv[2]; const testModule = require(testScript); const testFunction: () => Promise<void> | void = typeof testModule == 'function' ? testModule : typeof testModule.default == 'function' ? testModule.default : () => { throw new Error('Invalid test module.'); }; (async () => { try { await testFunction(); } catch (e) { console.error('Test Process error', e); process.exitCode = -1; } finally { process.exit(); } })();
{ "end_byte": 516, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/utils/test_process.ts" }
angular-cli/tests/legacy-cli/e2e/utils/utils.ts_0_1519
import assert from 'assert'; import { mkdtemp, realpath, rm } from 'fs/promises'; import { tmpdir } from 'os'; import path from 'path'; export function expectToFail(fn: () => Promise<any>, errorMessage?: string): Promise<Error> { return fn().then( () => { const functionSource = fn.name || (<any>fn).source || fn.toString(); const errorDetails = errorMessage ? `\n\tDetails:\n\t${errorMessage}` : ''; throw new Error( `Function ${functionSource} was expected to fail, but succeeded.${errorDetails}`, ); }, (err) => { return err instanceof Error ? err : new Error(err); }, ); } export async function mktempd(prefix: string, tempRoot?: string): Promise<string> { return realpath(await mkdtemp(path.join(tempRoot ?? tmpdir(), prefix))); } export async function mockHome(cb: (home: string) => Promise<void>): Promise<void> { const tempHome = await mktempd('angular-cli-e2e-home-'); const oldHome = process.env.HOME; process.env.HOME = tempHome; try { await cb(tempHome); } finally { process.env.HOME = oldHome; await rm(tempHome, { recursive: true, force: true }); } } export function assertIsError(value: unknown): asserts value is Error & { code?: string } { const isError = value instanceof Error || // The following is needing to identify errors coming from RxJs. (typeof value === 'object' && value && 'name' in value && 'message' in value); assert(isError, 'catch clause variable is not an Error instance'); }
{ "end_byte": 1519, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/utils/utils.ts" }
angular-cli/tests/legacy-cli/e2e/utils/packages.ts_0_2122
import { getGlobalVariable } from './env'; import { ProcessOutput, silentBun, silentNpm, silentPnpm, silentYarn } from './process'; export interface PkgInfo { readonly name: string; readonly version: string; readonly path: string; } export function getActivePackageManager(): 'npm' | 'yarn' | 'bun' | 'pnpm' { return getGlobalVariable('package-manager'); } export async function installWorkspacePackages(options?: { force?: boolean }): Promise<void> { switch (getActivePackageManager()) { case 'npm': const npmArgs = ['install']; if (options?.force) { npmArgs.push('--force'); } await silentNpm(...npmArgs); break; case 'yarn': await silentYarn('install'); break; case 'pnpm': await silentPnpm('install'); break; case 'bun': await silentBun('install'); break; } } export async function installPackage(specifier: string, registry?: string): Promise<ProcessOutput> { const registryOption = registry ? [`--registry=${registry}`] : []; switch (getActivePackageManager()) { case 'npm': return silentNpm('install', specifier, ...registryOption); case 'yarn': return silentYarn('add', specifier, ...registryOption); case 'bun': return silentBun('add', specifier, ...registryOption); case 'pnpm': return silentPnpm('add', specifier, ...registryOption); } } export async function uninstallPackage(name: string): Promise<ProcessOutput> { switch (getActivePackageManager()) { case 'npm': return silentNpm('uninstall', name); case 'yarn': return silentYarn('remove', name); case 'bun': return silentBun('remove', name); case 'pnpm': return silentPnpm('remove', name); } } export async function setRegistry(useTestRegistry: boolean): Promise<void> { const url = useTestRegistry ? getGlobalVariable('package-registry') : 'https://registry.npmjs.org'; // Ensure local test registry is used when outside a project // Yarn supports both `NPM_CONFIG_REGISTRY` and `YARN_REGISTRY`. process.env['NPM_CONFIG_REGISTRY'] = url; }
{ "end_byte": 2122, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/utils/packages.ts" }
angular-cli/tests/legacy-cli/e2e/utils/tar.ts_0_1270
/** * @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 fs from 'fs'; import { normalize } from 'path'; import { Parse } from 'tar'; /** * Extract and return the contents of a single file out of a tar file. * * @param tarball the tar file to extract from * @param filePath the path of the file to extract * @returns the Buffer of file or an error on fs/tar error or file not found */ export async function extractFile(tarball: string, filePath: string): Promise<Buffer> { return new Promise((resolve, reject) => { fs.createReadStream(tarball) .pipe( new Parse({ strict: true, filter: (p) => normalize(p) === normalize(filePath), // TODO: @types/tar 'entry' does not have ReadEntry.on onentry: (entry: any) => { const chunks: Buffer[] = []; entry.on('data', (chunk: any) => chunks!.push(chunk)); entry.on('error', reject); entry.on('finish', () => resolve(Buffer.concat(chunks!))); }, }), ) .on('close', () => reject(`${tarball} does not contain ${filePath}`)); }); }
{ "end_byte": 1270, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/utils/tar.ts" }
angular-cli/tests/legacy-cli/e2e/utils/registry.ts_0_3156
import { ChildProcess, fork } from 'node:child_process'; import { on } from 'node:events'; import { join } from 'node:path'; import { getGlobalVariable } from './env'; import { writeFile, readFile } from './fs'; import { mktempd } from './utils'; export async function createNpmRegistry( port: number, httpsPort: number, withAuthentication = false, ): Promise<ChildProcess> { // Setup local package registry const registryPath = await mktempd('angular-cli-e2e-registry-'); let configContent = await readFile( join(__dirname, '../../', withAuthentication ? 'verdaccio_auth.yaml' : 'verdaccio.yaml'), ); configContent = configContent.replace(/\$\{HTTP_PORT\}/g, String(port)); configContent = configContent.replace(/\$\{HTTPS_PORT\}/g, String(httpsPort)); const configPath = join(registryPath, 'verdaccio.yaml'); await writeFile(configPath, configContent); const verdaccioServer = fork(require.resolve('verdaccio/bin/verdaccio'), ['-c', configPath]); for await (const events of on(verdaccioServer, 'message', { signal: AbortSignal.timeout(30_000), })) { if ( events.some( (event: unknown) => event && typeof event === 'object' && 'verdaccio_started' in event && event.verdaccio_started, ) ) { break; } } return verdaccioServer; } // Token was generated using `echo -n 'testing:s3cret' | openssl base64`. const VALID_TOKEN = `dGVzdGluZzpzM2NyZXQ=`; export function createNpmConfigForAuthentication( /** * When true, the authentication token will be scoped to the registry URL. * @example * ```ini * //localhost:4876/:_auth="dGVzdGluZzpzM2NyZXQ=" * ``` * * When false, the authentication will be added as seperate key. * @example * ```ini * _auth="dGVzdGluZzpzM2NyZXQ="` * ``` */ scopedAuthentication: boolean, /** When true, an incorrect token is used. Use this to validate authentication failures. */ invalidToken = false, ): Promise<void> { const token = invalidToken ? `invalid=` : VALID_TOKEN; const registry = (getGlobalVariable('package-secure-registry') as string).replace(/^\w+:/, ''); return writeFile( '.npmrc', scopedAuthentication ? ` ${registry}:_auth="${token}" registry=http:${registry} ` : ` _auth="${token}" registry=http:${registry} `, ); } export function setNpmEnvVarsForAuthentication( /** When true, an incorrect token is used. Use this to validate authentication failures. */ invalidToken = false, /** When true, `YARN_REGISTRY` is used instead of `NPM_CONFIG_REGISTRY`. */ useYarnEnvVariable = false, ): void { delete process.env['YARN_REGISTRY']; delete process.env['NPM_CONFIG_REGISTRY']; const registryKey = useYarnEnvVariable ? 'YARN_REGISTRY' : 'NPM_CONFIG_REGISTRY'; process.env[registryKey] = getGlobalVariable('package-secure-registry'); process.env['NPM_CONFIG__AUTH'] = invalidToken ? `invalid=` : VALID_TOKEN; // Needed for verdaccio when used with yarn // https://verdaccio.org/docs/en/cli-registry#yarn process.env['NPM_CONFIG_ALWAYS_AUTH'] = 'true'; }
{ "end_byte": 3156, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/utils/registry.ts" }
angular-cli/tests/legacy-cli/e2e/utils/BUILD.bazel_0_581
load("//tools:defaults.bzl", "ts_library") ts_library( name = "utils", testonly = True, srcs = glob(["**/*.ts"]), data = [ "//tests/legacy-cli/e2e/ng-snapshot", ], visibility = ["//visibility:public"], deps = [ "@npm//@types/semver", "@npm//@types/tar", "@npm//ansi-colors", "@npm//fast-glob", "@npm//npm", "@npm//protractor", "@npm//rxjs", "@npm//semver", "@npm//tar", "@npm//tree-kill", "@npm//verdaccio", "@npm//verdaccio-auth-memory", ], )
{ "end_byte": 581, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/utils/BUILD.bazel" }
angular-cli/tests/legacy-cli/e2e/utils/version.ts_0_392
import * as fs from 'fs'; import * as semver from 'semver'; export function readNgVersion(): string { const packageJson: any = JSON.parse( fs.readFileSync('./node_modules/@angular/core/package.json', 'utf8'), ) as { version: string }; return packageJson['version']; } export function ngVersionMatches(range: string): boolean { return semver.satisfies(readNgVersion(), range); }
{ "end_byte": 392, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/utils/version.ts" }
angular-cli/tests/legacy-cli/e2e/utils/env.ts_0_760
const ENV_PREFIX = 'LEGACY_CLI__'; export function setGlobalVariable(name: string, value: any) { if (value === undefined) { delete process.env[ENV_PREFIX + name]; } else { process.env[ENV_PREFIX + name] = JSON.stringify(value); } } export function getGlobalVariable<T = any>(name: string): T { const value = process.env[ENV_PREFIX + name]; if (value === undefined) { throw new Error(`Trying to access variable "${name}" but it's not defined.`); } return JSON.parse(value) as T; } export function getGlobalVariablesEnv(): NodeJS.ProcessEnv { return Object.keys(process.env) .filter((v) => v.startsWith(ENV_PREFIX)) .reduce<NodeJS.ProcessEnv>((vars, n) => { vars[n] = process.env[n]; return vars; }, {}); }
{ "end_byte": 760, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/utils/env.ts" }
angular-cli/tests/legacy-cli/e2e/utils/jest.ts_0_981
import { silentNpm } from './process'; import { updateJsonFile } from './project'; /** Updates the `test` builder in the current workspace to use Jest with the given options. */ export async function applyJestBuilder( options: {} = { tsConfig: 'tsconfig.spec.json', polyfills: ['zone.js', 'zone.js/testing'], }, ): Promise<void> { await silentNpm('install', '[email protected]', '[email protected]', '--save-dev'); await updateJsonFile('angular.json', (json) => { const projects = Object.values(json['projects']); if (projects.length !== 1) { throw new Error( `Expected exactly one project but found ${projects.length} projects named ${Object.keys( json['projects'], ).join(', ')}`, ); } const project = projects[0]! as any; // Update to Jest builder. const test = project['architect']['test']; test['builder'] = '@angular-devkit/build-angular:jest'; test['options'] = options; }); }
{ "end_byte": 981, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/utils/jest.ts" }
angular-cli/tests/legacy-cli/e2e/utils/git.ts_0_607
import { git, silentGit } from './process'; export async function gitClean(): Promise<void> { await silentGit('clean', '-df'); await silentGit('reset', '--hard'); } export async function expectGitToBeClean(): Promise<void> { const { stdout } = await silentGit('status', '--porcelain'); if (stdout != '') { throw new Error('Git repo is not clean...\n' + stdout); } } export async function gitCommit(message: string): Promise<void> { await git('add', '-A'); const { stdout } = await silentGit('status', '--porcelain'); if (stdout != '') { await git('commit', '-am', message); } }
{ "end_byte": 607, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/utils/git.ts" }
angular-cli/tests/legacy-cli/e2e/assets/protractor-saucelabs.conf.js_0_2311
// @ts-check // Protractor configuration file, see link for more information // https://github.com/angular/protractor/blob/master/lib/config.ts // https://saucelabs.com/platform/platform-configurator const { SpecReporter, StacktraceOption } = require('jasmine-spec-reporter'); const tunnelIdentifier = process.env['SAUCE_TUNNEL_IDENTIFIER']; /** * @type { import("protractor").Config } */ exports.config = { sauceUser: process.env['SAUCE_USERNAME'], sauceKey: process.env['SAUCE_ACCESS_KEY'], allScriptsTimeout: 11000, specs: ['./src/**/*.e2e-spec.ts'], // NOTE: https://saucelabs.com/products/platform-configurator can be used to determine configuration values multiCapabilities: [ { browserName: 'chrome', platform: 'Windows 11', version: '119', tunnelIdentifier, }, { browserName: 'chrome', platform: 'Windows 11', version: '116', tunnelIdentifier, }, { browserName: 'firefox', version: '119', platform: 'Windows 11', tunnelIdentifier, }, { browserName: 'firefox', version: '102', // Latest Firefox ESR version as of Sep 2023 platform: 'Windows 11', tunnelIdentifier, }, { browserName: 'safari', platform: 'macOS 13', version: '17', tunnelIdentifier, }, { browserName: 'safari', platform: 'macOS 12', version: '16', tunnelIdentifier, }, { browserName: 'MicrosoftEdge', platform: 'Windows 11', version: '118', tunnelIdentifier, }, { browserName: 'MicrosoftEdge', platform: 'Windows 11', version: '115', tunnelIdentifier, }, ], // Only allow one session at a time to prevent over saturation of Saucelabs sessions. maxSessions: 1, SELENIUM_PROMISE_MANAGER: false, baseUrl: 'http://localhost:2000/', framework: 'jasmine', jasmineNodeOpts: { showColors: true, defaultTimeoutInterval: 30000, print: function () {}, }, onPrepare() { require('ts-node').register({ project: require('path').join(__dirname, './tsconfig.json'), }); jasmine.getEnv().addReporter( new SpecReporter({ spec: { displayStacktrace: StacktraceOption.PRETTY, }, }), ); }, };
{ "end_byte": 2311, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/assets/protractor-saucelabs.conf.js" }
angular-cli/tests/legacy-cli/e2e/assets/BUILD.bazel_0_165
load("@build_bazel_rules_nodejs//:index.bzl", "copy_to_bin") copy_to_bin( name = "assets", srcs = glob(["**"]), visibility = ["//visibility:public"], )
{ "end_byte": 165, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/assets/BUILD.bazel" }
angular-cli/tests/legacy-cli/e2e/assets/nested-schematic-dependency/index.js_0_86
exports.default = (options) => tree => tree.create(options.name || 'empty-file', '');
{ "end_byte": 86, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/assets/nested-schematic-dependency/index.js" }
angular-cli/tests/legacy-cli/e2e/assets/15.0-project/README.md_0_1106
# FifteenProject This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 15.2.8. ## Development server Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The application will automatically reload if you change any of the source files. ## Code scaffolding Run `ng generate component component-name` to generate a new component. You can also use `ng generate --help` to see all the available schematics you can generate. ## Build Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. ## Running unit tests Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). ## Running end-to-end tests Run `ng e2e` to execute the end-to-end tests via a platform of your choice. To use this command, you need to first add a package that implements end-to-end testing capabilities. ## Further help To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI Overview](https://angular.dev/tools/cli) and [Command Reference](https://angular.dev/cli) pages.
{ "end_byte": 1106, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/assets/15.0-project/README.md" }
angular-cli/tests/legacy-cli/e2e/assets/15.0-project/src/index.html_0_300
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>FifteenProject</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> </head> <body> <app-root></app-root> </body> </html>
{ "end_byte": 300, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/assets/15.0-project/src/index.html" }
angular-cli/tests/legacy-cli/e2e/assets/15.0-project/src/main.ts_0_214
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; platformBrowserDynamic().bootstrapModule(AppModule) .catch(err => console.error(err));
{ "end_byte": 214, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/assets/15.0-project/src/main.ts" }
angular-cli/tests/legacy-cli/e2e/assets/15.0-project/src/styles.css_0_80
/* You can add global styles to this file, and also import other style files */
{ "end_byte": 80, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/assets/15.0-project/src/styles.css" }
angular-cli/tests/legacy-cli/e2e/assets/15.0-project/src/app/app.component.html_0_572
<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * --> <!-- * * * * * * * * * * * The content below * * * * * * * * * * * --> <!-- * * * * * * * * * * is only a placeholder * * * * * * * * * * --> <!-- * * * * * * * * * * and can be replaced. * * * * * * * * * * * --> <!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * --> <!-- * * * * * * * * * Delete the template below * * * * * * * * * * --> <!-- * * * * * * * to get started with your project! * * * * * * * * --> <!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -->
{ "end_byte": 572, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/assets/15.0-project/src/app/app.component.html" }
angular-cli/tests/legacy-cli/e2e/assets/15.0-project/src/app/app.component.html_574_5881
<style> :host { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; font-size: 14px; color: #333; box-sizing: border-box; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } h1, h2, h3, h4, h5, h6 { margin: 8px 0; } p { margin: 0; } .spacer { flex: 1; } .toolbar { position: absolute; top: 0; left: 0; right: 0; height: 60px; display: flex; align-items: center; background-color: #1976d2; color: white; font-weight: 600; } .toolbar img { margin: 0 16px; } .toolbar #twitter-logo { height: 40px; margin: 0 8px; } .toolbar #youtube-logo { height: 40px; margin: 0 16px; } .toolbar #twitter-logo:hover, .toolbar #youtube-logo:hover { opacity: 0.8; } .content { display: flex; margin: 82px auto 32px; padding: 0 16px; max-width: 960px; flex-direction: column; align-items: center; } svg.material-icons { height: 24px; width: auto; } svg.material-icons:not(:last-child) { margin-right: 8px; } .card svg.material-icons path { fill: #888; } .card-container { display: flex; flex-wrap: wrap; justify-content: center; margin-top: 16px; } .card { all: unset; border-radius: 4px; border: 1px solid #eee; background-color: #fafafa; height: 40px; width: 200px; margin: 0 8px 16px; padding: 16px; display: flex; flex-direction: row; justify-content: center; align-items: center; transition: all 0.2s ease-in-out; line-height: 24px; } .card-container .card:not(:last-child) { margin-right: 0; } .card.card-small { height: 16px; width: 168px; } .card-container .card:not(.highlight-card) { cursor: pointer; } .card-container .card:not(.highlight-card):hover { transform: translateY(-3px); box-shadow: 0 4px 17px rgba(0, 0, 0, 0.35); } .card-container .card:not(.highlight-card):hover .material-icons path { fill: rgb(105, 103, 103); } .card.highlight-card { background-color: #1976d2; color: white; font-weight: 600; border: none; width: auto; min-width: 30%; position: relative; } .card.card.highlight-card span { margin-left: 60px; } svg#rocket { width: 80px; position: absolute; left: -10px; top: -24px; } svg#rocket-smoke { height: calc(100vh - 95px); position: absolute; top: 10px; right: 180px; z-index: -10; } a, a:visited, a:hover { color: #1976d2; text-decoration: none; } a:hover { color: #125699; } .terminal { position: relative; width: 80%; max-width: 600px; border-radius: 6px; padding-top: 45px; margin-top: 8px; overflow: hidden; background-color: rgb(15, 15, 16); } .terminal::before { content: "\2022 \2022 \2022"; position: absolute; top: 0; left: 0; height: 4px; background: rgb(58, 58, 58); color: #c2c3c4; width: 100%; font-size: 2rem; line-height: 0; padding: 14px 0; text-indent: 4px; } .terminal pre { font-family: SFMono-Regular,Consolas,Liberation Mono,Menlo,monospace; color: white; padding: 0 1rem 1rem; margin: 0; } .circle-link { height: 40px; width: 40px; border-radius: 40px; margin: 8px; background-color: white; border: 1px solid #eeeeee; display: flex; justify-content: center; align-items: center; cursor: pointer; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24); transition: 1s ease-out; } .circle-link:hover { transform: translateY(-0.25rem); box-shadow: 0px 3px 15px rgba(0, 0, 0, 0.2); } footer { margin-top: 8px; display: flex; align-items: center; line-height: 20px; } footer a { display: flex; align-items: center; } .github-star-badge { color: #24292e; display: flex; align-items: center; font-size: 12px; padding: 3px 10px; border: 1px solid rgba(27,31,35,.2); border-radius: 3px; background-image: linear-gradient(-180deg,#fafbfc,#eff3f6 90%); margin-left: 4px; font-weight: 600; } .github-star-badge:hover { background-image: linear-gradient(-180deg,#f0f3f6,#e6ebf1 90%); border-color: rgba(27,31,35,.35); background-position: -.5em; } .github-star-badge .material-icons { height: 16px; width: 16px; margin-right: 4px; } svg#clouds { position: fixed; bottom: -160px; left: -230px; z-index: -10; width: 1920px; } /* Responsive Styles */ @media screen and (max-width: 767px) { .card-container > *:not(.circle-link) , .terminal { width: 100%; } .card:not(.highlight-card) { height: 16px; margin: 8px 0; } .card.highlight-card span { margin-left: 72px; } svg#rocket-smoke { right: 120px; transform: rotate(-5deg); } } @media screen and (max-width: 575px) { svg#rocket-smoke { display: none; visibility: hidden; } } </style> <!-- Toolbar -->
{ "end_byte": 5881, "start_byte": 574, "url": "https://github.com/angular/angular-cli/blob/main/tests/legacy-cli/e2e/assets/15.0-project/src/app/app.component.html" }