_id
stringlengths 21
254
| text
stringlengths 1
93.7k
| metadata
dict |
---|---|---|
angular-cli/packages/angular/cli/src/commands/e2e/cli.ts_0_1291 | /**
* @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 { MissingTargetChoice } from '../../command-builder/architect-base-command-module';
import { ArchitectCommandModule } from '../../command-builder/architect-command-module';
import { CommandModuleImplementation } from '../../command-builder/command-module';
import { RootCommands } from '../command-config';
export default class E2eCommandModule
extends ArchitectCommandModule
implements CommandModuleImplementation
{
override missingTargetChoices: MissingTargetChoice[] = [
{
name: 'Playwright',
value: 'playwright-ng-schematics',
},
{
name: 'Cypress',
value: '@cypress/schematic',
},
{
name: 'Nightwatch',
value: '@nightwatch/schematics',
},
{
name: 'WebdriverIO',
value: '@wdio/schematics',
},
{
name: 'Puppeteer',
value: '@puppeteer/ng-schematics',
},
];
multiTarget = true;
command = 'e2e [project]';
aliases = RootCommands['e2e'].aliases;
describe = 'Builds and serves an Angular application, then runs end-to-end tests.';
longDescriptionPath?: string;
}
| {
"end_byte": 1291,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/e2e/cli.ts"
} |
angular-cli/packages/angular/cli/src/commands/analytics/cli.ts_0_1410 | /**
* @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 { join } from 'node:path';
import { Argv } from 'yargs';
import {
CommandModule,
CommandModuleImplementation,
Options,
} from '../../command-builder/command-module';
import {
addCommandModuleToYargs,
demandCommandFailureMessage,
} from '../../command-builder/utilities/command';
import { AnalyticsInfoCommandModule } from './info/cli';
import {
AnalyticsDisableModule,
AnalyticsEnableModule,
AnalyticsPromptModule,
} from './settings/cli';
export default class AnalyticsCommandModule
extends CommandModule
implements CommandModuleImplementation
{
command = 'analytics';
describe = 'Configures the gathering of Angular CLI usage metrics.';
longDescriptionPath = join(__dirname, 'long-description.md');
builder(localYargs: Argv): Argv {
const subcommands = [
AnalyticsInfoCommandModule,
AnalyticsDisableModule,
AnalyticsEnableModule,
AnalyticsPromptModule,
].sort(); // sort by class name.
for (const module of subcommands) {
localYargs = addCommandModuleToYargs(localYargs, module, this.context);
}
return localYargs.demandCommand(1, demandCommandFailureMessage).strict();
}
run(_options: Options<{}>): void {}
}
| {
"end_byte": 1410,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/analytics/cli.ts"
} |
angular-cli/packages/angular/cli/src/commands/analytics/long-description.md_0_1347 | You can help the Angular Team to prioritize features and improvements by permitting the Angular team to send command-line command usage statistics to Google.
The Angular Team does not collect usage statistics unless you explicitly opt in. When installing the Angular CLI you are prompted to allow global collection of usage statistics.
If you say no or skip the prompt, no data is collected.
### What is collected?
Usage analytics include the commands and selected flags for each execution.
Usage analytics may include the following information:
- Your operating system \(macOS, Linux distribution, Windows\) and its version.
- Package manager name and version \(local version only\).
- Node.js version \(local version only\).
- Angular CLI version \(local version only\).
- Command name that was run.
- Workspace information, the number of application and library projects.
- For schematics commands \(add, generate and new\), the schematic collection and name and a list of selected flags.
- For build commands \(build, serve\), the builder name, the number and size of bundles \(initial and lazy\), compilation units, the time it took to build and rebuild, and basic Angular-specific API usage.
Only Angular owned and developed schematics and builders are reported.
Third-party schematics and builders do not send data to the Angular Team.
| {
"end_byte": 1347,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/analytics/long-description.md"
} |
angular-cli/packages/angular/cli/src/commands/analytics/settings/cli.ts_0_2365 | /**
* @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 { Argv } from 'yargs';
import {
getAnalyticsInfoString,
promptAnalytics,
setAnalyticsConfig,
} from '../../../analytics/analytics';
import {
CommandModule,
CommandModuleImplementation,
Options,
} from '../../../command-builder/command-module';
interface AnalyticsCommandArgs {
global: boolean;
}
abstract class AnalyticsSettingModule
extends CommandModule<AnalyticsCommandArgs>
implements CommandModuleImplementation<AnalyticsCommandArgs>
{
longDescriptionPath?: string;
builder(localYargs: Argv): Argv<AnalyticsCommandArgs> {
return localYargs
.option('global', {
description: `Configure analytics gathering and reporting globally in the caller's home directory.`,
alias: ['g'],
type: 'boolean',
default: false,
})
.strict();
}
abstract override run({ global }: Options<AnalyticsCommandArgs>): Promise<void>;
}
export class AnalyticsDisableModule
extends AnalyticsSettingModule
implements CommandModuleImplementation<AnalyticsCommandArgs>
{
command = 'disable';
aliases = 'off';
describe = 'Disables analytics gathering and reporting for the user.';
async run({ global }: Options<AnalyticsCommandArgs>): Promise<void> {
await setAnalyticsConfig(global, false);
process.stderr.write(await getAnalyticsInfoString(this.context));
}
}
export class AnalyticsEnableModule
extends AnalyticsSettingModule
implements CommandModuleImplementation<AnalyticsCommandArgs>
{
command = 'enable';
aliases = 'on';
describe = 'Enables analytics gathering and reporting for the user.';
async run({ global }: Options<AnalyticsCommandArgs>): Promise<void> {
await setAnalyticsConfig(global, true);
process.stderr.write(await getAnalyticsInfoString(this.context));
}
}
export class AnalyticsPromptModule
extends AnalyticsSettingModule
implements CommandModuleImplementation<AnalyticsCommandArgs>
{
command = 'prompt';
describe = 'Prompts the user to set the analytics gathering status interactively.';
async run({ global }: Options<AnalyticsCommandArgs>): Promise<void> {
await promptAnalytics(this.context, global, true);
}
}
| {
"end_byte": 2365,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/analytics/settings/cli.ts"
} |
angular-cli/packages/angular/cli/src/commands/analytics/info/cli.ts_0_876 | /**
* @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 { Argv } from 'yargs';
import { getAnalyticsInfoString } from '../../../analytics/analytics';
import {
CommandModule,
CommandModuleImplementation,
Options,
} from '../../../command-builder/command-module';
export class AnalyticsInfoCommandModule
extends CommandModule
implements CommandModuleImplementation
{
command = 'info';
describe = 'Prints analytics gathering and reporting configuration in the console.';
longDescriptionPath?: string;
builder(localYargs: Argv): Argv {
return localYargs.strict();
}
async run(_options: Options<{}>): Promise<void> {
this.context.logger.info(await getAnalyticsInfoString(this.context));
}
}
| {
"end_byte": 876,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/commands/analytics/info/cli.ts"
} |
angular-cli/packages/angular/cli/src/analytics/analytics.ts_0_6783 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { json, tags } from '@angular-devkit/core';
import { randomUUID } from 'crypto';
import type { CommandContext } from '../command-builder/command-module';
import { colors } from '../utilities/color';
import { getWorkspace } from '../utilities/config';
import { analyticsDisabled } from '../utilities/environment-options';
import { askConfirmation } from '../utilities/prompt';
import { isTTY } from '../utilities/tty';
/* eslint-disable no-console */
/**
* This is the ultimate safelist for checking if a package name is safe to report to analytics.
*/
export const analyticsPackageSafelist = [
/^@angular\//,
/^@angular-devkit\//,
/^@nguniversal\//,
'@schematics/angular',
];
export function isPackageNameSafeForAnalytics(name: string): boolean {
return analyticsPackageSafelist.some((pattern) => {
if (typeof pattern == 'string') {
return pattern === name;
} else {
return pattern.test(name);
}
});
}
/**
* Set analytics settings. This does not work if the user is not inside a project.
* @param global Which config to use. "global" for user-level, and "local" for project-level.
* @param value Either a user ID, true to generate a new User ID, or false to disable analytics.
*/
export async function setAnalyticsConfig(global: boolean, value: string | boolean): Promise<void> {
const level = global ? 'global' : 'local';
const workspace = await getWorkspace(level);
if (!workspace) {
throw new Error(`Could not find ${level} workspace.`);
}
const cli = (workspace.extensions['cli'] ??= {});
if (!workspace || !json.isJsonObject(cli)) {
throw new Error(`Invalid config found at ${workspace.filePath}. CLI should be an object.`);
}
cli.analytics = value === true ? randomUUID() : value;
await workspace.save();
}
/**
* Prompt the user for usage gathering permission.
* @param force Whether to ask regardless of whether or not the user is using an interactive shell.
* @return Whether or not the user was shown a prompt.
*/
export async function promptAnalytics(
context: CommandContext,
global: boolean,
force = false,
): Promise<boolean> {
const level = global ? 'global' : 'local';
const workspace = await getWorkspace(level);
if (!workspace) {
throw new Error(`Could not find a ${level} workspace. Are you in a project?`);
}
if (force || isTTY()) {
const answer = await askConfirmation(
`
Would you like to share pseudonymous usage data about this project with the Angular Team
at Google under Google's Privacy Policy at https://policies.google.com/privacy. For more
details and how to change this setting, see https://angular.dev/cli/analytics.
`,
false,
);
await setAnalyticsConfig(global, answer);
if (answer) {
console.log('');
console.log(
tags.stripIndent`
Thank you for sharing pseudonymous usage data. Should you change your mind, the following
command will disable this feature entirely:
${colors.yellow(`ng analytics disable${global ? ' --global' : ''}`)}
`,
);
console.log('');
}
process.stderr.write(await getAnalyticsInfoString(context));
return true;
}
return false;
}
/**
* Get the analytics user id.
*
* @returns
* - `string` user id.
* - `false` when disabled.
* - `undefined` when not configured.
*/
async function getAnalyticsUserIdForLevel(
level: 'local' | 'global',
): Promise<string | false | undefined> {
if (analyticsDisabled) {
return false;
}
const workspace = await getWorkspace(level);
const analyticsConfig: string | undefined | null | { uid?: string } | boolean =
workspace?.getCli()?.['analytics'];
if (analyticsConfig === false) {
return false;
} else if (analyticsConfig === undefined || analyticsConfig === null) {
return undefined;
} else {
if (typeof analyticsConfig == 'string') {
return analyticsConfig;
} else if (typeof analyticsConfig == 'object' && typeof analyticsConfig['uid'] == 'string') {
return analyticsConfig['uid'];
}
return undefined;
}
}
export async function getAnalyticsUserId(
context: CommandContext,
skipPrompt = false,
): Promise<string | undefined> {
const { workspace } = context;
// Global config takes precedence over local config only for the disabled check.
// IE:
// global: disabled & local: enabled = disabled
// global: id: 123 & local: id: 456 = 456
// check global
const globalConfig = await getAnalyticsUserIdForLevel('global');
if (globalConfig === false) {
return undefined;
}
// Not disabled globally, check locally or not set globally and command is run outside of workspace example: `ng new`
if (workspace || globalConfig === undefined) {
const level = workspace ? 'local' : 'global';
let localOrGlobalConfig = await getAnalyticsUserIdForLevel(level);
if (localOrGlobalConfig === undefined) {
if (!skipPrompt) {
// config is unset, prompt user.
// TODO: This should honor the `no-interactive` option.
// It is currently not an `ng` option but rather only an option for specific commands.
// The concept of `ng`-wide options are needed to cleanly handle this.
await promptAnalytics(context, !workspace /** global */);
localOrGlobalConfig = await getAnalyticsUserIdForLevel(level);
}
}
if (localOrGlobalConfig === false) {
return undefined;
} else if (typeof localOrGlobalConfig === 'string') {
return localOrGlobalConfig;
}
}
return globalConfig;
}
function analyticsConfigValueToHumanFormat(value: unknown): 'enabled' | 'disabled' | 'not set' {
if (value === false) {
return 'disabled';
} else if (typeof value === 'string' || value === true) {
return 'enabled';
} else {
return 'not set';
}
}
export async function getAnalyticsInfoString(context: CommandContext): Promise<string> {
const analyticsInstance = await getAnalyticsUserId(context, true /** skipPrompt */);
const { globalConfiguration, workspace: localWorkspace } = context;
const globalSetting = globalConfiguration?.getCli()?.['analytics'];
const localSetting = localWorkspace?.getCli()?.['analytics'];
return (
tags.stripIndents`
Global setting: ${analyticsConfigValueToHumanFormat(globalSetting)}
Local setting: ${
localWorkspace
? analyticsConfigValueToHumanFormat(localSetting)
: 'No local workspace configuration file.'
}
Effective status: ${analyticsInstance ? 'enabled' : 'disabled'}
` + '\n'
);
}
| {
"end_byte": 6783,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/analytics/analytics.ts"
} |
angular-cli/packages/angular/cli/src/analytics/analytics-parameters.ts_0_3267 | /**
* @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
*/
/** Any changes in this file needs to be done in the mts version. */
export type PrimitiveTypes = string | number | boolean;
/**
* GA built-in request parameters
* @see https://www.thyngster.com/ga4-measurement-protocol-cheatsheet
* @see http://go/depot/google3/analytics/container_tag/templates/common/gold/mpv2_schema.js
*/
export enum RequestParameter {
ClientId = 'cid',
DebugView = '_dbg',
GtmVersion = 'gtm',
Language = 'ul',
NewToSite = '_nsi',
NonInteraction = 'ni',
PageLocation = 'dl',
PageTitle = 'dt',
ProtocolVersion = 'v',
SessionEngaged = 'seg',
SessionId = 'sid',
SessionNumber = 'sct',
SessionStart = '_ss',
TrackingId = 'tid',
TrafficType = 'tt',
UserAgentArchitecture = 'uaa',
UserAgentBitness = 'uab',
UserAgentFullVersionList = 'uafvl',
UserAgentMobile = 'uamb',
UserAgentModel = 'uam',
UserAgentPlatform = 'uap',
UserAgentPlatformVersion = 'uapv',
UserId = 'uid',
}
/**
* User scoped custom dimensions.
* @notes
* - User custom dimensions limit is 25.
* - `up.*` string type.
* - `upn.*` number type.
* @see https://support.google.com/analytics/answer/10075209?hl=en
*/
export enum UserCustomDimension {
UserId = 'up.ng_user_id',
OsArchitecture = 'up.ng_os_architecture',
NodeVersion = 'up.ng_node_version',
NodeMajorVersion = 'upn.ng_node_major_version',
AngularCLIVersion = 'up.ng_cli_version',
AngularCLIMajorVersion = 'upn.ng_cli_major_version',
PackageManager = 'up.ng_package_manager',
PackageManagerVersion = 'up.ng_pkg_manager_version',
PackageManagerMajorVersion = 'upn.ng_pkg_manager_major_v',
}
/**
* Event scoped custom dimensions.
* @notes
* - Event custom dimensions limit is 50.
* - `ep.*` string type.
* - `epn.*` number type.
* @see https://support.google.com/analytics/answer/10075209?hl=en
*/
export enum EventCustomDimension {
Command = 'ep.ng_command',
SchematicCollectionName = 'ep.ng_schematic_collection_name',
SchematicName = 'ep.ng_schematic_name',
Standalone = 'ep.ng_standalone',
SSR = 'ep.ng_ssr',
Style = 'ep.ng_style',
Routing = 'ep.ng_routing',
InlineTemplate = 'ep.ng_inline_template',
InlineStyle = 'ep.ng_inline_style',
BuilderTarget = 'ep.ng_builder_target',
Aot = 'ep.ng_aot',
Optimization = 'ep.ng_optimization',
}
/**
* Event scoped custom mertics.
* @notes
* - Event scoped custom mertics limit is 50.
* - `ep.*` string type.
* - `epn.*` number type.
* @see https://support.google.com/analytics/answer/10075209?hl=en
*/
export enum EventCustomMetric {
AllChunksCount = 'epn.ng_all_chunks_count',
LazyChunksCount = 'epn.ng_lazy_chunks_count',
InitialChunksCount = 'epn.ng_initial_chunks_count',
ChangedChunksCount = 'epn.ng_changed_chunks_count',
DurationInMs = 'epn.ng_duration_ms',
CssSizeInBytes = 'epn.ng_css_size_bytes',
JsSizeInBytes = 'epn.ng_js_size_bytes',
NgComponentCount = 'epn.ng_component_count',
AllProjectsCount = 'epn.all_projects_count',
LibraryProjectsCount = 'epn.libs_projects_count',
ApplicationProjectsCount = 'epn.apps_projects_count',
}
| {
"end_byte": 3267,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/analytics/analytics-parameters.ts"
} |
angular-cli/packages/angular/cli/src/analytics/analytics-collector.ts_0_7433 | /**
* @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 { randomUUID } from 'crypto';
import * as https from 'https';
import * as os from 'os';
import * as querystring from 'querystring';
import * as semver from 'semver';
import type { CommandContext } from '../command-builder/command-module';
import { ngDebug } from '../utilities/environment-options';
import { assertIsError } from '../utilities/error';
import { VERSION } from '../utilities/version';
import {
EventCustomDimension,
EventCustomMetric,
PrimitiveTypes,
RequestParameter,
UserCustomDimension,
} from './analytics-parameters';
const TRACKING_ID_PROD = 'G-VETNJBW8L4';
const TRACKING_ID_STAGING = 'G-TBMPRL1BTM';
export class AnalyticsCollector {
private trackingEventsQueue: Record<string, PrimitiveTypes | undefined>[] | undefined;
private readonly requestParameterStringified: string;
private readonly userParameters: Record<UserCustomDimension, PrimitiveTypes | undefined>;
constructor(
private context: CommandContext,
userId: string,
) {
const requestParameters: Partial<Record<RequestParameter, PrimitiveTypes>> = {
[RequestParameter.ProtocolVersion]: 2,
[RequestParameter.ClientId]: userId,
[RequestParameter.UserId]: userId,
[RequestParameter.TrackingId]:
/^\d+\.\d+\.\d+$/.test(VERSION.full) && VERSION.full !== '0.0.0'
? TRACKING_ID_PROD
: TRACKING_ID_STAGING,
// Built-in user properties
[RequestParameter.SessionId]: randomUUID(),
[RequestParameter.UserAgentArchitecture]: os.arch(),
[RequestParameter.UserAgentPlatform]: os.platform(),
[RequestParameter.UserAgentPlatformVersion]: os.release(),
[RequestParameter.UserAgentMobile]: 0,
[RequestParameter.SessionEngaged]: 1,
// The below is needed for tech details to be collected.
[RequestParameter.UserAgentFullVersionList]:
'Google%20Chrome;111.0.5563.64|Not(A%3ABrand;8.0.0.0|Chromium;111.0.5563.64',
};
if (ngDebug) {
requestParameters[RequestParameter.DebugView] = 1;
}
this.requestParameterStringified = querystring.stringify(requestParameters);
const parsedVersion = semver.parse(process.version);
const packageManagerVersion = context.packageManager.version;
this.userParameters = {
// While architecture is being collect by GA as UserAgentArchitecture.
// It doesn't look like there is a way to query this. Therefore we collect this as a custom user dimension too.
[UserCustomDimension.OsArchitecture]: os.arch(),
// While User ID is being collected by GA, this is not visible in reports/for filtering.
[UserCustomDimension.UserId]: userId,
[UserCustomDimension.NodeVersion]: parsedVersion
? `${parsedVersion.major}.${parsedVersion.minor}.${parsedVersion.patch}`
: 'other',
[UserCustomDimension.NodeMajorVersion]: parsedVersion?.major,
[UserCustomDimension.PackageManager]: context.packageManager.name,
[UserCustomDimension.PackageManagerVersion]: packageManagerVersion,
[UserCustomDimension.PackageManagerMajorVersion]: packageManagerVersion
? +packageManagerVersion.split('.', 1)[0]
: undefined,
[UserCustomDimension.AngularCLIVersion]: VERSION.full,
[UserCustomDimension.AngularCLIMajorVersion]: VERSION.major,
};
}
reportWorkspaceInfoEvent(
parameters: Partial<Record<EventCustomMetric, string | boolean | number | undefined>>,
): void {
this.event('workspace_info', parameters);
}
reportRebuildRunEvent(
parameters: Partial<
Record<EventCustomMetric & EventCustomDimension, string | boolean | number | undefined>
>,
): void {
this.event('run_rebuild', parameters);
}
reportBuildRunEvent(
parameters: Partial<
Record<EventCustomMetric & EventCustomDimension, string | boolean | number | undefined>
>,
): void {
this.event('run_build', parameters);
}
reportArchitectRunEvent(parameters: Partial<Record<EventCustomDimension, PrimitiveTypes>>): void {
this.event('run_architect', parameters);
}
reportSchematicRunEvent(parameters: Partial<Record<EventCustomDimension, PrimitiveTypes>>): void {
this.event('run_schematic', parameters);
}
reportCommandRunEvent(command: string): void {
this.event('run_command', { [EventCustomDimension.Command]: command });
}
private event(eventName: string, parameters?: Record<string, PrimitiveTypes>): void {
this.trackingEventsQueue ??= [];
this.trackingEventsQueue.push({
...this.userParameters,
...parameters,
'en': eventName,
});
}
/**
* Flush on an interval (if the event loop is waiting).
*
* @returns a method that when called will terminate the periodic
* flush and call flush one last time.
*/
periodFlush(): () => Promise<void> {
let analyticsFlushPromise = Promise.resolve();
const analyticsFlushInterval = setInterval(() => {
if (this.trackingEventsQueue?.length) {
analyticsFlushPromise = analyticsFlushPromise.then(() => this.flush());
}
}, 4000);
return () => {
clearInterval(analyticsFlushInterval);
// Flush one last time.
return analyticsFlushPromise.then(() => this.flush());
};
}
async flush(): Promise<void> {
const pendingTrackingEvents = this.trackingEventsQueue;
this.context.logger.debug(`Analytics flush size. ${pendingTrackingEvents?.length}.`);
if (!pendingTrackingEvents?.length) {
return;
}
// The below is needed so that if flush is called multiple times,
// we don't report the same event multiple times.
this.trackingEventsQueue = undefined;
try {
await this.send(pendingTrackingEvents);
} catch (error) {
// Failure to report analytics shouldn't crash the CLI.
assertIsError(error);
this.context.logger.debug(`Send analytics error. ${error.message}.`);
}
}
private async send(data: Record<string, PrimitiveTypes | undefined>[]): Promise<void> {
return new Promise<void>((resolve, reject) => {
const request = https.request(
{
host: 'www.google-analytics.com',
method: 'POST',
path: '/g/collect?' + this.requestParameterStringified,
headers: {
// The below is needed for tech details to be collected even though we provide our own information from the OS Node.js module
'user-agent':
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
},
},
(response) => {
// The below is needed as otherwise the response will never close which will cause the CLI not to terminate.
response.on('data', () => {});
if (response.statusCode !== 200 && response.statusCode !== 204) {
reject(
new Error(`Analytics reporting failed with status code: ${response.statusCode}.`),
);
} else {
resolve();
}
},
);
request.on('error', reject);
const queryParameters = data.map((p) => querystring.stringify(p)).join('\n');
request.write(queryParameters);
request.end();
});
}
}
| {
"end_byte": 7433,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/analytics/analytics-collector.ts"
} |
angular-cli/packages/angular/cli/src/analytics/analytics-parameters.mts_0_3261 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/** This is a copy of analytics-parameters.ts and is needed for `yarn admin validate-user-analytics` due to ts-node. */
/**
* GA built-in request parameters
* @see https://www.thyngster.com/ga4-measurement-protocol-cheatsheet
* @see http://go/depot/google3/analytics/container_tag/templates/common/gold/mpv2_schema.js
*/
export enum RequestParameter {
ClientId = 'cid',
DebugView = '_dbg',
GtmVersion = 'gtm',
Language = 'ul',
NewToSite = '_nsi',
NonInteraction = 'ni',
PageLocation = 'dl',
PageTitle = 'dt',
ProtocolVersion = 'v',
SessionEngaged = 'seg',
SessionId = 'sid',
SessionNumber = 'sct',
SessionStart = '_ss',
TrackingId = 'tid',
TrafficType = 'tt',
UserAgentArchitecture = 'uaa',
UserAgentBitness = 'uab',
UserAgentFullVersionList = 'uafvl',
UserAgentMobile = 'uamb',
UserAgentModel = 'uam',
UserAgentPlatform = 'uap',
UserAgentPlatformVersion = 'uapv',
UserId = 'uid',
}
/**
* User scoped custom dimensions.
* @notes
* - User custom dimensions limit is 25.
* - `up.*` string type.
* - `upn.*` number type.
* @see https://support.google.com/analytics/answer/10075209?hl=en
*/
export enum UserCustomDimension {
UserId = 'up.ng_user_id',
OsArchitecture = 'up.ng_os_architecture',
NodeVersion = 'up.ng_node_version',
NodeMajorVersion = 'upn.ng_node_major_version',
AngularCLIVersion = 'up.ng_cli_version',
AngularCLIMajorVersion = 'upn.ng_cli_major_version',
PackageManager = 'up.ng_package_manager',
PackageManagerVersion = 'up.ng_pkg_manager_version',
PackageManagerMajorVersion = 'upn.ng_pkg_manager_major_v',
}
/**
* Event scoped custom dimensions.
* @notes
* - Event custom dimensions limit is 50.
* - `ep.*` string type.
* - `epn.*` number type.
* @see https://support.google.com/analytics/answer/10075209?hl=en
*/
export enum EventCustomDimension {
Command = 'ep.ng_command',
SchematicCollectionName = 'ep.ng_schematic_collection_name',
SchematicName = 'ep.ng_schematic_name',
Standalone = 'ep.ng_standalone',
SSR = 'ep.ng_ssr',
Style = 'ep.ng_style',
Routing = 'ep.ng_routing',
InlineTemplate = 'ep.ng_inline_template',
InlineStyle = 'ep.ng_inline_style',
BuilderTarget = 'ep.ng_builder_target',
Aot = 'ep.ng_aot',
Optimization = 'ep.ng_optimization',
}
/**
* Event scoped custom mertics.
* @notes
* - Event scoped custom mertics limit is 50.
* - `ep.*` string type.
* - `epn.*` number type.
* @see https://support.google.com/analytics/answer/10075209?hl=en
*/
export enum EventCustomMetric {
AllChunksCount = 'epn.ng_all_chunks_count',
LazyChunksCount = 'epn.ng_lazy_chunks_count',
InitialChunksCount = 'epn.ng_initial_chunks_count',
ChangedChunksCount = 'epn.ng_changed_chunks_count',
DurationInMs = 'epn.ng_duration_ms',
CssSizeInBytes = 'epn.ng_css_size_bytes',
JsSizeInBytes = 'epn.ng_js_size_bytes',
NgComponentCount = 'epn.ng_component_count',
AllProjectsCount = 'epn.all_projects_count',
LibraryProjectsCount = 'epn.libs_projects_count',
ApplicationProjectsCount = 'epn.apps_projects_count',
}
| {
"end_byte": 3261,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/cli/src/analytics/analytics-parameters.mts"
} |
angular-cli/packages/angular/ssr/private_export.ts_0_890 | /**
* @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
*/
// ɵgetRoutesFromAngularRouterConfig is only used by the Webpack based server builder.
export {
getRoutesFromAngularRouterConfig as ɵgetRoutesFromAngularRouterConfig,
extractRoutesAndCreateRouteTree as ɵextractRoutesAndCreateRouteTree,
} from './src/routes/ng-routes';
export {
getOrCreateAngularServerApp as ɵgetOrCreateAngularServerApp,
destroyAngularServerApp as ɵdestroyAngularServerApp,
} from './src/app';
export {
setAngularAppManifest as ɵsetAngularAppManifest,
setAngularAppEngineManifest as ɵsetAngularAppEngineManifest,
} from './src/manifest';
export { InlineCriticalCssProcessor as ɵInlineCriticalCssProcessor } from './src/utils/inline-critical-css';
| {
"end_byte": 890,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/private_export.ts"
} |
angular-cli/packages/angular/ssr/README.md_0_73 | # Angular SSR
Read the dev guide [here](https://angular.dev/guide/ssr).
| {
"end_byte": 73,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/README.md"
} |
angular-cli/packages/angular/ssr/public_api_transitive.ts_0_623 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// This file exports symbols that are not part of the public API but are
// dependencies of public API symbols. Including them here ensures they
// are tracked in the API golden file, preventing accidental breaking changes.
export type {
ServerRouteAppShell,
ServerRouteClient,
ServerRoutePrerender,
ServerRoutePrerenderWithParams,
ServerRouteServer,
ServerRouteCommon,
} from './src/routes/route-config';
| {
"end_byte": 623,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/public_api_transitive.ts"
} |
angular-cli/packages/angular/ssr/BUILD.bazel_0_2216 | load("@npm//@angular/build-tooling/bazel/api-golden:index.bzl", "api_golden_test", "api_golden_test_npm_package")
load("@rules_pkg//:pkg.bzl", "pkg_tar")
load("//tools:defaults.bzl", "ng_package", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "ssr",
package_name = "@angular/ssr",
srcs = glob(
include = [
"*.ts",
"src/**/*.ts",
],
exclude = [
"**/*_spec.ts",
],
),
module_name = "@angular/ssr",
tsconfig = "//:tsconfig-build-ng",
deps = [
"//packages/angular/ssr/third_party/beasties:bundled_beasties_lib",
"//packages/angular/ssr/tokens",
"@npm//@angular/common",
"@npm//@angular/core",
"@npm//@angular/platform-server",
"@npm//@angular/router",
"@npm//tslib",
],
)
ng_package(
name = "npm_package",
package_name = "@angular/ssr",
srcs = [
":package.json",
"//packages/angular/ssr/third_party/beasties:bundled_beasties_lib",
],
externals = [
"@angular/ssr",
"@angular/ssr/node",
"@angular/ssr/tokens",
"../../third_party/beasties",
],
nested_packages = [
"//packages/angular/ssr/schematics:npm_package",
],
tags = ["release-package"],
deps = [
":ssr",
"//packages/angular/ssr/node",
"//packages/angular/ssr/tokens",
],
)
pkg_tar(
name = "npm_package_archive",
srcs = [":npm_package"],
extension = "tgz",
strip_prefix = "./npm_package",
# should not be built unless it is a dependency of another rule
tags = ["manual"],
)
api_golden_test_npm_package(
name = "ssr_api",
data = [
":npm_package",
"//goldens:public-api",
],
golden_dir = "angular_cli/goldens/public-api/angular/ssr",
npm_package = "angular_cli/packages/angular/ssr/npm_package",
)
api_golden_test(
name = "ssr_transitive_api",
data = [
":ssr",
"//goldens:public-api",
],
entry_point = "angular_cli/packages/angular/ssr/public_api_transitive.d.ts",
golden = "angular_cli/goldens/public-api/angular/ssr/index_transitive.api.md",
)
| {
"end_byte": 2216,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/BUILD.bazel"
} |
angular-cli/packages/angular/ssr/index.ts_0_234 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './public_api';
| {
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/index.ts"
} |
angular-cli/packages/angular/ssr/public_api.ts_0_481 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './private_export';
export { AngularAppEngine } from './src/app-engine';
export { createRequestHandler } from './src/handler';
export {
type PrerenderFallback,
type ServerRoute,
provideServerRoutesConfig,
RenderMode,
} from './src/routes/route-config';
| {
"end_byte": 481,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/public_api.ts"
} |
angular-cli/packages/angular/ssr/test/assets_spec.ts_0_1268 | /**
* @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 { ServerAssets } from '../src/assets';
describe('ServerAsset', () => {
let assetManager: ServerAssets;
beforeAll(() => {
assetManager = new ServerAssets({
bootstrap: undefined as never,
assets: new Map(
Object.entries({
'index.server.html': async () => '<html>Index</html>',
'index.other.html': async () => '<html>Other</html>',
}),
),
});
});
it('should retrieve and cache the content of index.server.html', async () => {
const content = await assetManager.getIndexServerHtml();
expect(content).toBe('<html>Index</html>');
});
it('should throw an error if the asset path does not exist', async () => {
await expectAsync(assetManager.getServerAsset('nonexistent.html')).toBeRejectedWithError(
"Server asset 'nonexistent.html' does not exist.",
);
});
it('should retrieve the content of index.other.html', async () => {
const content = await assetManager.getServerAsset('index.other.html');
expect(content).toBe('<html>Other</html>');
});
});
| {
"end_byte": 1268,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/test/assets_spec.ts"
} |
angular-cli/packages/angular/ssr/test/testing-utils.ts_0_2555 | /**
* @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 { Component, provideExperimentalZonelessChangeDetection } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { provideServerRendering } from '@angular/platform-server';
import { RouterOutlet, Routes, provideRouter } from '@angular/router';
import { setAngularAppManifest } from '../src/manifest';
import { ServerRoute, provideServerRoutesConfig } from '../src/routes/route-config';
/**
* Configures the Angular application for testing by setting up the Angular app manifest,
* configuring server-side rendering, and bootstrapping the application with the provided routes.
* This function generates a basic HTML template with a base href and sets up the necessary
* Angular components and providers for testing purposes.
*
* @param routes - An array of route definitions to be used by the Angular Router.
* @param serverRoutes - An array of ServerRoute definitions to be used for server-side rendering.
* @param [baseHref=''] - An optional base href to be used in the HTML template.
*/
export function setAngularAppTestingManifest(
routes: Routes,
serverRoutes: ServerRoute[],
baseHref = '',
): void {
setAngularAppManifest({
inlineCriticalCss: false,
assets: new Map(
Object.entries({
'index.server.html': async () =>
`<html>
<head>
<title>SSR page</title>
<base href="/${baseHref}" />
</head>
<body>
<app-root></app-root>
</body>
</html>
`,
'index.csr.html': async () =>
`<html>
<head>
<title>CSR page</title>
<base href="/${baseHref}" />
</head>
<body>
<app-root></app-root>
</body>
</html>
`,
}),
),
bootstrap: async () => () => {
@Component({
standalone: true,
selector: 'app-root',
template: '<router-outlet />',
imports: [RouterOutlet],
})
class AppComponent {}
return bootstrapApplication(AppComponent, {
providers: [
provideServerRendering(),
provideExperimentalZonelessChangeDetection(),
provideRouter(routes),
provideServerRoutesConfig(serverRoutes),
],
});
},
});
}
| {
"end_byte": 2555,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/test/testing-utils.ts"
} |
angular-cli/packages/angular/ssr/test/i18n_spec.ts_0_2460 | /**
* @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 { getPotentialLocaleIdFromUrl } from '../src/i18n';
describe('getPotentialLocaleIdFromUrl', () => {
it('should extract locale ID correctly when basePath is present', () => {
const url = new URL('https://example.com/base/en/page');
const basePath = '/base';
const localeId = getPotentialLocaleIdFromUrl(url, basePath);
expect(localeId).toBe('en');
});
it('should extract locale ID correctly when basePath has trailing slash', () => {
const url = new URL('https://example.com/base/en/page');
const basePath = '/base/';
const localeId = getPotentialLocaleIdFromUrl(url, basePath);
expect(localeId).toBe('en');
});
it('should extract locale ID correctly when url has no trailing slash', () => {
const url = new URL('https://example.com/base/en');
const basePath = '/base/';
const localeId = getPotentialLocaleIdFromUrl(url, basePath);
expect(localeId).toBe('en');
});
it('should extract locale ID correctly when url no trailing slash', () => {
const url = new URL('https://example.com/base/en/');
const basePath = '/base/';
const localeId = getPotentialLocaleIdFromUrl(url, basePath);
expect(localeId).toBe('en');
});
it('should handle URL with no pathname after basePath', () => {
const url = new URL('https://example.com/base/');
const basePath = '/base';
const localeId = getPotentialLocaleIdFromUrl(url, basePath);
expect(localeId).toBe('');
});
it('should handle URL where basePath is the entire pathname', () => {
const url = new URL('https://example.com/base');
const basePath = '/base';
const localeId = getPotentialLocaleIdFromUrl(url, basePath);
expect(localeId).toBe('');
});
it('should handle complex basePath correctly', () => {
const url = new URL('https://example.com/base/path/en/page');
const basePath = '/base/path';
const localeId = getPotentialLocaleIdFromUrl(url, basePath);
expect(localeId).toBe('en');
});
it('should handle URL with query parameters and hash', () => {
const url = new URL('https://example.com/base/en?query=param#hash');
const basePath = '/base';
const localeId = getPotentialLocaleIdFromUrl(url, basePath);
expect(localeId).toBe('en');
});
});
| {
"end_byte": 2460,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/test/i18n_spec.ts"
} |
angular-cli/packages/angular/ssr/test/hooks_spec.ts_0_2161 | /**
* @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 { Hooks } from '../src/hooks';
describe('Hooks', () => {
let hooks: Hooks & { run: Function };
const url = new URL('http://example.com/');
beforeEach(() => {
hooks = new Hooks() as Hooks & { run: Function };
});
describe('on', () => {
it('should register a pre-transform hook', () => {
hooks.on('html:transform:pre', (ctx) => '');
expect(hooks.has('html:transform:pre')).toBeTrue();
});
it('should register multiple hooks under the same name', () => {
hooks.on('html:transform:pre', (ctx) => '');
hooks.on('html:transform:pre', (ctx) => '');
expect(hooks.has('html:transform:pre')).toBeTrue();
});
});
describe('run', () => {
it('should execute pre-transform hooks in sequence', async () => {
hooks.on('html:transform:pre', ({ html }) => html + '1');
hooks.on('html:transform:pre', ({ html }) => html + '2');
const result = await hooks.run('html:transform:pre', { html: 'start', url });
expect(result).toBe('start12');
});
it('should return the context html if no hooks are registered', async () => {
const result = await hooks.run('html:transform:pre', { html: 'start', url });
expect(result).toBe('start');
});
it('should throw an error for unknown hook names', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await expectAsync(hooks.run('unknown:hook' as any, { html: 'start' })).toBeRejectedWithError(
'Running hook "unknown:hook" is not supported.',
);
});
});
describe('has', () => {
it('should return true if a hook is registered', () => {
const handler = (ctx: { html: string }) => '';
hooks.on('html:transform:pre', handler);
expect(hooks.has('html:transform:pre')).toBeTrue();
});
it('should return false if no hook is registered', () => {
expect(hooks.has('html:transform:pre')).toBeFalse();
});
});
});
| {
"end_byte": 2161,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/test/hooks_spec.ts"
} |
angular-cli/packages/angular/ssr/test/BUILD.bazel_0_1281 | load("@npm//@angular/build-tooling/bazel/spec-bundling:index.bzl", "spec_bundle")
load("@npm//@bazel/jasmine:index.bzl", "jasmine_node_test")
load("//tools:defaults.bzl", "ts_library")
ESM_TESTS = [
"app_spec.ts",
"app-engine_spec.ts",
"routes/router_spec.ts",
"routes/ng-routes_spec.ts",
]
ts_library(
name = "unit_test_lib",
testonly = True,
srcs = glob(
include = ["**/*_spec.ts"],
exclude = ESM_TESTS + ["npm_package/**"],
),
deps = [
"//packages/angular/ssr",
],
)
ts_library(
name = "unit_test_with_esm_deps_lib",
testonly = True,
srcs = ESM_TESTS + ["testing-utils.ts"],
deps = [
"//packages/angular/ssr",
"@npm//@angular/common",
"@npm//@angular/compiler",
"@npm//@angular/core",
"@npm//@angular/platform-browser",
"@npm//@angular/platform-server",
"@npm//@angular/router",
],
)
spec_bundle(
name = "unit_test_with_esm_deps_lib_bundled",
downlevel_async_await = False,
platform = "node",
run_angular_linker = False,
deps = [
":unit_test_with_esm_deps_lib",
],
)
jasmine_node_test(
name = "test",
deps = [
":unit_test_lib",
":unit_test_with_esm_deps_lib_bundled",
],
)
| {
"end_byte": 1281,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/test/BUILD.bazel"
} |
angular-cli/packages/angular/ssr/test/app-engine_spec.ts_0_6928 | /**
* @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
*/
// The compiler is needed as tests are in JIT.
/* eslint-disable import/no-unassigned-import */
import '@angular/compiler';
/* eslint-enable import/no-unassigned-import */
import { Component } from '@angular/core';
import { destroyAngularServerApp, getOrCreateAngularServerApp } from '../src/app';
import { AngularAppEngine } from '../src/app-engine';
import { setAngularAppEngineManifest } from '../src/manifest';
import { RenderMode } from '../src/routes/route-config';
import { setAngularAppTestingManifest } from './testing-utils';
describe('AngularAppEngine', () => {
let appEngine: AngularAppEngine;
describe('Localized app', () => {
beforeAll(() => {
destroyAngularServerApp();
setAngularAppEngineManifest({
// Note: Although we are testing only one locale, we need to configure two or more
// to ensure that we test a different code path.
entryPoints: new Map(
['it', 'en'].map((locale) => [
locale,
async () => {
@Component({
standalone: true,
selector: `app-home-${locale}`,
template: `Home works ${locale.toUpperCase()}`,
})
class HomeComponent {}
setAngularAppTestingManifest(
[{ path: 'home', component: HomeComponent }],
[{ path: '**', renderMode: RenderMode.Server }],
locale,
);
return {
ɵgetOrCreateAngularServerApp: getOrCreateAngularServerApp,
ɵdestroyAngularServerApp: destroyAngularServerApp,
};
},
]),
),
basePath: '',
staticPathsHeaders: new Map([
[
'/about',
[
['Cache-Control', 'no-cache'],
['X-Some-Header', 'value'],
],
],
]),
});
appEngine = new AngularAppEngine();
});
describe('render', () => {
it('should return null for requests to unknown pages', async () => {
const request = new Request('https://example.com/unknown/page');
const response = await appEngine.render(request);
expect(response).toBeNull();
});
it('should return null for requests with unknown locales', async () => {
const request = new Request('https://example.com/es/home');
const response = await appEngine.render(request);
expect(response).toBeNull();
});
it('should return a rendered page with correct locale', async () => {
const request = new Request('https://example.com/it/home');
const response = await appEngine.render(request);
expect(await response?.text()).toContain('Home works IT');
});
it('should correctly render the content when the URL ends with "index.html" with correct locale', async () => {
const request = new Request('https://example.com/it/home/index.html');
const response = await appEngine.render(request);
expect(await response?.text()).toContain('Home works IT');
});
it('should return null for requests to unknown pages in a locale', async () => {
const request = new Request('https://example.com/it/unknown/page');
const response = await appEngine.render(request);
expect(response).toBeNull();
});
it('should return null for requests to file-like resources in a locale', async () => {
const request = new Request('https://example.com/it/logo.png');
const response = await appEngine.render(request);
expect(response).toBeNull();
});
});
describe('getPrerenderHeaders', () => {
it('should return headers for a known path without index.html', () => {
const request = new Request('https://example.com/about');
const headers = appEngine.getPrerenderHeaders(request);
expect(Object.fromEntries(headers.entries())).toEqual({
'Cache-Control': 'no-cache',
'X-Some-Header': 'value',
});
});
it('should return headers for a known path with index.html', () => {
const request = new Request('https://example.com/about/index.html');
const headers = appEngine.getPrerenderHeaders(request);
expect(Object.fromEntries(headers.entries())).toEqual({
'Cache-Control': 'no-cache',
'X-Some-Header': 'value',
});
});
it('should return no headers for unknown paths', () => {
const request = new Request('https://example.com/unknown/path');
const headers = appEngine.getPrerenderHeaders(request);
expect(headers).toHaveSize(0);
});
});
});
describe('Non-localized app', () => {
beforeAll(() => {
destroyAngularServerApp();
setAngularAppEngineManifest({
entryPoints: new Map([
[
'',
async () => {
@Component({
standalone: true,
selector: 'app-home',
template: `Home works`,
})
class HomeComponent {}
setAngularAppTestingManifest(
[{ path: 'home', component: HomeComponent }],
[{ path: '**', renderMode: RenderMode.Server }],
);
return {
ɵgetOrCreateAngularServerApp: getOrCreateAngularServerApp,
ɵdestroyAngularServerApp: destroyAngularServerApp,
};
},
],
]),
basePath: '',
staticPathsHeaders: new Map(),
});
appEngine = new AngularAppEngine();
});
it('should return null for requests to file-like resources', async () => {
const request = new Request('https://example.com/logo.png');
const response = await appEngine.render(request);
expect(response).toBeNull();
});
it('should return null for requests to unknown pages', async () => {
const request = new Request('https://example.com/unknown/page');
const response = await appEngine.render(request);
expect(response).toBeNull();
});
it('should return a rendered page for known paths', async () => {
const request = new Request('https://example.com/home');
const response = await appEngine.render(request);
expect(await response?.text()).toContain('Home works');
});
it('should correctly render the content when the URL ends with "index.html"', async () => {
const request = new Request('https://example.com/home/index.html');
const response = await appEngine.render(request);
expect(await response?.text()).toContain('Home works');
});
});
});
| {
"end_byte": 6928,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/test/app-engine_spec.ts"
} |
angular-cli/packages/angular/ssr/test/app_spec.ts_0_5442 | /**
* @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
*/
// The compiler is needed as tests are in JIT.
/* eslint-disable import/no-unassigned-import */
import '@angular/compiler';
/* eslint-enable import/no-unassigned-import */
import { Component } from '@angular/core';
import { AngularServerApp, destroyAngularServerApp } from '../src/app';
import { RenderMode } from '../src/routes/route-config';
import { setAngularAppTestingManifest } from './testing-utils';
describe('AngularServerApp', () => {
let app: AngularServerApp;
beforeAll(() => {
destroyAngularServerApp();
@Component({
standalone: true,
selector: 'app-home',
template: `Home works`,
})
class HomeComponent {}
setAngularAppTestingManifest(
[
{ path: 'home', component: HomeComponent },
{ path: 'home-csr', component: HomeComponent },
{ path: 'page-with-headers', component: HomeComponent },
{ path: 'page-with-status', component: HomeComponent },
{ path: 'redirect', redirectTo: 'home' },
{ path: 'redirect/relative', redirectTo: 'home' },
{ path: 'redirect/absolute', redirectTo: '/home' },
],
[
{
path: 'home-csr',
renderMode: RenderMode.Client,
},
{
path: 'page-with-status',
renderMode: RenderMode.Server,
status: 201,
},
{
path: 'page-with-headers',
renderMode: RenderMode.Server,
headers: {
'Cache-Control': 'no-cache',
'X-Some-Header': 'value',
},
},
{
path: '**',
renderMode: RenderMode.Server,
},
],
);
app = new AngularServerApp();
});
describe('render', () => {
it('should correctly render the content for the requested page', async () => {
const response = await app.render(new Request('http://localhost/home'));
expect(await response?.text()).toContain('Home works');
});
it(`should correctly render the content when the URL ends with 'index.html'`, async () => {
const response = await app.render(new Request('http://localhost/home/index.html'));
expect(await response?.text()).toContain('Home works');
});
it('should correctly handle top level redirects', async () => {
const response = await app.render(new Request('http://localhost/redirect'));
expect(response?.headers.get('location')).toContain('http://localhost/home');
expect(response?.status).toBe(302);
});
it('should correctly handle relative nested redirects', async () => {
const response = await app.render(new Request('http://localhost/redirect/relative'));
expect(response?.headers.get('location')).toContain('http://localhost/redirect/home');
expect(response?.status).toBe(302);
});
it('should correctly handle absolute nested redirects', async () => {
const response = await app.render(new Request('http://localhost/redirect/absolute'));
expect(response?.headers.get('location')).toContain('http://localhost/home');
expect(response?.status).toBe(302);
});
it('should handle request abortion gracefully', async () => {
const controller = new AbortController();
const request = new Request('http://localhost/home', { signal: controller.signal });
// Schedule the abortion of the request in the next microtask
queueMicrotask(() => {
controller.abort();
});
await expectAsync(app.render(request)).toBeRejectedWithError(/Request for: .+ was aborted/);
});
it('should return configured headers for pages with specific header settings', async () => {
const response = await app.render(new Request('http://localhost/page-with-headers'));
const headers = response?.headers.entries() ?? [];
expect(Object.fromEntries(headers)).toEqual({
'cache-control': 'no-cache',
'x-some-header': 'value',
'content-type': 'text/html;charset=UTF-8',
});
});
it('should return only default headers for pages without specific header configurations', async () => {
const response = await app.render(new Request('http://localhost/home'));
const headers = response?.headers.entries() ?? [];
expect(Object.fromEntries(headers)).toEqual({
'content-type': 'text/html;charset=UTF-8', // default header
});
});
it('should return the configured status for pages with specific status settings', async () => {
const response = await app.render(new Request('http://localhost/page-with-status'));
expect(response?.status).toBe(201);
});
it('should return static `index.csr.html` for routes with CSR rendering mode', async () => {
const response = await app.render(new Request('http://localhost/home-csr'));
const content = await response?.text();
expect(content).toContain('<title>CSR page</title>');
expect(content).not.toContain('ng-server-context');
});
it('should include `ng-server-context="ssr"` for SSR rendering mode', async () => {
const response = await app.render(new Request('http://localhost/home'));
expect(await response?.text()).toContain('ng-server-context="ssr"');
});
});
});
| {
"end_byte": 5442,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/test/app_spec.ts"
} |
angular-cli/packages/angular/ssr/test/npm_package/package_spec.ts_0_1736 | /**
* @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 { runfiles } from '@bazel/runfiles';
import { existsSync } from 'node:fs';
import { readFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
/**
* Resolve paths for the Beasties license file and the golden reference file.
*/
const ANGULAR_SSR_PACKAGE_PATH = dirname(
runfiles.resolve('angular_cli/packages/angular/ssr/npm_package/package.json'),
);
/**
* Path to the actual license file for the Beasties library.
* This file is located in the `third_party/beasties` directory of the Angular CLI npm package.
*/
const CRITTERS_ACTUAL_LICENSE_FILE_PATH = join(
ANGULAR_SSR_PACKAGE_PATH,
'third_party/beasties/THIRD_PARTY_LICENSES.txt',
);
/**
* Path to the golden reference license file for the Beasties library.
* This file is used as a reference for comparison and is located in the same directory as this script.
*/
const CRITTERS_GOLDEN_LICENSE_FILE_PATH = join(__dirname, 'THIRD_PARTY_LICENSES.txt.golden');
describe('NPM Package Tests', () => {
it('should not include the contents of third_party/beasties/index.js in the FESM bundle', async () => {
const fesmFilePath = join(ANGULAR_SSR_PACKAGE_PATH, 'fesm2022/ssr.mjs');
const fesmContent = await readFile(fesmFilePath, 'utf-8');
expect(fesmContent).toContain(`import Beasties from '../third_party/beasties/index.js'`);
});
describe('third_party/beasties/THIRD_PARTY_LICENSES.txt', () => {
it('should exist', () => {
expect(existsSync(CRITTERS_ACTUAL_LICENSE_FILE_PATH)).toBe(true);
});
});
});
| {
"end_byte": 1736,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/test/npm_package/package_spec.ts"
} |
angular-cli/packages/angular/ssr/test/npm_package/THIRD_PARTY_LICENSES.txt.golden_0_9523 |
--------------------------------------------------------------------------------
Package: beasties
License: Apache-2.0
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages. | {
"end_byte": 9523,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/test/npm_package/THIRD_PARTY_LICENSES.txt.golden"
} |
angular-cli/packages/angular/ssr/test/npm_package/THIRD_PARTY_LICENSES.txt.golden_9525_11569 | 9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018 Google Inc.
Copyright 2024 Daniel Roe
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--------------------------------------------------------------------------------
Package: boolbase
License: ISC | {
"end_byte": 11569,
"start_byte": 9525,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/test/npm_package/THIRD_PARTY_LICENSES.txt.golden"
} |
angular-cli/packages/angular/ssr/test/npm_package/THIRD_PARTY_LICENSES.txt.golden_11572_22487 | --------------------------------------------------------------------------------
Package: css-select
License: BSD-2-Clause
Copyright (c) Felix Böhm
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--------------------------------------------------------------------------------
Package: css-what
License: BSD-2-Clause
Copyright (c) Felix Böhm
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--------------------------------------------------------------------------------
Package: dom-serializer
License: MIT
License
(The MIT License)
Copyright (c) 2014 The cheeriojs contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------------
Package: domelementtype
License: BSD-2-Clause
Copyright (c) Felix Böhm
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--------------------------------------------------------------------------------
Package: domhandler
License: BSD-2-Clause
Copyright (c) Felix Böhm
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--------------------------------------------------------------------------------
Package: domutils
License: BSD-2-Clause
Copyright (c) Felix Böhm
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--------------------------------------------------------------------------------
Package: entities
License: BSD-2-Clause
Copyright (c) Felix Böhm
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--------------------------------------------------------------------------------
Package: htmlparser2
License: MIT
Copyright 2010, 2011, Chris Winberry <[email protected]>. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
--------------------------------------------------------------------------------
Package: nanoid
License: MIT
The MIT License (MIT)
Copyright 2017 Andrey Sitnik <[email protected]> | {
"end_byte": 22487,
"start_byte": 11572,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/test/npm_package/THIRD_PARTY_LICENSES.txt.golden"
} |
angular-cli/packages/angular/ssr/test/npm_package/THIRD_PARTY_LICENSES.txt.golden_22489_29509 | Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------------
Package: nth-check
License: BSD-2-Clause
Copyright (c) Felix Böhm
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--------------------------------------------------------------------------------
Package: pathe
License: MIT
MIT License
Copyright (c) Pooya Parsa <[email protected]> - Daniel Roe <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--------------------------------------------------------------------------------
Copyright Joyent, Inc. and other Node contributors.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------------
Package: picocolors
License: ISC
ISC License
Copyright (c) 2021-2024 Oleksii Raspopov, Kostiantyn Denysov, Anton Verinov
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--------------------------------------------------------------------------------
Package: postcss
License: MIT
The MIT License (MIT)
Copyright 2013 Andrey Sitnik <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------------
Package: postcss-media-query-parser
License: MIT | {
"end_byte": 29509,
"start_byte": 22489,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/test/npm_package/THIRD_PARTY_LICENSES.txt.golden"
} |
angular-cli/packages/angular/ssr/test/npm_package/THIRD_PARTY_LICENSES.txt.golden_29512_30781 | --------------------------------------------------------------------------------
Package: unenv
License: MIT
MIT License
Copyright (c) Pooya Parsa <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--------------------------------------------------------------------------------
| {
"end_byte": 30781,
"start_byte": 29512,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/test/npm_package/THIRD_PARTY_LICENSES.txt.golden"
} |
angular-cli/packages/angular/ssr/test/npm_package/BUILD.bazel_0_1632 | load("@bazel_skylib//rules:diff_test.bzl", "diff_test")
load("@bazel_skylib//rules:write_file.bzl", "write_file")
load("@npm//@bazel/jasmine:index.bzl", "jasmine_node_test")
load("//tools:defaults.bzl", "ts_library")
ts_library(
name = "unit_test_lib",
testonly = True,
srcs = glob(["**/*.ts"]),
deps = [
"@npm//@bazel/runfiles",
],
)
jasmine_node_test(
name = "test",
srcs = [":unit_test_lib"],
data = [
"//packages/angular/ssr:npm_package",
],
)
genrule(
name = "beasties_license_file",
srcs = [
"//packages/angular/ssr:npm_package",
],
outs = [
"THIRD_PARTY_LICENSES.txt",
],
cmd = """
cp $(location //packages/angular/ssr:npm_package)/third_party/beasties/THIRD_PARTY_LICENSES.txt $(location :THIRD_PARTY_LICENSES.txt)
""",
)
diff_test(
name = "beasties_license_test",
failure_message = """
To accept the new golden file, execute:
yarn bazel run //packages/angular/ssr/test/npm_package:beasties_license_test.accept
""",
file1 = ":THIRD_PARTY_LICENSES.txt.golden",
file2 = ":beasties_license_file",
)
write_file(
name = "beasties_license_test.accept",
out = "beasties_license_file_accept.sh",
content =
[
"#!/usr/bin/env bash",
"cd ${BUILD_WORKSPACE_DIRECTORY}",
"yarn bazel build //packages/angular/ssr:npm_package",
"cp -fv dist/bin/packages/angular/ssr/npm_package/third_party/beasties/THIRD_PARTY_LICENSES.txt packages/angular/ssr/test/npm_package/THIRD_PARTY_LICENSES.txt.golden",
],
is_executable = True,
)
| {
"end_byte": 1632,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/test/npm_package/BUILD.bazel"
} |
angular-cli/packages/angular/ssr/test/utils/url_spec.ts_0_4742 | /**
* @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 {
addLeadingSlash,
joinUrlParts,
stripIndexHtmlFromURL,
stripLeadingSlash,
stripTrailingSlash,
} from '../../src/utils/url';
describe('URL Utils', () => {
describe('stripTrailingSlash', () => {
it('should remove trailing slash from URL', () => {
expect(stripTrailingSlash('/path/')).toBe('/path');
});
it('should not modify URL if no trailing slash is present', () => {
expect(stripTrailingSlash('/path')).toBe('/path');
});
it('should handle empty URL', () => {
expect(stripTrailingSlash('')).toBe('');
});
it('should handle URL with only a trailing slash', () => {
expect(stripTrailingSlash('/')).toBe('/');
});
});
describe('stripLeadingSlash', () => {
it('should remove leading slash from URL', () => {
expect(stripLeadingSlash('/path/')).toBe('path/');
});
it('should not modify URL if no leading slash is present', () => {
expect(stripLeadingSlash('path/')).toBe('path/');
});
it('should handle empty URL', () => {
expect(stripLeadingSlash('')).toBe('');
});
it('should handle URL with only a leading slash', () => {
expect(stripLeadingSlash('/')).toBe('/');
});
});
describe('addLeadingSlash', () => {
it('should add a leading slash to a URL without one', () => {
expect(addLeadingSlash('path/')).toBe('/path/');
});
it('should not modify URL if it already has a leading slash', () => {
expect(addLeadingSlash('/path/')).toBe('/path/');
});
it('should handle empty URL', () => {
expect(addLeadingSlash('')).toBe('/');
});
});
describe('joinUrlParts', () => {
it('should join multiple URL parts with normalized slashes', () => {
expect(joinUrlParts('', 'path/', '/to/resource')).toBe('/path/to/resource');
});
it('should handle URL parts with leading and trailing slashes', () => {
expect(joinUrlParts('/', '/path/', 'to/resource/')).toBe('/path/to/resource');
});
it('should handle empty URL parts', () => {
expect(joinUrlParts('', '', 'path', '', 'to/resource')).toBe('/path/to/resource');
});
it('should handle an all-empty URL parts', () => {
expect(joinUrlParts('', '')).toBe('/');
});
});
describe('stripIndexHtmlFromURL', () => {
it('should remove /index.html from the end of the URL path', () => {
const url = new URL('http://www.example.com/page/index.html');
const result = stripIndexHtmlFromURL(url);
expect(result.href).toBe('http://www.example.com/page');
});
it('should not modify the URL if /index.html is not present', () => {
const url = new URL('http://www.example.com/page');
const result = stripIndexHtmlFromURL(url);
expect(result.href).toBe('http://www.example.com/page');
});
it('should handle URLs without a path', () => {
const url = new URL('http://www.example.com/index.html');
const result = stripIndexHtmlFromURL(url);
expect(result.href).toBe('http://www.example.com/');
});
it('should not modify the URL if /index.html is in the middle of the path', () => {
const url = new URL('http://www.example.com/index.html/page');
const result = stripIndexHtmlFromURL(url);
expect(result.href).toBe('http://www.example.com/index.html/page');
});
it('should handle URLs with query parameters and /index.html at the end', () => {
const url = new URL('http://www.example.com/page/index.html?query=123');
const result = stripIndexHtmlFromURL(url);
expect(result.href).toBe('http://www.example.com/page?query=123');
});
it('should handle URLs with a fragment and /index.html at the end', () => {
const url = new URL('http://www.example.com/page/index.html#section');
const result = stripIndexHtmlFromURL(url);
expect(result.href).toBe('http://www.example.com/page#section');
});
it('should handle URLs with both query parameters and fragments and /index.html at the end', () => {
const url = new URL('http://www.example.com/page/index.html?query=123#section');
const result = stripIndexHtmlFromURL(url);
expect(result.href).toBe('http://www.example.com/page?query=123#section');
});
it('should handle URLs with HTTPS scheme and /index.html at the end', () => {
const url = new URL('https://www.example.com/page/index.html');
const result = stripIndexHtmlFromURL(url);
expect(result.href).toBe('https://www.example.com/page');
});
});
});
| {
"end_byte": 4742,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/test/utils/url_spec.ts"
} |
angular-cli/packages/angular/ssr/test/utils/lru_cache_spec.ts_0_2060 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { LRUCache } from '../../src/utils/lru-cache';
describe('LRUCache', () => {
let cache: LRUCache<string, number>;
beforeEach(() => {
cache = new LRUCache<string, number>(3);
});
it('should create a cache with the correct capacity', () => {
expect(cache.capacity).toBe(3); // Test internal capacity
});
it('should store and retrieve a key-value pair', () => {
cache.put('a', 1);
expect(cache.get('a')).toBe(1);
});
it('should return undefined for non-existent keys', () => {
expect(cache.get('nonExistentKey')).toBeUndefined();
});
it('should remove the least recently used item when capacity is exceeded', () => {
cache.put('a', 1);
cache.put('b', 2);
cache.put('c', 3);
// Cache is full now, adding another item should evict the least recently used ('a')
cache.put('d', 4);
expect(cache.get('a')).toBeUndefined(); // 'a' should be evicted
expect(cache.get('b')).toBe(2); // 'b', 'c', 'd' should remain
expect(cache.get('c')).toBe(3);
expect(cache.get('d')).toBe(4);
});
it('should update the value if the key already exists', () => {
cache.put('a', 1);
cache.put('a', 10); // Update the value of 'a'
expect(cache.get('a')).toBe(10); // 'a' should have the updated value
});
it('should move the accessed key to the most recently used position', () => {
cache.put('a', 1);
cache.put('b', 2);
cache.put('c', 3);
// Access 'a', it should be moved to the most recently used position
expect(cache.get('a')).toBe(1);
// Adding 'd' should now evict 'b', since 'a' was just accessed
cache.put('d', 4);
expect(cache.get('b')).toBeUndefined(); // 'b' should be evicted
expect(cache.get('a')).toBe(1); // 'a' should still be present
expect(cache.get('c')).toBe(3);
expect(cache.get('d')).toBe(4);
});
});
| {
"end_byte": 2060,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/test/utils/lru_cache_spec.ts"
} |
angular-cli/packages/angular/ssr/test/routes/route-tree_spec.ts_0_7567 | /**
* @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 { RouteTree } from '../../src/routes/route-tree';
describe('RouteTree', () => {
let routeTree: RouteTree;
beforeEach(() => {
routeTree = new RouteTree();
});
describe('toObject and fromObject', () => {
it('should convert the route tree to a nested object and back', () => {
routeTree.insert('/home', { redirectTo: '/home-page' });
routeTree.insert('/about', { redirectTo: '/about-page' });
routeTree.insert('/products/:id', {});
routeTree.insert('/api/details', { redirectTo: '/api/details-page' });
const routeTreeObj = routeTree.toObject();
expect(routeTreeObj).toEqual([
{ redirectTo: '/home-page', route: '/home' },
{ redirectTo: '/about-page', route: '/about' },
{ route: '/products/:id' },
{ redirectTo: '/api/details-page', route: '/api/details' },
]);
const newRouteTree = RouteTree.fromObject(routeTreeObj);
expect(newRouteTree.match('/home')).toEqual({ redirectTo: '/home-page', route: '/home' });
expect(newRouteTree.match('/about')).toEqual({ redirectTo: '/about-page', route: '/about' });
expect(newRouteTree.match('/products/123')).toEqual({ route: '/products/:id' });
expect(newRouteTree.match('/api/details')).toEqual({
redirectTo: '/api/details-page',
route: '/api/details',
});
});
it('should handle complex route structures when converting to and from object', () => {
routeTree.insert('/shop/categories/:category/products/:id', { redirectTo: '/shop/products' });
routeTree.insert('/shop/cart', { redirectTo: '/shop/cart-page' });
const routeTreeObj = routeTree.toObject();
const newRouteTree = RouteTree.fromObject(routeTreeObj);
expect(newRouteTree.match('/shop/categories/electronics/products/123')).toEqual({
redirectTo: '/shop/products',
route: '/shop/categories/:category/products/:id',
});
expect(newRouteTree.match('/shop/cart')).toEqual({
redirectTo: '/shop/cart-page',
route: '/shop/cart',
});
});
it('should construct a RouteTree from a nested object representation', () => {
const routeTreeObj = [
{ redirectTo: '/home-page', route: '/home' },
{ redirectTo: '/about-page', route: '/about' },
{
redirectTo: '/api/details-page',
route: '/api/*/details',
},
];
const newRouteTree = RouteTree.fromObject(routeTreeObj);
expect(newRouteTree.match('/home')).toEqual({ redirectTo: '/home-page', route: '/home' });
expect(newRouteTree.match('/about')).toEqual({ redirectTo: '/about-page', route: '/about' });
expect(newRouteTree.match('/api/users/details')).toEqual({
redirectTo: '/api/details-page',
route: '/api/*/details',
});
expect(newRouteTree.match('/nonexistent')).toBeUndefined();
});
it('should handle an empty RouteTree correctly', () => {
const routeTreeObj = routeTree.toObject();
expect(routeTreeObj).toEqual([]);
const newRouteTree = RouteTree.fromObject(routeTreeObj);
expect(newRouteTree.match('/any-path')).toBeUndefined();
});
it('should preserve insertion order when converting to and from object', () => {
routeTree.insert('/first', {});
routeTree.insert('/:id', {});
routeTree.insert('/second', {});
const routeTreeObj = routeTree.toObject();
expect(routeTreeObj).toEqual([{ route: '/first' }, { route: '/:id' }, { route: '/second' }]);
const newRouteTree = RouteTree.fromObject(routeTreeObj);
expect(newRouteTree.match('/first')).toEqual({ route: '/first' });
expect(newRouteTree.match('/second')).toEqual({ route: '/:id' });
expect(newRouteTree.match('/third')).toEqual({ route: '/:id' });
});
});
describe('match', () => {
it('should handle empty routes', () => {
routeTree.insert('', {});
expect(routeTree.match('')).toEqual({ route: '' });
});
it('should insert and match basic routes', () => {
routeTree.insert('/home', {});
routeTree.insert('/about', {});
expect(routeTree.match('/home')).toEqual({ route: '/home' });
expect(routeTree.match('/about')).toEqual({ route: '/about' });
expect(routeTree.match('/contact')).toBeUndefined();
});
it('should handle wildcard segments', () => {
routeTree.insert('/api/users', {});
routeTree.insert('/api/products', {});
routeTree.insert('/api/*/details', {});
expect(routeTree.match('/api/users')).toEqual({ route: '/api/users' });
expect(routeTree.match('/api/products')).toEqual({ route: '/api/products' });
expect(routeTree.match('/api/orders/details')).toEqual({ route: '/api/*/details' });
});
it('should handle catch all (double wildcard) segments', () => {
routeTree.insert('/api/users', {});
routeTree.insert('/api/*/users/**', {});
routeTree.insert('/api/**', {});
expect(routeTree.match('/api/users')).toEqual({ route: '/api/users' });
expect(routeTree.match('/api/products')).toEqual({ route: '/api/**' });
expect(routeTree.match('/api/info/users/details')).toEqual({ route: '/api/*/users/**' });
expect(routeTree.match('/api/user/details')).toEqual({ route: '/api/**' });
});
it('should prioritize earlier insertions in case of conflicts', () => {
routeTree.insert('/blog/*', {});
routeTree.insert('/blog/article', { redirectTo: 'blog' });
expect(routeTree.match('/blog/article')).toEqual({ route: '/blog/*' });
});
it('should handle parameterized segments as wildcards', () => {
routeTree.insert('/users/:id', {});
expect(routeTree.match('/users/123')).toEqual({ route: '/users/:id' });
});
it('should handle complex route structures', () => {
routeTree.insert('/shop/categories/:category', {});
routeTree.insert('/shop/categories/:category/products/:id', {});
expect(routeTree.match('/shop/categories/electronics')).toEqual({
route: '/shop/categories/:category',
});
expect(routeTree.match('/shop/categories/electronics/products/456')).toEqual({
route: '/shop/categories/:category/products/:id',
});
});
it('should return undefined for unmatched routes', () => {
routeTree.insert('/foo', {});
expect(routeTree.match('/bar')).toBeUndefined();
});
it('should handle multiple wildcards in a path', () => {
routeTree.insert('/a/*/b/*/c', {});
expect(routeTree.match('/a/1/b/2/c')).toEqual({ route: '/a/*/b/*/c' });
});
it('should handle trailing slashes', () => {
routeTree.insert('/foo/', {});
expect(routeTree.match('/foo')).toEqual({ route: '/foo' });
expect(routeTree.match('/foo/')).toEqual({ route: '/foo' });
});
it('should handle case-sensitive matching', () => {
routeTree.insert('/case', {});
expect(routeTree.match('/CASE')).toBeUndefined();
});
it('should handle routes with special characters', () => {
routeTree.insert('/path with spaces', {});
routeTree.insert('/path/with/slashes', {});
expect(routeTree.match('/path with spaces')).toEqual({ route: '/path with spaces' });
expect(routeTree.match('/path/with/slashes')).toEqual({ route: '/path/with/slashes' });
});
});
});
| {
"end_byte": 7567,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/test/routes/route-tree_spec.ts"
} |
angular-cli/packages/angular/ssr/test/routes/ng-routes_spec.ts_0_8105 | /**
* @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
*/
// The compiler is needed as tests are in JIT.
/* eslint-disable import/no-unassigned-import */
import '@angular/compiler';
/* eslint-enable import/no-unassigned-import */
import { Component } from '@angular/core';
import { extractRoutesAndCreateRouteTree } from '../../src/routes/ng-routes';
import { PrerenderFallback, RenderMode } from '../../src/routes/route-config';
import { setAngularAppTestingManifest } from '../testing-utils';
describe('extractRoutesAndCreateRouteTree', () => {
const url = new URL('http://localhost');
@Component({
standalone: true,
selector: 'app-dummy-comp',
template: `dummy works`,
})
class DummyComponent {}
it('should extract routes and create a route tree', async () => {
setAngularAppTestingManifest(
[
{ path: '', component: DummyComponent },
{ path: 'home', component: DummyComponent },
{ path: 'redirect', redirectTo: 'home' },
{ path: 'user/:id', component: DummyComponent },
],
[
{ path: 'home', renderMode: RenderMode.Client },
{ path: 'redirect', renderMode: RenderMode.Server, status: 301 },
{ path: '**', renderMode: RenderMode.Server },
],
);
const { routeTree, errors } = await extractRoutesAndCreateRouteTree(url);
expect(errors).toHaveSize(0);
expect(routeTree.toObject()).toEqual([
{ route: '/', renderMode: RenderMode.Server },
{ route: '/home', renderMode: RenderMode.Client },
{ route: '/redirect', renderMode: RenderMode.Server, status: 301, redirectTo: '/home' },
{ route: '/user/:id', renderMode: RenderMode.Server },
]);
});
it('should handle invalid route configuration path', async () => {
setAngularAppTestingManifest(
[{ path: 'home', component: DummyComponent }],
[
// This path starts with a slash, which should trigger an error
{ path: '/invalid', renderMode: RenderMode.Client },
],
);
const { errors } = await extractRoutesAndCreateRouteTree(url);
expect(errors[0]).toContain(
`Invalid '/invalid' route configuration: the path cannot start with a slash.`,
);
});
describe('when `invokeGetPrerenderParams` is true', () => {
it('should resolve parameterized routes for SSG and add a fallback route if fallback is Server', async () => {
setAngularAppTestingManifest(
[{ path: 'user/:id/role/:role', component: DummyComponent }],
[
{
path: 'user/:id/role/:role',
renderMode: RenderMode.Prerender,
fallback: PrerenderFallback.Server,
async getPrerenderParams() {
return [
{ id: 'joe', role: 'admin' },
{ id: 'jane', role: 'writer' },
];
},
},
],
);
const { routeTree, errors } = await extractRoutesAndCreateRouteTree(url, undefined, true);
expect(errors).toHaveSize(0);
expect(routeTree.toObject()).toEqual([
{ route: '/user/joe/role/admin', renderMode: RenderMode.Prerender },
{
route: '/user/jane/role/writer',
renderMode: RenderMode.Prerender,
},
{ route: '/user/:id/role/:role', renderMode: RenderMode.Server },
]);
});
it('should resolve parameterized routes for SSG and add a fallback route if fallback is Client', async () => {
setAngularAppTestingManifest(
[
{ path: 'home', component: DummyComponent },
{ path: 'user/:id/role/:role', component: DummyComponent },
],
[
{
path: 'user/:id/role/:role',
renderMode: RenderMode.Prerender,
fallback: PrerenderFallback.Client,
async getPrerenderParams() {
return [
{ id: 'joe', role: 'admin' },
{ id: 'jane', role: 'writer' },
];
},
},
{ path: '**', renderMode: RenderMode.Server },
],
);
const { routeTree, errors } = await extractRoutesAndCreateRouteTree(url, undefined, true);
expect(errors).toHaveSize(0);
expect(routeTree.toObject()).toEqual([
{ route: '/home', renderMode: RenderMode.Server },
{ route: '/user/joe/role/admin', renderMode: RenderMode.Prerender },
{
route: '/user/jane/role/writer',
renderMode: RenderMode.Prerender,
},
{ route: '/user/:id/role/:role', renderMode: RenderMode.Client },
]);
});
it('should resolve parameterized routes for SSG and not add a fallback route if fallback is None', async () => {
setAngularAppTestingManifest(
[
{ path: 'home', component: DummyComponent },
{ path: 'user/:id/role/:role', component: DummyComponent },
],
[
{
path: 'user/:id/role/:role',
renderMode: RenderMode.Prerender,
fallback: PrerenderFallback.None,
async getPrerenderParams() {
return [
{ id: 'joe', role: 'admin' },
{ id: 'jane', role: 'writer' },
];
},
},
{ path: '**', renderMode: RenderMode.Server },
],
);
const { routeTree, errors } = await extractRoutesAndCreateRouteTree(url, undefined, true);
expect(errors).toHaveSize(0);
expect(routeTree.toObject()).toEqual([
{ route: '/home', renderMode: RenderMode.Server },
{ route: '/user/joe/role/admin', renderMode: RenderMode.Prerender },
{
route: '/user/jane/role/writer',
renderMode: RenderMode.Prerender,
},
]);
});
});
it('should not resolve parameterized routes for SSG when `invokeGetPrerenderParams` is false', async () => {
setAngularAppTestingManifest(
[
{ path: 'home', component: DummyComponent },
{ path: 'user/:id/role/:role', component: DummyComponent },
],
[
{
path: 'user/:id/role/:role',
renderMode: RenderMode.Prerender,
async getPrerenderParams() {
return [
{ id: 'joe', role: 'admin' },
{ id: 'jane', role: 'writer' },
];
},
},
{ path: '**', renderMode: RenderMode.Server },
],
);
const { routeTree, errors } = await extractRoutesAndCreateRouteTree(url, undefined, false);
expect(errors).toHaveSize(0);
expect(routeTree.toObject()).toEqual([
{ route: '/home', renderMode: RenderMode.Server },
{ route: '/user/:id/role/:role', renderMode: RenderMode.Server },
]);
});
it('should not include fallback routes for SSG when `includePrerenderFallbackRoutes` is false', async () => {
setAngularAppTestingManifest(
[
{ path: 'home', component: DummyComponent },
{ path: 'user/:id/role/:role', component: DummyComponent },
],
[
{
path: 'user/:id/role/:role',
fallback: PrerenderFallback.Client,
renderMode: RenderMode.Prerender,
async getPrerenderParams() {
return [
{ id: 'joe', role: 'admin' },
{ id: 'jane', role: 'writer' },
];
},
},
{ path: '**', renderMode: RenderMode.Server },
],
);
const { routeTree, errors } = await extractRoutesAndCreateRouteTree(
url,
/** manifest */ undefined,
/** invokeGetPrerenderParams */ true,
/** includePrerenderFallbackRoutes */ false,
);
expect(errors).toHaveSize(0);
expect(routeTree.toObject()).toEqual([
{ route: '/home', renderMode: RenderMode.Server },
{ route: '/user/joe/role/admin', renderMode: RenderMode.Prerender },
{
route: '/user/jane/role/writer',
renderMode: RenderMode.Prerender,
},
]);
}); | {
"end_byte": 8105,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/test/routes/ng-routes_spec.ts"
} |
angular-cli/packages/angular/ssr/test/routes/ng-routes_spec.ts_8109_12661 | it('should include fallback routes for SSG when `includePrerenderFallbackRoutes` is true', async () => {
setAngularAppTestingManifest(
[
{ path: 'home', component: DummyComponent },
{ path: 'user/:id/role/:role', component: DummyComponent },
],
[
{
path: 'user/:id/role/:role',
renderMode: RenderMode.Prerender,
fallback: PrerenderFallback.Client,
async getPrerenderParams() {
return [
{ id: 'joe', role: 'admin' },
{ id: 'jane', role: 'writer' },
];
},
},
{ path: '**', renderMode: RenderMode.Server },
],
);
const { routeTree, errors } = await extractRoutesAndCreateRouteTree(
url,
/** manifest */ undefined,
/** invokeGetPrerenderParams */ true,
/** includePrerenderFallbackRoutes */ true,
);
expect(errors).toHaveSize(0);
expect(routeTree.toObject()).toEqual([
{ route: '/home', renderMode: RenderMode.Server },
{ route: '/user/joe/role/admin', renderMode: RenderMode.Prerender },
{
route: '/user/jane/role/writer',
renderMode: RenderMode.Prerender,
},
{ route: '/user/:id/role/:role', renderMode: RenderMode.Client },
]);
});
it(`should not error when a catch-all route didn't match any Angular route.`, async () => {
setAngularAppTestingManifest(
[{ path: 'home', component: DummyComponent }],
[
{ path: 'home', renderMode: RenderMode.Server },
{ path: '**', renderMode: RenderMode.Server },
],
);
const { errors } = await extractRoutesAndCreateRouteTree(
url,
/** manifest */ undefined,
/** invokeGetPrerenderParams */ false,
/** includePrerenderFallbackRoutes */ false,
);
expect(errors).toHaveSize(0);
});
it('should error when a route is not defined in the server routing configuration', async () => {
setAngularAppTestingManifest(
[{ path: 'home', component: DummyComponent }],
[
{ path: 'home', renderMode: RenderMode.Server },
{ path: 'invalid', renderMode: RenderMode.Server },
],
);
const { errors } = await extractRoutesAndCreateRouteTree(
url,
/** manifest */ undefined,
/** invokeGetPrerenderParams */ false,
/** includePrerenderFallbackRoutes */ false,
);
expect(errors).toHaveSize(1);
expect(errors[0]).toContain(
`The 'invalid' server route does not match any routes defined in the Angular routing configuration`,
);
});
it('should error when a server route is not defined in the Angular routing configuration', async () => {
setAngularAppTestingManifest(
[
{ path: 'home', component: DummyComponent },
{ path: 'invalid', component: DummyComponent },
],
[{ path: 'home', renderMode: RenderMode.Server }],
);
const { errors } = await extractRoutesAndCreateRouteTree(
url,
/** manifest */ undefined,
/** invokeGetPrerenderParams */ false,
/** includePrerenderFallbackRoutes */ false,
);
expect(errors).toHaveSize(1);
expect(errors[0]).toContain(
`The 'invalid' route does not match any route defined in the server routing configuration`,
);
});
it(`should error when 'RenderMode.AppShell' is used on more than one route`, async () => {
setAngularAppTestingManifest(
[
{ path: 'home', component: DummyComponent },
{ path: 'shell', component: DummyComponent },
],
[{ path: '**', renderMode: RenderMode.AppShell }],
);
const { errors } = await extractRoutesAndCreateRouteTree(
url,
/** manifest */ undefined,
/** invokeGetPrerenderParams */ false,
/** includePrerenderFallbackRoutes */ false,
);
expect(errors).toHaveSize(1);
expect(errors[0]).toContain(
`Both 'home' and 'shell' routes have their 'renderMode' set to 'AppShell'.`,
);
});
it('should apply RenderMode matching the wildcard when no Angular routes are defined', async () => {
setAngularAppTestingManifest([], [{ path: '**', renderMode: RenderMode.Server }]);
const { errors, routeTree } = await extractRoutesAndCreateRouteTree(
url,
/** manifest */ undefined,
/** invokeGetPrerenderParams */ false,
/** includePrerenderFallbackRoutes */ false,
);
expect(errors).toHaveSize(0);
expect(routeTree.toObject()).toEqual([{ route: '/', renderMode: RenderMode.Server }]);
});
}); | {
"end_byte": 12661,
"start_byte": 8109,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/test/routes/ng-routes_spec.ts"
} |
angular-cli/packages/angular/ssr/test/routes/router_spec.ts_0_4338 | /**
* @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
*/
// The compiler is needed as tests are in JIT.
/* eslint-disable import/no-unassigned-import */
import '@angular/compiler';
/* eslint-enable import/no-unassigned-import */
import { Component } from '@angular/core';
import { AngularAppManifest, getAngularAppManifest } from '../../src/manifest';
import { RenderMode } from '../../src/routes/route-config';
import { ServerRouter } from '../../src/routes/router';
import { setAngularAppTestingManifest } from '../testing-utils';
describe('ServerRouter', () => {
let router: ServerRouter;
let manifest: AngularAppManifest;
beforeAll(() => {
@Component({
standalone: true,
selector: 'app-dummy',
template: `dummy works`,
})
class DummyComponent {}
setAngularAppTestingManifest(
[
{ path: 'home', component: DummyComponent },
{ path: 'redirect', redirectTo: 'home' },
{ path: 'encoding url', component: DummyComponent },
{ path: 'user/:id', component: DummyComponent },
],
[
{ path: 'redirect', renderMode: RenderMode.Server, status: 301 },
{ path: '**', renderMode: RenderMode.Server },
],
);
manifest = getAngularAppManifest();
});
describe('from', () => {
it('should build the route tree', async () => {
router = await ServerRouter.from(manifest, new URL('http://localhost'));
// Check that routes are correctly built
expect(router.match(new URL('http://localhost/home'))).toEqual({
route: '/home',
renderMode: RenderMode.Server,
});
expect(router.match(new URL('http://localhost/redirect'))).toEqual({
redirectTo: '/home',
route: '/redirect',
renderMode: RenderMode.Server,
status: 301,
});
expect(router.match(new URL('http://localhost/user/123'))).toEqual({
route: '/user/:id',
renderMode: RenderMode.Server,
});
});
it('should return the existing promise if a build from is already in progress', () => {
const promise1 = ServerRouter.from(manifest, new URL('http://localhost'));
const promise2 = ServerRouter.from(manifest, new URL('http://localhost'));
expect(promise1).toBe(promise2); // Ensure both promises are the same
});
});
describe('match', () => {
beforeAll(async () => {
router = await ServerRouter.from(manifest, new URL('http://localhost'));
});
it('should match a URL to the route tree metadata', () => {
const homeMetadata = router.match(new URL('http://localhost/home'));
const redirectMetadata = router.match(new URL('http://localhost/redirect'));
const userMetadata = router.match(new URL('http://localhost/user/123'));
expect(homeMetadata).toEqual({
route: '/home',
renderMode: RenderMode.Server,
});
expect(redirectMetadata).toEqual({
redirectTo: '/home',
route: '/redirect',
status: 301,
renderMode: RenderMode.Server,
});
expect(userMetadata).toEqual({
route: '/user/:id',
renderMode: RenderMode.Server,
});
});
it('should correctly match URLs ending with /index.html', () => {
const homeMetadata = router.match(new URL('http://localhost/home/index.html'));
const userMetadata = router.match(new URL('http://localhost/user/123/index.html'));
const redirectMetadata = router.match(new URL('http://localhost/redirect/index.html'));
expect(homeMetadata).toEqual({
route: '/home',
renderMode: RenderMode.Server,
});
expect(redirectMetadata).toEqual({
redirectTo: '/home',
route: '/redirect',
status: 301,
renderMode: RenderMode.Server,
});
expect(userMetadata).toEqual({
route: '/user/:id',
renderMode: RenderMode.Server,
});
});
it('should handle encoded URLs', () => {
const encodedUserMetadata = router.match(new URL('http://localhost/encoding%20url'));
expect(encodedUserMetadata).toEqual({
route: '/encoding url',
renderMode: RenderMode.Server,
});
});
});
});
| {
"end_byte": 4338,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/test/routes/router_spec.ts"
} |
angular-cli/packages/angular/ssr/third_party/beasties/rollup.config.mjs_0_2137 | /**
* @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 { nodeResolve } from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import alias from '@rollup/plugin-alias';
import { createRollupLicensePlugin } from 'rollup-license-plugin';
import { nodeless } from 'unenv';
/**
* Header text that will be added to the top of the output license extraction file.
*/
const EXTRACTION_FILE_HEADER = '';
/**
* The package entry separator to use within the output license extraction file.
*/
const EXTRACTION_FILE_SEPARATOR = '-'.repeat(80) + '\n';
const { path, fs } = nodeless.alias;
export default {
plugins: [
nodeResolve({
preferBuiltins: false,
browser: true,
jail: process.cwd(),
}),
commonjs(),
alias({
entries: {
'node:path': path,
'node:fs': fs,
},
}),
createRollupLicensePlugin({
additionalFiles: {
'THIRD_PARTY_LICENSES.txt': (packages) => {
const extractedLicenses = {};
for (const { name, license, licenseText } of packages) {
// Generate the package's license entry in the output content
let extractedLicenseContent = `Package: ${name}\n`;
extractedLicenseContent += `License: ${license}\n`;
extractedLicenseContent += `\n${(licenseText ?? '').trim().replace(/\r?\n/g, '\n')}\n`;
extractedLicenseContent += EXTRACTION_FILE_SEPARATOR;
extractedLicenses[name] = extractedLicenseContent;
}
// Get the keys of the object and sort them and etract and join the values corresponding to the sorted keys
const joinedLicenseContent = Object.keys(extractedLicenses)
.sort()
.map((pkgName) => extractedLicenses[pkgName])
.join('');
return `${EXTRACTION_FILE_HEADER}\n${EXTRACTION_FILE_SEPARATOR}${joinedLicenseContent}`;
},
},
}),
],
output: {
exports: 'auto',
},
};
| {
"end_byte": 2137,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/third_party/beasties/rollup.config.mjs"
} |
angular-cli/packages/angular/ssr/third_party/beasties/BUILD.bazel_0_1550 | load("@npm//@bazel/rollup:index.bzl", "rollup_bundle")
load("//tools:defaults.bzl", "js_library")
package(default_visibility = ["//visibility:public"])
js_library(
name = "bundled_beasties_lib",
srcs = [
"index.d.ts",
":bundled_beasties_files",
],
deps = [
"@npm//beasties",
],
)
# Filter out esbuild metadata files and only copy the necessary files
genrule(
name = "bundled_beasties_files",
srcs = [
":bundled_beasties",
],
outs = [
"index.js",
"index.js.map",
"THIRD_PARTY_LICENSES.txt",
],
cmd = """
for f in $(locations :bundled_beasties); do
# Only process files inside the bundled_beasties directory
if [[ "$${f}" == *bundled_beasties ]]; then
cp "$${f}/index.js" $(location :index.js)
cp "$${f}/index.js.map" $(location :index.js.map)
cp "$${f}/THIRD_PARTY_LICENSES.txt" $(location :THIRD_PARTY_LICENSES.txt)
fi
done
""",
)
rollup_bundle(
name = "bundled_beasties",
config_file = ":rollup.config.mjs",
entry_points = {
"@npm//:node_modules/beasties/dist/index.mjs": "index",
},
format = "esm",
link_workspace_root = True,
output_dir = True,
sourcemap = "true",
deps = [
"@npm//@rollup/plugin-alias",
"@npm//@rollup/plugin-commonjs",
"@npm//@rollup/plugin-node-resolve",
"@npm//beasties",
"@npm//rollup-license-plugin",
"@npm//unenv",
],
)
| {
"end_byte": 1550,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/third_party/beasties/BUILD.bazel"
} |
angular-cli/packages/angular/ssr/third_party/beasties/index.d.ts_0_239 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export { default } from 'beasties';
| {
"end_byte": 239,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/third_party/beasties/index.d.ts"
} |
angular-cli/packages/angular/ssr/node/BUILD.bazel_0_419 | load("//tools:defaults.bzl", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "node",
srcs = glob(
[
"*.ts",
"src/**/*.ts",
],
),
module_name = "@angular/ssr/node",
deps = [
"//packages/angular/ssr",
"@npm//@angular/core",
"@npm//@angular/platform-server",
"@npm//@types/node",
],
)
| {
"end_byte": 419,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/node/BUILD.bazel"
} |
angular-cli/packages/angular/ssr/node/index.ts_0_234 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './public_api';
| {
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/node/index.ts"
} |
angular-cli/packages/angular/ssr/node/public_api.ts_0_624 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export {
CommonEngine,
type CommonEngineRenderOptions,
type CommonEngineOptions,
} from './src/common-engine/common-engine';
export { AngularNodeAppEngine } from './src/app-engine';
export { createNodeRequestHandler } from './src/handler';
export { writeResponseToNodeResponse } from './src/response';
export { createWebRequestFromNodeRequest } from './src/request';
export { isMainModule } from './src/module';
| {
"end_byte": 624,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/node/public_api.ts"
} |
angular-cli/packages/angular/ssr/node/test/request_spec.ts_0_4821 | /**
* @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 { IncomingMessage, Server, ServerResponse, createServer, request } from 'node:http';
import { AddressInfo } from 'node:net';
import { createWebRequestFromNodeRequest } from '../src/request';
describe('createWebRequestFromNodeRequest', () => {
let server: Server;
let port: number;
function extractNodeRequest(makeRequest: () => void): Promise<IncomingMessage> {
const nodeRequest = getNodeRequest();
makeRequest();
return nodeRequest;
}
async function getNodeRequest(): Promise<IncomingMessage> {
const { req, res } = await new Promise<{ req: IncomingMessage; res: ServerResponse }>(
(resolve) => {
server.once('request', (req, res) => resolve({ req, res }));
},
);
res.end();
return req;
}
beforeAll((done) => {
server = createServer();
server.listen(0, () => {
port = (server.address() as AddressInfo).port;
done();
});
});
afterAll((done) => {
server.close(done);
});
describe('GET Handling', () => {
it('should correctly handle a basic GET request', async () => {
const nodeRequest = await extractNodeRequest(() => {
request({
host: 'localhost',
port,
path: '/basic-get',
method: 'GET',
}).end();
});
const webRequest = createWebRequestFromNodeRequest(nodeRequest);
expect(webRequest.method).toBe('GET');
expect(webRequest.url).toBe(`http://localhost:${port}/basic-get`);
});
it('should correctly handle GET request with query parameters', async () => {
const nodeRequest = await extractNodeRequest(() => {
request({
host: 'localhost',
port,
path: '/search?query=hello&page=2',
method: 'GET',
}).end();
});
const webRequest = createWebRequestFromNodeRequest(nodeRequest);
expect(webRequest.method).toBe('GET');
expect(webRequest.url).toBe(`http://localhost:${port}/search?query=hello&page=2`);
});
it('should correctly handle GET request with custom headers', async () => {
const nodeRequest = await extractNodeRequest(() => {
request({
hostname: 'localhost',
port,
path: '/with-headers',
method: 'GET',
headers: {
'X-Custom-Header1': 'value1',
'X-Custom-Header2': 'value2',
},
}).end();
});
const webRequest = createWebRequestFromNodeRequest(nodeRequest);
expect(webRequest.method).toBe('GET');
expect(webRequest.url).toBe(`http://localhost:${port}/with-headers`);
expect(webRequest.headers.get('x-custom-header1')).toBe('value1');
expect(webRequest.headers.get('x-custom-header2')).toBe('value2');
});
});
describe('POST Handling', () => {
it('should handle POST request with JSON body and correct response', async () => {
const postData = JSON.stringify({ message: 'Hello from POST' });
const nodeRequest = await extractNodeRequest(() => {
const clientRequest = request({
hostname: 'localhost',
port,
path: '/post-json',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData),
},
});
clientRequest.write(postData);
clientRequest.end();
});
const webRequest = createWebRequestFromNodeRequest(nodeRequest);
expect(webRequest.method).toBe('POST');
expect(webRequest.url).toBe(`http://localhost:${port}/post-json`);
expect(webRequest.headers.get('content-type')).toBe('application/json');
expect(await webRequest.json()).toEqual({ message: 'Hello from POST' });
});
it('should handle POST request with empty text body', async () => {
const postData = '';
const nodeRequest = await extractNodeRequest(() => {
const clientRequest = request({
hostname: 'localhost',
port,
path: '/post-text',
method: 'POST',
headers: {
'Content-Type': 'text/plain',
'Content-Length': Buffer.byteLength(postData),
},
});
clientRequest.write(postData);
clientRequest.end();
});
const webRequest = createWebRequestFromNodeRequest(nodeRequest);
expect(webRequest.method).toBe('POST');
expect(webRequest.url).toBe(`http://localhost:${port}/post-text`);
expect(webRequest.headers.get('content-type')).toBe('text/plain');
expect(await webRequest.text()).toBe('');
});
});
});
| {
"end_byte": 4821,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/node/test/request_spec.ts"
} |
angular-cli/packages/angular/ssr/node/test/response_spec.ts_0_3087 | /**
* @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 { IncomingMessage, Server, createServer, request as requestCb } from 'node:http';
import { AddressInfo } from 'node:net';
import { writeResponseToNodeResponse } from '../src/response';
describe('writeResponseToNodeResponse', () => {
let server: Server;
function simulateResponse(
res: Response,
): Promise<{ response: IncomingMessage; body: string | null }> {
server.once('request', (req, nodeResponse) => {
void writeResponseToNodeResponse(res, nodeResponse);
});
return new Promise<{
body: string | null;
response: IncomingMessage;
}>((resolve, reject) => {
const { port } = server.address() as AddressInfo;
const clientRequest = requestCb(
{
host: 'localhost',
port,
},
(response) => {
let body: string | null = null;
response
.on('data', (chunk) => {
body ??= '';
body += chunk;
})
.on('end', () => resolve({ response, body }))
.on('error', reject);
},
);
clientRequest.end();
});
}
beforeAll((done) => {
server = createServer();
server.listen(0, done);
});
afterAll((done) => {
server.close(done);
});
it('should write status, headers, and body to Node.js response', async () => {
const { response, body } = await simulateResponse(
new Response('Hello, world!', {
status: 201,
headers: {
'Content-Type': 'text/plain',
'X-Custom-Header': 'custom-value',
},
}),
);
expect(response.statusCode).toBe(201);
expect(response.headers['content-type']).toBe('text/plain');
expect(response.headers['x-custom-header']).toBe('custom-value');
expect(body).toBe('Hello, world!');
});
it('should handle empty body', async () => {
const { response, body } = await simulateResponse(
new Response(null, {
status: 204,
}),
);
expect(response.statusCode).toBe(204);
expect(body).toBeNull();
});
it('should handle JSON content types', async () => {
const jsonData = JSON.stringify({ message: 'Hello JSON' });
const { response, body } = await simulateResponse(
new Response(jsonData, {
headers: { 'Content-Type': 'application/json' },
}),
);
expect(response.statusCode).toBe(200);
expect(body).toBe(jsonData);
});
it('should set cookies on the ServerResponse', async () => {
const cookieValue: string[] = [
'myCookie=myValue; Path=/; HttpOnly',
'anotherCookie=anotherValue; Path=/test',
];
const headers = new Headers();
cookieValue.forEach((v) => headers.append('set-cookie', v));
const { response } = await simulateResponse(new Response(null, { headers }));
expect(response.headers['set-cookie']).toEqual(cookieValue);
});
});
| {
"end_byte": 3087,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/node/test/response_spec.ts"
} |
angular-cli/packages/angular/ssr/node/test/BUILD.bazel_0_348 | load("@npm//@bazel/jasmine:index.bzl", "jasmine_node_test")
load("//tools:defaults.bzl", "ts_library")
ts_library(
name = "unit_test_lib",
testonly = True,
srcs = glob(["**/*_spec.ts"]),
deps = [
"//packages/angular/ssr/node",
],
)
jasmine_node_test(
name = "test",
deps = [
":unit_test_lib",
],
)
| {
"end_byte": 348,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/node/test/BUILD.bazel"
} |
angular-cli/packages/angular/ssr/node/src/module.ts_0_1229 | /**
* @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 { argv } from 'node:process';
import { fileURLToPath } from 'node:url';
/**
* Determines whether the provided URL represents the main entry point module.
*
* This function checks if the provided URL corresponds to the main ESM module being executed directly.
* It's useful for conditionally executing code that should only run when a module is the entry point,
* such as starting a server or initializing an application.
*
* It performs two key checks:
* 1. Verifies if the URL starts with 'file:', ensuring it is a local file.
* 2. Compares the URL's resolved file path with the first command-line argument (`process.argv[1]`),
* which points to the file being executed.
*
* @param url The URL of the module to check. This should typically be `import.meta.url`.
* @returns `true` if the provided URL represents the main entry point, otherwise `false`.
* @developerPreview
*/
export function isMainModule(url: string): boolean {
return url.startsWith('file:') && argv[1] === fileURLToPath(url);
}
| {
"end_byte": 1229,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/node/src/module.ts"
} |
angular-cli/packages/angular/ssr/node/src/response.ts_0_2005 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import type { ServerResponse } from 'node:http';
/**
* Streams a web-standard `Response` into a Node.js `ServerResponse`.
*
* @param source - The web-standard `Response` object to stream from.
* @param destination - The Node.js `ServerResponse` object to stream into.
* @returns A promise that resolves once the streaming operation is complete.
* @developerPreview
*/
export async function writeResponseToNodeResponse(
source: Response,
destination: ServerResponse,
): Promise<void> {
const { status, headers, body } = source;
destination.statusCode = status;
let cookieHeaderSet = false;
for (const [name, value] of headers.entries()) {
if (name === 'set-cookie') {
if (cookieHeaderSet) {
continue;
}
// Sets the 'set-cookie' header only once to ensure it is correctly applied.
// Concatenating 'set-cookie' values can lead to incorrect behavior, so we use a single value from `headers.getSetCookie()`.
destination.setHeader(name, headers.getSetCookie());
cookieHeaderSet = true;
} else {
destination.setHeader(name, value);
}
}
if (!body) {
destination.end();
return;
}
try {
const reader = body.getReader();
destination.on('close', () => {
reader.cancel().catch((error) => {
// eslint-disable-next-line no-console
console.error(
`An error occurred while writing the response body for: ${destination.req.url}.`,
error,
);
});
});
// eslint-disable-next-line no-constant-condition
while (true) {
const { done, value } = await reader.read();
if (done) {
destination.end();
break;
}
destination.write(value);
}
} catch {
destination.end('Internal server error.');
}
}
| {
"end_byte": 2005,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/node/src/response.ts"
} |
angular-cli/packages/angular/ssr/node/src/request.ts_0_2448 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import type { IncomingHttpHeaders, IncomingMessage } from 'node:http';
/**
* Converts a Node.js `IncomingMessage` into a Web Standard `Request`.
*
* @param nodeRequest - The Node.js `IncomingMessage` object to convert.
* @returns A Web Standard `Request` object.
* @developerPreview
*/
export function createWebRequestFromNodeRequest(nodeRequest: IncomingMessage): Request {
const { headers, method = 'GET' } = nodeRequest;
const withBody = method !== 'GET' && method !== 'HEAD';
return new Request(createRequestUrl(nodeRequest), {
method,
headers: createRequestHeaders(headers),
body: withBody ? nodeRequest : undefined,
duplex: withBody ? 'half' : undefined,
});
}
/**
* Creates a `Headers` object from Node.js `IncomingHttpHeaders`.
*
* @param nodeHeaders - The Node.js `IncomingHttpHeaders` object to convert.
* @returns A `Headers` object containing the converted headers.
*/
function createRequestHeaders(nodeHeaders: IncomingHttpHeaders): Headers {
const headers = new Headers();
for (const [name, value] of Object.entries(nodeHeaders)) {
if (typeof value === 'string') {
headers.append(name, value);
} else if (Array.isArray(value)) {
for (const item of value) {
headers.append(name, item);
}
}
}
return headers;
}
/**
* Creates a `URL` object from a Node.js `IncomingMessage`, taking into account the protocol, host, and port.
*
* @param nodeRequest - The Node.js `IncomingMessage` object to extract URL information from.
* @returns A `URL` object representing the request URL.
*/
function createRequestUrl(nodeRequest: IncomingMessage): URL {
const { headers, socket, url = '' } = nodeRequest;
const protocol =
headers['x-forwarded-proto'] ?? ('encrypted' in socket && socket.encrypted ? 'https' : 'http');
const hostname = headers['x-forwarded-host'] ?? headers.host ?? headers[':authority'];
const port = headers['x-forwarded-port'] ?? socket.localPort;
if (Array.isArray(hostname)) {
throw new Error('host value cannot be an array.');
}
let hostnameWithPort = hostname;
if (port && !hostname?.includes(':')) {
hostnameWithPort += `:${port}`;
}
return new URL(url, `${protocol}://${hostnameWithPort}`);
}
| {
"end_byte": 2448,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/node/src/request.ts"
} |
angular-cli/packages/angular/ssr/node/src/app-engine.ts_0_2972 | /**
* @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 { AngularAppEngine } from '@angular/ssr';
import type { IncomingMessage } from 'node:http';
import { createWebRequestFromNodeRequest } from './request';
/**
* Angular server application engine.
* Manages Angular server applications (including localized ones), handles rendering requests,
* and optionally transforms index HTML before rendering.
*
* @note This class should be instantiated once and used as a singleton across the server-side
* application to ensure consistent handling of rendering requests and resource management.
*
* @developerPreview
*/
export class AngularNodeAppEngine {
private readonly angularAppEngine = new AngularAppEngine();
/**
* Renders an HTTP response based on the incoming request using the Angular server application.
*
* The method processes the incoming request, determines the appropriate route, and prepares the
* rendering context to generate a response. If the request URL corresponds to a static file (excluding `/index.html`),
* the method returns `null`.
*
* Example: A request to `https://www.example.com/page/index.html` will render the Angular route
* associated with `https://www.example.com/page`.
*
* @param request - The incoming HTTP request object to be rendered.
* @param requestContext - Optional additional context for the request, such as metadata or custom settings.
* @returns A promise that resolves to a `Response` object, or `null` if the request URL is for a static file
* (e.g., `./logo.png`) rather than an application route.
*/
render(request: IncomingMessage, requestContext?: unknown): Promise<Response | null> {
return this.angularAppEngine.render(createWebRequestFromNodeRequest(request), requestContext);
}
/**
* Retrieves HTTP headers for a request associated with statically generated (SSG) pages,
* based on the URL pathname.
*
* @param request - The incoming request object.
* @returns A `Map` containing the HTTP headers as key-value pairs.
* @note This function should be used exclusively for retrieving headers of SSG pages.
* @example
* ```typescript
* const angularAppEngine = new AngularNodeAppEngine();
*
* app.use(express.static('dist/browser', {
* setHeaders: (res, path) => {
* // Retrieve headers for the current request
* const headers = angularAppEngine.getPrerenderHeaders(res.req);
*
* // Apply the retrieved headers to the response
* for (const [key, value] of headers) {
* res.setHeader(key, value);
* }
* }
}));
* ```
*/
getPrerenderHeaders(request: IncomingMessage): ReadonlyMap<string, string> {
return this.angularAppEngine.getPrerenderHeaders(createWebRequestFromNodeRequest(request));
}
}
| {
"end_byte": 2972,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/node/src/app-engine.ts"
} |
angular-cli/packages/angular/ssr/node/src/handler.ts_0_2243 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import type { IncomingMessage, ServerResponse } from 'node:http';
/**
* Represents a middleware function for handling HTTP requests in a Node.js environment.
*
* @param req - The incoming HTTP request object.
* @param res - The outgoing HTTP response object.
* @param next - A callback function that signals the completion of the middleware or forwards the error if provided.
*
* @returns A Promise that resolves to void or simply void. The handler can be asynchronous.
*/
type RequestHandlerFunction = (
req: IncomingMessage,
res: ServerResponse,
next: (err?: unknown) => void,
) => Promise<void> | void;
/**
* Attaches metadata to the handler function to mark it as a special handler for Node.js environments.
*
* @typeParam T - The type of the handler function.
* @param handler - The handler function to be defined and annotated.
* @returns The same handler function passed as an argument, with metadata attached.
*
* @example
* Usage in an Express application:
* ```ts
* const app = express();
* export default createNodeRequestHandler(app);
* ```
*
* @example
* Usage in a Hono application:
* ```ts
* const app = new Hono();
* export default createNodeRequestHandler(async (req, res, next) => {
* try {
* const webRes = await app.fetch(createWebRequestFromNodeRequest(req));
* if (webRes) {
* await writeResponseToNodeResponse(webRes, res);
* } else {
* next();
* }
* } catch (error) {
* next(error);
* }
* }));
* ```
*
* @example
* Usage in a Fastify application:
* ```ts
* const app = Fastify();
* export default createNodeRequestHandler(async (req, res) => {
* await app.ready();
* app.server.emit('request', req, res);
* res.send('Hello from Fastify with Node Next Handler!');
* }));
* ```
* @developerPreview
*/
export function createNodeRequestHandler<T extends RequestHandlerFunction>(handler: T): T {
(handler as T & { __ng_node_request_handler__?: boolean })['__ng_node_request_handler__'] = true;
return handler;
}
| {
"end_byte": 2243,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/node/src/handler.ts"
} |
angular-cli/packages/angular/ssr/node/src/common-engine/peformance-profiler.ts_0_1847 | /**
* @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
*/
const PERFORMANCE_MARK_PREFIX = '🅰️';
export function printPerformanceLogs(): void {
let maxWordLength = 0;
const benchmarks: [step: string, value: string][] = [];
for (const { name, duration } of performance.getEntriesByType('measure')) {
if (!name.startsWith(PERFORMANCE_MARK_PREFIX)) {
continue;
}
// `🅰️:Retrieve SSG Page` -> `Retrieve SSG Page:`
const step = name.slice(PERFORMANCE_MARK_PREFIX.length + 1) + ':';
if (step.length > maxWordLength) {
maxWordLength = step.length;
}
benchmarks.push([step, `${duration.toFixed(1)}ms`]);
performance.clearMeasures(name);
}
/* eslint-disable no-console */
console.log('********** Performance results **********');
for (const [step, value] of benchmarks) {
const spaces = maxWordLength - step.length + 5;
console.log(step + ' '.repeat(spaces) + value);
}
console.log('*****************************************');
/* eslint-enable no-console */
}
export async function runMethodAndMeasurePerf<T>(
label: string,
asyncMethod: () => Promise<T>,
): Promise<T> {
const labelName = `${PERFORMANCE_MARK_PREFIX}:${label}`;
const startLabel = `start:${labelName}`;
const endLabel = `end:${labelName}`;
try {
performance.mark(startLabel);
return await asyncMethod();
} finally {
performance.mark(endLabel);
performance.measure(labelName, startLabel, endLabel);
performance.clearMarks(startLabel);
performance.clearMarks(endLabel);
}
}
export function noopRunMethodAndMeasurePerf<T>(
label: string,
asyncMethod: () => Promise<T>,
): Promise<T> {
return asyncMethod();
}
| {
"end_byte": 1847,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/node/src/common-engine/peformance-profiler.ts"
} |
angular-cli/packages/angular/ssr/node/src/common-engine/common-engine.ts_0_6479 | /**
* @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 { ApplicationRef, StaticProvider, Type } from '@angular/core';
import { renderApplication, renderModule, ɵSERVER_CONTEXT } from '@angular/platform-server';
import * as fs from 'node:fs';
import { dirname, join, normalize, resolve } from 'node:path';
import { URL } from 'node:url';
import { CommonEngineInlineCriticalCssProcessor } from './inline-css-processor';
import {
noopRunMethodAndMeasurePerf,
printPerformanceLogs,
runMethodAndMeasurePerf,
} from './peformance-profiler';
const SSG_MARKER_REGEXP = /ng-server-context=["']\w*\|?ssg\|?\w*["']/;
export interface CommonEngineOptions {
/** A method that when invoked returns a promise that returns an `ApplicationRef` instance once resolved or an NgModule. */
bootstrap?: Type<{}> | (() => Promise<ApplicationRef>);
/** A set of platform level providers for all requests. */
providers?: StaticProvider[];
/** Enable request performance profiling data collection and printing the results in the server console. */
enablePerformanceProfiler?: boolean;
}
export interface CommonEngineRenderOptions {
/** A method that when invoked returns a promise that returns an `ApplicationRef` instance once resolved or an NgModule. */
bootstrap?: Type<{}> | (() => Promise<ApplicationRef>);
/** A set of platform level providers for the current request. */
providers?: StaticProvider[];
url?: string;
document?: string;
documentFilePath?: string;
/**
* Reduce render blocking requests by inlining critical CSS.
* Defaults to true.
*/
inlineCriticalCss?: boolean;
/**
* Base path location of index file.
* Defaults to the 'documentFilePath' dirname when not provided.
*/
publicPath?: string;
}
/**
* A common engine to use to server render an application.
*/
export class CommonEngine {
private readonly templateCache = new Map<string, string>();
private readonly inlineCriticalCssProcessor = new CommonEngineInlineCriticalCssProcessor();
private readonly pageIsSSG = new Map<string, boolean>();
constructor(private options?: CommonEngineOptions) {}
/**
* Render an HTML document for a specific URL with specified
* render options
*/
async render(opts: CommonEngineRenderOptions): Promise<string> {
const enablePerformanceProfiler = this.options?.enablePerformanceProfiler;
const runMethod = enablePerformanceProfiler
? runMethodAndMeasurePerf
: noopRunMethodAndMeasurePerf;
let html = await runMethod('Retrieve SSG Page', () => this.retrieveSSGPage(opts));
if (html === undefined) {
html = await runMethod('Render Page', () => this.renderApplication(opts));
if (opts.inlineCriticalCss !== false) {
const content = await runMethod('Inline Critical CSS', () =>
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
this.inlineCriticalCss(html!, opts),
);
html = content;
}
}
if (enablePerformanceProfiler) {
printPerformanceLogs();
}
return html;
}
private inlineCriticalCss(html: string, opts: CommonEngineRenderOptions): Promise<string> {
const outputPath =
opts.publicPath ?? (opts.documentFilePath ? dirname(opts.documentFilePath) : '');
return this.inlineCriticalCssProcessor.process(html, outputPath);
}
private async retrieveSSGPage(opts: CommonEngineRenderOptions): Promise<string | undefined> {
const { publicPath, documentFilePath, url } = opts;
if (!publicPath || !documentFilePath || url === undefined) {
return undefined;
}
const { pathname } = new URL(url, 'resolve://');
// Do not use `resolve` here as otherwise it can lead to path traversal vulnerability.
// See: https://portswigger.net/web-security/file-path-traversal
const pagePath = join(publicPath, pathname, 'index.html');
if (this.pageIsSSG.get(pagePath)) {
// Serve pre-rendered page.
return fs.promises.readFile(pagePath, 'utf-8');
}
if (!pagePath.startsWith(normalize(publicPath))) {
// Potential path traversal detected.
return undefined;
}
if (pagePath === resolve(documentFilePath) || !(await exists(pagePath))) {
// View matches with prerender path or file does not exist.
this.pageIsSSG.set(pagePath, false);
return undefined;
}
// Static file exists.
const content = await fs.promises.readFile(pagePath, 'utf-8');
const isSSG = SSG_MARKER_REGEXP.test(content);
this.pageIsSSG.set(pagePath, isSSG);
return isSSG ? content : undefined;
}
private async renderApplication(opts: CommonEngineRenderOptions): Promise<string> {
const moduleOrFactory = this.options?.bootstrap ?? opts.bootstrap;
if (!moduleOrFactory) {
throw new Error('A module or bootstrap option must be provided.');
}
const extraProviders: StaticProvider[] = [
{ provide: ɵSERVER_CONTEXT, useValue: 'ssr' },
...(opts.providers ?? []),
...(this.options?.providers ?? []),
];
let document = opts.document;
if (!document && opts.documentFilePath) {
document = await this.getDocument(opts.documentFilePath);
}
const commonRenderingOptions = {
url: opts.url,
document,
};
return isBootstrapFn(moduleOrFactory)
? renderApplication(moduleOrFactory, {
platformProviders: extraProviders,
...commonRenderingOptions,
})
: renderModule(moduleOrFactory, { extraProviders, ...commonRenderingOptions });
}
/** Retrieve the document from the cache or the filesystem */
private async getDocument(filePath: string): Promise<string> {
let doc = this.templateCache.get(filePath);
if (!doc) {
doc = await fs.promises.readFile(filePath, 'utf-8');
this.templateCache.set(filePath, doc);
}
return doc;
}
}
async function exists(path: fs.PathLike): Promise<boolean> {
try {
await fs.promises.access(path, fs.constants.F_OK);
return true;
} catch {
return false;
}
}
function isBootstrapFn(value: unknown): value is () => Promise<ApplicationRef> {
// We can differentiate between a module and a bootstrap function by reading compiler-generated `ɵmod` static property:
return typeof value === 'function' && !('ɵmod' in value);
}
| {
"end_byte": 6479,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/node/src/common-engine/common-engine.ts"
} |
angular-cli/packages/angular/ssr/node/src/common-engine/inline-css-processor.ts_0_923 | /**
* @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 { ɵInlineCriticalCssProcessor as InlineCriticalCssProcessor } from '@angular/ssr';
import { readFile } from 'node:fs/promises';
export class CommonEngineInlineCriticalCssProcessor {
private readonly resourceCache = new Map<string, string>();
async process(html: string, outputPath: string | undefined): Promise<string> {
const beasties = new InlineCriticalCssProcessor(async (path) => {
let resourceContent = this.resourceCache.get(path);
if (resourceContent === undefined) {
resourceContent = await readFile(path, 'utf-8');
this.resourceCache.set(path, resourceContent);
}
return resourceContent;
}, outputPath);
return beasties.process(html);
}
}
| {
"end_byte": 923,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/node/src/common-engine/inline-css-processor.ts"
} |
angular-cli/packages/angular/ssr/schematics/BUILD.bazel_0_2591 | # Copyright Google Inc. 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
load("@npm//@bazel/jasmine:index.bzl", "jasmine_node_test")
load("//tools:defaults.bzl", "pkg_npm", "ts_library")
load("//tools:ts_json_schema.bzl", "ts_json_schema")
licenses(["notice"])
package(default_visibility = ["//visibility:public"])
# Create a list of Tuple("path/file.json", "path_file") to be used as rules
ALL_SCHEMA_TARGETS = [
(
x,
x.replace("/", "_").replace("-", "_").replace(".json", ""),
)
for x in glob(
include = ["*/schema.json"],
exclude = [
# NB: we need to exclude the nested node_modules that is laid out by yarn workspaces
"node_modules/**",
],
)
]
# Create all the targets.
[
ts_json_schema(
name = name,
src = src,
)
for (src, name) in ALL_SCHEMA_TARGETS
]
filegroup(
name = "schematics_assets",
srcs = glob(
[
"**/*.json",
],
),
)
ts_library(
name = "schematics",
package_name = "@angular/ssr/schematics",
srcs = glob(
include = ["**/*.ts"],
exclude = [
"**/*_spec.ts",
# NB: we need to exclude the nested node_modules that is laid out by yarn workspaces
"node_modules/**",
],
) + [
"//packages/angular/ssr/schematics:" + src.replace(".json", ".ts")
for (src, _) in ALL_SCHEMA_TARGETS
],
data = [":schematics_assets"],
deps = [
"//packages/angular_devkit/schematics",
"//packages/schematics/angular",
],
)
ts_library(
name = "ssr_schematics_test_lib",
testonly = True,
srcs = glob(
include = [
"**/*_spec.ts",
],
exclude = [
# NB: we need to exclude the nested node_modules that is laid out by yarn workspaces
"node_modules/**",
],
),
# @external_begin
deps = [
":schematics",
"//packages/angular_devkit/schematics/testing",
],
# @external_end
)
jasmine_node_test(
name = "ssr_schematics_test",
srcs = [":ssr_schematics_test_lib"],
deps = [
"@npm//jasmine",
"@npm//source-map",
"@npm//typescript",
],
)
# This package is intended to be combined into the main @angular/ssr package as a dep.
pkg_npm(
name = "npm_package",
pkg_json = None,
visibility = ["//packages/angular/ssr:__pkg__"],
deps = [
":schematics",
],
)
| {
"end_byte": 2591,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/schematics/BUILD.bazel"
} |
angular-cli/packages/angular/ssr/schematics/ng-add/index.ts_0_416 | /**
* @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 { externalSchematic } from '@angular-devkit/schematics';
import { Schema as SSROptions } from './schema';
export default (options: SSROptions) => externalSchematic('@schematics/angular', 'ssr', options);
| {
"end_byte": 416,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/schematics/ng-add/index.ts"
} |
angular-cli/packages/angular/ssr/schematics/ng-add/index_spec.ts_0_1558 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// eslint-disable-next-line import/no-extraneous-dependencies
import { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing';
import { join } from 'node:path';
describe('@angular/ssr ng-add schematic', () => {
const defaultOptions = {
project: 'test-app',
};
const schematicRunner = new SchematicTestRunner(
'@angular/ssr',
require.resolve(join(__dirname, '../collection.json')),
);
let appTree: UnitTestTree;
const workspaceOptions = {
name: 'workspace',
newProjectRoot: 'projects',
version: '6.0.0',
};
beforeEach(async () => {
appTree = await schematicRunner.runExternalSchematic(
'@schematics/angular',
'workspace',
workspaceOptions,
);
appTree = await schematicRunner.runExternalSchematic(
'@schematics/angular',
'application',
{
name: 'test-app',
inlineStyle: false,
inlineTemplate: false,
routing: false,
style: 'css',
skipTests: false,
standalone: true,
},
appTree,
);
});
it('works', async () => {
const filePath = '/projects/test-app/src/server.ts';
expect(appTree.exists(filePath)).toBeFalse();
const tree = await schematicRunner.runSchematic('ng-add', defaultOptions, appTree);
expect(tree.exists(filePath)).toBeTrue();
});
});
| {
"end_byte": 1558,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/schematics/ng-add/index_spec.ts"
} |
angular-cli/packages/angular/ssr/tokens/BUILD.bazel_0_380 | load("//tools:defaults.bzl", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "tokens",
srcs = glob(
[
"*.ts",
"src/**/*.ts",
],
),
module_name = "@angular/ssr/tokens",
tsconfig = "//:tsconfig-build-ng",
deps = [
"@npm//@angular/core",
"@npm//tslib",
],
)
| {
"end_byte": 380,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/tokens/BUILD.bazel"
} |
angular-cli/packages/angular/ssr/tokens/index.ts_0_234 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './public_api';
| {
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/tokens/index.ts"
} |
angular-cli/packages/angular/ssr/tokens/public_api.ts_0_276 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export { REQUEST, RESPONSE_INIT, REQUEST_CONTEXT } from './src/tokens';
| {
"end_byte": 276,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/tokens/public_api.ts"
} |
angular-cli/packages/angular/ssr/tokens/src/tokens.ts_0_719 | /**
* @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 { InjectionToken } from '@angular/core';
/**
* Injection token for the current request.
* @developerPreview
*/
export const REQUEST = new InjectionToken<Request>('REQUEST');
/**
* Injection token for the response initialization options.
* @developerPreview
*/
export const RESPONSE_INIT = new InjectionToken<ResponseInit>('RESPONSE_INIT');
/**
* Injection token for additional request context.
* @developerPreview
*/
export const REQUEST_CONTEXT = new InjectionToken<unknown>('REQUEST_CONTEXT');
| {
"end_byte": 719,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/tokens/src/tokens.ts"
} |
angular-cli/packages/angular/ssr/src/i18n.ts_0_1453 | /**
* @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
*/
/**
* Extracts a potential locale ID from a given URL based on the specified base path.
*
* This function parses the URL to locate a potential locale identifier that immediately
* follows the base path segment in the URL's pathname. If the URL does not contain a valid
* locale ID, an empty string is returned.
*
* @param url - The full URL from which to extract the locale ID.
* @param basePath - The base path used as the reference point for extracting the locale ID.
* @returns The extracted locale ID if present, or an empty string if no valid locale ID is found.
*
* @example
* ```js
* const url = new URL('https://example.com/base/en/page');
* const basePath = '/base';
* const localeId = getPotentialLocaleIdFromUrl(url, basePath);
* console.log(localeId); // Output: 'en'
* ```
*/
export function getPotentialLocaleIdFromUrl(url: URL, basePath: string): string {
const { pathname } = url;
// Move forward of the base path section.
let start = basePath.length;
if (pathname[start] === '/') {
start++;
}
// Find the next forward slash.
let end = pathname.indexOf('/', start);
if (end === -1) {
end = pathname.length;
}
// Extract the potential locale id.
return pathname.slice(start, end);
}
| {
"end_byte": 1453,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/src/i18n.ts"
} |
angular-cli/packages/angular/ssr/src/app.ts_0_2108 | /**
* @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 { LOCALE_ID, StaticProvider, ɵresetCompiledComponents } from '@angular/core';
import { REQUEST, REQUEST_CONTEXT, RESPONSE_INIT } from '@angular/ssr/tokens';
import { ServerAssets } from './assets';
import { Hooks } from './hooks';
import { getAngularAppManifest } from './manifest';
import { RenderMode } from './routes/route-config';
import { ServerRouter } from './routes/router';
import { sha256 } from './utils/crypto';
import { InlineCriticalCssProcessor } from './utils/inline-critical-css';
import { LRUCache } from './utils/lru-cache';
import { AngularBootstrap, renderAngular } from './utils/ng';
/**
* Maximum number of critical CSS entries the cache can store.
* This value determines the capacity of the LRU (Least Recently Used) cache, which stores critical CSS for pages.
*/
const MAX_INLINE_CSS_CACHE_ENTRIES = 50;
/**
* A mapping of `RenderMode` enum values to corresponding string representations.
*
* This record is used to map each `RenderMode` to a specific string value that represents
* the server context. The string values are used internally to differentiate
* between various rendering strategies when processing routes.
*
* - `RenderMode.Prerender` maps to `'ssg'` (Static Site Generation).
* - `RenderMode.Server` maps to `'ssr'` (Server-Side Rendering).
* - `RenderMode.AppShell` maps to `'app-shell'` (pre-rendered application shell).
* - `RenderMode.Client` maps to an empty string `''` (Client-Side Rendering, no server context needed).
*/
const SERVER_CONTEXT_VALUE: Record<RenderMode, string> = {
[RenderMode.Prerender]: 'ssg',
[RenderMode.Server]: 'ssr',
[RenderMode.AppShell]: 'app-shell',
[RenderMode.Client]: '',
};
/**
* Represents a locale-specific Angular server application managed by the server application engine.
*
* The `AngularServerApp` class handles server-side rendering and asset management for a specific locale.
*/
| {
"end_byte": 2108,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/src/app.ts"
} |
angular-cli/packages/angular/ssr/src/app.ts_2109_11238 | xport class AngularServerApp {
/**
* Hooks for extending or modifying the behavior of the server application.
* This instance can be used to attach custom functionality to various events in the server application lifecycle.
*/
hooks = new Hooks();
/**
* The manifest associated with this server application.
*/
private readonly manifest = getAngularAppManifest();
/**
* An instance of ServerAsset that handles server-side asset.
*/
private readonly assets = new ServerAssets(this.manifest);
/**
* The router instance used for route matching and handling.
*/
private router: ServerRouter | undefined;
/**
* The `inlineCriticalCssProcessor` is responsible for handling critical CSS inlining.
*/
private inlineCriticalCssProcessor: InlineCriticalCssProcessor | undefined;
/**
* The bootstrap mechanism for the server application.
*/
private boostrap: AngularBootstrap | undefined;
/**
* Cache for storing critical CSS for pages.
* Stores a maximum of MAX_INLINE_CSS_CACHE_ENTRIES entries.
*
* Uses an LRU (Least Recently Used) eviction policy, meaning that when the cache is full,
* the least recently accessed page's critical CSS will be removed to make space for new entries.
*/
private readonly criticalCssLRUCache = new LRUCache<string, string>(MAX_INLINE_CSS_CACHE_ENTRIES);
/**
* Renders a response for the given HTTP request using the server application.
*
* This method processes the request and returns a response based on the specified rendering context.
*
* @param request - The incoming HTTP request to be rendered.
* @param requestContext - Optional additional context for rendering, such as request metadata.
*
* @returns A promise that resolves to the HTTP response object resulting from the rendering, or null if no match is found.
*/
render(request: Request, requestContext?: unknown): Promise<Response | null> {
return Promise.race([
this.createAbortPromise(request),
this.handleRendering(request, /** isSsrMode */ true, requestContext),
]);
}
/**
* Renders a page based on the provided URL via server-side rendering and returns the corresponding HTTP response.
* The rendering process can be interrupted by an abort signal, where the first resolved promise (either from the abort
* or the render process) will dictate the outcome.
*
* @param url - The full URL to be processed and rendered by the server.
* @param signal - (Optional) An `AbortSignal` object that allows for the cancellation of the rendering process.
* @returns A promise that resolves to the generated HTTP response object, or `null` if no matching route is found.
*/
renderStatic(url: URL, signal?: AbortSignal): Promise<Response | null> {
const request = new Request(url, { signal });
return Promise.race([
this.createAbortPromise(request),
this.handleRendering(request, /** isSsrMode */ false),
]);
}
/**
* Creates a promise that rejects when the request is aborted.
*
* @param request - The HTTP request to monitor for abortion.
* @returns A promise that never resolves but rejects with an `AbortError` if the request is aborted.
*/
private createAbortPromise(request: Request): Promise<never> {
return new Promise<never>((_, reject) => {
request.signal.addEventListener(
'abort',
() => {
const abortError = new Error(
`Request for: ${request.url} was aborted.\n${request.signal.reason}`,
);
abortError.name = 'AbortError';
reject(abortError);
},
{ once: true },
);
});
}
/**
* Handles the server-side rendering process for the given HTTP request.
* This method matches the request URL to a route and performs rendering if a matching route is found.
*
* @param request - The incoming HTTP request to be processed.
* @param isSsrMode - A boolean indicating whether the rendering is performed in server-side rendering (SSR) mode.
* @param requestContext - Optional additional context for rendering, such as request metadata.
*
* @returns A promise that resolves to the rendered response, or null if no matching route is found.
*/
private async handleRendering(
request: Request,
isSsrMode: boolean,
requestContext?: unknown,
): Promise<Response | null> {
const url = new URL(request.url);
this.router ??= await ServerRouter.from(this.manifest, url);
const matchedRoute = this.router.match(url);
if (!matchedRoute) {
// Not a known Angular route.
return null;
}
const { redirectTo, status } = matchedRoute;
if (redirectTo !== undefined) {
// Note: The status code is validated during route extraction.
// 302 Found is used by default for redirections
// See: https://developer.mozilla.org/en-US/docs/Web/API/Response/redirect_static#status
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return Response.redirect(new URL(redirectTo, url), (status as any) ?? 302);
}
const { renderMode = isSsrMode ? RenderMode.Server : RenderMode.Prerender, headers } =
matchedRoute;
const platformProviders: StaticProvider[] = [];
let responseInit: ResponseInit | undefined;
if (isSsrMode) {
// Initialize the response with status and headers if available.
responseInit = {
status,
headers: new Headers({
'Content-Type': 'text/html;charset=UTF-8',
...headers,
}),
};
if (renderMode === RenderMode.Server) {
// Configure platform providers for request and response only for SSR.
platformProviders.push(
{
provide: REQUEST,
useValue: request,
},
{
provide: REQUEST_CONTEXT,
useValue: requestContext,
},
{
provide: RESPONSE_INIT,
useValue: responseInit,
},
);
} else if (renderMode === RenderMode.Client) {
// Serve the client-side rendered version if the route is configured for CSR.
return new Response(await this.assets.getServerAsset('index.csr.html'), responseInit);
}
}
const {
manifest: { bootstrap, inlineCriticalCss, locale },
hooks,
assets,
} = this;
if (locale !== undefined) {
platformProviders.push({
provide: LOCALE_ID,
useValue: locale,
});
}
let html = await assets.getIndexServerHtml();
// Skip extra microtask if there are no pre hooks.
if (hooks.has('html:transform:pre')) {
html = await hooks.run('html:transform:pre', { html, url });
}
this.boostrap ??= await bootstrap();
html = await renderAngular(
html,
this.boostrap,
url,
platformProviders,
SERVER_CONTEXT_VALUE[renderMode],
);
if (inlineCriticalCss) {
// Optionally inline critical CSS.
this.inlineCriticalCssProcessor ??= new InlineCriticalCssProcessor((path: string) => {
const fileName = path.split('/').pop() ?? path;
return this.assets.getServerAsset(fileName);
});
// TODO(alanagius): remove once Node.js version 18 is no longer supported.
if (isSsrMode && typeof crypto === 'undefined') {
// eslint-disable-next-line no-console
console.error(
`The global 'crypto' module is unavailable. ` +
`If you are running on Node.js, please ensure you are using version 20 or later, ` +
`which includes built-in support for the Web Crypto module.`,
);
}
if (isSsrMode && typeof crypto !== 'undefined') {
// Only cache if we are running in SSR Mode.
const cacheKey = await sha256(html);
let htmlWithCriticalCss = this.criticalCssLRUCache.get(cacheKey);
if (htmlWithCriticalCss === undefined) {
htmlWithCriticalCss = await this.inlineCriticalCssProcessor.process(html);
this.criticalCssLRUCache.put(cacheKey, htmlWithCriticalCss);
}
html = htmlWithCriticalCss;
} else {
html = await this.inlineCriticalCssProcessor.process(html);
}
}
return new Response(html, responseInit);
}
}
let angularServerApp: AngularServerApp | undefined;
/**
* Retrieves or creates an instance of `AngularServerApp`.
* - If an instance of `AngularServerApp` already exists, it will return the existing one.
* - If no instance exists, it will create a new one with the provided options.
* @returns The existing or newly created instance of `AngularServerApp`.
*/
export function getOrCreateAngularServerApp(): AngularServerApp {
return (angularServerApp ??= new AngularServerApp());
}
/**
* Destroys the existing `AngularServerApp` instance, releasing associated resources and resetting the
* reference to `undefined`.
*
* This function is primarily used to enable the recreation of the `AngularServerApp` instance,
* typically when server configuration or application state needs to be refreshed.
*/
| {
"end_byte": 11238,
"start_byte": 2109,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/src/app.ts"
} |
angular-cli/packages/angular/ssr/src/app.ts_11239_11661 | xport function destroyAngularServerApp(): void {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
// Need to clean up GENERATED_COMP_IDS map in `@angular/core`.
// Otherwise an incorrect component ID generation collision detected warning will be displayed in development.
// See: https://github.com/angular/angular-cli/issues/25924
ɵresetCompiledComponents();
}
angularServerApp = undefined;
}
| {
"end_byte": 11661,
"start_byte": 11239,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/src/app.ts"
} |
angular-cli/packages/angular/ssr/src/assets.ts_0_1341 | /**
* @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 { AngularAppManifest } from './manifest';
/**
* Manages server-side assets.
*/
export class ServerAssets {
/**
* Creates an instance of ServerAsset.
*
* @param manifest - The manifest containing the server assets.
*/
constructor(private readonly manifest: AngularAppManifest) {}
/**
* Retrieves the content of a server-side asset using its path.
*
* @param path - The path to the server asset.
* @returns A promise that resolves to the asset content as a string.
* @throws Error If the asset path is not found in the manifest, an error is thrown.
*/
async getServerAsset(path: string): Promise<string> {
const asset = this.manifest.assets.get(path);
if (!asset) {
throw new Error(`Server asset '${path}' does not exist.`);
}
return asset();
}
/**
* Retrieves and caches the content of 'index.server.html'.
*
* @returns A promise that resolves to the content of 'index.server.html'.
* @throws Error If there is an issue retrieving the asset.
*/
getIndexServerHtml(): Promise<string> {
return this.getServerAsset('index.server.html');
}
}
| {
"end_byte": 1341,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/src/assets.ts"
} |
angular-cli/packages/angular/ssr/src/app-engine.ts_0_5946 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import type { AngularServerApp } from './app';
import { Hooks } from './hooks';
import { getPotentialLocaleIdFromUrl } from './i18n';
import { EntryPointExports, getAngularAppEngineManifest } from './manifest';
import { stripIndexHtmlFromURL, stripTrailingSlash } from './utils/url';
/**
* Angular server application engine.
* Manages Angular server applications (including localized ones), handles rendering requests,
* and optionally transforms index HTML before rendering.
*
* @note This class should be instantiated once and used as a singleton across the server-side
* application to ensure consistent handling of rendering requests and resource management.
*
* @developerPreview
*/
export class AngularAppEngine {
/**
* Hooks for extending or modifying the behavior of the server application.
* These hooks are used by the Angular CLI when running the development server and
* provide extensibility points for the application lifecycle.
*
* @private
*/
static ɵhooks = /* #__PURE__*/ new Hooks();
/**
* Provides access to the hooks for extending or modifying the server application's behavior.
* This allows attaching custom functionality to various server application lifecycle events.
*
* @internal
*/
get hooks(): Hooks {
return AngularAppEngine.ɵhooks;
}
/**
* The manifest for the server application.
*/
private readonly manifest = getAngularAppEngineManifest();
/**
* A cache that holds entry points, keyed by their potential locale string.
*/
private readonly entryPointsCache = new Map<string, Promise<EntryPointExports>>();
/**
* Renders a response for the given HTTP request using the server application.
*
* This method processes the request, determines the appropriate route and rendering context,
* and returns an HTTP response.
*
* If the request URL appears to be for a file (excluding `/index.html`), the method returns `null`.
* A request to `https://www.example.com/page/index.html` will render the Angular route
* corresponding to `https://www.example.com/page`.
*
* @param request - The incoming HTTP request object to be rendered.
* @param requestContext - Optional additional context for the request, such as metadata.
* @returns A promise that resolves to a Response object, or `null` if the request URL represents a file (e.g., `./logo.png`)
* rather than an application route.
*/
async render(request: Request, requestContext?: unknown): Promise<Response | null> {
// Skip if the request looks like a file but not `/index.html`.
const url = new URL(request.url);
const entryPoint = await this.getEntryPointExportsForUrl(url);
if (!entryPoint) {
return null;
}
const { ɵgetOrCreateAngularServerApp: getOrCreateAngularServerApp } = entryPoint;
// Note: Using `instanceof` is not feasible here because `AngularServerApp` will
// be located in separate bundles, making `instanceof` checks unreliable.
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const serverApp = getOrCreateAngularServerApp() as AngularServerApp;
serverApp.hooks = this.hooks;
return serverApp.render(request, requestContext);
}
/**
* Retrieves HTTP headers for a request associated with statically generated (SSG) pages,
* based on the URL pathname.
*
* @param request - The incoming request object.
* @returns A `Map` containing the HTTP headers as key-value pairs.
* @note This function should be used exclusively for retrieving headers of SSG pages.
*/
getPrerenderHeaders(request: Request): ReadonlyMap<string, string> {
if (this.manifest.staticPathsHeaders.size === 0) {
return new Map();
}
const { pathname } = stripIndexHtmlFromURL(new URL(request.url));
const headers = this.manifest.staticPathsHeaders.get(stripTrailingSlash(pathname));
return new Map(headers);
}
/**
* Retrieves the exports for a specific entry point, caching the result.
*
* @param potentialLocale - The locale string used to find the corresponding entry point.
* @returns A promise that resolves to the entry point exports or `undefined` if not found.
*/
private getEntryPointExports(potentialLocale: string): Promise<EntryPointExports> | undefined {
const cachedEntryPoint = this.entryPointsCache.get(potentialLocale);
if (cachedEntryPoint) {
return cachedEntryPoint;
}
const { entryPoints } = this.manifest;
const entryPoint = entryPoints.get(potentialLocale);
if (!entryPoint) {
return undefined;
}
const entryPointExports = entryPoint();
this.entryPointsCache.set(potentialLocale, entryPointExports);
return entryPointExports;
}
/**
* Retrieves the entry point for a given URL by determining the locale and mapping it to
* the appropriate application bundle.
*
* This method determines the appropriate entry point and locale for rendering the application by examining the URL.
* If there is only one entry point available, it is returned regardless of the URL.
* Otherwise, the method extracts a potential locale identifier from the URL and looks up the corresponding entry point.
*
* @param url - The URL of the request.
* @returns A promise that resolves to the entry point exports or `undefined` if not found.
*/
private getEntryPointExportsForUrl(url: URL): Promise<EntryPointExports> | undefined {
const { entryPoints, basePath } = this.manifest;
if (entryPoints.size === 1) {
return this.getEntryPointExports('');
}
const potentialLocale = getPotentialLocaleIdFromUrl(url, basePath);
return this.getEntryPointExports(potentialLocale);
}
}
| {
"end_byte": 5946,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/src/app-engine.ts"
} |
angular-cli/packages/angular/ssr/src/global.d.ts_0_250 | /**
* @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
*/
declare const ngDevMode: boolean | undefined;
| {
"end_byte": 250,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/src/global.d.ts"
} |
angular-cli/packages/angular/ssr/src/manifest.ts_0_5196 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import type { SerializableRouteTreeNode } from './routes/route-tree';
import { AngularBootstrap } from './utils/ng';
/**
* Represents the exports of an Angular server application entry point.
*/
export interface EntryPointExports {
/**
* A reference to the function that creates an Angular server application instance.
*
* @note The return type is `unknown` to prevent circular dependency issues.
*/
ɵgetOrCreateAngularServerApp: () => unknown;
/**
* A reference to the function that destroys the `AngularServerApp` instance.
*/
ɵdestroyAngularServerApp: () => void;
}
/**
* Manifest for the Angular server application engine, defining entry points.
*/
export interface AngularAppEngineManifest {
/**
* A map of entry points for the server application.
* Each entry in the map consists of:
* - `key`: The base href for the entry point.
* - `value`: A function that returns a promise resolving to an object of type `EntryPointExports`.
*/
readonly entryPoints: ReadonlyMap<string, () => Promise<EntryPointExports>>;
/**
* The base path for the server application.
* This is used to determine the root path of the application.
*/
readonly basePath: string;
/**
* A map that associates static paths with their corresponding HTTP headers.
* Each entry in the map consists of:
* - `key`: The static path as a string.
* - `value`: An array of tuples, where each tuple contains:
* - `headerName`: The name of the HTTP header.
* - `headerValue`: The value of the HTTP header.
*/
readonly staticPathsHeaders: ReadonlyMap<
string,
readonly [headerName: string, headerValue: string][]
>;
}
/**
* Manifest for a specific Angular server application, defining assets and bootstrap logic.
*/
export interface AngularAppManifest {
/**
* A map of assets required by the server application.
* Each entry in the map consists of:
* - `key`: The path of the asset.
* - `value`: A function returning a promise that resolves to the file contents of the asset.
*/
readonly assets: ReadonlyMap<string, () => Promise<string>>;
/**
* The bootstrap mechanism for the server application.
* A function that returns a promise that resolves to an `NgModule` or a function
* returning a promise that resolves to an `ApplicationRef`.
*/
readonly bootstrap: () => Promise<AngularBootstrap>;
/**
* Indicates whether critical CSS should be inlined into the HTML.
* If set to `true`, critical CSS will be inlined for faster page rendering.
*/
readonly inlineCriticalCss?: boolean;
/**
* The route tree representation for the routing configuration of the application.
* This represents the routing information of the application, mapping route paths to their corresponding metadata.
* It is used for route matching and navigation within the server application.
*/
readonly routes?: SerializableRouteTreeNode;
/**
* An optional string representing the locale or language code to be used for
* the application, aiding with localization and rendering content specific to the locale.
*/
readonly locale?: string;
}
/**
* The Angular app manifest object.
* This is used internally to store the current Angular app manifest.
*/
let angularAppManifest: AngularAppManifest | undefined;
/**
* Sets the Angular app manifest.
*
* @param manifest - The manifest object to set for the Angular application.
*/
export function setAngularAppManifest(manifest: AngularAppManifest): void {
angularAppManifest = manifest;
}
/**
* Gets the Angular app manifest.
*
* @returns The Angular app manifest.
* @throws Will throw an error if the Angular app manifest is not set.
*/
export function getAngularAppManifest(): AngularAppManifest {
if (!angularAppManifest) {
throw new Error(
'Angular app manifest is not set. ' +
`Please ensure you are using the '@angular/build:application' builder to build your server application.`,
);
}
return angularAppManifest;
}
/**
* The Angular app engine manifest object.
* This is used internally to store the current Angular app engine manifest.
*/
let angularAppEngineManifest: AngularAppEngineManifest | undefined;
/**
* Sets the Angular app engine manifest.
*
* @param manifest - The engine manifest object to set.
*/
export function setAngularAppEngineManifest(manifest: AngularAppEngineManifest): void {
angularAppEngineManifest = manifest;
}
/**
* Gets the Angular app engine manifest.
*
* @returns The Angular app engine manifest.
* @throws Will throw an error if the Angular app engine manifest is not set.
*/
export function getAngularAppEngineManifest(): AngularAppEngineManifest {
if (!angularAppEngineManifest) {
throw new Error(
'Angular app engine manifest is not set. ' +
`Please ensure you are using the '@angular/build:application' builder to build your server application.`,
);
}
return angularAppEngineManifest;
}
| {
"end_byte": 5196,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/src/manifest.ts"
} |
angular-cli/packages/angular/ssr/src/handler.ts_0_1406 | /**
* @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
*/
/**
* Function for handling HTTP requests in a web environment.
*
* @param request - The incoming HTTP request object.
* @returns A Promise resolving to a `Response` object, `null`, or directly a `Response`,
* supporting both synchronous and asynchronous handling.
*/
type RequestHandlerFunction = (request: Request) => Promise<Response | null> | null | Response;
/**
* Annotates a request handler function with metadata, marking it as a special
* handler.
*
* @param handler - The request handler function to be annotated.
* @returns The same handler function passed in, with metadata attached.
*
* @example
* Example usage in a Hono application:
* ```ts
* const app = new Hono();
* export default createRequestHandler(app.fetch);
* ```
*
* @example
* Example usage in a H3 application:
* ```ts
* const app = createApp();
* const handler = toWebHandler(app);
* export default createRequestHandler(handler);
* ```
* @developerPreview
*/
export function createRequestHandler(handler: RequestHandlerFunction): RequestHandlerFunction {
(handler as RequestHandlerFunction & { __ng_request_handler__?: boolean })[
'__ng_request_handler__'
] = true;
return handler;
}
| {
"end_byte": 1406,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/src/handler.ts"
} |
angular-cli/packages/angular/ssr/src/hooks.ts_0_4501 | /**
* @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
*/
/**
* Defines a handler function type for transforming HTML content.
* This function receives an object with the HTML to be processed.
*
* @param ctx - An object containing the URL and HTML content to be transformed.
* @returns The transformed HTML as a string or a promise that resolves to the transformed HTML.
*/
type HtmlTransformHandler = (ctx: { url: URL; html: string }) => string | Promise<string>;
/**
* Defines the names of available hooks for registering and triggering custom logic within the application.
*/
type HookName = keyof HooksMapping;
/**
* Mapping of hook names to their corresponding handler types.
*/
interface HooksMapping {
'html:transform:pre': HtmlTransformHandler;
}
/**
* Manages a collection of hooks and provides methods to register and execute them.
* Hooks are functions that can be invoked with specific arguments to allow modifications or enhancements.
*/
export class Hooks {
/**
* A map of hook names to arrays of hook functions.
* Each hook name can have multiple associated functions, which are executed in sequence.
*/
private readonly store = new Map<HookName, Function[]>();
/**
* Executes all hooks associated with the specified name, passing the given argument to each hook function.
* The hooks are invoked sequentially, and the argument may be modified by each hook.
*
* @template Hook - The type of the hook name. It should be one of the keys of `HooksMapping`.
* @param name - The name of the hook whose functions will be executed.
* @param context - The input value to be passed to each hook function. The value is mutated by each hook function.
* @returns A promise that resolves once all hook functions have been executed.
*
* @example
* ```typescript
* const hooks = new Hooks();
* hooks.on('html:transform:pre', async (ctx) => {
* ctx.html = ctx.html.replace(/foo/g, 'bar');
* return ctx.html;
* });
* const result = await hooks.run('html:transform:pre', { html: '<div>foo</div>' });
* console.log(result); // '<div>bar</div>'
* ```
* @internal
*/
async run<Hook extends keyof HooksMapping>(
name: Hook,
context: Parameters<HooksMapping[Hook]>[0],
): Promise<Awaited<ReturnType<HooksMapping[Hook]>>> {
const hooks = this.store.get(name);
switch (name) {
case 'html:transform:pre': {
if (!hooks) {
return context.html as Awaited<ReturnType<HooksMapping[Hook]>>;
}
const ctx = { ...context };
for (const hook of hooks) {
ctx.html = await hook(ctx);
}
return ctx.html as Awaited<ReturnType<HooksMapping[Hook]>>;
}
default:
throw new Error(`Running hook "${name}" is not supported.`);
}
}
/**
* Registers a new hook function under the specified hook name.
* This function should be a function that takes an argument of type `T` and returns a `string` or `Promise<string>`.
*
* @template Hook - The type of the hook name. It should be one of the keys of `HooksMapping`.
* @param name - The name of the hook under which the function will be registered.
* @param handler - A function to be executed when the hook is triggered. The handler will be called with an argument
* that may be modified by the hook functions.
*
* @remarks
* - If there are existing handlers registered under the given hook name, the new handler will be added to the list.
* - If no handlers are registered under the given hook name, a new list will be created with the handler as its first element.
*
* @example
* ```typescript
* hooks.on('html:transform:pre', async (ctx) => {
* return ctx.html.replace(/foo/g, 'bar');
* });
* ```
*/
on<Hook extends HookName>(name: Hook, handler: HooksMapping[Hook]): void {
const hooks = this.store.get(name);
if (hooks) {
hooks.push(handler);
} else {
this.store.set(name, [handler]);
}
}
/**
* Checks if there are any hooks registered under the specified name.
*
* @param name - The name of the hook to check.
* @returns `true` if there are hooks registered under the specified name, otherwise `false`.
*/
has(name: HookName): boolean {
return !!this.store.get(name)?.length;
}
}
| {
"end_byte": 4501,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/src/hooks.ts"
} |
angular-cli/packages/angular/ssr/src/console.ts_0_1295 | /**
* @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 { ɵConsole } from '@angular/core';
/**
* Custom implementation of the Angular Console service that filters out specific log messages.
*
* This class extends the internal Angular `ɵConsole` class to provide customized logging behavior.
* It overrides the `log` method to suppress logs that match certain predefined messages.
*/
export class Console extends ɵConsole {
/**
* A set of log messages that should be ignored and not printed to the console.
*/
private readonly ignoredLogs = new Set(['Angular is running in development mode.']);
/**
* Logs a message to the console if it is not in the set of ignored messages.
*
* @param message - The message to log to the console.
*
* This method overrides the `log` method of the `ɵConsole` class. It checks if the
* message is in the `ignoredLogs` set. If it is not, it delegates the logging to
* the parent class's `log` method. Otherwise, the message is suppressed.
*/
override log(message: string): void {
if (!this.ignoredLogs.has(message)) {
super.log(message);
}
}
}
| {
"end_byte": 1295,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/src/console.ts"
} |
angular-cli/packages/angular/ssr/src/utils/ng.ts_0_3700 | /**
* @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 { ɵConsole } from '@angular/core';
import type { ApplicationRef, StaticProvider, Type } from '@angular/core';
import {
ɵSERVER_CONTEXT as SERVER_CONTEXT,
renderApplication,
renderModule,
} from '@angular/platform-server';
import { Console } from '../console';
import { stripIndexHtmlFromURL } from './url';
/**
* Represents the bootstrap mechanism for an Angular application.
*
* This type can either be:
* - A reference to an Angular component or module (`Type<unknown>`) that serves as the root of the application.
* - A function that returns a `Promise<ApplicationRef>`, which resolves with the root application reference.
*/
export type AngularBootstrap = Type<unknown> | (() => Promise<ApplicationRef>);
/**
* Renders an Angular application or module to an HTML string.
*
* This function determines whether the provided `bootstrap` value is an Angular module
* or a bootstrap function and calls the appropriate rendering method (`renderModule` or
* `renderApplication`) based on that determination.
*
* @param html - The HTML string to be used as the initial document content.
* @param bootstrap - Either an Angular module type or a function that returns a promise
* resolving to an `ApplicationRef`.
* @param url - The URL of the application. This is used for server-side rendering to
* correctly handle route-based rendering.
* @param platformProviders - An array of platform providers to be used during the
* rendering process.
* @param serverContext - A string representing the server context, used to provide additional
* context or metadata during server-side rendering.
* @returns A promise that resolves to a string containing the rendered HTML.
*/
export function renderAngular(
html: string,
bootstrap: AngularBootstrap,
url: URL,
platformProviders: StaticProvider[],
serverContext: string,
): Promise<string> {
const providers = [
{
provide: SERVER_CONTEXT,
useValue: serverContext,
},
{
// An Angular Console Provider that does not print a set of predefined logs.
provide: ɵConsole,
// Using `useClass` would necessitate decorating `Console` with `@Injectable`,
// which would require switching from `ts_library` to `ng_module`. This change
// would also necessitate various patches of `@angular/bazel` to support ESM.
useFactory: () => new Console(),
},
...platformProviders,
];
// A request to `http://www.example.com/page/index.html` will render the Angular route corresponding to `http://www.example.com/page`.
const urlToRender = stripIndexHtmlFromURL(url).toString();
return isNgModule(bootstrap)
? renderModule(bootstrap, {
url: urlToRender,
document: html,
extraProviders: providers,
})
: renderApplication(bootstrap, {
url: urlToRender,
document: html,
platformProviders: providers,
});
}
/**
* Type guard to determine if a given value is an Angular module.
* Angular modules are identified by the presence of the `ɵmod` static property.
* This function helps distinguish between Angular modules and bootstrap functions.
*
* @param value - The value to be checked.
* @returns True if the value is an Angular module (i.e., it has the `ɵmod` property), false otherwise.
*/
export function isNgModule(value: AngularBootstrap): value is Type<unknown> {
return 'ɵmod' in value;
}
| {
"end_byte": 3700,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/src/utils/ng.ts"
} |
angular-cli/packages/angular/ssr/src/utils/lru-cache.ts_0_3900 | /**
* @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
*/
/**
* Represents a node in the doubly linked list.
*/
interface Node<Key, Value> {
key: Key;
value: Value;
prev: Node<Key, Value> | undefined;
next: Node<Key, Value> | undefined;
}
/**
* A Least Recently Used (LRU) cache implementation.
*
* This cache stores a fixed number of key-value pairs, and when the cache exceeds its capacity,
* the least recently accessed items are evicted.
*
* @template Key - The type of the cache keys.
* @template Value - The type of the cache values.
*/
export class LRUCache<Key, Value> {
/**
* The maximum number of items the cache can hold.
*/
capacity: number;
/**
* Internal storage for the cache, mapping keys to their associated nodes in the linked list.
*/
private readonly cache = new Map<Key, Node<Key, Value>>();
/**
* Head of the doubly linked list, representing the most recently used item.
*/
private head: Node<Key, Value> | undefined;
/**
* Tail of the doubly linked list, representing the least recently used item.
*/
private tail: Node<Key, Value> | undefined;
/**
* Creates a new LRUCache instance.
* @param capacity The maximum number of items the cache can hold.
*/
constructor(capacity: number) {
this.capacity = capacity;
}
/**
* Gets the value associated with the given key.
* @param key The key to retrieve the value for.
* @returns The value associated with the key, or undefined if the key is not found.
*/
get(key: Key): Value | undefined {
const node = this.cache.get(key);
if (node) {
this.moveToHead(node);
return node.value;
}
return undefined;
}
/**
* Puts a key-value pair into the cache.
* If the key already exists, the value is updated.
* If the cache is full, the least recently used item is evicted.
* @param key The key to insert or update.
* @param value The value to associate with the key.
*/
put(key: Key, value: Value): void {
const cachedNode = this.cache.get(key);
if (cachedNode) {
// Update existing node
cachedNode.value = value;
this.moveToHead(cachedNode);
return;
}
// Create a new node
const newNode: Node<Key, Value> = { key, value, prev: undefined, next: undefined };
this.cache.set(key, newNode);
this.addToHead(newNode);
if (this.cache.size > this.capacity) {
// Evict the LRU item
const tail = this.removeTail();
if (tail) {
this.cache.delete(tail.key);
}
}
}
/**
* Adds a node to the head of the linked list.
* @param node The node to add.
*/
private addToHead(node: Node<Key, Value>): void {
node.next = this.head;
node.prev = undefined;
if (this.head) {
this.head.prev = node;
}
this.head = node;
if (!this.tail) {
this.tail = node;
}
}
/**
* Removes a node from the linked list.
* @param node The node to remove.
*/
private removeNode(node: Node<Key, Value>): void {
if (node.prev) {
node.prev.next = node.next;
} else {
this.head = node.next;
}
if (node.next) {
node.next.prev = node.prev;
} else {
this.tail = node.prev;
}
}
/**
* Moves a node to the head of the linked list.
* @param node The node to move.
*/
private moveToHead(node: Node<Key, Value>): void {
this.removeNode(node);
this.addToHead(node);
}
/**
* Removes the tail node from the linked list.
* @returns The removed tail node, or undefined if the list is empty.
*/
private removeTail(): Node<Key, Value> | undefined {
const node = this.tail;
if (node) {
this.removeNode(node);
}
return node;
}
}
| {
"end_byte": 3900,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/src/utils/lru-cache.ts"
} |
angular-cli/packages/angular/ssr/src/utils/crypto.ts_0_786 | /**
* @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
*/
/**
* Generates a SHA-256 hash of the provided string.
*
* @param data - The input string to be hashed.
* @returns A promise that resolves to the SHA-256 hash of the input,
* represented as a hexadecimal string.
*/
export async function sha256(data: string): Promise<string> {
const encodedData = new TextEncoder().encode(data);
const hashBuffer = await crypto.subtle.digest('SHA-256', encodedData);
const hashParts: string[] = [];
for (const h of new Uint8Array(hashBuffer)) {
hashParts.push(h.toString(16).padStart(2, '0'));
}
return hashParts.join('');
}
| {
"end_byte": 786,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/src/utils/crypto.ts"
} |
angular-cli/packages/angular/ssr/src/utils/url.ts_0_3928 | /**
* @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
*/
/**
* Removes the trailing slash from a URL if it exists.
*
* @param url - The URL string from which to remove the trailing slash.
* @returns The URL string without a trailing slash.
*
* @example
* ```js
* stripTrailingSlash('path/'); // 'path'
* stripTrailingSlash('/path'); // '/path'
* stripTrailingSlash('/'); // '/'
* stripTrailingSlash(''); // ''
* ```
*/
export function stripTrailingSlash(url: string): string {
// Check if the last character of the URL is a slash
return url.length > 1 && url[url.length - 1] === '/' ? url.slice(0, -1) : url;
}
/**
* Removes the leading slash from a URL if it exists.
*
* @param url - The URL string from which to remove the leading slash.
* @returns The URL string without a leading slash.
*
* @example
* ```js
* stripLeadingSlash('/path'); // 'path'
* stripLeadingSlash('/path/'); // 'path/'
* stripLeadingSlash('/'); // '/'
* stripLeadingSlash(''); // ''
* ```
*/
export function stripLeadingSlash(url: string): string {
// Check if the first character of the URL is a slash
return url.length > 1 && url[0] === '/' ? url.slice(1) : url;
}
/**
* Adds a leading slash to a URL if it does not already have one.
*
* @param url - The URL string to which the leading slash will be added.
* @returns The URL string with a leading slash.
*
* @example
* ```js
* addLeadingSlash('path'); // '/path'
* addLeadingSlash('/path'); // '/path'
* ```
*/
export function addLeadingSlash(url: string): string {
// Check if the URL already starts with a slash
return url[0] === '/' ? url : `/${url}`;
}
/**
* Joins URL parts into a single URL string.
*
* This function takes multiple URL segments, normalizes them by removing leading
* and trailing slashes where appropriate, and then joins them into a single URL.
*
* @param parts - The parts of the URL to join. Each part can be a string with or without slashes.
* @returns The joined URL string, with normalized slashes.
*
* @example
* ```js
* joinUrlParts('path/', '/to/resource'); // '/path/to/resource'
* joinUrlParts('/path/', 'to/resource'); // '/path/to/resource'
* joinUrlParts('', ''); // '/'
* ```
*/
export function joinUrlParts(...parts: string[]): string {
const normalizeParts: string[] = [];
for (const part of parts) {
if (part === '') {
// Skip any empty parts
continue;
}
let normalizedPart = part;
if (part[0] === '/') {
normalizedPart = normalizedPart.slice(1);
}
if (part[part.length - 1] === '/') {
normalizedPart = normalizedPart.slice(0, -1);
}
if (normalizedPart !== '') {
normalizeParts.push(normalizedPart);
}
}
return addLeadingSlash(normalizeParts.join('/'));
}
/**
* Strips `/index.html` from the end of a URL's path, if present.
*
* This function is used to convert URLs pointing to an `index.html` file into their directory
* equivalents. For example, it transforms a URL like `http://www.example.com/page/index.html`
* into `http://www.example.com/page`.
*
* @param url - The URL object to process.
* @returns A new URL object with `/index.html` removed from the path, if it was present.
*
* @example
* ```typescript
* const originalUrl = new URL('http://www.example.com/page/index.html');
* const cleanedUrl = stripIndexHtmlFromURL(originalUrl);
* console.log(cleanedUrl.href); // Output: 'http://www.example.com/page'
* ```
*/
export function stripIndexHtmlFromURL(url: URL): URL {
if (url.pathname.endsWith('/index.html')) {
const modifiedURL = new URL(url);
// Remove '/index.html' from the pathname
modifiedURL.pathname = modifiedURL.pathname.slice(0, /** '/index.html'.length */ -11);
return modifiedURL;
}
return url;
}
| {
"end_byte": 3928,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/src/utils/url.ts"
} |
angular-cli/packages/angular/ssr/src/utils/inline-critical-css.ts_0_7964 | /**
* @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 Beasties from '../../third_party/beasties';
/**
* Pattern used to extract the media query set by Beasties in an `onload` handler.
*/
const MEDIA_SET_HANDLER_PATTERN = /^this\.media=["'](.*)["'];?$/;
/**
* Name of the attribute used to save the Beasties media query so it can be re-assigned on load.
*/
const CSP_MEDIA_ATTR = 'ngCspMedia';
/**
* Script that dynamically updates the `media` attribute of `<link>` tags based on a custom attribute (`CSP_MEDIA_ATTR`).
*
* NOTE:
* We do not use `document.querySelectorAll('link').forEach((s) => s.addEventListener('load', ...)`
* because load events are not always triggered reliably on Chrome.
* See: https://github.com/angular/angular-cli/issues/26932 and https://crbug.com/1521256
*
* The script:
* - Ensures the event target is a `<link>` tag with the `CSP_MEDIA_ATTR` attribute.
* - Updates the `media` attribute with the value of `CSP_MEDIA_ATTR` and then removes the attribute.
* - Removes the event listener when all relevant `<link>` tags have been processed.
* - Uses event capturing (the `true` parameter) since load events do not bubble up the DOM.
*/
const LINK_LOAD_SCRIPT_CONTENT = `
(() => {
const CSP_MEDIA_ATTR = '${CSP_MEDIA_ATTR}';
const documentElement = document.documentElement;
// Listener for load events on link tags.
const listener = (e) => {
const target = e.target;
if (
!target ||
target.tagName !== 'LINK' ||
!target.hasAttribute(CSP_MEDIA_ATTR)
) {
return;
}
target.media = target.getAttribute(CSP_MEDIA_ATTR);
target.removeAttribute(CSP_MEDIA_ATTR);
if (!document.head.querySelector(\`link[\${CSP_MEDIA_ATTR}]\`)) {
documentElement.removeEventListener('load', listener);
}
};
documentElement.addEventListener('load', listener, true);
})();`;
/** Partial representation of an `HTMLElement`. */
interface PartialHTMLElement {
getAttribute(name: string): string | null;
setAttribute(name: string, value: string): void;
hasAttribute(name: string): boolean;
removeAttribute(name: string): void;
appendChild(child: PartialHTMLElement): void;
insertBefore(newNode: PartialHTMLElement, referenceNode?: PartialHTMLElement): void;
remove(): void;
name: string;
textContent: string;
tagName: string | null;
children: PartialHTMLElement[];
next: PartialHTMLElement | null;
prev: PartialHTMLElement | null;
}
/** Partial representation of an HTML `Document`. */
interface PartialDocument {
head: PartialHTMLElement;
createElement(tagName: string): PartialHTMLElement;
querySelector(selector: string): PartialHTMLElement | null;
}
/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */
// We use Typescript declaration merging because `embedLinkedStylesheet` it's not declared in
// the `Beasties` types which means that we can't call the `super` implementation.
interface BeastiesBase {
embedLinkedStylesheet(link: PartialHTMLElement, document: PartialDocument): Promise<unknown>;
}
class BeastiesBase extends Beasties {}
/* eslint-enable @typescript-eslint/no-unsafe-declaration-merging */
export class InlineCriticalCssProcessor extends BeastiesBase {
private addedCspScriptsDocuments = new WeakSet<PartialDocument>();
private documentNonces = new WeakMap<PartialDocument, string | null>();
constructor(
public override readFile: (path: string) => Promise<string>,
readonly outputPath?: string,
) {
super({
logger: {
// eslint-disable-next-line no-console
warn: (s: string) => console.warn(s),
// eslint-disable-next-line no-console
error: (s: string) => console.error(s),
info: () => {},
},
logLevel: 'warn',
path: outputPath,
publicPath: undefined,
compress: false,
pruneSource: false,
reduceInlineStyles: false,
mergeStylesheets: false,
// Note: if `preload` changes to anything other than `media`, the logic in
// `embedLinkedStylesheet` will have to be updated.
preload: 'media',
noscriptFallback: true,
inlineFonts: true,
});
}
/**
* Override of the Beasties `embedLinkedStylesheet` method
* that makes it work with Angular's CSP APIs.
*/
override async embedLinkedStylesheet(
link: PartialHTMLElement,
document: PartialDocument,
): Promise<unknown> {
if (link.getAttribute('media') === 'print' && link.next?.name === 'noscript') {
// Workaround for https://github.com/GoogleChromeLabs/critters/issues/64
// NB: this is only needed for the webpack based builders.
const media = link.getAttribute('onload')?.match(MEDIA_SET_HANDLER_PATTERN);
if (media) {
link.removeAttribute('onload');
link.setAttribute('media', media[1]);
link?.next?.remove();
}
}
const returnValue = await super.embedLinkedStylesheet(link, document);
const cspNonce = this.findCspNonce(document);
if (cspNonce) {
const beastiesMedia = link.getAttribute('onload')?.match(MEDIA_SET_HANDLER_PATTERN);
if (beastiesMedia) {
// If there's a Beasties-generated `onload` handler and the file has an Angular CSP nonce,
// we have to remove the handler, because it's incompatible with CSP. We save the value
// in a different attribute and we generate a script tag with the nonce that uses
// `addEventListener` to apply the media query instead.
link.removeAttribute('onload');
link.setAttribute(CSP_MEDIA_ATTR, beastiesMedia[1]);
this.conditionallyInsertCspLoadingScript(document, cspNonce, link);
}
// Ideally we would hook in at the time Beasties inserts the `style` tags, but there isn't
// a way of doing that at the moment so we fall back to doing it any time a `link` tag is
// inserted. We mitigate it by only iterating the direct children of the `<head>` which
// should be pretty shallow.
document.head.children.forEach((child) => {
if (child.tagName === 'style' && !child.hasAttribute('nonce')) {
child.setAttribute('nonce', cspNonce);
}
});
}
return returnValue;
}
/**
* Finds the CSP nonce for a specific document.
*/
private findCspNonce(document: PartialDocument): string | null {
if (this.documentNonces.has(document)) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return this.documentNonces.get(document)!;
}
// HTML attribute are case-insensitive, but the parser used by Beasties is case-sensitive.
const nonceElement = document.querySelector('[ngCspNonce], [ngcspnonce]');
const cspNonce =
nonceElement?.getAttribute('ngCspNonce') || nonceElement?.getAttribute('ngcspnonce') || null;
this.documentNonces.set(document, cspNonce);
return cspNonce;
}
/**
* Inserts the `script` tag that swaps the critical CSS at runtime,
* if one hasn't been inserted into the document already.
*/
private conditionallyInsertCspLoadingScript(
document: PartialDocument,
nonce: string,
link: PartialHTMLElement,
): void {
if (this.addedCspScriptsDocuments.has(document)) {
return;
}
if (document.head.textContent.includes(LINK_LOAD_SCRIPT_CONTENT)) {
// Script was already added during the build.
this.addedCspScriptsDocuments.add(document);
return;
}
const script = document.createElement('script');
script.setAttribute('nonce', nonce);
script.textContent = LINK_LOAD_SCRIPT_CONTENT;
// Prepend the script to the head since it needs to
// run as early as possible, before the `link` tags.
document.head.insertBefore(script, link);
this.addedCspScriptsDocuments.add(document);
}
}
| {
"end_byte": 7964,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/src/utils/inline-critical-css.ts"
} |
angular-cli/packages/angular/ssr/src/routes/router.ts_0_3860 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { AngularAppManifest } from '../manifest';
import { stripIndexHtmlFromURL } from '../utils/url';
import { extractRoutesAndCreateRouteTree } from './ng-routes';
import { RouteTree, RouteTreeNodeMetadata } from './route-tree';
/**
* Manages the application's server routing logic by building and maintaining a route tree.
*
* This class is responsible for constructing the route tree from the Angular application
* configuration and using it to match incoming requests to the appropriate routes.
*/
export class ServerRouter {
/**
* Creates an instance of the `ServerRouter`.
*
* @param routeTree - An instance of `RouteTree` that holds the routing information.
* The `RouteTree` is used to match request URLs to the appropriate route metadata.
*/
private constructor(private readonly routeTree: RouteTree) {}
/**
* Static property to track the ongoing build promise.
*/
static #extractionPromise: Promise<ServerRouter> | undefined;
/**
* Creates or retrieves a `ServerRouter` instance based on the provided manifest and URL.
*
* If the manifest contains pre-built routes, a new `ServerRouter` is immediately created.
* Otherwise, it builds the router by extracting routes from the Angular configuration
* asynchronously. This method ensures that concurrent builds are prevented by re-using
* the same promise.
*
* @param manifest - An instance of `AngularAppManifest` that contains the route information.
* @param url - The URL for server-side rendering. The URL is needed to configure `ServerPlatformLocation`.
* This is necessary to ensure that API requests for relative paths succeed, which is crucial for correct route extraction.
* [Reference](https://github.com/angular/angular/blob/d608b857c689d17a7ffa33bbb510301014d24a17/packages/platform-server/src/location.ts#L51)
* @returns A promise resolving to a `ServerRouter` instance.
*/
static from(manifest: AngularAppManifest, url: URL): Promise<ServerRouter> {
if (manifest.routes) {
const routeTree = RouteTree.fromObject(manifest.routes);
return Promise.resolve(new ServerRouter(routeTree));
}
// Create and store a new promise for the build process.
// This prevents concurrent builds by re-using the same promise.
ServerRouter.#extractionPromise ??= extractRoutesAndCreateRouteTree(url, manifest)
.then(({ routeTree, errors }) => {
if (errors.length > 0) {
throw new Error(
'Error(s) occurred while extracting routes:\n' +
errors.map((error) => `- ${error}`).join('\n'),
);
}
return new ServerRouter(routeTree);
})
.finally(() => {
ServerRouter.#extractionPromise = undefined;
});
return ServerRouter.#extractionPromise;
}
/**
* Matches a request URL against the route tree to retrieve route metadata.
*
* This method strips 'index.html' from the URL if it is present and then attempts
* to find a match in the route tree. If a match is found, it returns the associated
* route metadata; otherwise, it returns `undefined`.
*
* @param url - The URL to be matched against the route tree.
* @returns The metadata for the matched route or `undefined` if no match is found.
*/
match(url: URL): RouteTreeNodeMetadata | undefined {
// Strip 'index.html' from URL if present.
// A request to `http://www.example.com/page/index.html` will render the Angular route corresponding to `http://www.example.com/page`.
const { pathname } = stripIndexHtmlFromURL(url);
return this.routeTree.match(decodeURIComponent(pathname));
}
}
| {
"end_byte": 3860,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/src/routes/router.ts"
} |
angular-cli/packages/angular/ssr/src/routes/ng-routes.ts_0_7373 | /**
* @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 { APP_BASE_HREF, PlatformLocation } from '@angular/common';
import {
ApplicationRef,
Compiler,
Injector,
runInInjectionContext,
ɵwhenStable as whenStable,
ɵConsole,
} from '@angular/core';
import { INITIAL_CONFIG, platformServer } from '@angular/platform-server';
import { Route, Router, ɵloadChildren as loadChildrenHelper } from '@angular/router';
import { ServerAssets } from '../assets';
import { Console } from '../console';
import { AngularAppManifest, getAngularAppManifest } from '../manifest';
import { AngularBootstrap, isNgModule } from '../utils/ng';
import { joinUrlParts, stripLeadingSlash } from '../utils/url';
import { PrerenderFallback, RenderMode, SERVER_ROUTES_CONFIG, ServerRoute } from './route-config';
import { RouteTree, RouteTreeNodeMetadata } from './route-tree';
/**
* Regular expression to match segments preceded by a colon in a string.
*/
const URL_PARAMETER_REGEXP = /(?<!\\):([^/]+)/g;
/**
* An set of HTTP status codes that are considered valid for redirect responses.
*/
const VALID_REDIRECT_RESPONSE_CODES = new Set([301, 302, 303, 307, 308]);
/**
* Additional metadata for a server configuration route tree.
*/
type ServerConfigRouteTreeAdditionalMetadata = Partial<ServerRoute> & {
/** Indicates if the route has been matched with the Angular router routes. */
presentInClientRouter?: boolean;
};
/**
* Metadata for a server configuration route tree node.
*/
type ServerConfigRouteTreeNodeMetadata = RouteTreeNodeMetadata &
ServerConfigRouteTreeAdditionalMetadata;
/**
* Result of extracting routes from an Angular application.
*/
interface AngularRouterConfigResult {
/**
* The base URL for the application.
* This is the base href that is used for resolving relative paths within the application.
*/
baseHref: string;
/**
* An array of `RouteTreeNodeMetadata` objects representing the application's routes.
*
* Each `RouteTreeNodeMetadata` contains details about a specific route, such as its path and any
* associated redirection targets. This array is asynchronously generated and
* provides information on how routes are structured and resolved.
*/
routes: RouteTreeNodeMetadata[];
/**
* Optional configuration for server routes.
*
* This property allows you to specify an array of server routes for configuration.
* If not provided, the default configuration or behavior will be used.
*/
serverRoutesConfig?: ServerRoute[] | null;
/**
* A list of errors encountered during the route extraction process.
*/
errors: string[];
}
/**
* Traverses an array of route configurations to generate route tree node metadata.
*
* This function processes each route and its children, handling redirects, SSG (Static Site Generation) settings,
* and lazy-loaded routes. It yields route metadata for each route and its potential variants.
*
* @param options - The configuration options for traversing routes.
* @returns An async iterable iterator yielding either route tree node metadata or an error object with an error message.
*/
async function* traverseRoutesConfig(options: {
routes: Route[];
compiler: Compiler;
parentInjector: Injector;
parentRoute: string;
serverConfigRouteTree: RouteTree<ServerConfigRouteTreeAdditionalMetadata> | undefined;
invokeGetPrerenderParams: boolean;
includePrerenderFallbackRoutes: boolean;
}): AsyncIterableIterator<RouteTreeNodeMetadata | { error: string }> {
const {
routes,
compiler,
parentInjector,
parentRoute,
serverConfigRouteTree,
invokeGetPrerenderParams,
includePrerenderFallbackRoutes,
} = options;
for (const route of routes) {
try {
const { path = '', redirectTo, loadChildren, children } = route;
const currentRoutePath = joinUrlParts(parentRoute, path);
// Get route metadata from the server config route tree, if available
let matchedMetaData: ServerConfigRouteTreeNodeMetadata | undefined;
if (serverConfigRouteTree) {
matchedMetaData = serverConfigRouteTree.match(currentRoutePath);
if (!matchedMetaData) {
yield {
error:
`The '${stripLeadingSlash(currentRoutePath)}' route does not match any route defined in the server routing configuration. ` +
'Please ensure this route is added to the server routing configuration.',
};
continue;
}
matchedMetaData.presentInClientRouter = true;
}
const metadata: ServerConfigRouteTreeNodeMetadata = {
...matchedMetaData,
route: currentRoutePath,
};
delete metadata.presentInClientRouter;
// Handle redirects
if (typeof redirectTo === 'string') {
const redirectToResolved = resolveRedirectTo(currentRoutePath, redirectTo);
if (metadata.status && !VALID_REDIRECT_RESPONSE_CODES.has(metadata.status)) {
yield {
error:
`The '${metadata.status}' status code is not a valid redirect response code. ` +
`Please use one of the following redirect response codes: ${[...VALID_REDIRECT_RESPONSE_CODES.values()].join(', ')}.`,
};
continue;
}
yield { ...metadata, redirectTo: redirectToResolved };
} else if (metadata.renderMode === RenderMode.Prerender) {
// Handle SSG routes
yield* handleSSGRoute(
metadata,
parentInjector,
invokeGetPrerenderParams,
includePrerenderFallbackRoutes,
);
} else {
yield metadata;
}
// Recursively process child routes
if (children?.length) {
yield* traverseRoutesConfig({
...options,
routes: children,
parentRoute: currentRoutePath,
});
}
// Load and process lazy-loaded child routes
if (loadChildren) {
const loadedChildRoutes = await loadChildrenHelper(
route,
compiler,
parentInjector,
).toPromise();
if (loadedChildRoutes) {
const { routes: childRoutes, injector = parentInjector } = loadedChildRoutes;
yield* traverseRoutesConfig({
...options,
routes: childRoutes,
parentInjector: injector,
parentRoute: currentRoutePath,
});
}
}
} catch (error) {
yield {
error: `Error processing route '${stripLeadingSlash(route.path ?? '')}': ${(error as Error).message}`,
};
}
}
}
/**
* Handles SSG (Static Site Generation) routes by invoking `getPrerenderParams` and yielding
* all parameterized paths, returning any errors encountered.
*
* @param metadata - The metadata associated with the route tree node.
* @param parentInjector - The dependency injection container for the parent route.
* @param invokeGetPrerenderParams - A flag indicating whether to invoke the `getPrerenderParams` function.
* @param includePrerenderFallbackRoutes - A flag indicating whether to include fallback routes in the result.
* @returns An async iterable iterator that yields route tree node metadata for each SSG path or errors.
*/
as | {
"end_byte": 7373,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/src/routes/ng-routes.ts"
} |
angular-cli/packages/angular/ssr/src/routes/ng-routes.ts_7374_13295 | nc function* handleSSGRoute(
metadata: ServerConfigRouteTreeNodeMetadata,
parentInjector: Injector,
invokeGetPrerenderParams: boolean,
includePrerenderFallbackRoutes: boolean,
): AsyncIterableIterator<RouteTreeNodeMetadata | { error: string }> {
if (metadata.renderMode !== RenderMode.Prerender) {
throw new Error(
`'handleSSGRoute' was called for a route which rendering mode is not prerender.`,
);
}
const { route: currentRoutePath, fallback, ...meta } = metadata;
const getPrerenderParams = 'getPrerenderParams' in meta ? meta.getPrerenderParams : undefined;
if ('getPrerenderParams' in meta) {
delete meta['getPrerenderParams'];
}
if (!URL_PARAMETER_REGEXP.test(currentRoutePath)) {
// Route has no parameters
yield {
...meta,
route: currentRoutePath,
};
return;
}
if (invokeGetPrerenderParams) {
if (!getPrerenderParams) {
yield {
error:
`The '${stripLeadingSlash(currentRoutePath)}' route uses prerendering and includes parameters, but 'getPrerenderParams' ` +
`is missing. Please define 'getPrerenderParams' function for this route in your server routing configuration ` +
`or specify a different 'renderMode'.`,
};
return;
}
const parameters = await runInInjectionContext(parentInjector, () => getPrerenderParams());
try {
for (const params of parameters) {
const routeWithResolvedParams = currentRoutePath.replace(URL_PARAMETER_REGEXP, (match) => {
const parameterName = match.slice(1);
const value = params[parameterName];
if (typeof value !== 'string') {
throw new Error(
`The 'getPrerenderParams' function defined for the '${stripLeadingSlash(currentRoutePath)}' route ` +
`returned a non-string value for parameter '${parameterName}'. ` +
`Please make sure the 'getPrerenderParams' function returns values for all parameters ` +
'specified in this route.',
);
}
return value;
});
yield { ...meta, route: routeWithResolvedParams };
}
} catch (error) {
yield { error: `${(error as Error).message}` };
return;
}
}
// Handle fallback render modes
if (
includePrerenderFallbackRoutes &&
(fallback !== PrerenderFallback.None || !invokeGetPrerenderParams)
) {
yield {
...meta,
route: currentRoutePath,
renderMode: fallback === PrerenderFallback.Client ? RenderMode.Client : RenderMode.Server,
};
}
}
/**
* Resolves the `redirectTo` property for a given route.
*
* This function processes the `redirectTo` property to ensure that it correctly
* resolves relative to the current route path. If `redirectTo` is an absolute path,
* it is returned as is. If it is a relative path, it is resolved based on the current route path.
*
* @param routePath - The current route path.
* @param redirectTo - The target path for redirection.
* @returns The resolved redirect path as a string.
*/
function resolveRedirectTo(routePath: string, redirectTo: string): string {
if (redirectTo[0] === '/') {
// If the redirectTo path is absolute, return it as is.
return redirectTo;
}
// Resolve relative redirectTo based on the current route path.
const segments = routePath.split('/');
segments.pop(); // Remove the last segment to make it relative.
return joinUrlParts(...segments, redirectTo);
}
/**
* Builds a server configuration route tree from the given server routes configuration.
*
* @param serverRoutesConfig - The array of server routes to be used for configuration.
* @returns An object containing:
* - `serverConfigRouteTree`: A populated `RouteTree` instance, which organizes the server routes
* along with their additional metadata.
* - `errors`: An array of strings that list any errors encountered during the route tree construction
* process, such as invalid paths.
*/
function buildServerConfigRouteTree(serverRoutesConfig: ServerRoute[]): {
errors: string[];
serverConfigRouteTree: RouteTree<ServerConfigRouteTreeAdditionalMetadata>;
} {
const serverConfigRouteTree = new RouteTree<ServerConfigRouteTreeAdditionalMetadata>();
const errors: string[] = [];
for (const { path, ...metadata } of serverRoutesConfig) {
if (path[0] === '/') {
errors.push(`Invalid '${path}' route configuration: the path cannot start with a slash.`);
continue;
}
serverConfigRouteTree.insert(path, metadata);
}
return { serverConfigRouteTree, errors };
}
/**
* Retrieves routes from the given Angular application.
*
* This function initializes an Angular platform, bootstraps the application or module,
* and retrieves routes from the Angular router configuration. It handles both module-based
* and function-based bootstrapping. It yields the resulting routes as `RouteTreeNodeMetadata` objects or errors.
*
* @param bootstrap - A function that returns a promise resolving to an `ApplicationRef` or an Angular module to bootstrap.
* @param document - The initial HTML document used for server-side rendering.
* This document is necessary to render the application on the server.
* @param url - The URL for server-side rendering. The URL is used to configure `ServerPlatformLocation`. This configuration is crucial
* for ensuring that API requests for relative paths succeed, which is essential for accurate route extraction.
* @param invokeGetPrerenderParams - A boolean flag indicating whether to invoke `getPrerenderParams` for parameterized SSG routes
* to handle prerendering paths. Defaults to `false`.
* @param includePrerenderFallbackRoutes - A flag indicating whether to include fallback routes in the result. Defaults to `true`.
*
* @returns A promise that resolves to an object of type `AngularRouterConfigResult` or errors.
*/
ex | {
"end_byte": 13295,
"start_byte": 7374,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/src/routes/ng-routes.ts"
} |
angular-cli/packages/angular/ssr/src/routes/ng-routes.ts_13296_19682 | ort async function getRoutesFromAngularRouterConfig(
bootstrap: AngularBootstrap,
document: string,
url: URL,
invokeGetPrerenderParams = false,
includePrerenderFallbackRoutes = true,
): Promise<AngularRouterConfigResult> {
const { protocol, host } = url;
// Create and initialize the Angular platform for server-side rendering.
const platformRef = platformServer([
{
provide: INITIAL_CONFIG,
useValue: { document, url: `${protocol}//${host}/` },
},
{
provide: ɵConsole,
useFactory: () => new Console(),
},
]);
try {
let applicationRef: ApplicationRef;
if (isNgModule(bootstrap)) {
const moduleRef = await platformRef.bootstrapModule(bootstrap);
applicationRef = moduleRef.injector.get(ApplicationRef);
} else {
applicationRef = await bootstrap();
}
// Wait until the application is stable.
await whenStable(applicationRef);
const injector = applicationRef.injector;
const router = injector.get(Router);
const routesResults: RouteTreeNodeMetadata[] = [];
const errors: string[] = [];
const baseHref =
injector.get(APP_BASE_HREF, null, { optional: true }) ??
injector.get(PlatformLocation).getBaseHrefFromDOM();
const compiler = injector.get(Compiler);
const serverRoutesConfig = injector.get(SERVER_ROUTES_CONFIG, null, { optional: true });
let serverConfigRouteTree: RouteTree<ServerConfigRouteTreeAdditionalMetadata> | undefined;
if (serverRoutesConfig) {
const result = buildServerConfigRouteTree(serverRoutesConfig);
serverConfigRouteTree = result.serverConfigRouteTree;
errors.push(...result.errors);
}
if (errors.length) {
return {
baseHref,
routes: routesResults,
errors,
};
}
if (router.config.length) {
// Retrieve all routes from the Angular router configuration.
const traverseRoutes = traverseRoutesConfig({
routes: router.config,
compiler,
parentInjector: injector,
parentRoute: '',
serverConfigRouteTree,
invokeGetPrerenderParams,
includePrerenderFallbackRoutes,
});
let seenAppShellRoute: string | undefined;
for await (const result of traverseRoutes) {
if ('error' in result) {
errors.push(result.error);
} else {
if (result.renderMode === RenderMode.AppShell) {
if (seenAppShellRoute !== undefined) {
errors.push(
`Error: Both '${seenAppShellRoute}' and '${stripLeadingSlash(result.route)}' routes have ` +
`their 'renderMode' set to 'AppShell'. AppShell renderMode should only be assigned to one route. ` +
`Please review your route configurations to ensure that only one route is set to 'RenderMode.AppShell'.`,
);
}
seenAppShellRoute = stripLeadingSlash(result.route);
}
routesResults.push(result);
}
}
if (serverConfigRouteTree) {
for (const { route, presentInClientRouter } of serverConfigRouteTree.traverse()) {
if (presentInClientRouter || route === '**') {
// Skip if matched or it's the catch-all route.
continue;
}
errors.push(
`The '${route}' server route does not match any routes defined in the Angular ` +
`routing configuration (typically provided as a part of the 'provideRouter' call). ` +
'Please make sure that the mentioned server route is present in the Angular routing configuration.',
);
}
}
} else {
const renderMode = serverConfigRouteTree?.match('')?.renderMode ?? RenderMode.Prerender;
routesResults.push({
route: '',
renderMode,
});
}
return {
baseHref,
routes: routesResults,
errors,
};
} finally {
platformRef.destroy();
}
}
/**
* Asynchronously extracts routes from the Angular application configuration
* and creates a `RouteTree` to manage server-side routing.
*
* @param url - The URL for server-side rendering. The URL is used to configure `ServerPlatformLocation`. This configuration is crucial
* for ensuring that API requests for relative paths succeed, which is essential for accurate route extraction.
* See:
* - https://github.com/angular/angular/blob/d608b857c689d17a7ffa33bbb510301014d24a17/packages/platform-server/src/location.ts#L51
* - https://github.com/angular/angular/blob/6882cc7d9eed26d3caeedca027452367ba25f2b9/packages/platform-server/src/http.ts#L44
* @param manifest - An optional `AngularAppManifest` that contains the application's routing and configuration details.
* If not provided, the default manifest is retrieved using `getAngularAppManifest()`.
* @param invokeGetPrerenderParams - A boolean flag indicating whether to invoke `getPrerenderParams` for parameterized SSG routes
* to handle prerendering paths. Defaults to `false`.
* @param includePrerenderFallbackRoutes - A flag indicating whether to include fallback routes in the result. Defaults to `true`.
*
* @returns A promise that resolves to an object containing:
* - `routeTree`: A populated `RouteTree` containing all extracted routes from the Angular application.
* - `errors`: An array of strings representing any errors encountered during the route extraction process.
*/
export async function extractRoutesAndCreateRouteTree(
url: URL,
manifest: AngularAppManifest = getAngularAppManifest(),
invokeGetPrerenderParams = false,
includePrerenderFallbackRoutes = true,
): Promise<{ routeTree: RouteTree; errors: string[] }> {
const routeTree = new RouteTree();
const document = await new ServerAssets(manifest).getIndexServerHtml();
const bootstrap = await manifest.bootstrap();
const { baseHref, routes, errors } = await getRoutesFromAngularRouterConfig(
bootstrap,
document,
url,
invokeGetPrerenderParams,
includePrerenderFallbackRoutes,
);
for (const { route, ...metadata } of routes) {
if (metadata.redirectTo !== undefined) {
metadata.redirectTo = joinUrlParts(baseHref, metadata.redirectTo);
}
const fullRoute = joinUrlParts(baseHref, route);
routeTree.insert(fullRoute, metadata);
}
return {
routeTree,
errors,
};
}
| {
"end_byte": 19682,
"start_byte": 13296,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/src/routes/ng-routes.ts"
} |
angular-cli/packages/angular/ssr/src/routes/route-config.ts_0_6126 | /**
* @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 { EnvironmentProviders, InjectionToken, makeEnvironmentProviders } from '@angular/core';
/**
* Different rendering modes for server routes.
* @developerPreview
*/
export enum RenderMode {
/** AppShell rendering mode, typically used for pre-rendered shells of the application. */
AppShell,
/** Server-Side Rendering (SSR) mode, where content is rendered on the server for each request. */
Server,
/** Client-Side Rendering (CSR) mode, where content is rendered on the client side in the browser. */
Client,
/** Static Site Generation (SSG) mode, where content is pre-rendered at build time and served as static files. */
Prerender,
}
/**
* Defines the fallback strategies for Static Site Generation (SSG) routes when a pre-rendered path is not available.
* This is particularly relevant for routes with parameterized URLs where some paths might not be pre-rendered at build time.
*
* @developerPreview
*/
export enum PrerenderFallback {
/**
* Fallback to Server-Side Rendering (SSR) if the pre-rendered path is not available.
* This strategy dynamically generates the page on the server at request time.
*/
Server,
/**
* Fallback to Client-Side Rendering (CSR) if the pre-rendered path is not available.
* This strategy allows the page to be rendered on the client side.
*/
Client,
/**
* No fallback; if the path is not pre-rendered, the server will not handle the request.
* This means the application will not provide any response for paths that are not pre-rendered.
*/
None,
}
/**
* Common interface for server routes, providing shared properties.
*/
export interface ServerRouteCommon {
/** The path associated with this route. */
path: string;
/** Optional additional headers to include in the response for this route. */
headers?: Record<string, string>;
/** Optional status code to return for this route. */
status?: number;
}
/**
* A server route that uses AppShell rendering mode.
*/
export interface ServerRouteAppShell extends Omit<ServerRouteCommon, 'headers' | 'status'> {
/** Specifies that the route uses AppShell rendering mode. */
renderMode: RenderMode.AppShell;
}
/**
* A server route that uses Client-Side Rendering (CSR) mode.
*/
export interface ServerRouteClient extends ServerRouteCommon {
/** Specifies that the route uses Client-Side Rendering (CSR) mode. */
renderMode: RenderMode.Client;
}
/**
* A server route that uses Static Site Generation (SSG) mode.
*/
export interface ServerRoutePrerender extends Omit<ServerRouteCommon, 'status'> {
/** Specifies that the route uses Static Site Generation (SSG) mode. */
renderMode: RenderMode.Prerender;
/** Fallback cannot be specified unless `getPrerenderParams` is used. */
fallback?: never;
}
/**
* A server route configuration that uses Static Site Generation (SSG) mode, including support for routes with parameters.
*/
export interface ServerRoutePrerenderWithParams extends Omit<ServerRoutePrerender, 'fallback'> {
/**
* Optional strategy to use if the SSG path is not pre-rendered.
* This is especially relevant for routes with parameterized URLs, where some paths may not be pre-rendered at build time.
*
* This property determines how to handle requests for paths that are not pre-rendered:
* - `PrerenderFallback.Server`: Use Server-Side Rendering (SSR) to dynamically generate the page at request time.
* - `PrerenderFallback.Client`: Use Client-Side Rendering (CSR) to fetch and render the page on the client side.
* - `PrerenderFallback.None`: No fallback; if the path is not pre-rendered, the server will not handle the request.
*
* @default `PrerenderFallback.Server` if not provided.
*/
fallback?: PrerenderFallback;
/**
* A function that returns a Promise resolving to an array of objects, each representing a route path with URL parameters.
* This function runs in the injector context, allowing access to Angular services and dependencies.
*
* @returns A Promise resolving to an array where each element is an object with string keys (representing URL parameter names)
* and string values (representing the corresponding values for those parameters in the route path).
*
* @example
* ```typescript
* export const serverRouteConfig: ServerRoutes[] = [
* {
* path: '/product/:id',
* renderMode: RenderMode.Prerender,
* async getPrerenderParams() {
* const productService = inject(ProductService);
* const ids = await productService.getIds(); // Assuming this returns ['1', '2', '3']
*
* return ids.map(id => ({ id })); // Generates paths like: [{ id: '1' }, { id: '2' }, { id: '3' }]
* },
* },
* ];
* ```
*/
getPrerenderParams: () => Promise<Record<string, string>[]>;
}
/**
* A server route that uses Server-Side Rendering (SSR) mode.
*/
export interface ServerRouteServer extends ServerRouteCommon {
/** Specifies that the route uses Server-Side Rendering (SSR) mode. */
renderMode: RenderMode.Server;
}
/**
* Server route configuration.
* @developerPreview
*/
export type ServerRoute =
| ServerRouteAppShell
| ServerRouteClient
| ServerRoutePrerender
| ServerRoutePrerenderWithParams
| ServerRouteServer;
/**
* Token for providing the server routes configuration.
* @internal
*/
export const SERVER_ROUTES_CONFIG = new InjectionToken<ServerRoute[]>('SERVER_ROUTES_CONFIG');
/**
* Configures the necessary providers for server routes configuration.
*
* @param routes - An array of server routes to be provided.
* @returns An `EnvironmentProviders` object that contains the server routes configuration.
* @developerPreview
*/
export function provideServerRoutesConfig(routes: ServerRoute[]): EnvironmentProviders {
return makeEnvironmentProviders([
{
provide: SERVER_ROUTES_CONFIG,
useValue: routes,
},
]);
}
| {
"end_byte": 6126,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/src/routes/route-config.ts"
} |
angular-cli/packages/angular/ssr/src/routes/route-tree.ts_0_4270 | /**
* @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 { stripTrailingSlash } from '../utils/url';
import { RenderMode } from './route-config';
/**
* Represents the serialized format of a route tree as an array of node metadata objects.
* Each entry in the array corresponds to a specific node's metadata within the route tree.
*/
export type SerializableRouteTreeNode = ReadonlyArray<RouteTreeNodeMetadata>;
/**
* Represents metadata for a route tree node, excluding the 'route' path segment.
*/
export type RouteTreeNodeMetadataWithoutRoute = Omit<RouteTreeNodeMetadata, 'route'>;
/**
* Describes metadata associated with a node in the route tree.
* This metadata includes information such as the route path and optional redirect instructions.
*/
export interface RouteTreeNodeMetadata {
/**
* Optional redirect path associated with this node.
* This defines where to redirect if this route is matched.
*/
redirectTo?: string;
/**
* The route path for this node.
*
* A "route" is a URL path or pattern that is used to navigate to different parts of a web application.
* It is made up of one or more segments separated by slashes `/`. For instance, in the URL `/products/details/42`,
* the full route is `/products/details/42`, with segments `products`, `details`, and `42`.
*
* Routes define how URLs map to views or components in an application. Each route segment contributes to
* the overall path that determines which view or component is displayed.
*
* - **Static Routes**: These routes have fixed segments. For example, `/about` or `/contact`.
* - **Parameterized Routes**: These include dynamic segments that act as placeholders, such as `/users/:id`,
* where `:id` could be any user ID.
*
* In the context of `RouteTreeNodeMetadata`, the `route` property represents the complete path that this node
* in the route tree corresponds to. This path is used to determine how a specific URL in the browser maps to the
* structure and content of the application.
*/
route: string;
/**
* Optional status code to return for this route.
*/
status?: number;
/**
* Optional additional headers to include in the response for this route.
*/
headers?: Record<string, string>;
/**
* Specifies the rendering mode used for this route.
* If not provided, the default rendering mode for the application will be used.
*/
renderMode?: RenderMode;
}
/**
* Represents a node within the route tree structure.
* Each node corresponds to a route segment and may have associated metadata and child nodes.
* The `AdditionalMetadata` type parameter allows for extending the node metadata with custom data.
*/
interface RouteTreeNode<AdditionalMetadata extends Record<string, unknown>> {
/**
* The segment value associated with this node.
* A segment is a single part of a route path, typically delimited by slashes (`/`).
* For example, in the route `/users/:id/profile`, the segments are `users`, `:id`, and `profile`.
* Segments can also be wildcards (`*`), which match any segment in that position of the route.
*/
segment: string;
/**
* The index indicating the order in which the route was inserted into the tree.
* This index helps determine the priority of routes during matching, with lower indexes
* indicating earlier inserted routes.
*/
insertionIndex: number;
/**
* A map of child nodes, keyed by their corresponding route segment or wildcard.
*/
children: Map<string, RouteTreeNode<AdditionalMetadata>>;
/**
* Optional metadata associated with this node, providing additional information such as redirects.
*/
metadata?: RouteTreeNodeMetadata & AdditionalMetadata;
}
/**
* A route tree implementation that supports efficient route matching, including support for wildcard routes.
* This structure is useful for organizing and retrieving routes in a hierarchical manner,
* enabling complex routing scenarios with nested paths.
*
* @typeParam AdditionalMetadata - Type of additional metadata that can be associated with route nodes.
*/ | {
"end_byte": 4270,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/src/routes/route-tree.ts"
} |
angular-cli/packages/angular/ssr/src/routes/route-tree.ts_4271_12294 | export class RouteTree<AdditionalMetadata extends Record<string, unknown> = {}> {
/**
* The root node of the route tree.
* All routes are stored and accessed relative to this root node.
*/
private readonly root = this.createEmptyRouteTreeNode('');
/**
* A counter that tracks the order of route insertion.
* This ensures that routes are matched in the order they were defined,
* with earlier routes taking precedence.
*/
private insertionIndexCounter = 0;
/**
* Inserts a new route into the route tree.
* The route is broken down into segments, and each segment is added to the tree.
* Parameterized segments (e.g., :id) are normalized to wildcards (*) for matching purposes.
*
* @param route - The route path to insert into the tree.
* @param metadata - Metadata associated with the route, excluding the route path itself.
*/
insert(route: string, metadata: RouteTreeNodeMetadataWithoutRoute & AdditionalMetadata): void {
let node = this.root;
const segments = this.getPathSegments(route);
for (const segment of segments) {
// Replace parameterized segments (e.g., :id) with a wildcard (*) for matching
const normalizedSegment = segment[0] === ':' ? '*' : segment;
let childNode = node.children.get(normalizedSegment);
if (!childNode) {
childNode = this.createEmptyRouteTreeNode(normalizedSegment);
node.children.set(normalizedSegment, childNode);
}
node = childNode;
}
// At the leaf node, store the full route and its associated metadata
node.metadata = {
...metadata,
route: segments.join('/'),
};
node.insertionIndex = this.insertionIndexCounter++;
}
/**
* Matches a given route against the route tree and returns the best matching route's metadata.
* The best match is determined by the lowest insertion index, meaning the earliest defined route
* takes precedence.
*
* @param route - The route path to match against the route tree.
* @returns The metadata of the best matching route or `undefined` if no match is found.
*/
match(route: string): (RouteTreeNodeMetadata & AdditionalMetadata) | undefined {
const segments = this.getPathSegments(route);
return this.traverseBySegments(segments)?.metadata;
}
/**
* Converts the route tree into a serialized format representation.
* This method converts the route tree into an array of metadata objects that describe the structure of the tree.
* The array represents the routes in a nested manner where each entry includes the route and its associated metadata.
*
* @returns An array of `RouteTreeNodeMetadata` objects representing the route tree structure.
* Each object includes the `route` and associated metadata of a route.
*/
toObject(): SerializableRouteTreeNode {
return Array.from(this.traverse());
}
/**
* Constructs a `RouteTree` from an object representation.
* This method is used to recreate a `RouteTree` instance from an array of metadata objects.
* The array should be in the format produced by `toObject`, allowing for the reconstruction of the route tree
* with the same routes and metadata.
*
* @param value - An array of `RouteTreeNodeMetadata` objects that represent the serialized format of the route tree.
* Each object should include a `route` and its associated metadata.
* @returns A new `RouteTree` instance constructed from the provided metadata objects.
*/
static fromObject(value: SerializableRouteTreeNode): RouteTree {
const tree = new RouteTree();
for (const { route, ...metadata } of value) {
tree.insert(route, metadata);
}
return tree;
}
/**
* A generator function that recursively traverses the route tree and yields the metadata of each node.
* This allows for easy and efficient iteration over all nodes in the tree.
*
* @param node - The current node to start the traversal from. Defaults to the root node of the tree.
*/
*traverse(node = this.root): Generator<RouteTreeNodeMetadata & AdditionalMetadata> {
if (node.metadata) {
yield node.metadata;
}
for (const childNode of node.children.values()) {
yield* this.traverse(childNode);
}
}
/**
* Extracts the path segments from a given route string.
*
* @param route - The route string from which to extract segments.
* @returns An array of path segments.
*/
private getPathSegments(route: string): string[] {
return stripTrailingSlash(route).split('/');
}
/**
* Recursively traverses the route tree from a given node, attempting to match the remaining route segments.
* If the node is a leaf node (no more segments to match) and contains metadata, the node is yielded.
*
* This function prioritizes exact segment matches first, followed by wildcard matches (`*`),
* and finally deep wildcard matches (`**`) that consume all segments.
*
* @param remainingSegments - The remaining segments of the route path to match.
* @param node - The current node in the route tree to start traversal from.
*
* @returns The node that best matches the remaining segments or `undefined` if no match is found.
*/
private traverseBySegments(
remainingSegments: string[] | undefined,
node = this.root,
): RouteTreeNode<AdditionalMetadata> | undefined {
const { metadata, children } = node;
// If there are no remaining segments and the node has metadata, return this node
if (!remainingSegments?.length) {
if (metadata) {
return node;
}
return;
}
// If the node has no children, end the traversal
if (!children.size) {
return;
}
const [segment, ...restSegments] = remainingSegments;
let currentBestMatchNode: RouteTreeNode<AdditionalMetadata> | undefined;
// 1. Exact segment match
const exactMatchNode = node.children.get(segment);
currentBestMatchNode = this.getHigherPriorityNode(
currentBestMatchNode,
this.traverseBySegments(restSegments, exactMatchNode),
);
// 2. Wildcard segment match (`*`)
const wildcardNode = node.children.get('*');
currentBestMatchNode = this.getHigherPriorityNode(
currentBestMatchNode,
this.traverseBySegments(restSegments, wildcardNode),
);
// 3. Deep wildcard segment match (`**`)
const deepWildcardNode = node.children.get('**');
currentBestMatchNode = this.getHigherPriorityNode(currentBestMatchNode, deepWildcardNode);
return currentBestMatchNode;
}
/**
* Compares two nodes and returns the node with higher priority based on insertion index.
* A node with a lower insertion index is prioritized as it was defined earlier.
*
* @param currentBestMatchNode - The current best match node.
* @param candidateNode - The node being evaluated for higher priority based on insertion index.
* @returns The node with higher priority (i.e., lower insertion index). If one of the nodes is `undefined`, the other node is returned.
*/
private getHigherPriorityNode(
currentBestMatchNode: RouteTreeNode<AdditionalMetadata> | undefined,
candidateNode: RouteTreeNode<AdditionalMetadata> | undefined,
): RouteTreeNode<AdditionalMetadata> | undefined {
if (!candidateNode) {
return currentBestMatchNode;
}
if (!currentBestMatchNode) {
return candidateNode;
}
return candidateNode.insertionIndex < currentBestMatchNode.insertionIndex
? candidateNode
: currentBestMatchNode;
}
/**
* Creates an empty route tree node with the specified segment.
* This helper function is used during the tree construction.
*
* @param segment - The route segment that this node represents.
* @returns A new, empty route tree node.
*/
private createEmptyRouteTreeNode(segment: string): RouteTreeNode<AdditionalMetadata> {
return {
segment,
insertionIndex: -1,
children: new Map(),
};
}
} | {
"end_byte": 12294,
"start_byte": 4271,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/ssr/src/routes/route-tree.ts"
} |
angular-cli/packages/angular/pwa/README.md_0_1148 | # `@angular/pwa`
This is a [schematic](https://angular.dev/tools/cli/schematics) for adding
[Progressive Web App](https://web.dev/progressive-web-apps/) support to an Angular project. Run the
schematic with the [Angular CLI](https://angular.dev/tools/cli):
```shell
ng add @angular/pwa --project <project-name>
```
Executing the command mentioned above will perform the following actions:
1. Adds [`@angular/service-worker`](https://npmjs.com/@angular/service-worker) as a dependency to your project.
1. Enables service worker builds in the Angular CLI.
1. Imports and registers the service worker in the application module.
1. Updates the `index.html` file:
- Includes a link to add the [manifest.webmanifest](https://developer.mozilla.org/en-US/docs/Web/Manifest) file.
- Adds a meta tag for `theme-color`.
1. Installs icon files to support the installed Progressive Web App (PWA).
1. Creates the service worker configuration file called `ngsw-config.json`, specifying caching behaviors and other settings.
See [Getting started with service workers](https://angular.dev/ecosystem/service-workers/getting-started)
for more information.
| {
"end_byte": 1148,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/pwa/README.md"
} |
angular-cli/packages/angular/pwa/BUILD.bazel_0_1674 | # Copyright Google Inc. 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
load("@npm//@bazel/jasmine:index.bzl", "jasmine_node_test")
load("//tools:defaults.bzl", "pkg_npm", "ts_library")
load("//tools:ts_json_schema.bzl", "ts_json_schema")
licenses(["notice"])
package(default_visibility = ["//visibility:public"])
ts_library(
name = "pwa",
package_name = "@angular/pwa",
srcs = [
"pwa/index.ts",
"//packages/angular/pwa:pwa/schema.ts",
],
data = [
"collection.json",
"pwa/schema.json",
] + glob(
include = [
"pwa/files/**/*",
],
),
deps = [
"//packages/angular_devkit/schematics",
"//packages/schematics/angular",
"@npm//@types/node",
"@npm//parse5-html-rewriting-stream",
],
)
ts_json_schema(
name = "pwa_schema",
src = "pwa/schema.json",
)
ts_library(
name = "pwa_test_lib",
testonly = True,
srcs = glob(["pwa/**/*_spec.ts"]),
deps = [
":pwa",
"//packages/angular_devkit/schematics/testing",
],
)
jasmine_node_test(
name = "pwa_test",
srcs = [":pwa_test_lib"],
)
genrule(
name = "license",
srcs = ["//:LICENSE"],
outs = ["LICENSE"],
cmd = "cp $(execpath //:LICENSE) $@",
)
pkg_npm(
name = "npm_package",
pkg_deps = [
"//packages/angular_devkit/schematics:package.json",
"//packages/schematics/angular:package.json",
],
tags = ["release-package"],
deps = [
":README.md",
":license",
":pwa",
],
)
| {
"end_byte": 1674,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/pwa/BUILD.bazel"
} |
angular-cli/packages/angular/pwa/pwa/index.ts_0_5814 | /**
* @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 {
Rule,
SchematicsException,
Tree,
apply,
chain,
externalSchematic,
mergeWith,
move,
template,
url,
} from '@angular-devkit/schematics';
import { readWorkspace, writeWorkspace } from '@schematics/angular/utility';
import { posix } from 'path';
import { Readable } from 'stream';
import { pipeline } from 'stream/promises';
import { Schema as PwaOptions } from './schema';
function updateIndexFile(path: string): Rule {
return async (host: Tree) => {
const originalContent = host.readText(path);
const { RewritingStream } = await loadEsmModule<typeof import('parse5-html-rewriting-stream')>(
'parse5-html-rewriting-stream',
);
const rewriter = new RewritingStream();
let needsNoScript = true;
rewriter.on('startTag', (startTag) => {
if (startTag.tagName === 'noscript') {
needsNoScript = false;
}
rewriter.emitStartTag(startTag);
});
rewriter.on('endTag', (endTag) => {
if (endTag.tagName === 'head') {
rewriter.emitRaw(' <link rel="manifest" href="manifest.webmanifest">\n');
rewriter.emitRaw(' <meta name="theme-color" content="#1976d2">\n');
} else if (endTag.tagName === 'body' && needsNoScript) {
rewriter.emitRaw(
' <noscript>Please enable JavaScript to continue using this application.</noscript>\n',
);
}
rewriter.emitEndTag(endTag);
});
return pipeline(Readable.from(originalContent), rewriter, async function (source) {
const chunks = [];
for await (const chunk of source) {
chunks.push(Buffer.from(chunk));
}
host.overwrite(path, Buffer.concat(chunks));
});
};
}
export default function (options: PwaOptions): Rule {
return async (host) => {
if (!options.title) {
options.title = options.project;
}
const workspace = await readWorkspace(host);
if (!options.project) {
throw new SchematicsException('Option "project" is required.');
}
const project = workspace.projects.get(options.project);
if (!project) {
throw new SchematicsException(`Project is not defined in this workspace.`);
}
if (project.extensions['projectType'] !== 'application') {
throw new SchematicsException(`PWA requires a project type of "application".`);
}
// Find all the relevant targets for the project
if (project.targets.size === 0) {
throw new SchematicsException(`Targets are not defined for this project.`);
}
const buildTargets = [];
const testTargets = [];
for (const target of project.targets.values()) {
if (
target.builder === '@angular-devkit/build-angular:browser' ||
target.builder === '@angular-devkit/build-angular:application'
) {
buildTargets.push(target);
} else if (target.builder === '@angular-devkit/build-angular:karma') {
testTargets.push(target);
}
}
// Find all index.html files in build targets
const indexFiles = new Set<string>();
for (const target of buildTargets) {
if (typeof target.options?.index === 'string') {
indexFiles.add(target.options.index);
}
if (!target.configurations) {
continue;
}
for (const options of Object.values(target.configurations)) {
if (typeof options?.index === 'string') {
indexFiles.add(options.index);
}
}
}
// Setup sources for the assets files to add to the project
const sourcePath = project.sourceRoot ?? posix.join(project.root, 'src');
// Setup service worker schematic options
const { title, ...swOptions } = options;
await writeWorkspace(host, workspace);
let assetsDir = posix.join(sourcePath, 'assets');
let iconsPath: string;
if (host.exists(assetsDir)) {
// Add manifest to asset configuration
const assetEntry = posix.join(
project.sourceRoot ?? posix.join(project.root, 'src'),
'manifest.webmanifest',
);
for (const target of [...buildTargets, ...testTargets]) {
if (target.options) {
if (Array.isArray(target.options.assets)) {
target.options.assets.push(assetEntry);
} else {
target.options.assets = [assetEntry];
}
} else {
target.options = { assets: [assetEntry] };
}
}
iconsPath = 'assets';
} else {
assetsDir = posix.join(project.root, 'public');
iconsPath = 'icons';
}
return chain([
externalSchematic('@schematics/angular', 'service-worker', swOptions),
mergeWith(
apply(url('./files/assets'), [template({ ...options, iconsPath }), move(assetsDir)]),
),
...[...indexFiles].map((path) => updateIndexFile(path)),
]);
};
}
/**
* This uses a dynamic import to load a module which may be ESM.
* CommonJS code can load ESM code via a dynamic import. Unfortunately, TypeScript
* will currently, unconditionally downlevel dynamic import into a require call.
* require calls cannot load ESM code and will result in a runtime error. To workaround
* this, a Function constructor is used to prevent TypeScript from changing the dynamic import.
* Once TypeScript provides support for keeping the dynamic import this workaround can
* be dropped.
*
* @param modulePath The path of the module to load.
* @returns A Promise that resolves to the dynamically imported module.
*/
function loadEsmModule<T>(modulePath: string | URL): Promise<T> {
return new Function('modulePath', `return import(modulePath);`)(modulePath) as Promise<T>;
}
| {
"end_byte": 5814,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/pwa/pwa/index.ts"
} |
angular-cli/packages/angular/pwa/pwa/index_spec.ts_0_6136 | /**
* @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 { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing';
import * as path from 'path';
import { Schema as PwaOptions } from './schema';
describe('PWA Schematic', () => {
const schematicRunner = new SchematicTestRunner(
'@angular/pwa',
require.resolve(path.join(__dirname, '../collection.json')),
);
const defaultOptions: PwaOptions = {
project: 'bar',
target: 'build',
title: 'Fake Title',
};
let appTree: UnitTestTree;
const workspaceOptions = {
name: 'workspace',
newProjectRoot: 'projects',
version: '6.0.0',
};
const appOptions = {
name: 'bar',
inlineStyle: false,
inlineTemplate: false,
routing: false,
style: 'css',
skipTests: false,
};
beforeEach(async () => {
appTree = await schematicRunner.runExternalSchematic(
'@schematics/angular',
'workspace',
workspaceOptions,
);
appTree = await schematicRunner.runExternalSchematic(
'@schematics/angular',
'application',
appOptions,
appTree,
);
});
it('should create icon files', async () => {
const dimensions = [72, 96, 128, 144, 152, 192, 384, 512];
const iconPath = '/projects/bar/public/icons/icon-';
const tree = await schematicRunner.runSchematic('ng-add', defaultOptions, appTree);
dimensions.forEach((d) => {
const path = `${iconPath}${d}x${d}.png`;
expect(tree.exists(path)).toBeTrue();
});
});
it('should reference the icons in the manifest correctly', async () => {
const tree = await schematicRunner.runSchematic('ng-add', defaultOptions, appTree);
const manifestText = tree.readContent('/projects/bar/public/manifest.webmanifest');
const manifest = JSON.parse(manifestText);
for (const icon of manifest.icons) {
expect(icon.src).toMatch(/^icons\/icon-\d+x\d+.png/);
}
});
it('should run the service worker schematic', async () => {
const tree = await schematicRunner.runSchematic('ng-add', defaultOptions, appTree);
const configText = tree.readContent('/angular.json');
const config = JSON.parse(configText);
const swFlag = config.projects.bar.architect.build.configurations.production.serviceWorker;
expect(swFlag).toBe('projects/bar/ngsw-config.json');
});
it('should create a manifest file', async () => {
const tree = await schematicRunner.runSchematic('ng-add', defaultOptions, appTree);
expect(tree.exists('/projects/bar/public/manifest.webmanifest')).toBeTrue();
});
it('should set the name & short_name in the manifest file', async () => {
const tree = await schematicRunner.runSchematic('ng-add', defaultOptions, appTree);
const manifestText = tree.readContent('/projects/bar/public/manifest.webmanifest');
const manifest = JSON.parse(manifestText);
expect(manifest.name).toEqual(defaultOptions.title);
expect(manifest.short_name).toEqual(defaultOptions.title);
});
it('should set the name & short_name in the manifest file when no title provided', async () => {
const options = { ...defaultOptions, title: undefined };
const tree = await schematicRunner.runSchematic('ng-add', options, appTree);
const manifestText = tree.readContent('/projects/bar/public/manifest.webmanifest');
const manifest = JSON.parse(manifestText);
expect(manifest.name).toEqual(defaultOptions.project);
expect(manifest.short_name).toEqual(defaultOptions.project);
});
it('should update the index file', async () => {
const tree = await schematicRunner.runSchematic('ng-add', defaultOptions, appTree);
const content = tree.readContent('projects/bar/src/index.html');
expect(content).toMatch(/<link rel="manifest" href="manifest.webmanifest">/);
expect(content).toMatch(/<meta name="theme-color" content="#1976d2">/);
expect(content).toMatch(
/<noscript>Please enable JavaScript to continue using this application.<\/noscript>/,
);
});
it('should not add noscript element to the index file if already present', async () => {
let index = appTree.readContent('projects/bar/src/index.html');
index = index.replace('</body>', '<noscript>NO JAVASCRIPT</noscript></body>');
appTree.overwrite('projects/bar/src/index.html', index);
const tree = await schematicRunner.runSchematic('ng-add', defaultOptions, appTree);
const content = tree.readContent('projects/bar/src/index.html');
expect(content).toMatch(/<link rel="manifest" href="manifest.webmanifest">/);
expect(content).toMatch(/<meta name="theme-color" content="#1976d2">/);
expect(content).not.toMatch(
/<noscript>Please enable JavaScript to continue using this application.<\/noscript>/,
);
expect(content).toMatch(/<noscript>NO JAVASCRIPT<\/noscript>/);
});
describe('Legacy browser builder', () => {
function convertBuilderToLegacyBrowser(): void {
const config = JSON.parse(appTree.readContent('/angular.json'));
const build = config.projects.bar.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,
};
appTree.overwrite('/angular.json', JSON.stringify(config, undefined, 2));
}
beforeEach(() => {
convertBuilderToLegacyBrowser();
});
it('should run the service worker schematic', async () => {
const tree = await schematicRunner.runSchematic('ng-add', defaultOptions, appTree);
const configText = tree.readContent('/angular.json');
const config = JSON.parse(configText);
const swFlag = config.projects.bar.architect.build.options.serviceWorker;
expect(swFlag).toBeTrue();
});
});
});
| {
"end_byte": 6136,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/pwa/pwa/index_spec.ts"
} |
angular-cli/packages/angular/pwa/pwa/files/assets/manifest.webmanifest_0_1380 | {
"name": "<%= title %>",
"short_name": "<%= title %>",
"theme_color": "#1976d2",
"background_color": "#fafafa",
"display": "standalone",
"scope": "./",
"start_url": "./",
"icons": [
{
"src": "<%= iconsPath %>/icon-72x72.png",
"sizes": "72x72",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "<%= iconsPath %>/icon-96x96.png",
"sizes": "96x96",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "<%= iconsPath %>/icon-128x128.png",
"sizes": "128x128",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "<%= iconsPath %>/icon-144x144.png",
"sizes": "144x144",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "<%= iconsPath %>/icon-152x152.png",
"sizes": "152x152",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "<%= iconsPath %>/icon-192x192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "<%= iconsPath %>/icon-384x384.png",
"sizes": "384x384",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "<%= iconsPath %>/icon-512x512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable any"
}
]
}
| {
"end_byte": 1380,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/pwa/pwa/files/assets/manifest.webmanifest"
} |
angular-cli/packages/angular/build/README.md_0_326 | # Angular Build System for Applications and Libraries
The sources for this package are in the [Angular CLI](https://github.com/angular/angular-cli) repository. Please file issues and pull requests against that repository.
Usage information and reference details can be found in repository [README](../../../README.md) file.
| {
"end_byte": 326,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/README.md"
} |
angular-cli/packages/angular/build/BUILD.bazel_0_5530 | load("@npm//@angular/build-tooling/bazel/api-golden:index.bzl", "api_golden_test_npm_package")
load("@npm//@bazel/jasmine:index.bzl", "jasmine_node_test")
load("//tools:defaults.bzl", "pkg_npm", "ts_library")
load("//tools:ts_json_schema.bzl", "ts_json_schema")
licenses(["notice"])
package(default_visibility = ["//visibility:public"])
ts_json_schema(
name = "application_schema",
src = "src/builders/application/schema.json",
)
ts_json_schema(
name = "dev-server_schema",
src = "src/builders/dev-server/schema.json",
)
ts_json_schema(
name = "extract_i18n_schema",
src = "src/builders/extract-i18n/schema.json",
)
ts_library(
name = "build",
package_name = "@angular/build",
srcs = glob(
include = [
"src/**/*.ts",
],
exclude = [
"src/test-utils.ts",
"src/**/*_spec.ts",
"src/**/tests/**/*.ts",
"src/testing/**/*.ts",
"src/private.ts",
],
) + [
"//packages/angular/build:src/builders/application/schema.ts",
"//packages/angular/build:src/builders/dev-server/schema.ts",
"//packages/angular/build:src/builders/extract-i18n/schema.ts",
],
data = glob(
include = [
"src/**/schema.json",
"src/**/*.js",
"src/**/*.mjs",
"src/**/*.html",
],
) + [
"builders.json",
"package.json",
],
module_name = "@angular/build",
module_root = "src/index.d.ts",
deps = [
"//packages/angular/ssr",
"//packages/angular/ssr/node",
"//packages/angular_devkit/architect",
"@npm//@ampproject/remapping",
"@npm//@angular/common",
"@npm//@angular/compiler",
"@npm//@angular/compiler-cli",
"@npm//@angular/core",
"@npm//@angular/localize",
"@npm//@angular/platform-server",
"@npm//@angular/service-worker",
"@npm//@babel/core",
"@npm//@babel/helper-annotate-as-pure",
"@npm//@babel/helper-split-export-declaration",
"@npm//@babel/plugin-syntax-import-attributes",
"@npm//@inquirer/confirm",
"@npm//@types/babel__core",
"@npm//@types/less",
"@npm//@types/node",
"@npm//@types/picomatch",
"@npm//@types/semver",
"@npm//@types/watchpack",
"@npm//@vitejs/plugin-basic-ssl",
"@npm//beasties",
"@npm//browserslist",
"@npm//esbuild",
"@npm//esbuild-wasm",
"@npm//fast-glob",
"@npm//https-proxy-agent",
"@npm//listr2",
"@npm//lmdb",
"@npm//magic-string",
"@npm//mrmime",
"@npm//parse5-html-rewriting-stream",
"@npm//picomatch",
"@npm//piscina",
"@npm//postcss",
"@npm//rollup",
"@npm//sass",
"@npm//semver",
"@npm//tslib",
"@npm//typescript",
"@npm//vite",
"@npm//watchpack",
],
)
ts_library(
name = "private",
srcs = ["src/private.ts"],
module_name = "@angular/build/private",
module_root = "src/private.d.ts",
deps = [
"//packages/angular/build",
],
)
ts_library(
name = "unit_test_lib",
testonly = True,
srcs = glob(
include = ["src/**/*_spec.ts"],
exclude = ["src/builders/**/tests/**"],
),
deps = [
":build",
":private",
"//packages/angular_devkit/core",
"//packages/angular_devkit/core/node",
"@npm//@angular/compiler-cli",
"@npm//@babel/core",
"@npm//prettier",
],
)
jasmine_node_test(
name = "unit_tests",
deps = [":unit_test_lib"],
)
ts_library(
name = "integration_test_lib",
testonly = True,
srcs = glob(include = ["src/builders/**/tests/**/*.ts"]),
deps = [
":build",
":private",
"//modules/testing/builder",
"//packages/angular_devkit/architect",
"//packages/angular_devkit/architect/node",
"//packages/angular_devkit/architect/testing",
"//packages/angular_devkit/core",
"//packages/angular_devkit/core/node",
# dev server only test deps
"@npm//@types/http-proxy",
"@npm//http-proxy",
"@npm//puppeteer",
# Base dependencies for the application in hello-world-app.
"@npm//@angular/common",
"@npm//@angular/compiler",
"@npm//@angular/compiler-cli",
"@npm//@angular/core",
"@npm//@angular/platform-browser",
"@npm//@angular/platform-browser-dynamic",
"@npm//@angular/router",
"@npm//rxjs",
"@npm//tslib",
"@npm//typescript",
"@npm//zone.js",
"@npm//buffer",
],
)
jasmine_node_test(
name = "integration_tests",
size = "large",
flaky = True,
shard_count = 10,
deps = [":integration_test_lib"],
)
genrule(
name = "license",
srcs = ["//:LICENSE"],
outs = ["LICENSE"],
cmd = "cp $(execpath //:LICENSE) $@",
)
pkg_npm(
name = "npm_package",
pkg_deps = [
"//packages/angular_devkit/architect:package.json",
],
tags = ["release-package"],
deps = [
":README.md",
":build",
":license",
":private",
],
)
api_golden_test_npm_package(
name = "api",
data = [
":npm_package",
"//goldens:public-api",
],
golden_dir = "angular_cli/goldens/public-api/angular/build",
npm_package = "angular_cli/packages/angular/build/npm_package",
)
| {
"end_byte": 5530,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/BUILD.bazel"
} |
angular-cli/packages/angular/build/src/private.ts_0_2657 | /**
* @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
*/
/**
* @fileoverview
* Private exports intended only for use with the @angular-devkit/build-angular package.
* All exports are not supported for external use, do not provide SemVer guarantees, and
* their existence may change in any future version.
*/
// Builders
export { buildApplicationInternal } from './builders/application';
export type { ApplicationBuilderInternalOptions } from './builders/application/options';
export { type Result, type ResultFile, ResultKind } from './builders/application/results';
export { serveWithVite } from './builders/dev-server/vite-server';
// Tools
export * from './tools/babel/plugins';
export type { ExternalResultMetadata } from './tools/esbuild/bundler-execution-result';
export { emitFilesToDisk } from './tools/esbuild/utils';
export { transformSupportedBrowsersToTargets } from './tools/esbuild/utils';
export { SassWorkerImplementation } from './tools/sass/sass-service';
export { SourceFileCache } from './tools/esbuild/angular/source-file-cache';
export { createJitResourceTransformer } from './tools/angular/transformers/jit-resource-transformer';
export { JavaScriptTransformer } from './tools/esbuild/javascript-transformer';
export { createCompilerPlugin } from './tools/esbuild/angular/compiler-plugin';
// Utilities
export * from './utils/bundle-calculator';
export { checkPort } from './utils/check-port';
export { deleteOutputDir } from './utils/delete-output-dir';
export { type I18nOptions, createI18nOptions, loadTranslations } from './utils/i18n-options';
export {
IndexHtmlGenerator,
type IndexHtmlGeneratorOptions,
type IndexHtmlGeneratorProcessOptions,
type IndexHtmlTransform,
} from './utils/index-file/index-html-generator';
export type { FileInfo } from './utils/index-file/augment-index-html';
export {
type InlineCriticalCssProcessOptions,
InlineCriticalCssProcessor,
type InlineCriticalCssProcessorOptions,
} from './utils/index-file/inline-critical-css';
export { loadProxyConfiguration } from './utils/load-proxy-config';
export { type TranslationLoader, createTranslationLoader } from './utils/load-translations';
export { purgeStaleBuildCache } from './utils/purge-cache';
export { augmentAppWithServiceWorker } from './utils/service-worker';
export { type BundleStats, generateBuildStatsTable } from './utils/stats-table';
export { getSupportedBrowsers } from './utils/supported-browsers';
export { assertCompatibleAngularVersion } from './utils/version';
| {
"end_byte": 2657,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/private.ts"
} |
angular-cli/packages/angular/build/src/typings.d.ts_0_835 | /**
* @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
*/
// The `bundled_beasties` causes issues with module mappings in Bazel,
// leading to unexpected behavior with esbuild. Specifically, the problem occurs
// when esbuild resolves to a different module or version than expected, due to
// how Bazel handles module mappings.
//
// This change aims to resolve esbuild types correctly and maintain consistency
// in the Bazel build process.
declare module 'esbuild' {
export * from 'esbuild-wasm';
}
/**
* Augment the Node.js module builtin types to support the v22.8+ compile cache functions
*/
declare module 'node:module' {
function getCompileCacheDir(): string | undefined;
}
| {
"end_byte": 835,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/typings.d.ts"
} |
angular-cli/packages/angular/build/src/index.ts_0_758 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export {
buildApplication,
type ApplicationBuilderOptions,
type ApplicationBuilderOutput,
} from './builders/application';
export { type BuildOutputFile, BuildOutputFileType } from './tools/esbuild/bundler-context';
export type { BuildOutputAsset } from './tools/esbuild/bundler-execution-result';
export {
executeDevServerBuilder,
type DevServerBuilderOptions,
type DevServerBuilderOutput,
} from './builders/dev-server';
export {
execute as executeExtractI18nBuilder,
type ExtractI18nBuilderOptions,
} from './builders/extract-i18n';
| {
"end_byte": 758,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/index.ts"
} |
angular-cli/packages/angular/build/src/tools/angular/angular-host.ts_0_8041 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import type ng from '@angular/compiler-cli';
import assert from 'node:assert';
import { createHash } from 'node:crypto';
import nodePath from 'node:path';
import type ts from 'typescript';
export type AngularCompilerOptions = ng.CompilerOptions;
export type AngularCompilerHost = ng.CompilerHost;
export interface AngularHostOptions {
fileReplacements?: Record<string, string>;
sourceFileCache?: Map<string, ts.SourceFile>;
modifiedFiles?: Set<string>;
externalStylesheets?: Map<string, string>;
transformStylesheet(
data: string,
containingFile: string,
stylesheetFile?: string,
order?: number,
className?: string,
): Promise<string | null>;
processWebWorker(workerFile: string, containingFile: string): string;
}
/**
* Patches in-place the `getSourceFiles` function on an instance of a TypeScript
* `Program` to ensure that all returned SourceFile instances have a `version`
* field. The `version` field is required when used with a TypeScript BuilderProgram.
* @param program The TypeScript Program instance to patch.
*/
export function ensureSourceFileVersions(program: ts.Program): void {
const baseGetSourceFiles = program.getSourceFiles;
// TODO: Update Angular compiler to add versions to all internal files and remove this
program.getSourceFiles = function (...parameters) {
const files: readonly (ts.SourceFile & { version?: string })[] = baseGetSourceFiles(
...parameters,
);
for (const file of files) {
if (file.version === undefined) {
file.version = createHash('sha256').update(file.text).digest('hex');
}
}
return files;
};
}
function augmentHostWithCaching(host: ts.CompilerHost, cache: Map<string, ts.SourceFile>): void {
const baseGetSourceFile = host.getSourceFile;
host.getSourceFile = function (
fileName,
languageVersion,
onError,
shouldCreateNewSourceFile,
...parameters
) {
if (!shouldCreateNewSourceFile && cache.has(fileName)) {
return cache.get(fileName);
}
const file = baseGetSourceFile.call(
host,
fileName,
languageVersion,
onError,
true,
...parameters,
);
if (file) {
cache.set(fileName, file);
}
return file;
};
}
function augmentResolveModuleNames(
typescript: typeof ts,
host: ts.CompilerHost,
resolvedModuleModifier: (
resolvedModule: ts.ResolvedModule | undefined,
moduleName: string,
) => ts.ResolvedModule | undefined,
moduleResolutionCache?: ts.ModuleResolutionCache,
): void {
if (host.resolveModuleNames) {
const baseResolveModuleNames = host.resolveModuleNames;
host.resolveModuleNames = function (moduleNames: string[], ...parameters) {
return moduleNames.map((name) => {
const result = baseResolveModuleNames.call(host, [name], ...parameters);
return resolvedModuleModifier(result[0], name);
});
};
} else {
host.resolveModuleNames = function (
moduleNames: string[],
containingFile: string,
_reusedNames: string[] | undefined,
redirectedReference: ts.ResolvedProjectReference | undefined,
options: ts.CompilerOptions,
) {
return moduleNames.map((name) => {
const result = typescript.resolveModuleName(
name,
containingFile,
options,
host,
moduleResolutionCache,
redirectedReference,
).resolvedModule;
return resolvedModuleModifier(result, name);
});
};
}
}
function normalizePath(path: string): string {
return nodePath.win32.normalize(path).replace(/\\/g, nodePath.posix.sep);
}
function augmentHostWithReplacements(
typescript: typeof ts,
host: ts.CompilerHost,
replacements: Record<string, string>,
moduleResolutionCache?: ts.ModuleResolutionCache,
): void {
if (Object.keys(replacements).length === 0) {
return;
}
const normalizedReplacements: Record<string, string> = {};
for (const [key, value] of Object.entries(replacements)) {
normalizedReplacements[normalizePath(key)] = normalizePath(value);
}
const tryReplace = (resolvedModule: ts.ResolvedModule | undefined) => {
const replacement = resolvedModule && normalizedReplacements[resolvedModule.resolvedFileName];
if (replacement) {
return {
resolvedFileName: replacement,
isExternalLibraryImport: /[/\\]node_modules[/\\]/.test(replacement),
};
} else {
return resolvedModule;
}
};
augmentResolveModuleNames(typescript, host, tryReplace, moduleResolutionCache);
}
export function createAngularCompilerHost(
typescript: typeof ts,
compilerOptions: AngularCompilerOptions,
hostOptions: AngularHostOptions,
): AngularCompilerHost {
// Create TypeScript compiler host
const host: AngularCompilerHost = typescript.createIncrementalCompilerHost(compilerOptions);
// Set the parsing mode to the same as TS 5.3+ default for tsc. This provides a parse
// performance improvement by skipping non-type related JSDoc parsing.
host.jsDocParsingMode = typescript.JSDocParsingMode.ParseForTypeErrors;
// The AOT compiler currently requires this hook to allow for a transformResource hook.
// Once the AOT compiler allows only a transformResource hook, this can be reevaluated.
host.readResource = async function (filename) {
return this.readFile(filename) ?? '';
};
// Add an AOT compiler resource transform hook
host.transformResource = async function (data, context) {
// Only style resources are transformed currently
if (context.type !== 'style') {
return null;
}
assert(
!context.resourceFile || !hostOptions.externalStylesheets?.has(context.resourceFile),
'External runtime stylesheets should not be transformed: ' + context.resourceFile,
);
// No transformation required if the resource is empty
if (data.trim().length === 0) {
return { content: '' };
}
const result = await hostOptions.transformStylesheet(
data,
context.containingFile,
context.resourceFile ?? undefined,
context.order,
context.className,
);
return typeof result === 'string' ? { content: result } : null;
};
host.resourceNameToFileName = function (resourceName, containingFile) {
const resolvedPath = nodePath.join(nodePath.dirname(containingFile), resourceName);
// All resource names that have HTML file extensions are assumed to be templates
if (resourceName.endsWith('.html') || !hostOptions.externalStylesheets) {
return resolvedPath;
}
// For external stylesheets, create a unique identifier and store the mapping
let externalId = hostOptions.externalStylesheets.get(resolvedPath);
if (externalId === undefined) {
externalId = createHash('sha256').update(resolvedPath).digest('hex');
hostOptions.externalStylesheets.set(resolvedPath, externalId);
}
return externalId + '.css';
};
// Allow the AOT compiler to request the set of changed templates and styles
host.getModifiedResourceFiles = function () {
return hostOptions.modifiedFiles;
};
// Augment TypeScript Host for file replacements option
if (hostOptions.fileReplacements) {
// Provide a resolution cache since overriding resolution prevents automatic creation
const resolutionCache = typescript.createModuleResolutionCache(
host.getCurrentDirectory(),
host.getCanonicalFileName.bind(host),
compilerOptions,
);
host.getModuleResolutionCache = () => resolutionCache;
augmentHostWithReplacements(typescript, host, hostOptions.fileReplacements, resolutionCache);
}
// Augment TypeScript Host with source file caching if provided
if (hostOptions.sourceFileCache) {
augmentHostWithCaching(host, hostOptions.sourceFileCache);
}
return host;
}
| {
"end_byte": 8041,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/angular/angular-host.ts"
} |
angular-cli/packages/angular/build/src/tools/angular/uri.ts_0_2944 | /**
* @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
*/
/**
* A string value representing the base namespace for Angular JIT mode related imports.
*/
const JIT_BASE_NAMESPACE = 'angular:jit';
/**
* A string value representing the namespace for Angular JIT mode related imports for
* Component styles. This namespace is used for both inline (`styles`) and external
* (`styleUrls`) styles.
*/
export const JIT_STYLE_NAMESPACE = `${JIT_BASE_NAMESPACE}:style` as const;
/**
* A string value representing the namespace for Angular JIT mode related imports for
* Component templates. This namespace is currently only used for external (`templateUrl`)
* templates.
*/
export const JIT_TEMPLATE_NAMESPACE = `${JIT_BASE_NAMESPACE}:template` as const;
/**
* A regular expression that can be used to match a Angular JIT mode namespace URI.
* It contains capture groups for the type (template/style), origin (file/inline), and specifier.
* The {@link parseJitUri} function can be used to parse and return an object representation of a JIT URI.
*/
export const JIT_NAMESPACE_REGEXP = new RegExp(
`^${JIT_BASE_NAMESPACE}:(template|style):(file|inline);(.*)$`,
);
/**
* Generates an Angular JIT mode namespace URI for a given file.
* @param file The path of the file to be included.
* @param type The type of the file (`style` or `template`).
* @returns A string containing the full JIT namespace URI.
*/
export function generateJitFileUri(file: string, type: 'style' | 'template') {
return `${JIT_BASE_NAMESPACE}:${type}:file;${file}`;
}
/**
* Generates an Angular JIT mode namespace URI for a given inline style or template.
* The provided content is base64 encoded and included in the URI.
* @param data The content to encode within the URI.
* @param type The type of the content (`style` or `template`).
* @returns A string containing the full JIT namespace URI.
*/
export function generateJitInlineUri(data: string | Uint8Array, type: 'style' | 'template') {
return `${JIT_BASE_NAMESPACE}:${type}:inline;${Buffer.from(data).toString('base64')}`;
}
/**
* Parses a string containing a JIT namespace URI.
* JIT namespace URIs are used to encode the information for an Angular component's stylesheets
* and templates when compiled in JIT mode.
* @param uri The URI to parse into its underlying components.
* @returns An object containing the namespace, type, origin, and specifier of the URI;
* `undefined` if not a JIT namespace URI.
*/
export function parseJitUri(uri: string) {
const matches = JIT_NAMESPACE_REGEXP.exec(uri);
if (!matches) {
return undefined;
}
return {
namespace: `${JIT_BASE_NAMESPACE}:${matches[1]}`,
type: matches[1] as 'style' | 'template',
origin: matches[2] as 'file' | 'inline',
specifier: matches[3],
};
}
| {
"end_byte": 2944,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/angular/uri.ts"
} |
angular-cli/packages/angular/build/src/tools/angular/transformers/jit-resource-transformer.ts_0_9699 | /**
* @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 ts from 'typescript';
import { generateJitFileUri, generateJitInlineUri } from '../uri';
/**
* Creates a TypeScript Transformer to transform Angular Component resource references into
* static import statements. This transformer is used in Angular's JIT compilation mode to
* support processing of component resources. When in AOT mode, the Angular AOT compiler handles
* this processing and this transformer is not used.
* @param getTypeChecker A function that returns a TypeScript TypeChecker instance for the program.
* @returns A TypeScript transformer factory.
*/
export function createJitResourceTransformer(
getTypeChecker: () => ts.TypeChecker,
): ts.TransformerFactory<ts.SourceFile> {
return (context: ts.TransformationContext) => {
const typeChecker = getTypeChecker();
const nodeFactory = context.factory;
const resourceImportDeclarations: ts.ImportDeclaration[] = [];
const visitNode: ts.Visitor = (node: ts.Node) => {
if (ts.isClassDeclaration(node)) {
const decorators = ts.getDecorators(node);
if (!decorators || decorators.length === 0) {
return node;
}
return nodeFactory.updateClassDeclaration(
node,
[
...decorators.map((current) =>
visitDecorator(nodeFactory, current, typeChecker, resourceImportDeclarations),
),
...(ts.getModifiers(node) ?? []),
],
node.name,
node.typeParameters,
node.heritageClauses,
node.members,
);
}
return ts.visitEachChild(node, visitNode, context);
};
return (sourceFile) => {
const updatedSourceFile = ts.visitEachChild(sourceFile, visitNode, context);
if (resourceImportDeclarations.length > 0) {
return nodeFactory.updateSourceFile(
updatedSourceFile,
ts.setTextRange(
nodeFactory.createNodeArray(
[...resourceImportDeclarations, ...updatedSourceFile.statements],
updatedSourceFile.statements.hasTrailingComma,
),
updatedSourceFile.statements,
),
updatedSourceFile.isDeclarationFile,
updatedSourceFile.referencedFiles,
updatedSourceFile.typeReferenceDirectives,
updatedSourceFile.hasNoDefaultLib,
updatedSourceFile.libReferenceDirectives,
);
} else {
return updatedSourceFile;
}
};
};
}
function visitDecorator(
nodeFactory: ts.NodeFactory,
node: ts.Decorator,
typeChecker: ts.TypeChecker,
resourceImportDeclarations: ts.ImportDeclaration[],
): ts.Decorator {
const origin = getDecoratorOrigin(node, typeChecker);
if (!origin || origin.module !== '@angular/core' || origin.name !== 'Component') {
return node;
}
if (!ts.isCallExpression(node.expression)) {
return node;
}
const decoratorFactory = node.expression;
const args = decoratorFactory.arguments;
if (args.length !== 1 || !ts.isObjectLiteralExpression(args[0])) {
// Unsupported component metadata
return node;
}
const objectExpression = args[0];
const styleReplacements: ts.Expression[] = [];
// visit all properties
let properties = ts.visitNodes(objectExpression.properties, (node) =>
ts.isObjectLiteralElementLike(node)
? visitComponentMetadata(nodeFactory, node, styleReplacements, resourceImportDeclarations)
: node,
) as ts.NodeArray<ts.ObjectLiteralElementLike>;
// replace properties with updated properties
if (styleReplacements.length > 0) {
const styleProperty = nodeFactory.createPropertyAssignment(
nodeFactory.createIdentifier('styles'),
nodeFactory.createArrayLiteralExpression(styleReplacements),
);
properties = nodeFactory.createNodeArray([...properties, styleProperty]);
}
return nodeFactory.updateDecorator(
node,
nodeFactory.updateCallExpression(
decoratorFactory,
decoratorFactory.expression,
decoratorFactory.typeArguments,
[nodeFactory.updateObjectLiteralExpression(objectExpression, properties)],
),
);
}
function visitComponentMetadata(
nodeFactory: ts.NodeFactory,
node: ts.ObjectLiteralElementLike,
styleReplacements: ts.Expression[],
resourceImportDeclarations: ts.ImportDeclaration[],
): ts.ObjectLiteralElementLike | undefined {
if (!ts.isPropertyAssignment(node) || ts.isComputedPropertyName(node.name)) {
return node;
}
switch (node.name.text) {
case 'templateUrl':
// Only analyze string literals
if (!ts.isStringLiteralLike(node.initializer)) {
return node;
}
return node.initializer.text.length === 0
? node
: nodeFactory.updatePropertyAssignment(
node,
nodeFactory.createIdentifier('template'),
createResourceImport(
nodeFactory,
generateJitFileUri(node.initializer.text, 'template'),
resourceImportDeclarations,
),
);
case 'styles':
if (ts.isStringLiteralLike(node.initializer)) {
styleReplacements.unshift(
createResourceImport(
nodeFactory,
generateJitInlineUri(node.initializer.text, 'style'),
resourceImportDeclarations,
),
);
return undefined;
}
if (ts.isArrayLiteralExpression(node.initializer)) {
const inlineStyles = ts.visitNodes(node.initializer.elements, (node) => {
if (!ts.isStringLiteralLike(node)) {
return node;
}
return node.text.length === 0
? undefined // An empty inline style is equivalent to not having a style element
: createResourceImport(
nodeFactory,
generateJitInlineUri(node.text, 'style'),
resourceImportDeclarations,
);
}) as ts.NodeArray<ts.Expression>;
// Inline styles should be placed first
styleReplacements.unshift(...inlineStyles);
// The inline styles will be added afterwards in combination with any external styles
return undefined;
}
return node;
case 'styleUrl':
if (ts.isStringLiteralLike(node.initializer)) {
styleReplacements.push(
createResourceImport(
nodeFactory,
generateJitFileUri(node.initializer.text, 'style'),
resourceImportDeclarations,
),
);
return undefined;
}
return node;
case 'styleUrls': {
if (!ts.isArrayLiteralExpression(node.initializer)) {
return node;
}
const externalStyles = ts.visitNodes(node.initializer.elements, (node) => {
if (!ts.isStringLiteralLike(node)) {
return node;
}
return node.text
? createResourceImport(
nodeFactory,
generateJitFileUri(node.text, 'style'),
resourceImportDeclarations,
)
: undefined;
}) as ts.NodeArray<ts.Expression>;
// External styles are applied after any inline styles
styleReplacements.push(...externalStyles);
// The external styles will be added afterwards in combination with any inline styles
return undefined;
}
default:
// All other elements are passed through
return node;
}
}
function createResourceImport(
nodeFactory: ts.NodeFactory,
url: string,
resourceImportDeclarations: ts.ImportDeclaration[],
): ts.Identifier {
const urlLiteral = nodeFactory.createStringLiteral(url);
const importName = nodeFactory.createIdentifier(
`__NG_CLI_RESOURCE__${resourceImportDeclarations.length}`,
);
resourceImportDeclarations.push(
nodeFactory.createImportDeclaration(
undefined,
nodeFactory.createImportClause(false, importName, undefined),
urlLiteral,
),
);
return importName;
}
function getDecoratorOrigin(
decorator: ts.Decorator,
typeChecker: ts.TypeChecker,
): { name: string; module: string } | null {
if (!ts.isCallExpression(decorator.expression)) {
return null;
}
let identifier: ts.Node;
let name = '';
if (ts.isPropertyAccessExpression(decorator.expression.expression)) {
identifier = decorator.expression.expression.expression;
name = decorator.expression.expression.name.text;
} else if (ts.isIdentifier(decorator.expression.expression)) {
identifier = decorator.expression.expression;
} else {
return null;
}
// NOTE: resolver.getReferencedImportDeclaration would work as well but is internal
const symbol = typeChecker.getSymbolAtLocation(identifier);
if (symbol && symbol.declarations && symbol.declarations.length > 0) {
const declaration = symbol.declarations[0];
let module: string;
if (ts.isImportSpecifier(declaration)) {
name = (declaration.propertyName || declaration.name).text;
module = (declaration.parent.parent.parent.moduleSpecifier as ts.StringLiteral).text;
} else if (ts.isNamespaceImport(declaration)) {
// Use the name from the decorator namespace property access
module = (declaration.parent.parent.moduleSpecifier as ts.StringLiteral).text;
} else if (ts.isImportClause(declaration)) {
name = (declaration.name as ts.Identifier).text;
module = (declaration.parent.moduleSpecifier as ts.StringLiteral).text;
} else {
return null;
}
return { name, module };
}
return null;
}
| {
"end_byte": 9699,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/angular/transformers/jit-resource-transformer.ts"
} |
angular-cli/packages/angular/build/src/tools/angular/transformers/jit-bootstrap-transformer.ts_0_7511 | /**
* @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 ts from 'typescript';
/**
* The name of the Angular platform that should be replaced within
* bootstrap call expressions to support AOT.
*/
const PLATFORM_BROWSER_DYNAMIC_NAME = 'platformBrowserDynamic';
export function replaceBootstrap(
getTypeChecker: () => ts.TypeChecker,
): ts.TransformerFactory<ts.SourceFile> {
return (context: ts.TransformationContext) => {
let bootstrapImport: ts.ImportDeclaration | undefined;
let bootstrapNamespace: ts.Identifier | undefined;
const replacedNodes: ts.Node[] = [];
const nodeFactory = context.factory;
const visitNode: ts.Visitor = (node: ts.Node) => {
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {
const target = node.expression;
if (target.text === PLATFORM_BROWSER_DYNAMIC_NAME) {
if (!bootstrapNamespace) {
bootstrapNamespace = nodeFactory.createUniqueName('__NgCli_bootstrap_');
bootstrapImport = nodeFactory.createImportDeclaration(
undefined,
nodeFactory.createImportClause(
false,
undefined,
nodeFactory.createNamespaceImport(bootstrapNamespace),
),
nodeFactory.createStringLiteral('@angular/platform-browser'),
);
}
replacedNodes.push(target);
return nodeFactory.updateCallExpression(
node,
nodeFactory.createPropertyAccessExpression(bootstrapNamespace, 'platformBrowser'),
node.typeArguments,
node.arguments,
);
}
}
return ts.visitEachChild(node, visitNode, context);
};
return (sourceFile: ts.SourceFile) => {
if (!sourceFile.text.includes(PLATFORM_BROWSER_DYNAMIC_NAME)) {
return sourceFile;
}
let updatedSourceFile = ts.visitEachChild(sourceFile, visitNode, context);
if (bootstrapImport) {
// Remove any unused platform browser dynamic imports
const removals = elideImports(
updatedSourceFile,
replacedNodes,
getTypeChecker,
context.getCompilerOptions(),
);
if (removals.size > 0) {
updatedSourceFile = ts.visitEachChild(
updatedSourceFile,
(node) => (removals.has(node) ? undefined : node),
context,
);
}
// Add new platform browser import
return nodeFactory.updateSourceFile(
updatedSourceFile,
ts.setTextRange(
nodeFactory.createNodeArray([bootstrapImport, ...updatedSourceFile.statements]),
sourceFile.statements,
),
);
} else {
return updatedSourceFile;
}
};
};
}
// Remove imports for which all identifiers have been removed.
// Needs type checker, and works even if it's not the first transformer.
// Works by removing imports for symbols whose identifiers have all been removed.
// Doesn't use the `symbol.declarations` because that previous transforms might have removed nodes
// but the type checker doesn't know.
// See https://github.com/Microsoft/TypeScript/issues/17552 for more information.
export function elideImports(
sourceFile: ts.SourceFile,
removedNodes: ts.Node[],
getTypeChecker: () => ts.TypeChecker,
compilerOptions: ts.CompilerOptions,
): Set<ts.Node> {
const importNodeRemovals = new Set<ts.Node>();
if (removedNodes.length === 0) {
return importNodeRemovals;
}
const typeChecker = getTypeChecker();
// Collect all imports and used identifiers
const usedSymbols = new Set<ts.Symbol>();
const imports: ts.ImportDeclaration[] = [];
ts.forEachChild(sourceFile, function visit(node) {
// Skip removed nodes.
if (removedNodes.includes(node)) {
return;
}
// Consider types for 'implements' as unused.
// A HeritageClause token can also be an 'AbstractKeyword'
// which in that case we should not elide the import.
if (ts.isHeritageClause(node) && node.token === ts.SyntaxKind.ImplementsKeyword) {
return;
}
// Record import and skip
if (ts.isImportDeclaration(node)) {
if (!node.importClause?.isTypeOnly) {
imports.push(node);
}
return;
}
// Type reference imports do not need to be emitted when emitDecoratorMetadata is disabled.
if (ts.isTypeReferenceNode(node) && !compilerOptions.emitDecoratorMetadata) {
return;
}
let symbol: ts.Symbol | undefined;
switch (node.kind) {
case ts.SyntaxKind.Identifier:
if (node.parent && ts.isShorthandPropertyAssignment(node.parent)) {
const shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(node.parent);
if (shorthandSymbol) {
symbol = shorthandSymbol;
}
} else {
symbol = typeChecker.getSymbolAtLocation(node);
}
break;
case ts.SyntaxKind.ExportSpecifier:
symbol = typeChecker.getExportSpecifierLocalTargetSymbol(node as ts.ExportSpecifier);
break;
case ts.SyntaxKind.ShorthandPropertyAssignment:
symbol = typeChecker.getShorthandAssignmentValueSymbol(node);
break;
}
if (symbol) {
usedSymbols.add(symbol);
}
ts.forEachChild(node, visit);
});
if (imports.length === 0) {
return importNodeRemovals;
}
const isUnused = (node: ts.Identifier) => {
// Do not remove JSX factory imports
if (node.text === compilerOptions.jsxFactory) {
return false;
}
const symbol = typeChecker.getSymbolAtLocation(node);
return symbol && !usedSymbols.has(symbol);
};
for (const node of imports) {
if (!node.importClause) {
// "import 'abc';"
continue;
}
const namedBindings = node.importClause.namedBindings;
if (namedBindings && ts.isNamespaceImport(namedBindings)) {
// "import * as XYZ from 'abc';"
if (isUnused(namedBindings.name)) {
importNodeRemovals.add(node);
}
} else {
const specifierNodeRemovals = [];
let clausesCount = 0;
// "import { XYZ, ... } from 'abc';"
if (namedBindings && ts.isNamedImports(namedBindings)) {
let removedClausesCount = 0;
clausesCount += namedBindings.elements.length;
for (const specifier of namedBindings.elements) {
if (specifier.isTypeOnly || isUnused(specifier.name)) {
removedClausesCount++;
// in case we don't have any more namedImports we should remove the parent ie the {}
const nodeToRemove =
clausesCount === removedClausesCount ? specifier.parent : specifier;
specifierNodeRemovals.push(nodeToRemove);
}
}
}
// "import XYZ from 'abc';"
if (node.importClause.name) {
clausesCount++;
if (node.importClause.isTypeOnly || isUnused(node.importClause.name)) {
specifierNodeRemovals.push(node.importClause.name);
}
}
if (specifierNodeRemovals.length === clausesCount) {
importNodeRemovals.add(node);
} else {
for (const specifierNodeRemoval of specifierNodeRemovals) {
importNodeRemovals.add(specifierNodeRemoval);
}
}
}
}
return importNodeRemovals;
}
| {
"end_byte": 7511,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/angular/transformers/jit-bootstrap-transformer.ts"
} |
angular-cli/packages/angular/build/src/tools/angular/transformers/web-worker-transformer.ts_0_4566 | /**
* @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 ts from 'typescript';
/**
* Creates a TypeScript Transformer to process Worker and SharedWorker entry points and transform
* the URL instances to reference the built and bundled worker code. This uses a callback process
* similar to the component stylesheets to allow the main esbuild plugin to process files as needed.
* Unsupported worker expressions will be left in their origin form.
* @param getTypeChecker A function that returns a TypeScript TypeChecker instance for the program.
* @returns A TypeScript transformer factory.
*/
export function createWorkerTransformer(
fileProcessor: (file: string, importer: string) => string,
): ts.TransformerFactory<ts.SourceFile> {
return (context: ts.TransformationContext) => {
const nodeFactory = context.factory;
const visitNode: ts.Visitor = (node: ts.Node) => {
// Check if the node is a valid new expression for a Worker or SharedWorker
// TODO: Add global scope check
if (
!ts.isNewExpression(node) ||
!ts.isIdentifier(node.expression) ||
(node.expression.text !== 'Worker' && node.expression.text !== 'SharedWorker')
) {
// Visit child nodes of non-Worker expressions
return ts.visitEachChild(node, visitNode, context);
}
// Worker should have atleast one argument but not more than two
if (!node.arguments || node.arguments.length < 1 || node.arguments.length > 2) {
return node;
}
// First argument must be a new URL expression
const workerUrlNode = node.arguments[0];
// TODO: Add global scope check
if (
!ts.isNewExpression(workerUrlNode) ||
!ts.isIdentifier(workerUrlNode.expression) ||
workerUrlNode.expression.text !== 'URL'
) {
return node;
}
// URL must have 2 arguments
if (!workerUrlNode.arguments || workerUrlNode.arguments.length !== 2) {
return node;
}
// URL arguments must be a string and then `import.meta.url`
if (
!ts.isStringLiteralLike(workerUrlNode.arguments[0]) ||
!ts.isPropertyAccessExpression(workerUrlNode.arguments[1]) ||
!ts.isMetaProperty(workerUrlNode.arguments[1].expression) ||
workerUrlNode.arguments[1].name.text !== 'url'
) {
return node;
}
const filePath = workerUrlNode.arguments[0].text;
const importer = node.getSourceFile().fileName;
// Process the file
const replacementPath = fileProcessor(filePath, importer);
// Update if the path changed
if (replacementPath !== filePath) {
return nodeFactory.updateNewExpression(
node,
node.expression,
node.typeArguments,
// Update Worker arguments
ts.setTextRange(
nodeFactory.createNodeArray(
[
nodeFactory.updateNewExpression(
workerUrlNode,
workerUrlNode.expression,
workerUrlNode.typeArguments,
// Update URL arguments
ts.setTextRange(
nodeFactory.createNodeArray(
[
nodeFactory.createStringLiteral(replacementPath),
workerUrlNode.arguments[1],
],
workerUrlNode.arguments.hasTrailingComma,
),
workerUrlNode.arguments,
),
),
// Use the second Worker argument (options) if present.
// Otherwise create a default options object for module Workers.
node.arguments[1] ??
nodeFactory.createObjectLiteralExpression([
nodeFactory.createPropertyAssignment(
'type',
nodeFactory.createStringLiteral('module'),
),
]),
],
node.arguments.hasTrailingComma,
),
node.arguments,
),
);
} else {
return node;
}
};
return (sourceFile) => {
// Skip transformer if there are no Workers
if (!sourceFile.text.includes('Worker')) {
return sourceFile;
}
return ts.visitEachChild(sourceFile, visitNode, context);
};
};
}
| {
"end_byte": 4566,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/angular/transformers/web-worker-transformer.ts"
} |
angular-cli/packages/angular/build/src/tools/angular/compilation/parallel-compilation.ts_0_5355 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import type { CompilerOptions } from '@angular/compiler-cli';
import type { PartialMessage } from 'esbuild';
import { createRequire } from 'node:module';
import { MessageChannel } from 'node:worker_threads';
import type { SourceFile } from 'typescript';
import { WorkerPool } from '../../../utils/worker-pool';
import type { AngularHostOptions } from '../angular-host';
import { AngularCompilation, DiagnosticModes, EmitFileResult } from './angular-compilation';
/**
* An Angular compilation which uses a Node.js Worker thread to load and execute
* the TypeScript and Angular compilers. This allows for longer synchronous actions
* such as semantic and template diagnostics to be calculated in parallel to the
* other aspects of the application bundling process. The worker thread also has
* a separate memory pool which significantly reduces the need for adjusting the
* main Node.js CLI process memory settings with large application code sizes.
*/
export class ParallelCompilation extends AngularCompilation {
readonly #worker: WorkerPool;
constructor(readonly jit: boolean) {
super();
// TODO: Convert to import.meta usage during ESM transition
const localRequire = createRequire(__filename);
this.#worker = new WorkerPool({
maxThreads: 1,
idleTimeout: Infinity,
filename: localRequire.resolve('./parallel-worker'),
});
}
override initialize(
tsconfig: string,
hostOptions: AngularHostOptions,
compilerOptionsTransformer?: (compilerOptions: CompilerOptions) => CompilerOptions,
): Promise<{
affectedFiles: ReadonlySet<SourceFile>;
compilerOptions: CompilerOptions;
referencedFiles: readonly string[];
externalStylesheets?: ReadonlyMap<string, string>;
}> {
const stylesheetChannel = new MessageChannel();
// The request identifier is required because Angular can issue multiple concurrent requests
stylesheetChannel.port1.on(
'message',
({ requestId, data, containingFile, stylesheetFile, order, className }) => {
hostOptions
.transformStylesheet(data, containingFile, stylesheetFile, order, className)
.then((value) => stylesheetChannel.port1.postMessage({ requestId, value }))
.catch((error) => stylesheetChannel.port1.postMessage({ requestId, error }));
},
);
// The web worker processing is a synchronous operation and uses shared memory combined with
// the Atomics API to block execution here until a response is received.
const webWorkerChannel = new MessageChannel();
const webWorkerSignal = new Int32Array(new SharedArrayBuffer(4));
webWorkerChannel.port1.on('message', ({ workerFile, containingFile }) => {
try {
const workerCodeFile = hostOptions.processWebWorker(workerFile, containingFile);
webWorkerChannel.port1.postMessage({ workerCodeFile });
} catch (error) {
webWorkerChannel.port1.postMessage({ error });
} finally {
Atomics.store(webWorkerSignal, 0, 1);
Atomics.notify(webWorkerSignal, 0);
}
});
// The compiler options transformation is a synchronous operation and uses shared memory combined
// with the Atomics API to block execution here until a response is received.
const optionsChannel = new MessageChannel();
const optionsSignal = new Int32Array(new SharedArrayBuffer(4));
optionsChannel.port1.on('message', (compilerOptions) => {
try {
const transformedOptions = compilerOptionsTransformer?.(compilerOptions) ?? compilerOptions;
optionsChannel.port1.postMessage({ transformedOptions });
} catch (error) {
webWorkerChannel.port1.postMessage({ error });
} finally {
Atomics.store(optionsSignal, 0, 1);
Atomics.notify(optionsSignal, 0);
}
});
// Execute the initialize function in the worker thread
return this.#worker.run(
{
fileReplacements: hostOptions.fileReplacements,
tsconfig,
jit: this.jit,
stylesheetPort: stylesheetChannel.port2,
optionsPort: optionsChannel.port2,
optionsSignal,
webWorkerPort: webWorkerChannel.port2,
webWorkerSignal,
},
{
name: 'initialize',
transferList: [stylesheetChannel.port2, optionsChannel.port2, webWorkerChannel.port2],
},
);
}
/**
* This is not needed with this compilation type since the worker will already send a response
* with the serializable esbuild compatible diagnostics.
*/
protected override collectDiagnostics(): never {
throw new Error('Not implemented in ParallelCompilation.');
}
override diagnoseFiles(
modes = DiagnosticModes.All,
): Promise<{ errors?: PartialMessage[]; warnings?: PartialMessage[] }> {
return this.#worker.run(modes, { name: 'diagnose' });
}
override emitAffectedFiles(): Promise<Iterable<EmitFileResult>> {
return this.#worker.run(undefined, { name: 'emit' });
}
override update(files: Set<string>): Promise<void> {
return this.#worker.run(files, { name: 'update' });
}
override close() {
return this.#worker.destroy();
}
}
| {
"end_byte": 5355,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/angular/compilation/parallel-compilation.ts"
} |
angular-cli/packages/angular/build/src/tools/angular/compilation/parallel-worker.ts_0_4085 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import type { PartialMessage } from 'esbuild';
import assert from 'node:assert';
import { randomUUID } from 'node:crypto';
import { type MessagePort, receiveMessageOnPort } from 'node:worker_threads';
import { SourceFileCache } from '../../esbuild/angular/source-file-cache';
import type { AngularCompilation, DiagnosticModes } from './angular-compilation';
import { AotCompilation } from './aot-compilation';
import { JitCompilation } from './jit-compilation';
export interface InitRequest {
jit: boolean;
tsconfig: string;
fileReplacements?: Record<string, string>;
stylesheetPort: MessagePort;
optionsPort: MessagePort;
optionsSignal: Int32Array;
webWorkerPort: MessagePort;
webWorkerSignal: Int32Array;
}
let compilation: AngularCompilation | undefined;
const sourceFileCache = new SourceFileCache();
export async function initialize(request: InitRequest) {
compilation ??= request.jit ? new JitCompilation() : new AotCompilation();
const stylesheetRequests = new Map<string, [(value: string) => void, (reason: Error) => void]>();
request.stylesheetPort.on('message', ({ requestId, value, error }) => {
if (error) {
stylesheetRequests.get(requestId)?.[1](error);
} else {
stylesheetRequests.get(requestId)?.[0](value);
}
});
const { compilerOptions, referencedFiles, externalStylesheets, templateUpdates } =
await compilation.initialize(
request.tsconfig,
{
fileReplacements: request.fileReplacements,
sourceFileCache,
modifiedFiles: sourceFileCache.modifiedFiles,
transformStylesheet(data, containingFile, stylesheetFile, order, className) {
const requestId = randomUUID();
const resultPromise = new Promise<string>((resolve, reject) =>
stylesheetRequests.set(requestId, [resolve, reject]),
);
request.stylesheetPort.postMessage({
requestId,
data,
containingFile,
stylesheetFile,
order,
className,
});
return resultPromise;
},
processWebWorker(workerFile, containingFile) {
Atomics.store(request.webWorkerSignal, 0, 0);
request.webWorkerPort.postMessage({ workerFile, containingFile });
Atomics.wait(request.webWorkerSignal, 0, 0);
const result = receiveMessageOnPort(request.webWorkerPort)?.message;
if (result?.error) {
throw result.error;
}
return result?.workerCodeFile ?? workerFile;
},
},
(compilerOptions) => {
Atomics.store(request.optionsSignal, 0, 0);
request.optionsPort.postMessage(compilerOptions);
Atomics.wait(request.optionsSignal, 0, 0);
const result = receiveMessageOnPort(request.optionsPort)?.message;
if (result?.error) {
throw result.error;
}
return result?.transformedOptions ?? compilerOptions;
},
);
return {
externalStylesheets,
templateUpdates,
referencedFiles,
// TODO: Expand? `allowJs`, `isolatedModules`, `sourceMap`, `inlineSourceMap` are the only fields needed currently.
compilerOptions: {
allowJs: compilerOptions.allowJs,
isolatedModules: compilerOptions.isolatedModules,
sourceMap: compilerOptions.sourceMap,
inlineSourceMap: compilerOptions.inlineSourceMap,
},
};
}
export async function diagnose(modes: DiagnosticModes): Promise<{
errors?: PartialMessage[];
warnings?: PartialMessage[];
}> {
assert(compilation);
const diagnostics = await compilation.diagnoseFiles(modes);
return diagnostics;
}
export async function emit() {
assert(compilation);
const files = await compilation.emitAffectedFiles();
return [...files];
}
export function update(files: Set<string>): void {
sourceFileCache.invalidate(files);
}
| {
"end_byte": 4085,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/angular/compilation/parallel-worker.ts"
} |
angular-cli/packages/angular/build/src/tools/angular/compilation/factory.ts_0_1172 | /**
* @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 { useParallelTs } from '../../../utils/environment-options';
import type { AngularCompilation } from './angular-compilation';
/**
* Creates an Angular compilation object that can be used to perform Angular application
* compilation either for AOT or JIT mode. By default a parallel compilation is created
* that uses a Node.js worker thread.
* @param jit True, for Angular JIT compilation; False, for Angular AOT compilation.
* @returns An instance of an Angular compilation object.
*/
export async function createAngularCompilation(jit: boolean): Promise<AngularCompilation> {
if (useParallelTs) {
const { ParallelCompilation } = await import('./parallel-compilation');
return new ParallelCompilation(jit);
}
if (jit) {
const { JitCompilation } = await import('./jit-compilation');
return new JitCompilation();
} else {
const { AotCompilation } = await import('./aot-compilation');
return new AotCompilation();
}
}
| {
"end_byte": 1172,
"start_byte": 0,
"url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/tools/angular/compilation/factory.ts"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.