_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/devtools/src/app/demo-app/todo/home/todo.component.scss_0_61
.destroy { cursor: pointer; display: unset !important; }
{ "end_byte": 61, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/todo/home/todo.component.scss" }
angular/devtools/src/app/demo-app/todo/home/todos.component.ts_0_2724
/** * @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 {ChangeDetectorRef, Component, EventEmitter, OnDestroy, OnInit, Output} from '@angular/core'; import {Todo} from './todo'; import {TodoFilter, TodosFilter} from './todos.pipe'; import {SamplePipe} from './sample.pipe'; import {TooltipDirective} from './tooltip.directive'; import {TodoComponent} from './todo.component'; import {RouterLink} from '@angular/router'; const fib = (n: number): number => { if (n === 1 || n === 2) { return 1; } return fib(n - 1) + fib(n - 2); }; @Component({ templateUrl: 'todos.component.html', selector: 'app-todos', standalone: true, imports: [RouterLink, TodoComponent, TooltipDirective, SamplePipe, TodosFilter], }) export class TodosComponent implements OnInit, OnDestroy { todos: Todo[] = [ { label: 'Buy milk', completed: false, id: '42', }, { label: 'Build something fun!', completed: false, id: '43', }, ]; @Output() update = new EventEmitter(); @Output() delete = new EventEmitter(); @Output() add = new EventEmitter(); private hashListener!: EventListenerOrEventListenerObject; constructor(private cdRef: ChangeDetectorRef) {} ngOnInit(): void { if (typeof window !== 'undefined') { window.addEventListener('hashchange', (this.hashListener = () => this.cdRef.markForCheck())); } } ngOnDestroy(): void { fib(40); if (typeof window !== 'undefined') { window.removeEventListener('hashchange', this.hashListener); } } get filterValue(): TodoFilter { if (typeof window !== 'undefined') { return (window.location.hash.replace(/^#\//, '') as TodoFilter) || TodoFilter.All; } return TodoFilter.All; } get itemsLeft(): number { return (this.todos || []).filter((t) => !t.completed).length; } clearCompleted(): void { (this.todos || []).filter((t) => t.completed).forEach((t) => this.delete.emit(t)); } addTodo(input: HTMLInputElement): void { const todo = { completed: false, label: input.value, }; const result: Todo = {...todo, id: Math.random().toString()}; this.todos.push(result); input.value = ''; } onChange(todo: Todo): void { if (!todo.id) { return; } } onDelete(todo: Todo): void { if (!todo.id) { return; } const idx = this.todos.findIndex((t) => t.id === todo.id); if (idx < 0) { return; } // tslint:disable-next-line:no-console console.log('Deleting', idx); this.todos.splice(idx, 1); } }
{ "end_byte": 2724, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/todo/home/todos.component.ts" }
angular/devtools/src/app/demo-app/todo/home/todos.service.ts_0_622
/** * @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 {Todo} from './todo'; export abstract class TodosService { getAll(): Promise<Todo[]> { throw new Error('Not implemented'); } createTodo(todo: Partial<Todo>): Promise<Todo> { throw new Error('Not implemented'); } updateTodo(todo: Todo): Promise<Todo> { throw new Error('Not implemented'); } deleteTodo({id}: {id: string}): Promise<void> { throw new Error('Not implemented'); } }
{ "end_byte": 622, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/todo/home/todos.service.ts" }
angular/devtools/src/app/demo-app/todo/home/todo.component.html_0_525
<li [class.completed]="todo.completed"> <div class="view" appTooltip> <input class="toggle" type="checkbox" [checked]="todo.completed" (change)="toggle()" /> <label (dblclick)="enableEditMode()" [style.display]="editMode ? 'none' : 'block'">{{ todo.label }}</label> <button class="destroy" (click)="delete.emit(todo)"></button> </div> <input class="edit" [value]="todo.label" [style.display]="editMode ? 'block' : 'none'" (keydown.enter)="completeEdit($any($event.target).value)" /> </li>
{ "end_byte": 525, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/todo/home/todo.component.html" }
angular/devtools/src/app/demo-app/todo/about/about.module.ts_0_585
/** * @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 {NgModule} from '@angular/core'; import {RouterModule} from '@angular/router'; import {AboutComponent} from './about.component'; @NgModule({ imports: [ RouterModule.forChild([ { path: '', pathMatch: 'full', component: AboutComponent, }, ]), AboutComponent, ], exports: [AboutComponent], }) export class AboutModule {}
{ "end_byte": 585, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/todo/about/about.module.ts" }
angular/devtools/src/app/demo-app/todo/about/about.component.ts_0_542
/** * @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} from '@angular/core'; import {RouterLink} from '@angular/router'; @Component({ selector: 'app-about', template: ` About component <a [routerLink]="">Home</a> <a [routerLink]="">Home</a> <a [routerLink]="">Home</a> `, standalone: true, imports: [RouterLink], }) export class AboutComponent {}
{ "end_byte": 542, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/todo/about/about.component.ts" }
angular/devtools/src/app/demo-app/todo/about/BUILD.bazel_0_294
load("//devtools/tools:ng_module.bzl", "ng_module") package(default_visibility = ["//visibility:public"]) ng_module( name = "about", srcs = [ "about.component.ts", "about.module.ts", ], deps = [ "//packages/core", "//packages/router", ], )
{ "end_byte": 294, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/todo/about/BUILD.bazel" }
angular/devtools/src/environments/environment.ts_0_257
/** * @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 const environment = { production: false, };
{ "end_byte": 257, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/environments/environment.ts" }
angular/devtools/src/environments/BUILD.bazel_0_256
load("//devtools/tools:typescript.bzl", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "environments", srcs = [ "environment.ts", ], deps = [ "//packages/platform-browser", ], )
{ "end_byte": 256, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/environments/BUILD.bazel" }
angular/devtools/src/styles/chrome_styles.scss_0_42
/** Specific style for Chrome browser */
{ "end_byte": 42, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/styles/chrome_styles.scss" }
angular/devtools/src/styles/firefox_styles.scss_0_43
/** Specific style for Firefox browser */
{ "end_byte": 43, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/styles/firefox_styles.scss" }
angular/scripts/compare-main-to-patch.js_0_6454
#!/usr/bin/env node /** * @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 */ 'use strict'; /** * This script compares commits in main and patch branches to find the delta between them. This is * useful for release reviews, to make sure all the necessary commits were included into the patch * branch and there is no discrepancy. * * Additionally, lists all 'feat' commits that were merged to the patch branch to aid in ensuring * features are only released to main. */ const {exec} = require('shelljs'); const semver = require('semver'); // Ignore commits that have specific patterns in commit message, it's ok for these commits to be // present only in one branch. Ignoring them reduced the "noise" in the final output. const ignoreCommitPatterns = [ 'release:', 'docs: release notes', 'build(docs-infra): upgrade cli command docs sources', ]; // Ignore feature commits that have specific patterns in commit message, it's ok for these commits // to be present in patch branch. const ignoreFeatureCheckPatterns = [ // It is ok and in fact desirable for dev-infra features to be on the patch branch. 'feat(dev-infra):', ]; // String to be displayed as a version for initial commits in a branch // (before first release from that branch). const initialVersion = 'initial'; // Helper methods function execGitCommand(gitCommand) { const output = exec(gitCommand, {silent: true}); if (output.code !== 0) { console.error(`Error: git command "${gitCommand}" failed: \n\n ${output.stderr}`); process.exit(1); } return output; } function toArray(rawGitCommandOutput) { return rawGitCommandOutput.trim().split('\n'); } function maybeExtractReleaseVersion(commit) { const versionRegex = /release: cut the (.*?) release/; const matches = commit.match(versionRegex); return matches ? matches[1] || matches[2] : null; } // Checks whether commit message matches any patterns in ignore list. function shouldIgnoreCommit(commitMessage, ignorePatterns) { return ignorePatterns.some((pattern) => commitMessage.indexOf(pattern) > -1); } /** * @param rawGitCommits * @returns {Map<string, [string, string]>} - Map of commit message to [commit info, version] */ function collectCommitsAsMap(rawGitCommits) { const commits = toArray(rawGitCommits); const commitsMap = new Map(); let version = initialVersion; commits.reverse().forEach((commit) => { const ignore = shouldIgnoreCommit(commit, ignoreCommitPatterns); // Keep track of the current version while going though the list of commits, so that we can use // this information in the output (i.e. display a version when a commit was introduced). version = maybeExtractReleaseVersion(commit) || version; if (!ignore) { // Extract original commit description from commit message, so that we can find matching // commit in other commit range. For example, for the following commit message: // // 15d3e741e9 feat: update the locale files (#33556) // // we extract only "feat: update the locale files" part and use it as a key, since commit SHA // and PR number may be different for the same commit in main and patch branches. const key = commit .slice(11) .replace(/\(\#\d+\)/g, '') .trim(); commitsMap.set(key, [commit, version]); } }); return commitsMap; } function getCommitInfoAsString(version, commitInfo) { const formattedVersion = version === initialVersion ? version : `${version}+`; return `[${formattedVersion}] ${commitInfo}`; } /** * Returns a list of items present in `mapA`, but *not* present in `mapB`. * This function is needed to compare 2 sets of commits and return the list of unique commits in the * first set. */ function diff(mapA, mapB) { const result = []; mapA.forEach((value, key) => { if (!mapB.has(key)) { result.push(getCommitInfoAsString(value[1], value[0])); } }); return result; } /** * @param {Map<string, [string, string]>} commitsMap - commit map from collectCommitsAsMap * @returns {string[]} List of commits with commit messages that start with 'feat' */ function listFeatures(commitsMap) { return Array.from(commitsMap.keys()).reduce((result, key) => { if (key.startsWith('feat') && !shouldIgnoreCommit(key, ignoreFeatureCheckPatterns)) { const value = commitsMap.get(key); result.push(getCommitInfoAsString(value[1], value[0])); } return result; }, []); } function getBranchByTag(tag) { const version = semver.parse(tag); return `${version.major}.${version.minor}.x`; // e.g. 9.0.x } function getLatestTag(tags) { // Exclude Next releases, since we cut them from main, so there is nothing to compare. const isNotNextVersion = (version) => version.indexOf('-next') === -1; return tags .filter(semver.valid) .filter(isNotNextVersion) .map(semver.clean) .sort(semver.rcompare)[0]; } // Main program function main() { execGitCommand('git fetch upstream'); // Extract tags information and pick the most recent version // that we'll use later to compare with main. const tags = toArray(execGitCommand('git tag')); const latestTag = getLatestTag(tags); // Based on the latest tag, generate the name of the patch branch. const branch = getBranchByTag(latestTag); // Extract main-only and patch-only commits using `git log` command. const mainCommits = execGitCommand( `git log --cherry-pick --oneline --right-only upstream/${branch}...upstream/main`, ); const patchCommits = execGitCommand( `git log --cherry-pick --oneline --left-only upstream/${branch}...upstream/main`, ); // Post-process commits and convert raw data into a Map, so that we can diff it easier. const mainCommitsMap = collectCommitsAsMap(mainCommits); const patchCommitsMap = collectCommitsAsMap(patchCommits); // tslint:disable-next-line:no-console console.log(` Comparing branches "${branch}" and main. ***** Only in MAIN ***** ${diff(mainCommitsMap, patchCommitsMap).join('\n') || 'No extra commits'} ***** Only in PATCH (${branch}) ***** ${diff(patchCommitsMap, mainCommitsMap).join('\n') || 'No extra commits'} ***** Features in PATCH (${branch}) - should always be empty ***** ${listFeatures(patchCommitsMap).join('\n') || 'No extra commits'} `); } main();
{ "end_byte": 6454, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/scripts/compare-main-to-patch.js" }
angular/scripts/test/run-saucelabs-tests.sh_0_2296
#!/usr/bin/env bash # Convienence script for running all saucelabs test targets. # See tools/saucelabs-daemon/README.md for more information. set -eu -o pipefail NUMBER_OF_PARALLEL_BROWSERS="${1:-2}" shift if [[ -z "${SAUCE_USERNAME:-}" ]]; then echo "ERROR: SAUCE_USERNAME environment variable must be set; see tools/saucelabs-daemon/README.md for more info." exit 1 fi if [[ -z "${SAUCE_ACCESS_KEY:-}" ]]; then echo "SAUCE_ACCESS_KEY environment variable must be set; see tools/saucelabs-daemon/README.md for more info." exit 1 fi if [[ -z "${SAUCE_TUNNEL_IDENTIFIER:-}" ]]; then echo "SAUCE_TUNNEL_IDENTIFIER environment variable must be set; see tools/saucelabs-daemon/README.md for more info." exit 1 fi # First build the background-service binary target so the build runs in the foreground yarn bazel build //tools/saucelabs-daemon/background-service --build_runfile_links # Query for the test targets to run TESTS=$(./node_modules/.bin/bazelisk query --output label '(kind(karma_web_test, ...) intersect attr("tags", "saucelabs", ...)) except attr("tags", "fixme-saucelabs", ...)') # Build all test targets so the build can fan out to all CPUs yarn bazel build ${TESTS} # Start the saucelabs-daemon background service in the background. Run directly from the generated # bash script instead of using bazel run so we get the PID of the node process. Otherwise killing # the child process in kill_background_service doesn't kill the spawn node process. cd dist/bin/tools/saucelabs-daemon/background-service/background-service.sh.runfiles/angular ../../background-service.sh "$NUMBER_OF_PARALLEL_BROWSERS" & BACKGROUND_SERVICE_PID=$! cd - > /dev/null # Trap on exit so we always kill the background service function kill_background_service { echo "Killing background service (pid $BACKGROUND_SERVICE_PID)..." kill $BACKGROUND_SERVICE_PID # Kill the backgound service wait $BACKGROUND_SERVICE_PID # Let the output of the background service flush echo "All done" } trap kill_background_service INT TERM # Small pause to give time for the background service to open up its IPC port and start listening sleep 2 # Run all of the saucelabs test targets yarn bazel test --config=saucelabs --jobs="$NUMBER_OF_PARALLEL_BROWSERS" ${TESTS} "$@" kill_background_service
{ "end_byte": 2296, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/scripts/test/run-saucelabs-tests.sh" }
angular/scripts/ci/payload-size.js_0_3589
/** * @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 */ 'use strict'; // Imports const fs = require('fs'); const path = require('path'); // Get limit file, project name and commit SHA from command line arguments. const [, , limitFile, project, commit] = process.argv; const THRESHOLD_BYTES = 5000; const THRESHOLD_PERCENT = 5; // Load sizes. const currentSizes = JSON.parse(fs.readFileSync('/tmp/current.log', 'utf8')); const allLimitSizes = JSON.parse(fs.readFileSync(limitFile, 'utf8')); const limitSizes = allLimitSizes[project]; if (!limitSizes) { throw new Error(`ERROR: Project '${project}' is missing from limit file ${limitFile}.`); } // Check current sizes against limits. let failed = false; const successMessages = []; const failureMessages = []; for (const compressionType in limitSizes) { if (typeof limitSizes[compressionType] === 'object') { const limitPerFile = limitSizes[compressionType]; for (const filename in limitPerFile) { const expectedSize = limitPerFile[filename]; const actualSize = currentSizes[`${compressionType}/${filename}`]; if (actualSize === undefined) { failed = true; // An expected compression type/file combination is missing. Maybe the file was renamed or // removed. Report it as an error, so the user updates the corresponding limit file. console.error( `ERROR: Commit ${commit} ${compressionType} ${filename} measurement is missing. ` + 'Maybe the file was renamed or removed.', ); } else { const absoluteSizeDiff = Math.abs(actualSize - expectedSize); // If size diff is larger than THRESHOLD_BYTES or THRESHOLD_PERCENT... if ( absoluteSizeDiff > THRESHOLD_BYTES || absoluteSizeDiff > (expectedSize * THRESHOLD_PERCENT) / 100 ) { failed = true; // We must also catch when the size is significantly lower than the payload limit, so // we are forced to update the expected payload number when the payload size reduces. // Otherwise, we won't be able to catch future regressions that happen to be below // the artificially inflated limit. const operator = actualSize > expectedSize ? 'exceeded' : 'fell below'; failureMessages.push( `FAIL: Commit ${commit} ${compressionType} ${filename} ${operator} expected size by ${THRESHOLD_BYTES} bytes or >${THRESHOLD_PERCENT}% ` + `(expected: ${expectedSize}, actual: ${actualSize}).`, ); } else { successMessages.push( `SUCCESS: Commit ${commit} ${compressionType} ${filename} did NOT cross size threshold of ${THRESHOLD_BYTES} bytes or >${THRESHOLD_PERCENT} ` + `(expected: ${expectedSize}, actual: ${actualSize}).`, ); } } } } } // Group failure messages separately from success messages so they are easier to find. successMessages.concat(failureMessages).forEach((message) => console.error(message)); if (failed) { const projectRoot = path.resolve(__dirname, '../..'); const limitFileRelPath = path.relative(projectRoot, limitFile); console.info( `If this is a desired change, please update the size limits in file '${limitFileRelPath}'.`, ); process.exit(1); } else { console.info( `Payload size check passed. All diffs are less than ${THRESHOLD_PERCENT}% or ${THRESHOLD_BYTES} bytes.`, ); }
{ "end_byte": 3589, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/scripts/ci/payload-size.js" }
angular/scripts/ci/bazel-payload-size.sh_0_844
#!/usr/bin/env bash set -eu -o pipefail # Source optional CI environment variables which are sandboxed out # of the environment when running integration tests under Bazel readonly bazelVarEnv="/tmp/bazel-ci-env.sh" if [[ -f "$bazelVarEnv" ]]; then source $bazelVarEnv fi # If running locally, at a minimum set PROJECT_ROOT if [[ -z "${PROJECT_ROOT:-}" ]]; then PROJECT_ROOT=$(cd $(dirname $0)/../..; pwd) fi # Bazel payload size tracking should always be treated as if this runs as part of # a pull request. i.e. the results are not uploaded. This is necessary as Bazel test # targets do not necessarily run for every commit, and cached results might originate # from RBE-built pull requests. We will overhaut size-tracking anyway.. export CI_PULL_REQUEST="true" source ${PROJECT_ROOT}/scripts/ci/payload-size.sh trackPayloadSize "$@"
{ "end_byte": 844, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/scripts/ci/bazel-payload-size.sh" }
angular/scripts/ci/payload-size.sh_0_4730
#!/usr/bin/env bash set -eu -o pipefail # statc makes `stat -c` work on both Linux & OSX function statc () { case $(uname) in Darwin*) format='-f%z' ;; *) format='-c%s' ;; esac stat ${format} $@ } # sedr makes `sed -r` work on both Linux & OSX function sedr () { case $(uname) in Darwin*) flag='-E' ;; *) flag='-r' ;; esac sed ${flag} "$@" } readonly PROJECT_NAME="angular-payload-size" NODE_MODULES_BIN=$PROJECT_ROOT/node_modules/.bin/ # Get the gzip size of a file with the specified compression level. # $1: string - The file path. # $2: number - The level of compression. getGzipSize() { local filePath=$1 local compLevel=$2 local compPath="$(mktemp).gz" local size=-1 gzip -c -$compLevel "$filePath" >> "$compPath" size=$(statc "$compPath") rm "$compPath" echo $size } # Calculate the size of target file uncompressed size, gzip7 size, gzip9 size # Write to global variable $payloadData, $filename calculateSize() { # Remove .js and -T74CPV26.js from the filename label=$(echo "$filename" | sed "s/\(-[A-Z0-9]\{8\}\)\?\.js//" | sed "s/.*\///") rawSize=$(statc $filename) gzip7Size=$(getGzipSize "$filename" 7) gzip9Size=$(getGzipSize "$filename" 9) # Log the sizes (for information/debugging purposes). printf "Size: %6d (gzip7: %6d, gzip9: %6d) %s\n" $rawSize $gzip7Size $gzip9Size $label payloadData="$payloadData\"uncompressed/$label\": $rawSize, " payloadData="$payloadData\"gzip7/$label\": $gzip7Size, " payloadData="$payloadData\"gzip9/$label\": $gzip9Size, " } # Check whether the file size is under limit. # Exit with an error if limit is exceeded. # $1: string - The name in database. # $2: string - The payload size limit file. checkSize() { name="$1" limitFile="$2" # PRs and non-PR pushes will always test against the size-limits of the current revision. node ${PROJECT_ROOT}/scripts/ci/payload-size.js $limitFile $name ${CI_COMMIT:-} } # Write timestamp to global variable `$payloadData`. addTimestamp() { # Add Timestamp timestamp=$(date +%s) payloadData="$payloadData\"timestamp\": $timestamp, " } # Write the current CI build URL to global variable `$payloadData`. # This allows mapping the data stored in the database to the CI build job that generated it, which # might contain more info/context. # $1: string - The CI build URL. addBuildUrl() { buildUrl="$1" payloadData="$payloadData\"buildUrl\": \"$buildUrl\", " } # Write the commit message for the specified CI commit to global variable `$payloadData`. # $1: string - The commit SHA for this build (in `<SHA-1>` format). addMessage() { message="${1}" message=$(echo $message | sed 's/\r//g' | sed 's/\\/\\\\/g' | sed 's/"/\\"/g') payloadData="$payloadData\"message\": \"$message\", " } # Convert the current `payloadData` value to a JSON string. # (Basically remove trailing `,` and wrap in `{...}`.) payloadToJson() { echo "{$(sedr 's|, *$||' <<< $payloadData)}" } # Upload data to firebase database if it's commit, print out data for pull requests. # $1: string - The name in database. uploadData() { name="$1" readonly safeBranchName=$(echo $CI_BRANCH | sed -e 's/\./_/g') readonly dbPath=/payload/$name/$safeBranchName/$CI_COMMIT readonly jsonPayload=$(payloadToJson) # WARNING: CI_SECRET_PAYLOAD_FIREBASE_TOKEN should NOT be printed. set +x $NODE_MODULES_BIN/firebase database:update --data "$jsonPayload" --project $PROJECT_NAME --force --token "$CI_SECRET_PAYLOAD_FIREBASE_TOKEN" $dbPath } # Track payload size. # $1: string - The name in database. # $2: string - The file path. # $3: true | false - Whether to check the payload size and fail the test if it exceeds limit. # $4: [string] - The payload size limit file. Only necessary if `$3` is `true`. trackPayloadSize() { name="$1" path="$2" checkSize="$3" limitFile="${4:-}" payloadData="" # Calculate the file sizes. echo "Calculating sizes for files in '$path'..." for filename in $path; do calculateSize done # Save the file sizes to be retrieved from `payload-size.js`. echo "$(payloadToJson)" > /tmp/current.log # If this is a non-PR build, upload the data to firebase. if [[ "${CI_PULL_REQUEST:-}" == "false" ]]; then echo "Uploading data for '$name'..." addTimestamp addBuildUrl $CI_BUILD_URL addMessage $CI_COMMIT uploadData $name else echo "Skipped uploading data for '$name', because this is a pull request." fi # Check the file sizes against the specified limits. if [[ $checkSize = true ]]; then echo "Verifying sizes against '$limitFile'..." checkSize $name $limitFile else echo "Skipped verifying sizes (checkSize: false)." fi }
{ "end_byte": 4730, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/scripts/ci/payload-size.sh" }
angular/scripts/ci/publish-build-artifacts.sh_0_4503
#!/usr/bin/env bash set -x -u -e -o pipefail # Setup environment readonly thisDir=$(cd $(dirname $0); pwd) # Find the most recent tag that is reachable from the current commit. # This is shallow clone of the repo, so we might need to fetch more commits to # find the tag. function getLatestTag { local depth=`git log --oneline | wc -l` local latestTag=`git describe --tags --abbrev=0 || echo NOT_FOUND` while [ "$latestTag" == "NOT_FOUND" ]; do # Avoid infinite loop. if [ "$depth" -gt "1000" ]; then echo "Error: Unable to find the latest tag." 1>&2 exit 1; fi # Increase the clone depth and look for a tag. depth=$((depth + 50)) git fetch --depth=$depth latestTag=`git describe --tags --abbrev=0 || echo NOT_FOUND` done echo $latestTag; } function publishRepo { COMPONENT=$1 ARTIFACTS_DIR=$2 BUILD_REPO="${COMPONENT}-builds" REPO_DIR="$(pwd)/tmp/${BUILD_REPO}" REPO_URL="https://github.com/angular/${BUILD_REPO}.git" if [ -n "${CREATE_REPOS:-}" ]; then curl -u "$ORG:$TOKEN" https://api.github.com/user/repos \ -d '{"name":"'$BUILD_REPO'", "auto_init": true}' fi echo "Pushing build artifacts to ${ORG}/${BUILD_REPO}" # create local repo folder and clone build repo into it rm -rf $REPO_DIR mkdir -p ${REPO_DIR} echo "Starting cloning process of ${REPO_URL} into ${REPO_DIR}.." ( if [[ $(git ls-remote --heads ${REPO_URL} ${BRANCH}) ]]; then echo "Branch ${BRANCH} already exists. Cloning that branch." git clone ${REPO_URL} ${REPO_DIR} --depth 100 --branch ${BRANCH} cd ${REPO_DIR} echo "Cloned repository and switched into the repository directory (${REPO_DIR})." else echo "Branch ${BRANCH} does not exist on ${BUILD_REPO} yet." echo "Cloning default branch and creating branch '${BRANCH}' on top of it." git clone ${REPO_URL} ${REPO_DIR} --depth 100 cd ${REPO_DIR} echo "Cloned repository and switched into directory. Creating new branch now.." git checkout -b ${BRANCH} fi ) # copy over build artifacts into the repo directory rm -rf $REPO_DIR/* cp -R $ARTIFACTS_DIR/* $REPO_DIR/ if [[ ${CI} ]]; then ( # The file ~/.git_credentials is created in /.circleci/config.yml cd $REPO_DIR && \ git config credential.helper "store --file=$HOME/.git_credentials" ) fi echo `date` > $REPO_DIR/BUILD_INFO echo $SHA >> $REPO_DIR/BUILD_INFO echo 'This file is used by the npm/yarn_install rule to detect APF. See https://github.com/bazelbuild/rules_nodejs/issues/927' > $REPO_DIR/ANGULAR_PACKAGE ( cd $REPO_DIR && \ git config user.name "${COMMITTER_USER_NAME}" && \ git config user.email "${COMMITTER_USER_EMAIL}" && \ git add --all && \ git commit -m "${COMMIT_MSG}" --quiet && \ git tag "${BUILD_VER}" --force && \ git push origin "${BRANCH}" --tags --force ) } # Publish all individual packages from packages-dist. function publishPackages { GIT_SCHEME=$1 PKGS_DIST=$2 BRANCH=$3 BUILD_VER=$4 for dir in $PKGS_DIST/*/ do if [[ ! -f "$dir/package.json" ]]; then # Only publish directories that contain a `package.json` file. echo "Skipping $dir, it does not contain a package to be published." continue fi COMPONENT="$(basename ${dir})" # Replace _ with - in component name. COMPONENT="${COMPONENT//_/-}" JS_BUILD_ARTIFACTS_DIR="${dir}" if [[ "$GIT_SCHEME" == "ssh" ]]; then REPO_URL="git@github.com:${ORG}/${COMPONENT}-builds.git" elif [[ "$GIT_SCHEME" == "http" ]]; then REPO_URL="https://github.com/${ORG}/${COMPONENT}-builds.git" else die "Don't have a way to publish to scheme $GIT_SCHEME" fi publishRepo "${COMPONENT}" "${JS_BUILD_ARTIFACTS_DIR}" done echo "Finished publishing build artifacts" } function publishAllBuilds() { GIT_SCHEME="$1" SHA=`git rev-parse HEAD` COMMIT_MSG=`git log --oneline -1` COMMITTER_USER_NAME=`git --no-pager show -s --format='%cN' HEAD` COMMITTER_USER_EMAIL=`git --no-pager show -s --format='%cE' HEAD` PACKAGES_DIST="$(pwd)/dist/packages-dist" local shortSha=`git rev-parse --short HEAD` local latestTag=`getLatestTag` publishPackages $GIT_SCHEME $PACKAGES_DIST $CUR_BRANCH "${latestTag}+${shortSha}" } # See docs/DEVELOPER.md for help CUR_BRANCH=$(git symbolic-ref --short HEAD) if [ $# -gt 0 ]; then ORG=$1 publishAllBuilds "ssh" else ORG="angular" publishAllBuilds "http" fi
{ "end_byte": 4503, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/scripts/ci/publish-build-artifacts.sh" }
angular/scripts/ci/create-package-archives.sh_0_1502
#!/usr/bin/env bash set -eu -o pipefail readonly safeBranchName="$(echo $1 | sed 's/^pull\//pr/' | sed 's/[^A-Za-z0-9_.-]/_/g')" readonly shortLastSha="$(git rev-parse --short $2)" readonly inputDir="$PROJECT_ROOT/$3" readonly outputDir="$PROJECT_ROOT/$4" readonly fileSuffix="-$safeBranchName-$shortLastSha.tgz" echo "Creating compressed archives for packages in '$inputDir'." # Create or clean-up the output directory. echo " Preparing output directory: $outputDir" rm -rf "$outputDir" mkdir -p "$outputDir" # If there are more than one packages in `$inputDir`... if [[ $(ls -1 "$inputDir" | wc -l) -gt 1 ]]; then # Create a compressed archive containing all packages. # (This is useful for copying all packages into `node_modules/` (without changing `package.json`).) outputFileName=all$fileSuffix echo " Creating archive with all packages --> '$outputFileName'..." tar --create --gzip --directory "$inputDir" --file "$outputDir/$outputFileName" --transform s/^\./packages/ . fi # Create a compressed archive for each package. # (This is useful for referencing the path/URL to the resulting archive in `package.json`.) for dir in $inputDir/* do packageName=`basename "$dir"` outputFileName="$packageName$fileSuffix" outputFilePath="$outputDir/$outputFileName" echo " Processing package '$packageName' --> '$outputFileName'..." tar --create --gzip --directory "$dir" --file "$outputFilePath" --transform s/^\./package/ . done echo "Done creating compressed archives."
{ "end_byte": 1502, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/scripts/ci/create-package-archives.sh" }
angular/scripts/benchmarks/results.mts_0_2382
/** * @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 path from 'path'; import Zip from 'adm-zip'; import type {JsonReport} from '../../packages/benchpress/src/reporter/json_file_reporter_types.js'; import {bold} from '@angular/ng-dev'; /** Results of an individual benchmark scenario. */ export interface ScenarioResult { id: string; data: JsonReport; summaryConsoleText: string; summaryMarkdownText: string; } /** * Overall result of a benchmark target. * A benchmark target may contain multiple scenarios. */ export interface OverallResult { scenarios: ScenarioResult[]; summaryConsoleText: string; summaryMarkdownText: string; } /** Collects and parses the benchmark results of the given Bazel target testlog directory. */ export function collectBenchmarkResults(testlogDir: string): OverallResult { const z = new Zip(path.join(testlogDir, 'test.outputs/outputs.zip')); const scenarioResults: ScenarioResult[] = []; for (const e of z.getEntries()) { if (path.extname(e.entryName) !== '.json') { continue; } const data = JSON.parse(z.readAsText(e.entryName)); // Skip files that do not look like benchpress reports. if (!isJsonReport(data)) { continue; } scenarioResults.push({ id: data.description.id, data, // Output used for console output when running locally/CI. summaryConsoleText: `\ ${data.metricsText} ${data.validSampleTexts.join('\n')} ${data.statsText}`, // Output used for e.g. GitHub actions. summaryMarkdownText: `\ <details><summary>Full example results</summary> \`\`\` ${data.metricsText} ${data.validSampleTexts.join('\n')} ${data.statsText} \`\`\` </details> \`\`\` ${data.metricsText} ${data.statsText} \`\`\``, }); } return { scenarios: scenarioResults, summaryConsoleText: scenarioResults .map((s) => `${bold(s.id)}\n\n${s.summaryConsoleText}`) .join('`\n'), summaryMarkdownText: scenarioResults .map((s) => `### ${s.id}\n\n${s.summaryMarkdownText}`) .join('`\n'), }; } /** Whether the object corresponds to a benchpress JSON report. */ function isJsonReport(data: any): data is JsonReport { return data['completeSample'] !== undefined; }
{ "end_byte": 2382, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/scripts/benchmarks/results.mts" }
angular/scripts/benchmarks/targets.mts_0_1724
/** * @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 path from 'path'; import {exec} from './utils.mjs'; /** Branded string representing a resolved Bazel benchmark target. */ export type ResolvedTarget = string & { __resolvedTarget: true; }; /** Finds all benchmark Bazel targets in the project. */ export async function findBenchmarkTargets(): Promise<string[]> { return ( await exec('bazel', [ 'query', '--output=label', `'kind("^web_test", //modules/...) intersect attr("name", "perf", //modules/...)'`, ]) ) .split(/\r?\n/) .filter((t) => t !== ''); } /** Gets the testlog path of a given Bazel target. */ export async function getTestlogPath(target: ResolvedTarget): Promise<string> { return path.join(await bazelTestlogDir(), target.substring(2).replace(':', '/')); } /** Resolves a given benchmark Bazel target to the fully expanded label. */ export async function resolveTarget(target: string): Promise<ResolvedTarget> { // If the target does not specify an explicit browser test target, we attempt // to automatically add the Chromium suffix. This is necessary for e.g. // resolving testlogs which would reside under the actual test target. if (!target.endsWith('_chromium')) { target = `${target}_chromium`; } return (await exec('bazel', ['query', '--output=label', target])).trim() as ResolvedTarget; } let testlogDir: string | null = null; async function bazelTestlogDir(): Promise<string> { return testlogDir ?? (testlogDir = (await exec('bazel', ['info', 'bazel-testlogs'])).trim()); }
{ "end_byte": 1724, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/scripts/benchmarks/targets.mts" }
angular/scripts/benchmarks/index.mts_0_7333
/** * @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 {setOutput} from '@actions/core'; import {GitClient, Log, bold, green, yellow} from '@angular/ng-dev'; import {select} from '@inquirer/prompts'; import yargs from 'yargs'; import {collectBenchmarkResults} from './results.mjs'; import {ResolvedTarget, findBenchmarkTargets, getTestlogPath, resolveTarget} from './targets.mjs'; import {exec} from './utils.mjs'; const benchmarkTestFlags = [ '--cache_test_results=no', '--color=yes', '--curses=no', // We may have RBE set up, but test should run locally on the same machine to // reduce fluctuation. Output streamed ensures that deps can build with RBE, but // tests run locally while also providing useful output for debugging. '--test_output=streamed', ]; await yargs(process.argv.slice(2)) .command( 'run-compare <compare-ref> [bazel-target]', 'Runs a benchmark between two SHAs', (argv) => argv .positional('compare-ref', { description: 'Comparison SHA', type: 'string', demandOption: true, }) .positional('bazel-target', {description: 'Bazel target', type: 'string'}), (args) => runCompare(args.bazelTarget, args.compareRef), ) .command( 'run [bazel-target]', 'Runs a benchmark', (argv) => argv.positional('bazel-target', {description: 'Bazel target', type: 'string'}), (args) => runBenchmarkCmd(args.bazelTarget), ) .command( 'prepare-for-github-action <comment-body>', false, // Do not show in help. (argv) => argv.positional('comment-body', {demandOption: true, type: 'string'}), (args) => prepareForGitHubAction(args.commentBody), ) .demandCommand() .scriptName('$0') .help() .strict() .parseAsync(); /** Prompts for a benchmark target. */ async function promptForBenchmarkTarget(): Promise<string> { const targets = await findBenchmarkTargets(); return await select({ message: 'Select benchmark target to run:', choices: targets.map((t) => ({value: t, name: t})), }); } /** * Prepares a benchmark comparison running via GitHub action. This command is * used by the GitHub action YML workflow and is responsible for extracting * e.g. command information or fetching/resolving Git refs of the comparison range. * * This is a helper used by the GitHub action to perform benchmark * comparisons. Commands follow the format of: `/benchmark-compare <sha> <target>`. */ async function prepareForGitHubAction(commentBody: string): Promise<void> { const matches = /\/[^ ]+ ([^ ]+) ([^ ]+)/.exec(commentBody); if (matches === null) { Log.error('Could not extract information from comment', commentBody); process.exit(1); } const git = await GitClient.get(); const [_, compareRefRaw, benchmarkTarget] = matches; // We assume the PR is checked out and therefore `HEAD` is the PR head SHA. const prHeadSha = git.run(['rev-parse', 'HEAD']).stdout.trim(); setOutput('benchmarkTarget', benchmarkTarget); setOutput('prHeadSha', prHeadSha); // Attempt to find the compare SHA. The commit may be either part of the // pull request, or might be a commit unrelated to the PR- but part of the // upstream repository. We attempt to fetch/resolve the SHA in both remotes. const compareRefResolve = git.runGraceful(['rev-parse', compareRefRaw]); let compareRefSha = compareRefResolve.stdout.trim(); if (compareRefSha === '' || compareRefResolve.status !== 0) { git.run(['fetch', '--depth=1', git.getRepoGitUrl(), compareRefRaw]); compareRefSha = git.run(['rev-parse', 'FETCH_HEAD']).stdout.trim(); } setOutput('compareSha', compareRefSha); } /** Runs a specified benchmark, or a benchmark selected via prompt. */ async function runBenchmarkCmd(bazelTargetRaw: string | undefined): Promise<void> { if (bazelTargetRaw === undefined) { bazelTargetRaw = await promptForBenchmarkTarget(); } const bazelTarget = await resolveTarget(bazelTargetRaw); const testlogPath = await getTestlogPath(bazelTarget); await runBenchmarkTarget(bazelTarget); const workingDirResults = await collectBenchmarkResults(testlogPath); Log.info('\n\n\n'); Log.info(bold(green('Results!'))); Log.info(workingDirResults.summaryConsoleText); } /** Runs a benchmark Bazel target. */ async function runBenchmarkTarget(bazelTarget: ResolvedTarget): Promise<void> { await exec('bazel', ['test', bazelTarget, ...benchmarkTestFlags]); } /** * Performs a comparison of benchmark results between the current * working stage and the comparison Git reference. */ async function runCompare(bazelTargetRaw: string | undefined, compareRef: string): Promise<void> { const git = await GitClient.get(); const currentRef = git.getCurrentBranchOrRevision(); if (git.hasUncommittedChanges()) { Log.warn(bold('You have uncommitted changes.')); Log.warn('The script will stash your changes and re-apply them so that'); Log.warn('the comparison ref can be checked out.'); Log.warn(''); } if (bazelTargetRaw === undefined) { bazelTargetRaw = await promptForBenchmarkTarget(); } const bazelTarget = await resolveTarget(bazelTargetRaw); const testlogPath = await getTestlogPath(bazelTarget); Log.log(green('Test log path:', testlogPath)); // Run benchmark with the current working stage. await runBenchmarkTarget(bazelTarget); const workingDirResults = await collectBenchmarkResults(testlogPath); // Stash working directory as we might be in the middle of developing // and we wouldn't want to discard changes when checking out the compare SHA. git.run(['stash']); try { Log.log(green('Fetching comparison revision.')); // Note: Not using a shallow fetch here as that would convert the local // user repository into an incomplete repository. git.run(['fetch', git.getRepoGitUrl(), compareRef]); Log.log(green('Checking out comparison revision.')); git.run(['checkout', 'FETCH_HEAD']); await exec('yarn'); await runBenchmarkTarget(bazelTarget); } finally { restoreWorkingStage(git, currentRef); } // Re-install dependencies for `HEAD`. await exec('yarn'); const comparisonResults = await collectBenchmarkResults(testlogPath); // If we are running in a GitHub action, expose the benchmark text // results as outputs. Useful if those are exposed as a GitHub comment then. if (process.env.GITHUB_ACTION !== undefined) { setOutput('comparisonResultsText', comparisonResults.summaryMarkdownText); setOutput('workingStageResultsText', workingDirResults.summaryMarkdownText); } Log.info('\n\n\n'); Log.info(bold(green('Results!'))); Log.info(bold(yellow(`Comparison reference (${compareRef}) results:`)), '\n'); Log.info(comparisonResults.summaryConsoleText); Log.info(bold(yellow(`Working stage (${currentRef}) results:`)), '\n'); Log.info(workingDirResults.summaryConsoleText); } function restoreWorkingStage(git: GitClient, initialRef: string) { Log.log(green('Restoring working stage')); git.run(['checkout', '-f', initialRef]); // Stash apply could fail if there were not changes in the working stage. git.runGraceful(['stash', 'apply']); }
{ "end_byte": 7333, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/scripts/benchmarks/index.mts" }
angular/scripts/benchmarks/README.md_0_483
## Benchmarks script This folder contains a convenience script for running benchmarks and performing comparisons. It can be run via `yarn benchmarks`. See command line help for possible commands. The benchmark script is used in conjunction with the benchmark compare GitHub actions workflow, allowing organization members to initiate a benchmark comparison via a GitHub comment in a PR. ### Docs See ![the benchmark documentation](../../contributing-docs/running-benchmarks.md).
{ "end_byte": 483, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/scripts/benchmarks/README.md" }
angular/scripts/benchmarks/utils.mts_0_1466
/** * @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 {Log} from '@angular/ng-dev'; import childProcess from 'child_process'; import path from 'path'; import url from 'url'; const scriptDir = path.dirname(url.fileURLToPath(import.meta.url)); /** Absolute disk path to the project directory. */ export const projectDir = path.join(scriptDir, '../..'); /** * Executes the given command, forwarding stdin, stdout and stderr while * still capturing stdout in order to return it. */ export function exec(cmd: string, args: string[] = []): Promise<string> { return new Promise((resolve, reject) => { Log.info('Running command:', cmd, args.join(' ')); const proc = childProcess.spawn(cmd, args, { shell: true, cwd: projectDir, // Only capture `stdout`. Forward the rest to the parent TTY. stdio: ['inherit', 'pipe', 'inherit'], }); let stdout = ''; proc.stdout.on('data', (chunk) => { stdout += chunk.toString('utf8'); process.stdout.write(chunk); }); proc.on('close', (status, signal) => { if (status !== 0 || signal !== null) { reject(`Command failed. Status code: ${status}. Signal: ${signal}`); } resolve(stdout); }); proc.on('error', (err) => { reject(`Command failed: ${err}`); }); }); }
{ "end_byte": 1466, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/scripts/benchmarks/utils.mts" }
angular/scripts/build/zone-js-builder.mts_0_2293
/** * @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 'path'; import sh from 'shelljs'; import {projectDir, bazelCmd, exec} from './package-builder.mjs'; /** * Build the `zone.js` npm package into `dist/bin/packages/zone.js/npm_package/` and copy it to * `destDir` for other scripts/tests to use. * * NOTE: The `zone.js` package is not built as part of `package-builder`'s `buildTargetPackages()` * nor is it copied into the same directory as the Angular packages (e.g. * `dist/packages-dist/`) despite its source's being inside `packages/`, because it is not * published to npm under the `@angular` scope (as happens for the rest of the packages). * * @param {string} destDir Path to the output directory into which we copy the npm package. * This path should either be absolute or relative to the project root. */ export function buildZoneJsPackage(destDir: string): void { console.info('##############################'); console.info(' Building zone.js npm package'); console.info('##############################'); exec(`${bazelCmd} run //packages/zone.js:npm_package.pack`); // Create the output directory. if (!sh.test('-d', destDir)) { sh.mkdir('-p', destDir); } const bazelBinPath = exec(`${bazelCmd} info bazel-bin`, true); // Copy artifacts to `destDir`, so they can be easier persisted on CI and used by non-bazel // scripts/tests. const buildOutputDir = join(bazelBinPath, 'packages/zone.js/npm_package'); const distTargetDir = join(destDir, 'zone.js'); console.info(`# Copy npm_package artifacts to ${distTargetDir}`); sh.rm('-rf', distTargetDir); sh.cp('-R', buildOutputDir, distTargetDir); sh.chmod('-R', 'u+w', distTargetDir); // Copy `zone.js.tgz` to `destDir`, so we can test // the archive generated by the `npm_package.pack` rule. const distArchiveTargetDir = `${destDir}/archive`; console.info(`# Copy npm_package archive file to ${distArchiveTargetDir}`); sh.rm('-rf', distArchiveTargetDir); sh.mkdir('-p', distArchiveTargetDir); sh.mv(`${projectDir}/zone.js-*.tgz`, `${distArchiveTargetDir}/zone.js.tgz`); }
{ "end_byte": 2293, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/scripts/build/zone-js-builder.mts" }
angular/scripts/build/angular-in-memory-web-api.mts_0_1974
/** * @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 'path'; import sh from 'shelljs'; import {projectDir, bazelCmd, exec} from './package-builder.mjs'; /** * Build the `angular-in-memory-web-api` npm package and copies it into the release * distribution directory. * * NOTE: The `angular-in-memory-web-api` package is not built as part of `package-builder`'s * `buildTargetPackages()` nor is it copied into the same directory as the Angular packages (e.g. * `dist/packages-dist/`) despite its source's being inside `packages/`, because it is not * published to npm under the `@angular` scope (as happens for the rest of the packages). * * @param {string} destDir Path to the output directory into which we copy the npm package. * This path should either be absolute or relative to the project root. */ export function buildAngularInMemoryWebApiPackage(destDir: string): void { console.info('##############################'); console.info(' Building angular-in-memory-web-api npm package'); console.info('##############################'); exec(`${bazelCmd} build //packages/misc/angular-in-memory-web-api:npm_package`); // Create the output directory. if (!sh.test('-d', destDir)) { sh.mkdir('-p', destDir); } const bazelBinPath = exec(`${bazelCmd} info bazel-bin`, true); // Copy artifacts to `destDir`, so they can be easier persisted on CI and used by non-bazel // scripts/tests. const buildOutputDir = join(bazelBinPath, 'packages/misc/angular-in-memory-web-api/npm_package'); const distTargetDir = join(destDir, 'angular-in-memory-web-api'); console.info(`# Copy npm_package artifacts to ${distTargetDir}`); sh.rm('-rf', distTargetDir); sh.cp('-R', buildOutputDir, distTargetDir); sh.chmod('-R', 'u+w', distTargetDir); }
{ "end_byte": 1974, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/scripts/build/angular-in-memory-web-api.mts" }
angular/scripts/build/package-builder.mts_0_5384
/** * @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 {execSync} from 'child_process'; import {join, dirname} from 'path'; import {BuiltPackage} from '@angular/ng-dev'; import {fileURLToPath} from 'url'; import sh from 'shelljs'; // ShellJS should exit if a command fails. sh.set('-e'); /** Path to the project directory. */ export const projectDir = join(dirname(fileURLToPath(import.meta.url)), '../..'); /** Command that runs Bazel. */ export const bazelCmd = process.env.BAZEL || `yarn -s bazel`; /** Name of the Bazel tag that will be used to find release package targets. */ const releaseTargetTag = 'release-with-framework'; /** Command that queries Bazel for all release package targets. */ const queryPackagesCmd = `${bazelCmd} query --output=label "attr('tags', '\\[.*${releaseTargetTag}.*\\]', //packages/...) ` + `intersect kind('ng_package|pkg_npm', //packages/...)"`; /** Path for the default distribution output directory. */ const defaultDistPath = join(projectDir, 'dist/packages-dist'); /** Builds the release packages for NPM. */ export function performNpmReleaseBuild(): BuiltPackage[] { return buildReleasePackages(defaultDistPath, /* isSnapshotBuild */ false); } /** * Builds the release packages as snapshot build. This means that the current * Git HEAD SHA is included in the version (for easier debugging and back tracing). */ export function performDefaultSnapshotBuild(): BuiltPackage[] { return buildReleasePackages(defaultDistPath, /* isSnapshotBuild */ true, [ // For snapshot builds, the Bazel package is still built. We want to have // GitHub snapshot builds for it. '//packages/bazel:npm_package', ]); } /** * Builds the release packages with the given compile mode and copies * the package output into the given directory. */ function buildReleasePackages( distPath: string, isSnapshotBuild: boolean, additionalTargets: string[] = [] ): BuiltPackage[] { console.info('######################################'); console.info(' Building release packages...'); console.info('######################################'); // List of targets to build. e.g. "packages/core:npm_package", or "packages/forms:npm_package". const targets = exec(queryPackagesCmd, true).split(/\r?\n/).concat(additionalTargets); const packageNames = getPackageNamesOfTargets(targets); const bazelBinPath = exec(`${bazelCmd} info bazel-bin`, true); const getBazelOutputPath = (pkgName: string) => join(bazelBinPath, 'packages', pkgName, 'npm_package'); const getDistPath = (pkgName: string) => join(distPath, pkgName); // Build with "--config=release" or `--config=snapshot-build` so that Bazel // runs the workspace stamping script. The stamping script ensures that the // version placeholder is populated in the release output. const stampConfigArg = `--config=${isSnapshotBuild ? 'snapshot-build' : 'release'}`; // Walk through each release package and clear previous "npm_package" outputs. This is // a workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1219. We need to // do this to ensure that the version placeholders are properly populated. packageNames.forEach((pkgName) => { const outputPath = getBazelOutputPath(pkgName); if (sh.test('-d', outputPath)) { sh.chmod('-R', 'u+w', outputPath); sh.rm('-rf', outputPath); } }); exec(`${bazelCmd} build ${stampConfigArg} ${targets.join(' ')}`); // Delete the distribution directory so that the output is guaranteed to be clean. Re-create // the empty directory so that we can copy the release packages into it later. sh.rm('-rf', distPath); sh.mkdir('-p', distPath); // Copy the package output into the specified distribution folder. packageNames.forEach((pkgName) => { const outputPath = getBazelOutputPath(pkgName); const targetFolder = getDistPath(pkgName); console.info(`> Copying package output to "${targetFolder}"`); sh.cp('-R', outputPath, targetFolder); sh.chmod('-R', 'u+w', targetFolder); }); return packageNames.map((pkg) => { return { name: `@angular/${pkg}`, outputPath: getDistPath(pkg), }; }); } /** * Gets the package names of the specified Bazel targets. * e.g. //packages/core:npm_package => core */ function getPackageNamesOfTargets(targets: string[]): string[] { return targets.map((targetName) => { const matches = targetName.match(/\/\/packages\/(.*):npm_package/); if (matches === null) { throw Error( `Found Bazel target with "${releaseTargetTag}" tag, but could not ` + `determine release output name: ${targetName}` ); } return matches[1]; }); } /** Executes the given command in the project directory. */ export function exec(command: string): void; /** Executes the given command in the project directory and returns its stdout. */ export function exec(command: string, captureStdout: true): string; export function exec(command: string, captureStdout?: true) { const stdout = execSync(command, { cwd: projectDir, stdio: ['inherit', captureStdout ? 'pipe' : 'inherit', 'inherit'], }); if (captureStdout) { process.stdout.write(stdout); return stdout.toString().trim(); } }
{ "end_byte": 5384, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/scripts/build/package-builder.mts" }
angular/scripts/build/build-packages-dist.mts_0_928
#!/usr/bin/env node /** * @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 {buildAngularInMemoryWebApiPackage} from './angular-in-memory-web-api.mjs'; import {performDefaultSnapshotBuild} from './package-builder.mjs'; import {buildZoneJsPackage} from './zone-js-builder.mjs'; // Build the legacy (view engine) npm packages into `dist/packages-dist/`. performDefaultSnapshotBuild(); // Build the `angular-in-memory-web-api` npm package into `dist/angular-in-memory-web-api-dist/`, // because it might be needed by other scripts/targets. buildAngularInMemoryWebApiPackage('dist/angular-in-memory-web-api-dist'); // Build the `zone.js` npm package into `dist/zone.js-dist/`, because it might be needed by other // scripts/tests. buildZoneJsPackage('dist/zone.js-dist');
{ "end_byte": 928, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/scripts/build/build-packages-dist.mts" }
angular/packages/types.d.ts_0_864
/** * @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 contains all ambient imports needed to compile the packages/ source code /// <reference types="hammerjs" /> /// <reference lib="es2015" /> /// <reference path="./goog.d.ts" /> /// <reference path="./system.d.ts" /> // Do not included "node" and "jasmine" types here as we don't // want these ambient types to be included everywhere. // Tests will bring in ambient node & jasmine types with // /packages/tsconfig-test.json when `testonly = True` is set // and packages such as platform-server that need these types should // use `/// <reference types="x">` in their main entry points declare let isNode: boolean; declare let isBrowser: boolean;
{ "end_byte": 864, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/types.d.ts" }
angular/packages/license-banner.txt_0_112
/** * @license Angular v0.0.0-PLACEHOLDER * (c) 2010-2024 Google LLC. https://angular.io/ * License: MIT */
{ "end_byte": 112, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/license-banner.txt" }
angular/packages/README.md_0_296
Angular ======= The sources for this package are in the main [Angular](https://github.com/angular/angular) repo. Please file issues and pull requests against that repo. Usage information and reference details can be found in [Angular documentation](https://angular.dev/overview). License: MIT
{ "end_byte": 296, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/README.md" }
angular/packages/circular-deps-test.conf.js_0_898
/** * @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 path = require('path'); module.exports = { baseDir: '../', goldenFile: '../goldens/circular-deps/packages.json', glob: `./**/*.ts`, // Command that will be displayed if the golden needs to be updated. approveCommand: 'yarn ts-circular-deps:approve', resolveModule: resolveModule, ignoreTypeOnlyChecks: true, }; /** * Custom module resolver that maps specifiers starting with `@angular/` to the * local packages folder. This ensures that cross package/entry-point dependencies * can be detected. */ function resolveModule(specifier) { if (specifier.startsWith('@angular/')) { return path.join(__dirname, specifier.slice('@angular/'.length)); } return null; }
{ "end_byte": 898, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/circular-deps-test.conf.js" }
angular/packages/empty.ts_0_389
/** * @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 intentionally left blank. It is used to load nothing in some cases. // Such as parse5/index is redirected here instead of loading into browser. export let __empty__: any;
{ "end_byte": 389, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/empty.ts" }
angular/packages/goog.d.ts_0_660
/** * @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 */ /** * Typings for google closure. */ declare namespace goog { /** * Note: Don't use this to check for advanced compilation, * as it is sometimes true. */ export const DEBUG: boolean; export const LOCALE: string; export const getMsg: (input: string, placeholders?: {[key: string]: string}) => string; export const getLocale: () => string; } /** * Use this flag to check for advanced compilation. */ declare const COMPILED: boolean;
{ "end_byte": 660, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/goog.d.ts" }
angular/packages/BUILD.bazel_0_4400
load("//tools:defaults.bzl", "ts_config", "ts_library") load("//:packages.bzl", "DOCS_ENTRYPOINTS") load("//adev/shared-docs/pipeline/api-gen/manifest:generate_api_manifest.bzl", "generate_api_manifest") package(default_visibility = ["//visibility:public"]) exports_files([ "tsconfig-build.json", "tsconfig.json", ]) ts_library( name = "types", srcs = glob(["*.ts"]), deps = [ "//packages/zone.js/lib:zone_d_ts", "@npm//@types/hammerjs", ], ) ts_config( name = "tsconfig-test", src = "tsconfig-test.json", deps = [":tsconfig-build.json"], ) ts_config( name = "tsec_config", src = "tsconfig-tsec-base.json", deps = [ ":tsconfig-build.json", ":tsec-exemption.json", ], ) exports_files([ "license-banner.txt", "README.md", "examples", ]) # All docgen targets for our doc site. Add package entrypoints to DOCS_ENTRYPOINTS in `packages.bzl`. filegroup( name = "files_for_docgen", srcs = ["//packages/%s:files_for_docgen" % entrypoint for entrypoint in DOCS_ENTRYPOINTS], ) # This target captures common dependencies needed for all `generate_api_docs` targets # throughout Angular's public API surface. filegroup( name = "common_files_and_deps_for_docs", srcs = [ "//packages:types", "//packages/common:files_for_docgen", "//packages/common/http:files_for_docgen", "//packages/core:files_for_docgen", "//packages/core/primitives/signals:files_for_docgen", "//packages/core/src/compiler:files_for_docgen", "//packages/core/src/di/interface:files_for_docgen", "//packages/core/src/interface:files_for_docgen", "//packages/core/src/reflection:files_for_docgen", "//packages/core/src/util:files_for_docgen", "//packages/platform-browser:files_for_docgen", "//packages/platform-browser-dynamic:files_for_docgen", "//packages/zone.js/lib:zone_d_ts", "@npm//rxjs", ], ) generate_api_manifest( name = "docs_api_manifest", srcs = [ "//packages/animations:animations_docs_extraction", "//packages/animations/browser:animations_browser_docs_extraction", "//packages/animations/browser/testing:animations_browser_testing_docs_extraction", "//packages/common:common_docs_extraction", "//packages/common/http:http_docs_extraction", "//packages/common/http/testing:http_testing_docs_extraction", "//packages/common/testing:common_testing_docs_extraction", "//packages/common/upgrade:common_upgrade_docs_extraction", "//packages/core:core_docs_extraction", "//packages/core/global:core_global_docs_extraction", "//packages/core/reference-manifests", "//packages/core/rxjs-interop:core_rxjs-interop_docs_extraction", "//packages/core/testing:core_testing_docs_extraction", "//packages/elements:elements_docs_extraction", "//packages/forms:forms_docs_extraction", "//packages/localize:localize_docs_extraction", "//packages/localize/src/localize:localize_init_docs_extraction", "//packages/platform-browser:platform-browser_docs_extraction", "//packages/platform-browser-dynamic:platform-browser_dynamic_docs_extraction", "//packages/platform-browser-dynamic/testing:platform-browser_dynamic_testing_docs_extraction", "//packages/platform-browser/animations:platform-browser_animations_docs_extraction", "//packages/platform-browser/animations/async:platform-browser_animations_async_docs_extraction", "//packages/platform-browser/testing:platform-browser_testing_docs_extraction", "//packages/platform-server:platform-server_docs_extraction", "//packages/platform-server/testing:platform-server_testing_docs_extraction", "//packages/router:router_docs_extraction", "//packages/router/testing:router_testing_docs_extraction", "//packages/router/upgrade:router_upgrade_docs_extraction", "//packages/service-worker:service-worker_docs_extraction", "//packages/upgrade:upgrade_docs_extraction", "//packages/upgrade/static:upgrade_static_docs_extraction", "//packages/upgrade/static/testing:upgrade_static_testing_docs_extraction", "//tools/manual_api_docs/blocks", "//tools/manual_api_docs/elements", ], )
{ "end_byte": 4400, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/BUILD.bazel" }
angular/packages/system.d.ts_0_264
/** * @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 */ /** Dummy typings for systemjs. */ declare var System: any;
{ "end_byte": 264, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/system.d.ts" }
angular/packages/compiler-cli/esbuild.config.js_0_597
/** * @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 */ module.exports = { resolveExtensions: ['.mjs', '.js'], // Note: `@bazel/esbuild` has a bug and does not pass-through the format from Starlark. format: 'esm', banner: { // Workaround for: https://github.com/evanw/esbuild/issues/946 js: ` import {createRequire as __cjsCompatRequire} from 'module'; const require = __cjsCompatRequire(import.meta.url); `, }, };
{ "end_byte": 597, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/esbuild.config.js" }
angular/packages/compiler-cli/BUILD.bazel_0_4893
load("@npm//@bazel/esbuild:index.bzl", "esbuild", "esbuild_config") load("//packages/bazel/src:ng_perf.bzl", "ng_perf_flag") load("//tools:defaults.bzl", "api_golden_test", "extract_types", "pkg_npm", "ts_config", "ts_library") package(default_visibility = ["//visibility:public"]) PUBLIC_TARGETS = [ ":compiler-cli", "//packages/compiler-cli/private", "//packages/compiler-cli/ngcc", "//packages/compiler-cli/linker", "//packages/compiler-cli/linker/babel", ] esbuild_config( name = "esbuild_config", config_file = "esbuild.config.js", ) esbuild( name = "bundles", config = ":esbuild_config", entry_points = [ ":index.ts", "//packages/compiler-cli:src/bin/ngc.ts", "//packages/compiler-cli/ngcc:index.ts", "//packages/compiler-cli:src/bin/ng_xi18n.ts", "//packages/compiler-cli/linker:index.ts", "//packages/compiler-cli/linker/babel:index.ts", "//packages/compiler-cli/private:bazel.ts", "//packages/compiler-cli/private:localize.ts", "//packages/compiler-cli/private:migrations.ts", "//packages/compiler-cli/private:tooling.ts", ], external = [ "@angular/compiler", "typescript", "@babel/core", "reflect-metadata", "chokidar", "convert-source-map", "semver", "@jridgewell/sourcemap-codec", "tslib", "yargs", ], format = "esm", platform = "node", splitting = True, target = "node12", deps = PUBLIC_TARGETS, ) ts_config( name = "tsconfig", src = "tsconfig-build.json", deps = ["//packages:tsconfig-build.json"], ) ts_library( name = "compiler-cli", srcs = glob( [ "*.ts", "src/**/*.ts", ], exclude = [ "src/integrationtest/**/*.ts", ], ), tsconfig = ":tsconfig", deps = [ "//packages/compiler", "//packages/compiler-cli/private", "//packages/compiler-cli/src/ngtsc/core", "//packages/compiler-cli/src/ngtsc/core:api", "//packages/compiler-cli/src/ngtsc/diagnostics", "//packages/compiler-cli/src/ngtsc/docs", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/incremental", "//packages/compiler-cli/src/ngtsc/indexer", "//packages/compiler-cli/src/ngtsc/logging", "//packages/compiler-cli/src/ngtsc/perf", "//packages/compiler-cli/src/ngtsc/program_driver", "//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/shims", "//packages/compiler-cli/src/ngtsc/transform/jit", "//packages/compiler-cli/src/ngtsc/translator", "//packages/compiler-cli/src/ngtsc/typecheck", "//packages/compiler-cli/src/ngtsc/typecheck/api", "//packages/compiler-cli/src/ngtsc/util", "@npm//@bazel/concatjs", "@npm//@types/node", "@npm//@types/yargs", "@npm//chokidar", "@npm//reflect-metadata", "@npm//typescript", ], ) extract_types( name = "api_type_definitions", deps = PUBLIC_TARGETS, ) pkg_npm( name = "npm_package", package_name = "@angular/compiler-cli", srcs = [ "package.json", ], tags = [ "release-with-framework", ], # Do not add more to this list. # Dependencies on the full npm_package cause long re-builds. visibility = [ "//adev:__pkg__", "//integration:__subpackages__", "//modules/ssr-benchmarks:__subpackages__", "//packages/compiler-cli/integrationtest:__pkg__", ], deps = [ ":api_type_definitions", ":bundles", ], ) api_golden_test( name = "error_code_api", data = [ ":npm_package", "//goldens:public-api", ], entry_point = "angular/packages/compiler-cli/npm_package/src/ngtsc/diagnostics/src/error_code.d.ts", golden = "angular/goldens/public-api/compiler-cli/error_code.api.md", ) api_golden_test( name = "extended_template_diagnostic_name_api", data = [ ":npm_package", "//goldens:public-api", ], entry_point = "angular/packages/compiler-cli/npm_package/src/ngtsc/diagnostics/src/extended_template_diagnostic_name.d.ts", golden = "angular/goldens/public-api/compiler-cli/extended_template_diagnostic_name.api.md", ) api_golden_test( name = "compiler_options_api", data = [ ":npm_package", "//goldens:public-api", ], entry_point = "angular/packages/compiler-cli/npm_package/src/ngtsc/core/api/src/public_options.d.ts", golden = "angular/goldens/public-api/compiler-cli/compiler_options.api.md", ) # Controls whether the Ivy compiler produces performance traces as part of each build ng_perf_flag( name = "ng_perf", build_setting_default = False, )
{ "end_byte": 4893, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/BUILD.bazel" }
angular/packages/compiler-cli/index.ts_0_1924
/** * @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 {NodeJSFileSystem, setFileSystem} from './src/ngtsc/file_system'; export {VERSION} from './src/version'; export * from './src/ngtsc/transform/jit'; export * from './src/transformers/api'; export * from './src/transformers/entry_points'; export * from './src/perform_compile'; // TODO(tbosch): remove this once usages in G3 are changed to `CompilerOptions` export {CompilerOptions as AngularCompilerOptions} from './src/transformers/api'; // Internal exports needed for packages relying on the compiler-cli. // TODO: Remove this when the CLI has switched to the private entry-point. export * from './private/tooling'; // Exposed as they are needed for relying on the `linker`. export * from './src/ngtsc/logging'; export * from './src/ngtsc/file_system'; // Exports for dealing with the `ngtsc` program. export {NgTscPlugin, PluginCompilerHost} from './src/ngtsc/tsc_plugin'; export {NgtscProgram} from './src/ngtsc/program'; export {OptimizeFor} from './src/ngtsc/typecheck/api'; // **Note**: Explicit named exports to make this file work with CJS/ESM interop without // needing to use a default import. NodeJS will expose named CJS exports as named ESM exports. // TODO(devversion): Remove these duplicate exports once devmode&prodmode is combined/ESM. export {ConsoleLogger, Logger, LogLevel} from './src/ngtsc/logging'; export {NodeJSFileSystem, absoluteFrom} from './src/ngtsc/file_system'; // Export documentation entities for Angular-internal API doc generation. export * from './src/ngtsc/docs/src/entities'; export * from './src/ngtsc/docs'; // Exposed for usage in 1P Angular plugin. export {isLocalCompilationDiagnostics} from './src/ngtsc/diagnostics'; setFileSystem(new NodeJSFileSystem());
{ "end_byte": 1924, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/index.ts" }
angular/packages/compiler-cli/ngcc/BUILD.bazel_0_257
load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "ngcc", srcs = ["index.ts"], tsconfig = "//packages/compiler-cli:tsconfig", deps = [ "@npm//@types/node", ], )
{ "end_byte": 257, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/ngcc/BUILD.bazel" }
angular/packages/compiler-cli/ngcc/index.ts_0_1958
#!/usr/bin/env node /** * @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 */ // https://github.com/chalk/chalk/blob/a370f468a43999e4397094ff5c3d17aadcc4860e/source/utilities.js#L21 function stringEncaseCRLFWithFirstIndex( value: string, prefix: string, postfix: string, index: number, ): string { let endIndex = 0; let returnValue = ''; do { const gotCR = value[index - 1] === '\r'; returnValue += value.substring(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? '\r\n' : '\n') + postfix; endIndex = index + 1; index = value.indexOf('\n', endIndex); } while (index !== -1); returnValue += value.substring(endIndex); return returnValue; } // adapted from // https://github.com/chalk/chalk/blob/a370f468a43999e4397094ff5c3d17aadcc4860e/source/index.js#L194 function styleMessage(message: string): string { // red + bold const open = '\x1b[31m\x1b[1m'; const close = '\x1b[22m\x1b[39m'; let styledMessage = message; const lfIndex = styledMessage.indexOf('\n'); if (lfIndex !== -1) { styledMessage = stringEncaseCRLFWithFirstIndex(styledMessage, close, open, lfIndex); } return open + styledMessage + close; } const warningMsg = ` ========================================== ALERT: As of Angular 16, "ngcc" is no longer required and not invoked during CLI builds. You are seeing this message because the current operation invoked the "ngcc" command directly. This "ngcc" invocation can be safely removed. A common reason for this is invoking "ngcc" from a "postinstall" hook in package.json. In Angular 17, this command will be removed. Remove this and any other invocations to prevent errors in later versions. ========================================== `; console.warn(styleMessage(warningMsg)); process.exit(0);
{ "end_byte": 1958, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/ngcc/index.ts" }
angular/packages/compiler-cli/test/mocks.ts_0_4377
/** * @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'; export type Entry = string | Directory; export interface Directory { [name: string]: Entry; } export class MockAotContext { private files: Entry[]; constructor( public currentDirectory: string, ...files: Entry[] ) { this.files = files; } fileExists(fileName: string): boolean { return typeof this.getEntry(fileName) === 'string'; } directoryExists(path: string): boolean { return path === this.currentDirectory || typeof this.getEntry(path) === 'object'; } readFile(fileName: string): string { const data = this.getEntry(fileName); if (typeof data === 'string') { return data; } return undefined!; } readResource(fileName: string): Promise<string> { const result = this.readFile(fileName); if (result == null) { return Promise.reject(new Error(`Resource not found: ${fileName}`)); } return Promise.resolve(result); } writeFile(fileName: string, data: string): void { const parts = fileName.split('/'); const name = parts.pop()!; const entry = this.getEntry(parts); if (entry && typeof entry !== 'string') { entry[name] = data; } } assumeFileExists(fileName: string): void { this.writeFile(fileName, ''); } getEntry(fileName: string | string[]): Entry | undefined { let parts = typeof fileName === 'string' ? fileName.split('/') : fileName; if (parts[0]) { parts = this.currentDirectory.split('/').concat(parts); } parts.shift(); parts = normalize(parts); return first(this.files, (files) => getEntryFromFiles(parts, files)); } getDirectories(path: string): string[] { const dir = this.getEntry(path); if (typeof dir !== 'object') { return []; } else { return Object.keys(dir).filter((key) => typeof dir[key] === 'object'); } } override(files: Entry) { return new MockAotContext(this.currentDirectory, files, ...this.files); } } function first<T>(a: T[], cb: (value: T) => T | undefined): T | undefined { for (const value of a) { const result = cb(value); if (result != null) return result; } return; } function getEntryFromFiles(parts: string[], files: Entry) { let current = files; while (parts.length) { const part = parts.shift()!; if (typeof current === 'string') { return undefined; } const next = (<Directory>current)[part]; if (next === undefined) { return undefined; } current = next; } return current; } function normalize(parts: string[]): string[] { const result: string[] = []; while (parts.length) { const part = parts.shift()!; switch (part) { case '.': break; case '..': result.pop(); break; default: result.push(part); } } return result; } export class MockCompilerHost implements ts.CompilerHost { constructor(private context: MockAotContext) {} fileExists(fileName: string): boolean { return this.context.fileExists(fileName); } readFile(fileName: string): string { return this.context.readFile(fileName); } directoryExists(directoryName: string): boolean { return this.context.directoryExists(directoryName); } getSourceFile( fileName: string, languageVersion: ts.ScriptTarget, onError?: (message: string) => void, ): ts.SourceFile { const sourceText = this.context.readFile(fileName); if (sourceText != null) { return ts.createSourceFile(fileName, sourceText, languageVersion); } else { return undefined!; } } getDefaultLibFileName(options: ts.CompilerOptions): string { return ts.getDefaultLibFileName(options); } writeFile: ts.WriteFileCallback = (fileName, text) => { this.context.writeFile(fileName, text); }; getCurrentDirectory(): string { return this.context.currentDirectory; } getCanonicalFileName(fileName: string): string { return fileName; } useCaseSensitiveFileNames(): boolean { return false; } getNewLine(): string { return '\n'; } getDirectories(path: string): string[] { return this.context.getDirectories(path); } }
{ "end_byte": 4377, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/mocks.ts" }
angular/packages/compiler-cli/test/version_helpers_spec.ts_0_2324
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {compareNumbers, compareVersions, isVersionBetween, toNumbers} from '../src/version_helpers'; describe('toNumbers', () => { it('should handle strings', () => { expect(toNumbers('2')).toEqual([2]); expect(toNumbers('2.1')).toEqual([2, 1]); expect(toNumbers('2.0.1')).toEqual([2, 0, 1]); }); }); describe('compareNumbers', () => { it('should handle empty arrays', () => { expect(compareNumbers([], [])).toEqual(0); }); it('should handle arrays of same length', () => { expect(compareNumbers([1], [3])).toEqual(-1); expect(compareNumbers([3], [1])).toEqual(1); expect(compareNumbers([1, 0], [1, 0])).toEqual(0); expect(compareNumbers([1, 1], [1, 0])).toEqual(1); expect(compareNumbers([1, 0], [1, 1])).toEqual(-1); expect(compareNumbers([1, 0, 9], [1, 1, 0])).toEqual(-1); expect(compareNumbers([1, 1, 0], [1, 0, 9])).toEqual(1); }); it('should handle arrays of different length', () => { expect(compareNumbers([2], [2, 1])).toEqual(-1); expect(compareNumbers([2, 1], [2])).toEqual(1); expect(compareNumbers([0, 9], [1])).toEqual(-1); expect(compareNumbers([1], [0, 9])).toEqual(1); expect(compareNumbers([2], [])).toEqual(1); expect(compareNumbers([], [2])).toEqual(-1); expect(compareNumbers([1, 0], [1, 0, 0, 0])).toEqual(0); }); }); describe('isVersionBetween', () => { it('should correctly check if a typescript version is within a given range', () => { expect(isVersionBetween('2.7.0', '2.40')).toEqual(false); expect(isVersionBetween('2.40', '2.7.0')).toEqual(true); expect(isVersionBetween('2.7.2', '2.7.0', '2.8.0')).toEqual(true); expect(isVersionBetween('2.7.2', '2.7.7', '2.8.0')).toEqual(false); }); }); describe('compareVersions', () => { it('should correctly compare versions', () => { expect(compareVersions('2.7.0', '2.40')).toEqual(-1); expect(compareVersions('2.40', '2.7.0')).toEqual(1); expect(compareVersions('2.40', '2.40')).toEqual(0); expect(compareVersions('2.40', '2.41')).toEqual(-1); expect(compareVersions('2', '2.1')).toEqual(-1); }); });
{ "end_byte": 2324, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/version_helpers_spec.ts" }
angular/packages/compiler-cli/test/typescript_support_spec.ts_0_2068
/** * @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 {checkVersion} from '../src/typescript_support'; describe('checkVersion', () => { const MIN_TS_VERSION = '2.7.2'; const MAX_TS_VERSION = '2.8.0'; const versionError = (version: string) => `The Angular Compiler requires TypeScript >=${MIN_TS_VERSION} and <${MAX_TS_VERSION} but ${version} was found instead.`; it('should not throw when a supported TypeScript version is used', () => { expect(() => checkVersion('2.7.2', MIN_TS_VERSION, MAX_TS_VERSION)).not.toThrow(); expect(() => checkVersion('2.7.9', MIN_TS_VERSION, MAX_TS_VERSION)).not.toThrow(); }); it('should handle a TypeScript version < the minimum supported one', () => { expect(() => checkVersion('2.4.1', MIN_TS_VERSION, MAX_TS_VERSION)).toThrowError( versionError('2.4.1'), ); expect(() => checkVersion('2.7.1', MIN_TS_VERSION, MAX_TS_VERSION)).toThrowError( versionError('2.7.1'), ); }); it('should handle a TypeScript version > the maximum supported one', () => { expect(() => checkVersion('2.9.0', MIN_TS_VERSION, MAX_TS_VERSION)).toThrowError( versionError('2.9.0'), ); expect(() => checkVersion('2.8.0', MIN_TS_VERSION, MAX_TS_VERSION)).toThrowError( versionError('2.8.0'), ); }); it('should throw when an out-of-bounds pre-release version is used', () => { expect(() => checkVersion('2.7.0-beta', MIN_TS_VERSION, MAX_TS_VERSION)).toThrowError( versionError('2.7.0-beta'), ); expect(() => checkVersion('2.8.5-rc.3', MIN_TS_VERSION, MAX_TS_VERSION)).toThrowError( versionError('2.8.5-rc.3'), ); }); it('should not throw when a valid pre-release version is used', () => { expect(() => checkVersion('2.7.2-beta', MIN_TS_VERSION, MAX_TS_VERSION)).not.toThrow(); expect(() => checkVersion('2.7.9-rc.8', MIN_TS_VERSION, MAX_TS_VERSION)).not.toThrow(); }); });
{ "end_byte": 2068, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/typescript_support_spec.ts" }
angular/packages/compiler-cli/test/perform_watch_spec.ts_0_473
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import * as fs from 'fs'; import * as path from 'path'; import ts from 'typescript'; import * as ng from '../index'; import {FileChangeEvent, performWatchCompilation} from '../src/perform_watch'; import {expectNoDiagnostics, setup, TestSupport} from './test_support';
{ "end_byte": 473, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/perform_watch_spec.ts" }
angular/packages/compiler-cli/test/perform_watch_spec.ts_475_8603
describe('perform watch', () => { let testSupport: TestSupport; let outDir: string; beforeEach(() => { testSupport = setup(); outDir = path.resolve(testSupport.basePath, 'outDir'); }); function createConfig(overrideOptions: ng.CompilerOptions = {}): ng.ParsedConfiguration { const options = testSupport.createCompilerOptions({outDir, ...overrideOptions}); return { options, rootNames: [path.resolve(testSupport.basePath, 'src/index.ts')], project: path.resolve(testSupport.basePath, 'src/tsconfig.json'), emitFlags: ng.EmitFlags.Default, errors: [], }; } it('should compile files during the initial run', () => { const config = createConfig(); const host = new MockWatchHost(config); testSupport.writeFiles({ 'src/main.ts': createModuleAndCompSource('main'), 'src/index.ts': `export * from './main'; `, }); const watchResult = performWatchCompilation(host); expectNoDiagnostics(config.options, watchResult.firstCompileResult); expect(fs.existsSync(path.resolve(outDir, 'src', 'main.js'))).toBe(true); }); it('should recompile components when its template changes', () => { const config = createConfig(); const host = new MockWatchHost(config); testSupport.writeFiles({ 'src/main.ts': createModuleAndCompSource('main', './main.html'), 'src/main.html': 'initial', 'src/index.ts': `export * from './main'; `, }); const watchResult = performWatchCompilation(host); expectNoDiagnostics(config.options, watchResult.firstCompileResult); const htmlPath = path.join(testSupport.basePath, 'src', 'main.html'); const genPath = path.posix.join(outDir, 'src', 'main.js'); const initial = fs.readFileSync(genPath, {encoding: 'utf8'}); expect(initial).toContain('"initial"'); testSupport.write(htmlPath, 'updated'); host.triggerFileChange(FileChangeEvent.Change, htmlPath); const updated = fs.readFileSync(genPath, {encoding: 'utf8'}); expect(updated).toContain('"updated"'); }); it('should cache files on subsequent runs', () => { const config = createConfig(); const host = new MockWatchHost(config); let fileExistsSpy: jasmine.Spy; let getSourceFileSpy: jasmine.Spy; host.createCompilerHost = (options: ng.CompilerOptions) => { const ngHost = ng.createCompilerHost({options}); fileExistsSpy = spyOn(ngHost, 'fileExists').and.callThrough(); getSourceFileSpy = spyOn(ngHost, 'getSourceFile').and.callThrough(); return ngHost; }; testSupport.writeFiles({ 'src/main.ts': createModuleAndCompSource('main'), 'src/util.ts': `export const x = 1;`, 'src/index.ts': ` export * from './main'; export * from './util'; `, }); const mainTsPath = path.posix.join(testSupport.basePath, 'src', 'main.ts'); const utilTsPath = path.posix.join(testSupport.basePath, 'src', 'util.ts'); const genPath = path.posix.join(outDir, 'src', 'main.js'); performWatchCompilation(host); expect(fs.existsSync(genPath)).toBe(true); expect(fileExistsSpy!).toHaveBeenCalledWith(mainTsPath); expect(fileExistsSpy!).toHaveBeenCalledWith(utilTsPath); expect(getSourceFileSpy!).toHaveBeenCalledWith( mainTsPath, jasmine.objectContaining({ languageVersion: ts.ScriptTarget.ES5, }), ); expect(getSourceFileSpy!).toHaveBeenCalledWith( utilTsPath, jasmine.objectContaining({ languageVersion: ts.ScriptTarget.ES5, }), ); fileExistsSpy!.calls.reset(); getSourceFileSpy!.calls.reset(); // trigger a single file change // -> all other files should be cached host.triggerFileChange(FileChangeEvent.Change, utilTsPath); expectNoDiagnostics(config.options, host.diagnostics); expect(fileExistsSpy!).not.toHaveBeenCalledWith(mainTsPath); expect(getSourceFileSpy!).not.toHaveBeenCalledWith(mainTsPath, jasmine.anything()); expect(getSourceFileSpy!).toHaveBeenCalledWith(utilTsPath, jasmine.anything()); // trigger a folder change // -> nothing should be cached host.triggerFileChange( FileChangeEvent.CreateDeleteDir, path.resolve(testSupport.basePath, 'src'), ); expectNoDiagnostics(config.options, host.diagnostics); expect(fileExistsSpy!).toHaveBeenCalledWith(mainTsPath); expect(fileExistsSpy!).toHaveBeenCalledWith(utilTsPath); expect(getSourceFileSpy!).toHaveBeenCalledWith(mainTsPath, jasmine.anything()); expect(getSourceFileSpy!).toHaveBeenCalledWith(utilTsPath, jasmine.anything()); }); // https://github.com/angular/angular/pull/26036 it('should handle redirected source files', () => { const config = createConfig(); const host = new MockWatchHost(config); host.createCompilerHost = (options: ng.CompilerOptions) => { const ngHost = ng.createCompilerHost({options}); return ngHost; }; // This file structure has an identical version of "a" under the root node_modules and inside // of "b". Because their package.json file indicates it is the exact same version of "a", // TypeScript will transform the source file of "node_modules/b/node_modules/a/index.d.ts" // into a redirect to "node_modules/a/index.d.ts". During watch compilations, we must assure // not to reintroduce "node_modules/b/node_modules/a/index.d.ts" as its redirected source file, // but instead using its original file. testSupport.writeFiles({ 'node_modules/a/index.js': `export class ServiceA {}`, 'node_modules/a/index.d.ts': `export declare class ServiceA {}`, 'node_modules/a/package.json': `{"name": "a", "version": "1.0"}`, 'node_modules/b/node_modules/a/index.js': `export class ServiceA {}`, 'node_modules/b/node_modules/a/index.d.ts': `export declare class ServiceA {}`, 'node_modules/b/node_modules/a/package.json': `{"name": "a", "version": "1.0"}`, 'node_modules/b/index.js': `export {ServiceA as ServiceB} from 'a';`, 'node_modules/b/index.d.ts': `export {ServiceA as ServiceB} from 'a';`, 'src/index.ts': ` import {ServiceA} from 'a'; import {ServiceB} from 'b'; `, }); const indexTsPath = path.posix.join(testSupport.basePath, 'src', 'index.ts'); performWatchCompilation(host); // Trigger a file change. This recreates the program from the old program. If redirect sources // were introduced into the new program, this would fail due to an assertion failure in TS. host.triggerFileChange(FileChangeEvent.Change, indexTsPath); expectNoDiagnostics(config.options, host.diagnostics); }); it('should recover from static analysis errors', () => { const config = createConfig(); const host = new MockWatchHost(config); const okFileContent = ` import {NgModule} from '@angular/core'; @NgModule() export class MyModule {} `; const errorFileContent = ` import {NgModule} from '@angular/core'; @NgModule((() => (1===1 ? null as any : null as any)) as any) export class MyModule {} `; const indexTsPath = path.resolve(testSupport.basePath, 'src', 'index.ts'); testSupport.write(indexTsPath, okFileContent); performWatchCompilation(host); expectNoDiagnostics(config.options, host.diagnostics); // Do it multiple times as the watch mode switches internal modes. // E.g. from regular compile to incremental, ... for (let i = 0; i < 3; i++) { host.diagnostics = []; testSupport.write(indexTsPath, okFileContent); host.triggerFileChange(FileChangeEvent.Change, indexTsPath); expectNoDiagnostics(config.options, host.diagnostics); host.diagnostics = []; testSupport.write(indexTsPath, errorFileContent); host.triggerFileChange(FileChangeEvent.Change, indexTsPath); const errDiags = host.diagnostics.filter((d) => d.category === ts.DiagnosticCategory.Error); expect(errDiags.length).toBe(1); expect(errDiags[0].messageText).toContain('@NgModule argument must be an object literal'); } }); });
{ "end_byte": 8603, "start_byte": 475, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/perform_watch_spec.ts" }
angular/packages/compiler-cli/test/perform_watch_spec.ts_8605_10634
function createModuleAndCompSource(prefix: string, template: string = prefix + 'template') { const templateEntry = template.endsWith('.html') ? `templateUrl: '${template}'` : `template: \`${template}\``; return ` import {Component, NgModule} from '@angular/core'; @Component({selector: '${prefix}', ${templateEntry}, standalone: false}) export class ${prefix}Comp {} @NgModule({declarations: [${prefix}Comp]}) export class ${prefix}Module {} `; } class MockWatchHost { nextTimeoutListenerId = 1; timeoutListeners: {[id: string]: () => void} = {}; fileChangeListeners: Array<((event: FileChangeEvent, fileName: string) => void) | null> = []; diagnostics: ts.Diagnostic[] = []; constructor(public config: ng.ParsedConfiguration) {} reportDiagnostics(diags: readonly ts.Diagnostic[]) { this.diagnostics.push(...diags); } readConfiguration() { return this.config; } createCompilerHost(options: ng.CompilerOptions) { return ng.createCompilerHost({options}); } createEmitCallback() { return undefined; } onFileChange( options: ng.CompilerOptions, listener: (event: FileChangeEvent, fileName: string) => void, ready: () => void, ) { const id = this.fileChangeListeners.length; this.fileChangeListeners.push(listener); ready(); return { close: () => (this.fileChangeListeners[id] = null), }; } setTimeout(callback: () => void): any { const id = this.nextTimeoutListenerId++; this.timeoutListeners[id] = callback; return id; } clearTimeout(timeoutId: any): void { delete this.timeoutListeners[timeoutId]; } flushTimeouts() { const listeners = this.timeoutListeners; this.timeoutListeners = {}; Object.keys(listeners).forEach((id) => listeners[id]()); } triggerFileChange(event: FileChangeEvent, fileName: string) { this.fileChangeListeners.forEach((listener) => { if (listener) { listener(event, fileName); } }); this.flushTimeouts(); } }
{ "end_byte": 10634, "start_byte": 8605, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/perform_watch_spec.ts" }
angular/packages/compiler-cli/test/perform_compile_spec.ts_0_8422
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import * as path from 'path'; import ts from 'typescript'; import {readConfiguration} from '../src/perform_compile'; import {setup, TestSupport} from './test_support'; describe('perform_compile', () => { let support: TestSupport; let basePath: string; beforeEach(() => { support = setup(); basePath = support.basePath; }); function writeSomeConfigs() { support.writeFiles({ 'tsconfig-level-1.json': `{ "extends": "./tsconfig-level-2.json", "angularCompilerOptions": { "annotateForClosureCompiler": true } } `, 'tsconfig-level-2.json': `{ "extends": "./tsconfig-level-3.json", "angularCompilerOptions": { "skipMetadataEmit": true } } `, 'tsconfig-level-3.json': `{ "angularCompilerOptions": { "annotateForClosureCompiler": false, "annotationsAs": "decorators" } } `, }); } it('should merge tsconfig "angularCompilerOptions"', () => { writeSomeConfigs(); const {options} = readConfiguration(path.resolve(basePath, 'tsconfig-level-1.json')); expect(options.annotateForClosureCompiler).toBeTrue(); expect(options.annotationsAs).toBe('decorators'); expect(options.skipMetadataEmit).toBeTrue(); }); it(`should return undefined when debug is not defined in "angularCompilerOptions"`, () => { writeSomeConfigs(); const {options} = readConfiguration(path.resolve(basePath, 'tsconfig-level-1.json')); expect(options['debug']).toBeUndefined(); }); it(`should return 'debug: false' when debug is disabled in "angularCompilerOptions"`, () => { writeSomeConfigs(); support.writeFiles({ 'tsconfig-level-3.json': `{ "angularCompilerOptions": { "debug": false } } `, }); const {options} = readConfiguration(path.resolve(basePath, 'tsconfig-level-1.json')); expect(options['debug']).toBeFalse(); }); it('should override options defined in tsconfig with those defined in `existingOptions`', () => { support.writeFiles({ 'tsconfig-level-1.json': `{ "compilerOptions": { "target": "es2020" }, "angularCompilerOptions": { "annotateForClosureCompiler": true } } `, }); const {options} = readConfiguration(path.resolve(basePath, 'tsconfig-level-1.json'), { annotateForClosureCompiler: false, target: ts.ScriptTarget.ES2015, debug: false, }); expect(options).toEqual( jasmine.objectContaining({ debug: false, target: ts.ScriptTarget.ES2015, annotateForClosureCompiler: false, }), ); }); it('should merge tsconfig "angularCompilerOptions" when extends points to node package', () => { support.writeFiles({ 'tsconfig-level-1.json': `{ "extends": "@angular-ru/tsconfig", "angularCompilerOptions": { "debug": false } } `, 'node_modules/@angular-ru/tsconfig/tsconfig.json': `{ "compilerOptions": { "strict": true }, "angularCompilerOptions": { "skipMetadataEmit": true } } `, 'node_modules/@angular-ru/tsconfig/package.json': `{ "name": "@angular-ru/tsconfig", "version": "0.0.0", "main": "./tsconfig.json" } `, }); const {options} = readConfiguration(path.resolve(basePath, 'tsconfig-level-1.json')); expect(options).toEqual( jasmine.objectContaining({ strict: true, skipMetadataEmit: true, debug: false, }), ); }); it('should merge tsconfig "angularCompilerOptions" when extends points to an extension less non rooted file', () => { support.writeFiles({ 'tsconfig-level-1.json': `{ "extends": "@1stg/tsconfig/angular", "angularCompilerOptions": { "debug": false } }`, 'node_modules/@1stg/tsconfig/angular.json': `{ "compilerOptions": { "strict": true }, "angularCompilerOptions": { "skipMetadataEmit": true } }`, 'node_modules/@1stg/tsconfig/package.json': `{ "name": "@1stg/tsconfig", "version": "0.0.0" }`, }); const {options} = readConfiguration(path.resolve(basePath, 'tsconfig-level-1.json')); expect(options).toEqual( jasmine.objectContaining({ strict: true, skipMetadataEmit: true, debug: false, }), ); }); it('should merge tsconfig "angularCompilerOptions" when extends points to a non rooted file without json extension', () => { support.writeFiles({ 'tsconfig-level-1.json': `{ "extends": "./tsconfig.app", "angularCompilerOptions": { "debug": false } }`, 'tsconfig.app.json': `{ "compilerOptions": { "strict": true }, "angularCompilerOptions": { "skipMetadataEmit": true } }`, }); const {options} = readConfiguration(path.resolve(basePath, 'tsconfig-level-1.json')); expect(options).toEqual( jasmine.objectContaining({ strict: true, skipMetadataEmit: true, debug: false, }), ); }); it('should merge tsconfig "angularCompilerOptions" when extends is aarray', () => { support.writeFiles({ 'tsconfig-level-1.json': `{ "extends": [ "./tsconfig-level-2.json", "./tsconfig-level-3.json", ], "compilerOptions": { "target": "es2020" }, "angularCompilerOptions": { "annotateForClosureCompiler": false, "debug": false } }`, 'tsconfig-level-2.json': `{ "compilerOptions": { "target": "es5", "module": "es2015" }, "angularCompilerOptions": { "skipMetadataEmit": true, "annotationsAs": "decorators" } }`, 'tsconfig-level-3.json': `{ "compilerOptions": { "target": "esnext", "module": "esnext" }, "angularCompilerOptions": { "annotateForClosureCompiler": true, "skipMetadataEmit": false } }`, }); const {options} = readConfiguration(path.resolve(basePath, 'tsconfig-level-1.json')); expect(options).toEqual( jasmine.objectContaining({ target: ts.ScriptTarget.ES2020, module: ts.ModuleKind.ESNext, debug: false, annotationsAs: 'decorators', annotateForClosureCompiler: false, skipMetadataEmit: false, }), ); }); it(`should not deep merge objects. (Ex: 'paths' and 'extendedDiagnostics')`, () => { support.writeFiles({ 'tsconfig-level-1.json': `{ "extends": "./tsconfig-level-2.json", "compilerOptions": { "paths": { "@angular/core": ["/*"] } }, "angularCompilerOptions": { "extendedDiagnostics": { "checks": { "textAttributeNotBinding": "suppress" } } } } `, 'tsconfig-level-2.json': `{ "compilerOptions": { "strict": false, "paths": { "@angular/common": ["/*"] } }, "angularCompilerOptions": { "skipMetadataEmit": true, "extendedDiagnostics": { "checks": { "nullishCoalescingNotNullable": "suppress" } } } } `, }); const {options} = readConfiguration(path.resolve(basePath, 'tsconfig-level-1.json')); expect(options).toEqual( jasmine.objectContaining({ strict: false, skipMetadataEmit: true, extendedDiagnostics: {checks: {textAttributeNotBinding: 'suppress'}}, paths: {'@angular/core': ['/*']}, }), ); }); });
{ "end_byte": 8422, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/perform_compile_spec.ts" }
angular/packages/compiler-cli/test/BUILD.bazel_0_2995
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") # Uses separate test rules to allow the tests to run in parallel ts_library( name = "test_utils", testonly = True, srcs = [ "mocks.ts", "test_support.ts", ], visibility = [ ":__subpackages__", "//packages/compiler-cli/src/ngtsc/transform/jit/test:__pkg__", "//packages/language-service/test:__subpackages__", ], deps = [ "//packages:types", "//packages/compiler", "//packages/compiler-cli", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/testing", "@npm//typescript", ], ) # extract_18n_spec ts_library( name = "extract_i18n_lib", testonly = True, srcs = [ "extract_i18n_spec.ts", ], deps = [ ":test_utils", "//packages/compiler", "//packages/compiler-cli", "@npm//typescript", ], ) jasmine_node_test( name = "extract_i18n", bootstrap = ["//tools/testing:node"], data = [ "//packages/core:npm_package", ], deps = [ ":extract_i18n_lib", "//packages/common:npm_package", "//packages/core", "@npm//yargs", ], ) # perform_watch_spec ts_library( name = "perform_watch_lib", testonly = True, srcs = [ "perform_watch_spec.ts", ], deps = [ ":test_utils", "//packages/compiler", "//packages/compiler-cli", "//packages/private/testing", "@npm//typescript", ], ) jasmine_node_test( name = "perform_watch", bootstrap = ["//tools/testing:node"], data = [ "//packages/core:npm_package", ], deps = [ ":perform_watch_lib", "//packages/core", ], ) # perform_compile_spec ts_library( name = "perform_compile_lib", testonly = True, srcs = [ "perform_compile_spec.ts", ], deps = [ ":test_utils", "//packages/compiler", "//packages/compiler-cli", "@npm//typescript", ], ) jasmine_node_test( name = "perform_compile", bootstrap = ["//tools/testing:node"], data = [ "//packages/core:npm_package", ], deps = [ ":perform_compile_lib", "//packages/core", ], ) ts_library( name = "typescript_support_lib", testonly = True, srcs = [ "typescript_support_spec.ts", ], deps = [ "//packages/compiler-cli", ], ) jasmine_node_test( name = "typescript_support", bootstrap = ["//tools/testing:node"], deps = [ ":typescript_support_lib", ], ) # version_helpers_spec ts_library( name = "version_helpers_lib", testonly = True, srcs = ["version_helpers_spec.ts"], deps = [ "//packages/compiler-cli", ], ) jasmine_node_test( name = "version_helpers", bootstrap = ["//tools/testing:node"], deps = [ ":version_helpers_lib", ], )
{ "end_byte": 2995, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/BUILD.bazel" }
angular/packages/compiler-cli/test/extract_i18n_spec.ts_0_6035
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import * as fs from 'fs'; import * as path from 'path'; import {mainXi18n} from '../src/extract_i18n'; import {setup} from './test_support'; const EXPECTED_XMB = `<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE messagebundle [ <!ELEMENT messagebundle (msg)*> <!ATTLIST messagebundle class CDATA #IMPLIED> <!ELEMENT msg (#PCDATA|ph|source)*> <!ATTLIST msg id CDATA #IMPLIED> <!ATTLIST msg seq CDATA #IMPLIED> <!ATTLIST msg name CDATA #IMPLIED> <!ATTLIST msg desc CDATA #IMPLIED> <!ATTLIST msg meaning CDATA #IMPLIED> <!ATTLIST msg obsolete (obsolete) #IMPLIED> <!ATTLIST msg xml:space (default|preserve) "default"> <!ATTLIST msg is_hidden CDATA #IMPLIED> <!ELEMENT source (#PCDATA)> <!ELEMENT ph (#PCDATA|ex)*> <!ATTLIST ph name CDATA #REQUIRED> <!ELEMENT ex (#PCDATA)> ]> <messagebundle handler="angular"> <msg id="8136548302122759730" desc="desc" meaning="meaning"><source>src/basic.html:1</source><source>src/comp2.ts:1</source><source>src/basic.html:1</source>translate me</msg> <msg id="9038505069473852515"><source>src/basic.html:3,4</source><source>src/comp2.ts:3,4</source><source>src/comp2.ts:2,3</source><source>src/basic.html:3,4</source> Welcome</msg> <msg id="5611534349548281834" desc="with ICU"><source>src/icu.html:1,3</source><source>src/icu.html:5</source>{VAR_PLURAL, plural, =1 {book} other {books} }</msg> <msg id="5811701742971715242" desc="with ICU and other things"><source>src/icu.html:4,6</source> foo <ph name="ICU"><ex>{ count, plural, =1 {...} other {...}}</ex>{ count, plural, =1 {...} other {...}}</ph> </msg> <msg id="7254052530614200029" desc="with placeholders"><source>src/placeholders.html:1,3</source>Name: <ph name="START_BOLD_TEXT"><ex>&lt;b&gt;</ex>&lt;b&gt;</ph><ph name="NAME"><ex>{{ name // i18n(ph=&quot;name&quot;) }}</ex>{{ name // i18n(ph=&quot;name&quot;) }}</ph><ph name="CLOSE_BOLD_TEXT"><ex>&lt;/b&gt;</ex>&lt;/b&gt;</ph></msg> </messagebundle> `; const EXPECTED_XLIFF = `<?xml version="1.0" encoding="UTF-8" ?> <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"> <file source-language="fr" datatype="plaintext" original="ng2.template"> <body> <trans-unit id="76e1eccb1b772fa9f294ef9c146ea6d0efa8a2d4" datatype="html"> <source>translate me</source> <context-group purpose="location"> <context context-type="sourcefile">src/basic.html</context> <context context-type="linenumber">1</context> </context-group> <context-group purpose="location"> <context context-type="sourcefile">src/comp2.ts</context> <context context-type="linenumber">1</context> </context-group> <context-group purpose="location"> <context context-type="sourcefile">src/basic.html</context> <context context-type="linenumber">1</context> </context-group> <note priority="1" from="description">desc</note> <note priority="1" from="meaning">meaning</note> </trans-unit> <trans-unit id="085a5ecc40cc87451d216725b2befd50866de18a" datatype="html"> <source> Welcome</source> <context-group purpose="location"> <context context-type="sourcefile">src/basic.html</context> <context context-type="linenumber">3</context> </context-group> <context-group purpose="location"> <context context-type="sourcefile">src/comp2.ts</context> <context context-type="linenumber">3</context> </context-group> <context-group purpose="location"> <context context-type="sourcefile">src/comp2.ts</context> <context context-type="linenumber">2</context> </context-group> <context-group purpose="location"> <context context-type="sourcefile">src/basic.html</context> <context context-type="linenumber">3</context> </context-group> </trans-unit> <trans-unit id="83937c05b1216e7f4c02a85454260e28fd72d1e3" datatype="html"> <source>{VAR_PLURAL, plural, =1 {book} other {books} }</source> <context-group purpose="location"> <context context-type="sourcefile">src/icu.html</context> <context context-type="linenumber">1</context> </context-group> <note priority="1" from="description">with ICU</note> </trans-unit> <trans-unit id="540c5f481129419ef21017f396b6c2d0869ca4d2" datatype="html"> <source> foo <x id="ICU" equiv-text="{ count, plural, =1 {...} other {...}}"/> </source> <context-group purpose="location"> <context context-type="sourcefile">src/icu.html</context> <context context-type="linenumber">4</context> </context-group> <note priority="1" from="description">with ICU and other things</note> </trans-unit> <trans-unit id="ca7678090fddd04441d63b1218177af65f23342d" datatype="html"> <source>{VAR_PLURAL, plural, =1 {book} other {books} }</source> <context-group purpose="location"> <context context-type="sourcefile">src/icu.html</context> <context context-type="linenumber">5</context> </context-group> </trans-unit> <trans-unit id="9311399c1ca7c75f771d77acb129e50581c6ec1f" datatype="html"> <source>Name: <x id="START_BOLD_TEXT" ctype="x-b" equiv-text="&lt;b&gt;"/><x id="NAME" equiv-text="{{ name // i18n(ph=&quot;name&quot;) }}"/><x id="CLOSE_BOLD_TEXT" ctype="x-b" equiv-text="&lt;/b&gt;"/></source> <context-group purpose="location"> <context context-type="sourcefile">src/placeholders.html</context> <context context-type="linenumber">1</context> </context-group> <note priority="1" from="description">with placeholders</note> </trans-unit> </body> </file> </xliff> `;
{ "end_byte": 6035, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/extract_i18n_spec.ts" }
angular/packages/compiler-cli/test/extract_i18n_spec.ts_6037_8226
const EXPECTED_XLIFF2 = `<?xml version="1.0" encoding="UTF-8" ?> <xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="en"> <file original="ng.template" id="ngi18n"> <unit id="8136548302122759730"> <notes> <note category="description">desc</note> <note category="meaning">meaning</note> <note category="location">src/basic.html:1</note> <note category="location">src/comp2.ts:1</note> <note category="location">src/basic.html:1</note> </notes> <segment> <source>translate me</source> </segment> </unit> <unit id="9038505069473852515"> <notes> <note category="location">src/basic.html:3,4</note> <note category="location">src/comp2.ts:3,4</note> <note category="location">src/comp2.ts:2,3</note> <note category="location">src/basic.html:3,4</note> </notes> <segment> <source> Welcome</source> </segment> </unit> <unit id="5611534349548281834"> <notes> <note category="description">with ICU</note> <note category="location">src/icu.html:1,3</note> <note category="location">src/icu.html:5</note> </notes> <segment> <source>{VAR_PLURAL, plural, =1 {book} other {books} }</source> </segment> </unit> <unit id="5811701742971715242"> <notes> <note category="description">with ICU and other things</note> <note category="location">src/icu.html:4,6</note> </notes> <segment> <source> foo <ph id="0" equiv="ICU" disp="{ count, plural, =1 {...} other {...}}"/> </source> </segment> </unit> <unit id="7254052530614200029"> <notes> <note category="description">with placeholders</note> <note category="location">src/placeholders.html:1,3</note> </notes> <segment> <source>Name: <pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="&lt;b&gt;" dispEnd="&lt;/b&gt;"><ph id="1" equiv="NAME" disp="{{ name // i18n(ph=&quot;name&quot;) }}"/></pc></source> </segment> </unit> </file> </xliff> `;
{ "end_byte": 8226, "start_byte": 6037, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/extract_i18n_spec.ts" }
angular/packages/compiler-cli/test/extract_i18n_spec.ts_8228_14014
describe('extract_i18n command line', () => { let basePath: string; let outDir: string; let write: (fileName: string, content: string) => void; let errorSpy: jasmine.Spy & ((s: string) => void); function writeConfig(tsconfig = '{"extends": "./tsconfig-base.json"}') { write('tsconfig.json', tsconfig); } beforeEach(() => { errorSpy = jasmine.createSpy('consoleError').and.callFake(console.error); const support = setup(); write = (fileName: string, content: string) => { support.write(fileName, content); }; basePath = support.basePath; outDir = path.join(basePath, 'built'); write( 'tsconfig-base.json', `{ "compilerOptions": { "experimentalDecorators": true, "skipLibCheck": true, "noImplicitAny": true, "types": [], "outDir": "built", "rootDir": ".", "baseUrl": ".", "declaration": true, "target": "es2015", "module": "es2015", "moduleResolution": "node", "lib": ["es2015", "dom"], "typeRoots": ["node_modules/@types"] } }`, ); }); function writeSources() { const welcomeMessage = ` <!--i18n--> Welcome<!--/i18n--> `; write( 'src/basic.html', `<div title="translate me" i18n-title="meaning|desc"></div> <p id="welcomeMessage">${welcomeMessage}</p>`, ); write( 'src/comp1.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'basic', templateUrl: './basic.html', standalone: false, }) export class BasicCmp1 {}`, ); write( 'src/comp2.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'basic2', template: \`<div title="translate me" i18n-title="meaning|desc"></div> <p id="welcomeMessage">${welcomeMessage}</p>\`, standalone: false, }) export class BasicCmp2 {} @Component({ selector: 'basic4', template: \`<p id="welcomeMessage">${welcomeMessage}</p>\`, standalone: false, }) export class BasicCmp4 {}`, ); write( 'src/comp3.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'basic3', templateUrl: './basic.html', standalone: false, }) export class BasicCmp3 {}`, ); write( 'src/placeholders.html', `<div i18n="with placeholders">Name: <b>{{ name // i18n(ph="name") }}</b></div>`, ); write( 'src/placeholder_cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'placeholders', templateUrl: './placeholders.html', standalone: false, }) export class PlaceholderCmp { name = 'whatever'; }`, ); write( 'src/icu.html', `<div i18n="with ICU">{ count, plural, =1 {book} other {books} }</div> <div i18n="with ICU and other things"> foo { count, plural, =1 {book} other {books} } </div>`, ); write( 'src/icu_cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'icu', templateUrl: './icu.html', standalone: false, }) export class IcuCmp { count = 3; }`, ); write( 'src/module.ts', ` import {NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; import {BasicCmp1} from './comp1'; import {BasicCmp2, BasicCmp4} from './comp2'; import {BasicCmp3} from './comp3'; import {PlaceholderCmp} from './placeholder_cmp'; import {IcuCmp} from './icu_cmp'; @NgModule({ declarations: [ BasicCmp1, BasicCmp2, BasicCmp3, BasicCmp4, PlaceholderCmp, IcuCmp, ], imports: [CommonModule], }) export class I18nModule {} `, ); } it('should extract xmb', () => { writeConfig(); writeSources(); const exitCode = mainXi18n( ['-p', basePath, '--i18nFormat=xmb', '--outFile=custom_file.xmb'], errorSpy, ); expect(errorSpy).not.toHaveBeenCalled(); expect(exitCode).toBe(0); const xmbOutput = path.join(outDir, 'custom_file.xmb'); expect(fs.existsSync(xmbOutput)).toBeTruthy(); const xmb = fs.readFileSync(xmbOutput, {encoding: 'utf-8'}); expect(xmb).toEqual(EXPECTED_XMB); }); it('should extract xlf', () => { writeConfig(); writeSources(); const exitCode = mainXi18n(['-p', basePath, '--i18nFormat=xlf', '--locale=fr'], errorSpy); expect(errorSpy).not.toHaveBeenCalled(); expect(exitCode).toBe(0); const xlfOutput = path.join(outDir, 'messages.xlf'); expect(fs.existsSync(xlfOutput)).toBeTruthy(); const xlf = fs.readFileSync(xlfOutput, {encoding: 'utf-8'}); expect(xlf).toEqual(EXPECTED_XLIFF); }); it('should extract xlf2', () => { writeConfig(); writeSources(); const exitCode = mainXi18n( ['-p', basePath, '--i18nFormat=xlf2', '--outFile=messages.xliff2.xlf'], errorSpy, ); expect(errorSpy).not.toHaveBeenCalled(); expect(exitCode).toBe(0); const xlfOutput = path.join(outDir, 'messages.xliff2.xlf'); expect(fs.existsSync(xlfOutput)).toBeTruthy(); const xlf = fs.readFileSync(xlfOutput, {encoding: 'utf-8'}); expect(xlf).toEqual(EXPECTED_XLIFF2); }); it('should not emit js', () => { writeConfig(); writeSources(); const exitCode = mainXi18n( ['-p', basePath, '--i18nFormat=xlf2', '--outFile=messages.xliff2.xlf'], errorSpy, ); expect(errorSpy).not.toHaveBeenCalled(); expect(exitCode).toBe(0); const moduleOutput = path.join(outDir, 'src', 'module.js'); expect(fs.existsSync(moduleOutput)).toBeFalsy(); }); });
{ "end_byte": 14014, "start_byte": 8228, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/extract_i18n_spec.ts" }
angular/packages/compiler-cli/test/test_support.ts_0_6173
/** * @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 */ /// <reference types="node" /> import * as fs from 'fs'; import * as path from 'path'; import ts from 'typescript'; import * as ng from '../index'; import {NodeJSFileSystem, setFileSystem} from '../src/ngtsc/file_system'; import {getAngularPackagesFromRunfiles, resolveFromRunfiles} from '../src/ngtsc/testing'; // TEST_TMPDIR is always set by Bazel. const tmpdir = process.env['TEST_TMPDIR']!; export function makeTempDir(): string { let dir: string; while (true) { const id = (Math.random() * 1000000).toFixed(0); dir = path.posix.join(tmpdir, `tmp.${id}`); if (!fs.existsSync(dir)) break; } fs.mkdirSync(dir); return dir; } export interface TestSupport { basePath: string; write(fileName: string, content: string): void; writeFiles(...mockDirs: {[fileName: string]: string}[]): void; createCompilerOptions(overrideOptions?: ng.CompilerOptions): ng.CompilerOptions; shouldExist(fileName: string): void; shouldNotExist(fileName: string): void; } function createTestSupportFor(basePath: string) { // Typescript uses identity comparison on `paths` and other arrays in order to determine // if program structure can be reused for incremental compilation, so we reuse the default // values unless overridden, and freeze them so that they can't be accidentally changed somewhere // in tests. const defaultCompilerOptions = { basePath, 'experimentalDecorators': true, 'skipLibCheck': true, 'strict': true, 'strictPropertyInitialization': false, 'types': Object.freeze([] as string[]) as string[], 'outDir': path.resolve(basePath, 'built'), 'rootDir': basePath, 'baseUrl': basePath, 'declaration': true, 'target': ts.ScriptTarget.ES5, 'newLine': ts.NewLineKind.LineFeed, 'module': ts.ModuleKind.ES2015, 'moduleResolution': ts.ModuleResolutionKind.Node10, 'lib': Object.freeze([ path.resolve(basePath, 'node_modules/typescript/lib/lib.es6.d.ts'), ]) as string[], 'paths': Object.freeze({'@angular/*': ['./node_modules/@angular/*']}) as { [index: string]: string[]; }, }; return { // We normalize the basePath into a posix path, so that multiple assertions which compare // paths don't need to normalize the path separators each time. basePath: normalizeSeparators(basePath), write, writeFiles, createCompilerOptions, shouldExist, shouldNotExist, }; function ensureDirExists(absolutePathToDir: string) { if (fs.existsSync(absolutePathToDir)) { if (!fs.statSync(absolutePathToDir).isDirectory()) { throw new Error(`'${absolutePathToDir}' exists and is not a directory.`); } } else { const parentDir = path.dirname(absolutePathToDir); ensureDirExists(parentDir); fs.mkdirSync(absolutePathToDir); } } function write(fileName: string, content: string) { const absolutePathToFile = path.resolve(basePath, fileName); ensureDirExists(path.dirname(absolutePathToFile)); fs.writeFileSync(absolutePathToFile, content); } function writeFiles(...mockDirs: {[fileName: string]: string}[]) { mockDirs.forEach((dir) => { Object.keys(dir).forEach((fileName) => { write(fileName, dir[fileName]); }); }); } function createCompilerOptions(overrideOptions: ng.CompilerOptions = {}): ng.CompilerOptions { return {...defaultCompilerOptions, ...overrideOptions}; } function shouldExist(fileName: string) { if (!fs.existsSync(path.resolve(basePath, fileName))) { throw new Error(`Expected ${fileName} to be emitted (basePath: ${basePath})`); } } function shouldNotExist(fileName: string) { if (fs.existsSync(path.resolve(basePath, fileName))) { throw new Error(`Did not expect ${fileName} to be emitted (basePath: ${basePath})`); } } } export function setupBazelTo(tmpDirPath: string) { const nodeModulesPath = path.join(tmpDirPath, 'node_modules'); const angularDirectory = path.join(nodeModulesPath, '@angular'); fs.mkdirSync(nodeModulesPath); fs.mkdirSync(angularDirectory); getAngularPackagesFromRunfiles().forEach(({pkgPath, name}) => { fs.symlinkSync(pkgPath, path.join(angularDirectory, name), 'junction'); }); // Link typescript const typeScriptSource = resolveFromRunfiles('npm/node_modules/typescript'); const typescriptDest = path.join(nodeModulesPath, 'typescript'); fs.symlinkSync(typeScriptSource, typescriptDest, 'junction'); // Link "rxjs" if it has been set up as a runfile. "rxjs" is linked optionally because // not all compiler-cli tests need "rxjs" set up. try { const rxjsSource = resolveFromRunfiles('npm/node_modules/rxjs'); const rxjsDest = path.join(nodeModulesPath, 'rxjs'); fs.symlinkSync(rxjsSource, rxjsDest, 'junction'); } catch (e: any) { if (e.code !== 'MODULE_NOT_FOUND') throw e; } } export function setup(): TestSupport { // // `TestSupport` provides its own file-system abstraction so we just use // // the native `NodeJSFileSystem` under the hood. setFileSystem(new NodeJSFileSystem()); const tmpDirPath = makeTempDir(); setupBazelTo(tmpDirPath); return createTestSupportFor(tmpDirPath); } export function expectNoDiagnostics(options: ng.CompilerOptions, diags: readonly ts.Diagnostic[]) { const errorDiags = diags.filter((d) => d.category !== ts.DiagnosticCategory.Message); if (errorDiags.length) { throw new Error(`Expected no diagnostics: ${ng.formatDiagnostics(errorDiags)}`); } } export function expectNoDiagnosticsInProgram(options: ng.CompilerOptions, p: ng.Program) { expectNoDiagnostics(options, [ ...p.getNgStructuralDiagnostics(), ...p.getTsSemanticDiagnostics(), ...p.getNgSemanticDiagnostics(), ]); } export function normalizeSeparators(path: string): string { return path.replace(/\\/g, '/'); } const STRIP_ANSI = /\x1B\x5B\d+m/g; export function stripAnsi(diags: string): string { return diags.replace(STRIP_ANSI, ''); }
{ "end_byte": 6173, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/test_support.ts" }
angular/packages/compiler-cli/test/compliance/README.md_0_8740
# Compliance test-cases This directory contains rules, helpers and test-cases for the Angular compiler compliance tests. There are three different types of tests that are run based on file-based "test-cases". * **Full compile** - in this test the source files defined by the test-case are fully compiled by Angular. The generated files are compared to "expected files" via a matching algorithm that is tolerant to whitespace and variable name changes. * **Local compile** - in this test the source files defined by the test-case are compiled in local mode by Angular. The generated files are compared to "expected files" via a matching algorithm similar to the case of "full compile" * **Partial compile** - in this test the source files defined by the test-case are "partially" compiled by Angular to produce files that can be published. These partially compiled files are compared directly against "golden files" to ensure that we do not inadvertently break the public API of partial declarations. * **Linked** - in this test the golden files mentioned in the previous bullet point, are passed to the Angular linker, which generates files that are comparable to the fully compiled files. These linked files are compared against the "expected files" in the same way as in the "full compile" tests. This way the compliance tests are able to check each mode and stage of compilation is accurate and does not change unexpectedly. ## Defining a test-case To define a test-case, create a new directory below `test_cases`. In this directory * add a new file called `TEST_CASES.json`. The format of this file is described below. * add an empty `GOLDEN_PARTIAL.js` file. This file will be updated by the tooling later. * add any `inputFiles` that will be compiled as part of the test-case. * add any `expected` files that will be compared to the files generated by compiling the source files. ### TEST_CASES.json format The `TEST_CASES.json` defines an object with one or more test-case definitions in the `cases` property. Each test-case can specify: * A `description` of the test. * The `inputFiles` that will be compiled. * Additional `compilerOptions` and `angularCompilerOptions` that are passed to the compiler. * Whether to exclude this test-case from certain tests running under certain compilation modes (`compilationModeFilter`). * A collection of `expectations` definitions that will be checked against the generated files. Note that there is a JSON schema for the `TEST_CASES.json` file stored at `test_cases/test_case_schema.json`. You should add a link to this schema at the top of your `TEST_CASES.json` file to provide validation and intellisense for this file in your IDE. For example: ```json { "$schema": "../test_case_schema.json", "cases": [ { "description": "description of the test - equivalent to an `it` clause message.", "inputFiles": ["abc.ts"], "expectations": [ { "failureMessage": "message to display if this expectation fails", "files": [ { "expected": "xyz.js", "generated": "abc.js" }, ... ] }, ... ], "compilerOptions": { ... }, "angularCompilerOptions": { ... } } ] } ``` ### Input files The input files are the source file that will be compiled as part of this test-case. Input files should be stored in the directory next to the `TEST_CASES.json`. The paths to the input files should be listed in the `inputFiles` property of `TEST_CASES.json`. The paths are relative to the `TEST_CASES.json` file. If no `inputFiles` property is provided, the default is `["test.ts"]`. Note that test-cases can share input files, but you should only do this if these input files are going to be compiled using the same options. This is because only one version of the compiled input file is retrieved from the golden partial file to be used in the linker tests. This can cause the linker tests to fail if they are provided with a compiled file (from the golden partial) that was compiled with different options to what are expected for that test-case. ### Expectations An expectation consists of a `failureMessage`, which is displayed if the expectation check fails, a collection of expected `files` pairs and/or a collection of `expectedErrors`. Each expected file-pair consists of a path to a `generated` file (relative to the build output folder), and a path to an `expected` file (relative to the test case). The `generated` file is checked to see if it "matches" the `expected` file. The matching is resilient to whitespace and variable name changes. If no `files` property is provided, the default is a collection of objects `{expected, generated}`, where `expected` and `generated` are computed by taking each path in the `inputFiles` collection and replacing the `.ts` extension with `.js` for full compilation and with `.local.js` for local compilation, respectively. Each expected error must have a `message` property and, optionally, a `location` property. These are parsed as regular expressions (so `.` and `(` etc must be escaped) and tested against the errors that are returned as diagnostics from the compilation. If no `failureMessage` property is provided, the default is `"Incorrect generated output."`. ### Expected file format The expected files look like JavaScript but are actually specially formatted to allow matching with the generated output. The generated and expected files are tokenized and then the tokens are intelligently matched to check whether they are equivalent. * Whitespace tolerant - the tokens can be separated by any amount of whitespace * Code skipping - you can skip sections of code in the generated output by adding an ellipsis (…) to the expectation file. * Identifier tolerant - identifiers in the expectation file that start and end with a dollar (e.g. `$r3$`) will be matched against any identifier. But the matching will ensure that the same identifier name appears consistently elsewhere in the file. * Macro expansion - we can add macros to the expected files that will be expanded to blocks of code dynamically. The following macros are defined in the `test_helpers/expected_file_macros.ts` file: * I18n messages - for example: `__i18nMsg__('message string', [ ['placeholder', 'pair] ], { meta: 'properties'})`. * Attribute markers - for example: `__AttributeMarker.Bindings__`. ### Source-map checks To check a mapping, add a `// SOURCE:` comment to the end of a line in an expectation file: ``` <generated code> // SOURCE: "<source-url>" "<source code>" ``` The generated code, stripped of the `// SOURCE: ` comment, will still be checked as normal by the `expectEmit()` helper. But, prior to that, the source-map segments are checked to ensure that there is a mapping from `<generated code>` to `<source code>` found in the file at `<source-url>`. Note: * The source-url should be absolute, with the directory containing the TEST_CASES.json file assumed to be `/`. * Whitespace is important and will be included when comparing the segments. * There is a single space character between each part of the line. * Double quotes in the mapping must be escaped. * Newlines within a mapping must be escaped since the mapping and comment must all appear on a single line of this file. ## Running tests The simplest way to run all the compliance tests is: ```sh yarn test //packages/compiler-cli/test/compliance/... ``` If you only want to run one of the three types of test you can be more specific: ```sh yarn test //packages/compiler-cli/test/compliance/full yarn test //packages/compiler-cli/test/compliance/linked yarn test //packages/compiler-cli/test/compliance/test_cases/... ``` (The last command runs the partial compilation tests.) ## Updating a golden partial file There is one golden partial file per `TEST_CASES.json` file. So even if this file defines multiple test-cases, which each contain multiple input files, there will only be one golden file. The golden file is generated by the tooling and should not be modified manually. When you first create a test-case, with an empty `GOLDEN_PARTIAL.js` file, or a change is made to the generated partial output, we must update the `GOLDEN_PARTIAL.js` file. This is done by running a specific bazel rule of the form: ```sh bazel run //packages/compiler-cli/test/compliance/test_cases:<path/to/test_case>.golden.update ``` where to replace `<path/to/test_case>` with the path (relative to `test_cases`) of the directory that contains the `GOLDEN_PARTIAL.js` to update. To update all golden partial files, the following command can be run: ```sh node packages/compiler-cli/test/compliance/update_all_goldens.js ``` ##
{ "end_byte": 8740, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/README.md" }
angular/packages/compiler-cli/test/compliance/README.md_8740_10073
Debugging test-cases The full and linked compliance tests are basically `jasmine_node_test` rules. As such, they can be debugged just like any other `jasmine_node_test`. The standard approach is to add `--config=debug` to the Bazel test command. For example: ```sg yarn test //packages/compiler-cli/test/compliance/full --config=debug yarn test //packages/compiler-cli/test/compliance/linked --config=debug ``` To debug generating the partial golden output use the following form of Bazel command: ```sh yarn bazel run //packages/compiler-cli/test/compliance/test_cases:partial_<path/to/test_case>.debug ``` The `path/to/test_case` is relative to the `test_cases` directory. So for this `TEST_CASES.json` file at: ``` packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_directives/matching/TEST_CASES.json ``` The command to debug the test-cases would be: ``` yarn bazel run //packages/compiler-cli/test/compliance/test_cases:partial_r3_view_compiler_directives/matching.debug ``` ### Focusing test-cases You can focus a test case by setting `"focusTest": true` in the `TEST_CASES.json` file. This is equivalent to using jasmine `fit()`. ### Excluding test-cases You can exclude a test case by setting `"excludeTest": true` in the `TEST_CASES.json` file. This is equivalent to using jasmine `xit()`.
{ "end_byte": 10073, "start_byte": 8740, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/README.md" }
angular/packages/compiler-cli/test/compliance/update_all_goldens.js_0_1300
#!/usr/bin/env node /** * @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 */ // tslint:disable:no-console import shelljs from 'shelljs'; const {exec} = shelljs; process.stdout.write('Gathering all partial golden update targets'); const queryCommand = `yarn bazel query --output label 'filter('golden.update', kind(nodejs_binary, //packages/compiler-cli/test/compliance/test_cases:*))'`; const allUpdateTargets = exec(queryCommand, {silent: true}) .trim() .split('\n') .map((test) => test.trim()); process.stdout.clearLine(); process.stdout.cursorTo(0); for (const [index, target] of allUpdateTargets.entries()) { const progress = `${index + 1} / ${allUpdateTargets.length}`; process.stdout.write(`[${progress}] Running: ${target}`); const commandResult = exec(`yarn bazel run ${target}`, {silent: true}); process.stdout.clearLine(); process.stdout.cursorTo(0); if (commandResult.code) { console.error(`[${progress}] Failed run: ${target}`); console.group(); console.error(commandResult.stdout || commandResult.stderr); console.groupEnd(); } else { console.log(`[${progress}] Successful run: ${target}`); } }
{ "end_byte": 1300, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/update_all_goldens.js" }
angular/packages/compiler-cli/test/compliance/full/BUILD.bazel_0_578
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") ts_library( name = "test_lib", testonly = True, srcs = ["full_compile_spec.ts"], deps = [ "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/test/compliance/test_helpers", ], ) jasmine_node_test( name = "full", bootstrap = ["//tools/testing:node_no_angular"], data = [ "//packages/compiler-cli/test/compliance/test_cases", "//packages/core:npm_package", ], shard_count = 2, deps = [ ":test_lib", ], )
{ "end_byte": 578, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/full/BUILD.bazel" }
angular/packages/compiler-cli/test/compliance/full/full_compile_spec.ts_0_885
/** * @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 {FileSystem} from '../../../src/ngtsc/file_system'; import {CompileResult, compileTest} from '../test_helpers/compile_test'; import {ComplianceTest} from '../test_helpers/get_compliance_tests'; import {runTests} from '../test_helpers/test_runner'; runTests('full compile', compileTests); /** * Fully compile all the input files in the given `test`. * * @param fs The mock file-system where the input files can be found. * @param test The compliance test whose input files should be compiled. */ function compileTests(fs: FileSystem, test: ComplianceTest): CompileResult { return compileTest(fs, test.inputFiles, test.compilerOptions, test.angularCompilerOptions); }
{ "end_byte": 885, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/full/full_compile_spec.ts" }
angular/packages/compiler-cli/test/compliance/partial/partial_compliance_goldens.bzl_0_1993
load("@build_bazel_rules_nodejs//:index.bzl", "generated_file_test") load("//tools:defaults.bzl", "nodejs_binary", "npm_package_bin") def partial_compliance_golden(filePath): """Creates the generate and testing targets for partial compile results. """ # Remove the "TEST_CASES.json" substring from the end of the provided path. path = filePath[:-len("/TEST_CASES.json")] generate_partial_name = "partial_%s" % path data = [ "//packages/compiler-cli/test/compliance/partial:generate_golden_partial_lib", "//packages/core:npm_package", filePath, ] + native.glob(["%s/*.ts" % path, "%s/**/*.html" % path, "%s/**/*.css" % path]) nodejs_binary( name = generate_partial_name, testonly = True, data = data, visibility = [":__pkg__"], entry_point = "//packages/compiler-cli/test/compliance/partial:cli.ts", templated_args = ["$(execpath %s)" % filePath], ) nodejs_binary( name = generate_partial_name + ".debug", testonly = True, data = data, visibility = [":__pkg__"], entry_point = "//packages/compiler-cli/test/compliance/partial:cli.ts", templated_args = ["--node_options=--inspect-brk", filePath], ) npm_package_bin( name = "_generated_%s" % path, tool = generate_partial_name, testonly = True, stdout = "%s/_generated.js" % path, link_workspace_root = True, # Disable the linker and rely on patched resolution which works better on Windows # and is less prone to race conditions when targets build concurrently. args = ["--nobazel_run_linker"], visibility = [":__pkg__"], data = [], ) generated_file_test( visibility = ["//visibility:public"], name = "%s.golden" % path, src = "//packages/compiler-cli/test/compliance/test_cases:%s/GOLDEN_PARTIAL.js" % path, generated = "_generated_%s" % path, )
{ "end_byte": 1993, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/partial/partial_compliance_goldens.bzl" }
angular/packages/compiler-cli/test/compliance/partial/cli.ts_0_380
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {fs} from '../test_helpers/get_compliance_tests'; import {generateGoldenPartial} from './generate_golden_partial'; generateGoldenPartial(fs.resolve(process.argv[2]));
{ "end_byte": 380, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/partial/cli.ts" }
angular/packages/compiler-cli/test/compliance/partial/BUILD.bazel_0_450
load("//tools:defaults.bzl", "ts_library") ts_library( name = "generate_golden_partial_lib", testonly = True, srcs = [ "cli.ts", "generate_golden_partial.ts", ], visibility = ["//packages/compiler-cli/test/compliance:__subpackages__"], deps = [ "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/test/compliance/test_helpers", ], ) exports_files([ "cli.ts", ])
{ "end_byte": 450, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/partial/BUILD.bazel" }
angular/packages/compiler-cli/test/compliance/partial/generate_golden_partial.ts_0_2380
/** * @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 {AbsoluteFsPath, FileSystem} from '../../../src/ngtsc/file_system'; import { compileTest, getBuildOutputDirectory, initMockTestFileSystem, } from '../test_helpers/compile_test'; import {ComplianceTest, getComplianceTests} from '../test_helpers/get_compliance_tests'; import {PartiallyCompiledFile, renderGoldenPartial} from '../test_helpers/golden_partials'; /** * Generate the golden partial output for the tests described in the `testConfigPath` config file. * * @param testConfigPath Absolute disk path of the `TEST_CASES.json` file that describes the tests. */ export function generateGoldenPartial(absTestConfigPath: AbsoluteFsPath): void { const files: PartiallyCompiledFile[] = []; const tests = getComplianceTests(absTestConfigPath); for (const test of tests) { const fs = initMockTestFileSystem(test.realTestPath); for (const file of compilePartials(fs, test)) { files.push(file); } } writeGoldenPartial(files); } /** * Partially compile the source files specified by the given `test`. * * @param fs The mock file-system to use when compiling partials. * @param test The information about the test being compiled. */ function* compilePartials(fs: FileSystem, test: ComplianceTest): Generator<PartiallyCompiledFile> { const builtDirectory = getBuildOutputDirectory(fs); const result = compileTest(fs, test.inputFiles, test.compilerOptions, { compilationMode: 'partial', ...test.angularCompilerOptions, }); if (result.errors.length > 0) { throw new Error( `Unexpected compilation errors: ${result.errors.map((e) => ` - ${e}`).join('\n')}`, ); } for (const generatedPath of result.emittedFiles) { yield { path: fs.relative(builtDirectory, generatedPath), content: fs.readFile(generatedPath), }; } } /** * Write the partially compiled files to the appropriate output destination. * * For now just push the concatenated partial files to standard out. * * @param files The partially compiled files. */ function writeGoldenPartial(files: PartiallyCompiledFile[]): void { // tslint:disable-next-line: no-console console.log(renderGoldenPartial(files)); }
{ "end_byte": 2380, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/partial/generate_golden_partial.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/replace.sh_0_2737
#!/bin/bash # Step 1: Find all .pipeline.js files recursively find . -type f -name "*.pipeline.js" | while read -r pipeline_file; do base_dir=$(dirname "$pipeline_file") base_name=$(basename "$pipeline_file" .pipeline.js) # Step 2: Attempt to delete the corresponding .js, .template.js, or _template.js file js_file="${base_dir}/${base_name}.js" template_js_file="${base_dir}/${base_name}.template.js" underscore_template_js_file="${base_dir}/${base_name}_template.js" file_deleted=false if [ -f "$js_file" ]; then rm "$js_file" && echo "Deleted file: $js_file" file_deleted=true fi if [ -f "$template_js_file" ]; then rm "$template_js_file" && echo "Deleted file: $template_js_file" file_deleted=true fi if [ -f "$underscore_template_js_file" ]; then rm "$underscore_template_js_file" && echo "Deleted file: $underscore_template_js_file" file_deleted=true fi if [ "$file_deleted" = false ]; then echo "Error: Corresponding file for $pipeline_file not found." fi # Step 3: Modify TEST_CASES.json if it exists in the same directory test_cases_file="${base_dir}/TEST_CASES.json" if [ -f "$test_cases_file" ]; then # Patterns to match "expected" before the filename js_pattern="expected.*$base_name\.js" template_js_pattern="expected.*$base_name\.template\.js" underscore_template_js_pattern="expected.*$base_name\_template\.js" # Use a more compatible sed in-place editing command if grep -q -E "expected.*(js|template\.js|_template\.js)" "$test_cases_file"; then # Determine if we are using GNU sed or BSD sed and adjust the command accordingly if sed --version 2>/dev/null | grep -q GNU; then # GNU sed sed -i "/$js_pattern/d" "$test_cases_file" sed -i "/$template_js_pattern/d" "$test_cases_file" sed -i "/$underscore_template_js_pattern/d" "$test_cases_file" else # BSD sed sed -i '' "/$js_pattern/d" "$test_cases_file" sed -i '' "/$template_js_pattern/d" "$test_cases_file" sed -i '' "/$underscore_template_js_pattern/d" "$test_cases_file" fi echo "Modified $test_cases_file to remove references to ${base_name}.js, ${base_name}.template.js, and/or ${base_name}_template.js with 'expected' preceding" else echo "Error: No line found in $test_cases_file for 'expected' preceding ${base_name}.js, ${base_name}.template.js, or ${base_name}_template.js" fi else echo "Error: TEST_CASES.json not found in $base_dir" fi done
{ "end_byte": 2737, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/replace.sh" }
angular/packages/compiler-cli/test/compliance/test_cases/list_golden_update_rules.ts_0_563
import {exec} from 'shelljs'; const {BUILD_WORKSPACE_DIRECTORY} = process.env; const rulesResult = exec( 'yarn --silent bazel query \'filter("\\.update$", kind(rule, //packages/compiler-cli/test/compliance/test_cases:*))\' --output label', {cwd: BUILD_WORKSPACE_DIRECTORY, env: process.env, silent: true}); if (rulesResult.code !== 0) { throw new Error('Failed to query Bazel for the update rules:\n' + rulesResult.stderr); } for (const rule of rulesResult.split('\n')) { if (rule.trim() !== '') { console.log('yarn bazel run ' + rule); } }
{ "end_byte": 563, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/list_golden_update_rules.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/BUILD.bazel_0_370
load("//packages/compiler-cli/test/compliance/partial:partial_compliance_goldens.bzl", "partial_compliance_golden") package(default_visibility = ["//packages/compiler-cli/test/compliance:__subpackages__"]) filegroup( name = "test_cases", srcs = glob(["*/**"]), ) [partial_compliance_golden(filePath = path) for path in glob(include = ["**/TEST_CASES.json"])]
{ "end_byte": 370, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/BUILD.bazel" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/for_pure_track_reuse_template.js_0_420
const $_forTrack0$ = ($index, $item) => $item.name[0].toUpperCase(); … function MyApp_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵrepeaterCreate(0, MyApp_For_1_Template, 1, 1, null, null, $_forTrack0$); $r3$.ɵɵrepeaterCreate(2, MyApp_For_3_Template, 1, 1, null, null, $_forTrack0$); } if (rf & 2) { $r3$.ɵɵrepeater(ctx.items); $r3$.ɵɵadvance(2); $r3$.ɵɵrepeater(ctx.otherItems); } }
{ "end_byte": 420, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/for_pure_track_reuse_template.js" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/if_element_root_node_template.js_0_300
consts: [["foo", "1", "bar", "2", 3, "binding"], ["foo", "4", "bar", "5", 3, "binding"], ["foo", "7", "bar", "8", 3, "binding"]], … $r3$.ɵɵtemplate(0, MyApp_Conditional_0_Template, 2, 2, "div", 0)(1, MyApp_Conditional_1_Template, 2, 2, "div", 1)(2, MyApp_Conditional_2_Template, 2, 2, "div", 2);
{ "end_byte": 300, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/if_element_root_node_template.js" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/for_pure_track_reuse.ts_0_442
import {Component} from '@angular/core'; @Component({ template: ` @for (item of items; track item.name[0].toUpperCase()) { {{item.name}} } @for (otherItem of otherItems; track otherItem.name[0].toUpperCase()) { {{otherItem.name}} } `, standalone: false }) export class MyApp { items = [{name: 'one'}, {name: 'two'}, {name: 'three'}]; otherItems = [{name: 'four'}, {name: 'five'}, {name: 'six'}]; }
{ "end_byte": 442, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/for_pure_track_reuse.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/for_template_variables_listener.ts_0_347
import {Component} from '@angular/core'; @Component({ template: ` <div> {{message}} @for (item of items; track item; let ev = $even) { <div (click)="log($index, ev, $first, $count)"></div> } </div> `, standalone: false }) export class MyApp { message = 'hello'; items = []; log(..._: any[]) {} }
{ "end_byte": 347, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/for_template_variables_listener.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/nested_for_listener_computed_template_variables_template.js_0_4303
function MyApp_For_1_For_2_For_3_Template(rf, ctx) { if (rf & 1) { const $_r19$ = $r3$.ɵɵgetCurrentView(); $r3$.ɵɵelementStart(0, "button", 0); $r3$.ɵɵlistener("click", function MyApp_For_1_For_2_For_3_Template_button_click_0_listener() { const $restoredCtx$ = $r3$.ɵɵrestoreView($_r19$); const $index_r14$ = $restoredCtx$.$index; const $count_r16$ = $restoredCtx$.$count; const $ctx_r18$ = $r3$.ɵɵnextContext(3); return $r3$.ɵɵresetView($ctx_r18$.innermostCb($index_r14$ % 2 !== 0, $index_r14$ % 2 === 0, $index_r14$ === 0, $index_r14$ === $count_r16$ - 1)); }); $r3$.ɵɵelementEnd(); $r3$.ɵɵelementStart(1, "button", 0); $r3$.ɵɵlistener("click", function MyApp_For_1_For_2_For_3_Template_button_click_1_listener() { $r3$.ɵɵrestoreView($_r19$); const $ctx_r21$ = $r3$.ɵɵnextContext(); const $index_2_r9$ = $ctx_r21$.$index; const $count_2_r11$ = $ctx_r21$.$count; const $ctx_r20$ = $r3$.ɵɵnextContext(2); return $r3$.ɵɵresetView($ctx_r20$.innerCb($index_2_r9$ % 2 !== 0, $index_2_r9$ % 2 === 0, $index_2_r9$ === 0, $index_2_r9$ === $count_2_r11$ - 1)); }); $r3$.ɵɵelementEnd(); $r3$.ɵɵelementStart(2, "button", 0); $r3$.ɵɵlistener("click", function MyApp_For_1_For_2_For_3_Template_button_click_2_listener() { $r3$.ɵɵrestoreView($_r19$); const $ctx_r23$ = $r3$.ɵɵnextContext(2); const $index_1_r3$ = $ctx_r23$.$index; const $count_1_r5$ = $ctx_r23$.$count; const $ctx_r22$ = $r3$.ɵɵnextContext(); return $r3$.ɵɵresetView($ctx_r22$.outerCb($index_1_r3$ % 2 !== 0, $index_1_r3$ % 2 === 0, $index_1_r3$ === 0, $index_1_r3$ === $count_1_r5$ - 1)); }); $r3$.ɵɵelementEnd(); } } … function MyApp_For_1_For_2_Template(rf, ctx) { if (rf & 1) { const $_r25$ = $r3$.ɵɵgetCurrentView(); $r3$.ɵɵelementStart(0, "button", 0); $r3$.ɵɵlistener("click", function MyApp_For_1_For_2_Template_button_click_0_listener() { const $restoredCtx2$ = $r3$.ɵɵrestoreView($_r25$); const $index_r8$ = $restoredCtx2$.$index; const $count_r10$ = $restoredCtx2$.$count; const $ctx_r24$ = $r3$.ɵɵnextContext(2); return $r3$.ɵɵresetView($ctx_r24$.innerCb($index_r8$ % 2 !== 0, $index_r8$ % 2 === 0, $index_r8$ === 0, $index_r8$ === $count_r10$ - 1)); }); $r3$.ɵɵelementEnd(); $r3$.ɵɵelementStart(1, "button", 0); $r3$.ɵɵlistener("click", function MyApp_For_1_For_2_Template_button_click_1_listener() { $r3$.ɵɵrestoreView($_r25$); const $ctx_r27$ = $r3$.ɵɵnextContext(); const $index_1_r3$ = $ctx_r27$.$index; const $count_1_r5$ = $ctx_r27$.$count; const $ctx_r26$ = $r3$.ɵɵnextContext(); return $r3$.ɵɵresetView($ctx_r26$.outerCb($index_1_r3$ % 2 !== 0, $index_1_r3$ % 2 === 0, $index_1_r3$ === 0, $index_1_r3$ === $count_1_r5$ - 1)); }); $r3$.ɵɵelementEnd(); $r3$.ɵɵrepeaterCreate(2, MyApp_For_1_For_2_For_3_Template, 3, 0, null, null, $r3$.ɵɵrepeaterTrackByIdentity); } if (rf & 2) { const $ctx_r6$ = $r3$.ɵɵnextContext(2); $r3$.ɵɵadvance(2); $r3$.ɵɵrepeater($ctx_r6$.items); } } … function MyApp_For_1_Template(rf, ctx) { if (rf & 1) { const $_r29$ = $r3$.ɵɵgetCurrentView(); $r3$.ɵɵelementStart(0, "button", 0); $r3$.ɵɵlistener("click", function MyApp_For_1_Template_button_click_0_listener() { const $restoredCtx3$ = $r3$.ɵɵrestoreView($_r29$); const $index_r2$ = $restoredCtx3$.$index; const $count_r4$ = $restoredCtx3$.$count; const $ctx_r28$ = $r3$.ɵɵnextContext(); return $r3$.ɵɵresetView($ctx_r28$.outerCb($index_r2$ % 2 !== 0, $index_r2$ % 2 === 0, $index_r2$ === 0, $index_r2$ === $count_r4$ - 1)); }); $r3$.ɵɵelementEnd(); $r3$.ɵɵrepeaterCreate(1, MyApp_For_1_For_2_Template, 4, 0, null, null, $r3$.ɵɵrepeaterTrackByIdentity); } if (rf & 2) { const $ctx_r0$ = $r3$.ɵɵnextContext(); $r3$.ɵɵadvance(); $r3$.ɵɵrepeater($ctx_r0$.items); } } … function MyApp_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵrepeaterCreate(0, MyApp_For_1_Template, 3, 0, null, null, $r3$.ɵɵrepeaterTrackByIdentity); } if (rf & 2) { $r3$.ɵɵrepeater(ctx.items); } }
{ "end_byte": 4303, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/nested_for_listener_computed_template_variables_template.js" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/if_nested_alias_listeners_template.pipeline.js_0_2614
function MyApp_Conditional_0_Conditional_1_Conditional_1_Template(rf, ctx) { if (rf & 1) { const $_r7$ = $r3$.ɵɵgetCurrentView(); $r3$.ɵɵelementStart(0, "button", 0); $r3$.ɵɵlistener("click", function MyApp_Conditional_0_Conditional_1_Conditional_1_Template_button_click_0_listener() { const $innermost_r5$ = $r3$.ɵɵrestoreView($_r7$); const $inner_r3$ = $r3$.ɵɵnextContext(); const $root_r1$ = $r3$.ɵɵnextContext(); const $ctx_r6$ = $r3$.ɵɵnextContext(); return $r3$.ɵɵresetView($ctx_r6$.log($ctx_r6$.value(), $root_r1$, $inner_r3$, $innermost_r5$)); }); $r3$.ɵɵelementEnd(); } } function MyApp_Conditional_0_Conditional_1_Template(rf, ctx) { if (rf & 1) { const $_r11$ = $r3$.ɵɵgetCurrentView(); $r3$.ɵɵelementStart(0, "button", 0); $r3$.ɵɵlistener("click", function MyApp_Conditional_0_Conditional_1_Template_button_click_0_listener() { const $inner_r3$ = $r3$.ɵɵrestoreView($_r11$); const $root_r1$ = $r3$.ɵɵnextContext(); const $ctx_r10$ = $r3$.ɵɵnextContext(); return $r3$.ɵɵresetView($ctx_r10$.log($ctx_r10$.value(), $root_r1$, $inner_r3$)); }); $r3$.ɵɵelementEnd(); $r3$.ɵɵtemplate(1, MyApp_Conditional_0_Conditional_1_Conditional_1_Template, 1, 0, "button"); } if (rf & 2) { let $MyApp_Conditional_0_Conditional_1_contFlowTmp$; const $ctx_r2$ = $r3$.ɵɵnextContext(2); $r3$.ɵɵadvance(); $r3$.ɵɵconditional(($MyApp_Conditional_0_Conditional_1_contFlowTmp$ = $ctx_r2$.value()) ? 1 : -1, $MyApp_Conditional_0_Conditional_1_contFlowTmp$); } } function MyApp_Conditional_0_Template(rf, ctx) { if (rf & 1) { const $_r14$ = $r3$.ɵɵgetCurrentView(); $r3$.ɵɵelementStart(0, "button", 0); $r3$.ɵɵlistener("click", function MyApp_Conditional_0_Template_button_click_0_listener() { const $root_r1$ = $r3$.ɵɵrestoreView($_r14$); const $ctx_r13$ = $r3$.ɵɵnextContext(); return $r3$.ɵɵresetView($ctx_r13$.log($ctx_r13$.value(), $root_r1$)); }); $r3$.ɵɵelementEnd(); $r3$.ɵɵtemplate(1, MyApp_Conditional_0_Conditional_1_Template, 2, 1); } if (rf & 2) { let $MyApp_Conditional_0_contFlowTmp$; const $ctx_r0$ = $r3$.ɵɵnextContext(); $r3$.ɵɵadvance(); $r3$.ɵɵconditional(($MyApp_Conditional_0_contFlowTmp$ = $ctx_r0$.value()) ? 1 : -1, $MyApp_Conditional_0_contFlowTmp$); } } … function MyApp_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵtemplate(0, MyApp_Conditional_0_Template, 2, 1); } if (rf & 2) { let $MyApp_contFlowTmp$; $r3$.ɵɵconditional(($MyApp_contFlowTmp$ = ctx.value()) ? 0 : -1, $MyApp_contFlowTmp$); } }
{ "end_byte": 2614, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/if_nested_alias_listeners_template.pipeline.js" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/if_template_root_node_template.js_0_297
consts: [["foo", "1", "bar", "2", 3, "binding"], ["foo", "4", "bar", "5", 3, "binding"], ["foo", "7", "bar", "8", 3, "binding"]], … $r3$.ɵɵtemplate(0, MyApp_Conditional_0_Template, 1, 1, null, 0)(1, MyApp_Conditional_1_Template, 1, 1, null, 1)(2, MyApp_Conditional_2_Template, 1, 1, null, 2);
{ "end_byte": 297, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/if_template_root_node_template.js" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/for_template_variables_scope.ts_0_500
import {Component} from '@angular/core'; @Component({ template: ` {{$index}} {{$count}} {{$first}} {{$last}} @for (item of items; track item) { {{$index}} {{$count}} {{$first}} {{$last}} } {{$index}} {{$count}} {{$first}} {{$last}} `, standalone: false }) export class MyApp { message = 'hello'; items = []; // These variables are defined so that the template type checker doesn't raise an error. $index: any; $count: any; $first: any; $last: any; }
{ "end_byte": 500, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/for_template_variables_scope.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/for_template_track_method_only_index.ts_0_346
import {Component} from '@angular/core'; @Component({ template: ` <div> {{message}} @for (item of items; track trackFn($index)) {} </div> `, standalone: false }) export class MyApp { message = 'hello'; items = [{name: 'one'}, {name: 'two'}, {name: 'three'}]; trackFn(index: number) { return index; } }
{ "end_byte": 346, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/for_template_track_method_only_index.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/for_with_empty_template.js_0_754
function MyApp_For_3_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵtext(0); } if (rf & 2) { const $item_r2$ = ctx.$implicit; $r3$.ɵɵtextInterpolate1(" ", $item_r2$.name, " "); } } function MyApp_ForEmpty_4_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵtext(0, " No items! "); } } … function MyApp_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵelementStart(0, "div"); $r3$.ɵɵtext(1); $r3$.ɵɵrepeaterCreate(2, MyApp_For_3_Template, 1, 1, null, null, $r3$.ɵɵrepeaterTrackByIdentity, false, MyApp_ForEmpty_4_Template, 1, 0); $r3$.ɵɵelementEnd(); } if (rf & 2) { $r3$.ɵɵadvance(); $r3$.ɵɵtextInterpolate1(" ", ctx.message, " "); $r3$.ɵɵadvance(); $r3$.ɵɵrepeater(ctx.items); } }
{ "end_byte": 754, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/for_with_empty_template.js" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/for_template_track_method_nested_template.js_0_126
$r3$.ɵɵrepeaterCreate(0, MyApp_ng_template_2_For_1_Template, 0, 0, null, null, $r3$.ɵɵcomponentInstance().trackFn, true);
{ "end_byte": 126, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/for_template_track_method_nested_template.js" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/for_track_by_field.ts_0_336
import {Component} from '@angular/core'; @Component({ template: ` <div> {{message}} @for (item of items; track item.name[0].toUpperCase()) { {{item.name}} } </div> `, standalone: false }) export class MyApp { message = 'hello'; items = [{name: 'one'}, {name: 'two'}, {name: 'three'}]; }
{ "end_byte": 336, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/for_track_by_field.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/for_track_literals_template.js_0_325
function $_forTrack0$($index, $item) { return this.trackFn({ foo: $item, bar: $item }, [$item, $item]); } … function MyApp_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵrepeaterCreate(0, MyApp_For_1_Template, 1, 1, null, null, $_forTrack0$, true); } if (rf & 2) { $r3$.ɵɵrepeater(ctx.items); } }
{ "end_byte": 325, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/for_track_literals_template.js" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/empty_switch_template.js_0_341
function MyApp_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵelementStart(0, "div"); $r3$.ɵɵtext(1); $r3$.ɵɵtext(2); $r3$.ɵɵelementEnd(); } if (rf & 2) { $r3$.ɵɵadvance(); $r3$.ɵɵtextInterpolate1(" ", ctx.message, " "); $r3$.ɵɵadvance(); $r3$.ɵɵtextInterpolate1(" ", ctx.message, " "); } }
{ "end_byte": 341, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/empty_switch_template.js" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/nested_for_computed_template_variables.ts_0_1078
import {Component} from '@angular/core'; @Component({ template: ` @for (outer of items; track outer; let outerOdd = $odd, outerEven = $even, outerFirst = $first, outerLast = $last) { Outer vars: {{outerOdd}} {{outerEven}} {{outerFirst}} {{outerLast}} @for (inner of items; track inner; let innerOdd = $odd, innerEven = $even, innerFirst = $first, innerLast = $last) { Inner vars: {{innerOdd}} {{innerEven}} {{innerFirst}} {{innerLast}} <br> Outer vars: {{outerOdd}} {{outerEven}} {{outerFirst}} {{outerLast}} @for (innermost of items; track innermost; let innermostOdd = $odd, innermostEven = $even, innermostFirst = $first, innermostLast = $last) { Innermost vars: {{innermostOdd}} {{innermostEven}} {{innermostFirst}} {{innermostLast}} <br> Inner vars: {{innerOdd}} {{innerEven}} {{innerFirst}} {{innerLast}} <br> Outer vars: {{outerOdd}} {{outerEven}} {{outerFirst}} {{outerLast}} } } } `, standalone: false }) export class MyApp { items = []; }
{ "end_byte": 1078, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/nested_for_computed_template_variables.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/switch_without_default.ts_0_378
import {Component} from '@angular/core'; @Component({ template: ` <div> {{message}} @switch (value()) { @case (0) { case 0 } @case (1) { case 1 } @case (2) { case 2 } } </div> `, standalone: false }) export class MyApp { message = 'hello'; value = () => 1; }
{ "end_byte": 378, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/switch_without_default.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/basic_if_else_if_template.js_0_962
function MyApp_Conditional_2_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵtext(0, " one "); } } function MyApp_Conditional_3_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵtext(0, " two "); } } function MyApp_Conditional_4_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵtext(0, " three "); } } function MyApp_Conditional_5_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵtext(0, " four "); } } … function MyApp_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵelementStart(0, "div"); $r3$.ɵɵtext(1); $r3$.ɵɵtemplate(2, MyApp_Conditional_2_Template, 1, 0)(3, MyApp_Conditional_3_Template, 1, 0)(4, MyApp_Conditional_4_Template, 1, 0)(5, MyApp_Conditional_5_Template, 1, 0); $r3$.ɵɵelementEnd(); } if (rf & 2) { $r3$.ɵɵadvance(); $r3$.ɵɵtextInterpolate1(" ", ctx.message, " "); $r3$.ɵɵadvance(); $r3$.ɵɵconditional(ctx.value() === 1 ? 2 : ctx.otherValue() === 2 ? 3 : ctx.message ? 4 : 5); } }
{ "end_byte": 962, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/basic_if_else_if_template.js" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/for_element_root_node.ts_0_431
import {Component, Directive, Input} from '@angular/core'; @Directive({selector: '[binding]'}) export class Binding { @Input() binding = 0; } @Component({ template: ` @for (item of items; track item) { <div foo="1" bar="2" [binding]="3">{{item}}</div> } @empty { <span empty-foo="1" empty-bar="2" [binding]="3">Empty!</span> } `, imports: [Binding], }) export class MyApp { items = [1, 2, 3]; }
{ "end_byte": 431, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/for_element_root_node.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/for_template_variables.ts_0_395
import {Component} from '@angular/core'; @Component({ template: ` <div> {{message}} @for (item of items; track item) { Index: {{$index}} First: {{$first}} Last: {{$last}} Even: {{$even}} Odd: {{$odd}} Count: {{$count}} } </div> `, standalone: false }) export class MyApp { message = 'hello'; items = []; }
{ "end_byte": 395, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/for_template_variables.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/for_impure_track_reuse.ts_0_532
import {Component} from '@angular/core'; @Component({ template: ` @for (item of items; track trackFn(item, message)) { {{item.name}} } @for (otherItem of otherItems; track trackFn(otherItem, message)) { {{otherItem.name}} } `, standalone: false }) export class MyApp { message = 'hello'; items = [{name: 'one'}, {name: 'two'}, {name: 'three'}]; otherItems = [{name: 'four'}, {name: 'five'}, {name: 'six'}]; trackFn(item: any, message: string) { return message + item.name; } }
{ "end_byte": 532, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/for_impure_track_reuse.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/if_template_root_node.ts_0_528
import {Component, Directive, Input} from '@angular/core'; @Directive({selector: '[binding]'}) export class Binding { @Input() binding = 0; } @Component({ template: ` @if (expr === 0) { <ng-template foo="1" bar="2" [binding]="3">{{expr}}</ng-template> } @else if (expr === 1) { <ng-template foo="4" bar="5" [binding]="6">{{expr}}</ng-template> } @else { <ng-template foo="7" bar="8" [binding]="9">{{expr}}</ng-template> } `, imports: [Binding], }) export class MyApp { expr = 0; }
{ "end_byte": 528, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/if_template_root_node.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/for_track_by_index.ts_0_316
import {Component} from '@angular/core'; @Component({ template: ` <div> {{message}} @for (item of items; track $index) { {{item.name}} } </div> `, standalone: false }) export class MyApp { message = 'hello'; items = [{name: 'one'}, {name: 'two'}, {name: 'three'}]; }
{ "end_byte": 316, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/for_track_by_index.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/switch_template_root_node_template.js_0_276
consts: [["foo", "1", "bar", "2", 3, "binding"], ["foo", "4", "bar", "5", 3, "binding"], ["foo", "7", "bar", "8", 3, "binding"]], … $r3$.ɵɵtemplate(0, MyApp_Case_0_Template, 1, 1, null, 0)(1, MyApp_Case_1_Template, 1, 1, null, 1)(2, MyApp_Case_2_Template, 1, 1, null, 2);
{ "end_byte": 276, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/switch_template_root_node_template.js" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/if_with_alias.ts_0_276
import {Component} from '@angular/core'; @Component({ template: ` <div> {{message}} @if (value(); as alias) { {{value()}} as {{alias}} } </div> `, standalone: false }) export class MyApp { message = 'hello'; value = () => 1; }
{ "end_byte": 276, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/if_with_alias.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/nested_for_template_variables.ts_0_624
import {Component} from '@angular/core'; @Component({ template: ` <div> {{message}} @for (item of items; track item; let outerCount = $count) { {{item.name}} @for (subitem of item.subItems; track subitem) { Outer: {{outerCount}} Inner: {{$count}} } } </div> `, standalone: false }) export class MyApp { message = 'hello'; items = [ {name: 'one', subItems: ['sub one', 'sub two', 'sub three']}, {name: 'two', subItems: ['sub one', 'sub two', 'sub three']}, {name: 'three', subItems: ['sub one', 'sub two', 'sub three']}, ]; }
{ "end_byte": 624, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/nested_for_template_variables.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/basic_for_template.js_0_604
function MyApp_For_3_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵtext(0); } if (rf & 2) { const item_r1 = ctx.$implicit; $r3$.ɵɵtextInterpolate1(" ", item_r1.name, " "); } } … function MyApp_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵelementStart(0, "div"); $r3$.ɵɵtext(1); $r3$.ɵɵrepeaterCreate(2, MyApp_For_3_Template, 1, 1, null, null, $r3$.ɵɵrepeaterTrackByIdentity); $r3$.ɵɵelementEnd(); } if (rf & 2) { $r3$.ɵɵadvance(); $r3$.ɵɵtextInterpolate1(" ", ctx.message, " "); $r3$.ɵɵadvance(); $r3$.ɵɵrepeater(ctx.items); } }
{ "end_byte": 604, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/basic_for_template.js" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/if_nested_alias_listeners.ts_0_480
import {Component} from '@angular/core'; @Component({ template: ` @if (value(); as root) { <button (click)="log(value(), root)"></button> @if (value(); as inner) { <button (click)="log(value(), root, inner)"></button> @if (value(); as innermost) { <button (click)="log(value(), root, inner, innermost)"></button> } } } `, standalone: false }) export class MyApp { value = () => 1; log(..._: any[]) {} }
{ "end_byte": 480, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/if_nested_alias_listeners.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/nested_for.ts_0_579
import {Component} from '@angular/core'; @Component({ template: ` <div> {{message}} @for (item of items; track item) { {{item.name}} @for (subitem of item.subItems; track $index) { {{subitem}} from {{item.name}} } } </div> `, standalone: false }) export class MyApp { message = 'hello'; items = [ {name: 'one', subItems: ['sub one', 'sub two', 'sub three']}, {name: 'two', subItems: ['sub one', 'sub two', 'sub three']}, {name: 'three', subItems: ['sub one', 'sub two', 'sub three']}, ]; }
{ "end_byte": 579, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/nested_for.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/nested_switch.ts_0_632
import {Component} from '@angular/core'; @Component({ template: ` <div> {{message}} @switch (value()) { @case (0) { case 0 } @case (1) { @switch (nestedValue()) { @case (0) { nested case 0 } @case (1) { nested case 1 } @case (2) { nested case 2 } } } @case (2) { case 2 } } </div> `, standalone: false }) export class MyApp { message = 'hello'; value = () => 1; nestedValue = () => 2; }
{ "end_byte": 632, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/nested_switch.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/nested_if_template.js_0_1834
function MyApp_Conditional_2_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵtext(0, " zero "); } } function MyApp_Conditional_3_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵtext(0, " one "); } } function MyApp_Conditional_4_Conditional_0_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵtext(0, " inner zero "); } } function MyApp_Conditional_4_Conditional_1_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵtext(0, " inner one "); } } function MyApp_Conditional_4_Conditional_2_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵtext(0, " inner two "); } } function MyApp_Conditional_4_Conditional_3_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵtext(0, " inner three "); } } function MyApp_Conditional_4_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵtemplate(0, MyApp_Conditional_4_Conditional_0_Template, 1, 0)(1, MyApp_Conditional_4_Conditional_1_Template, 1, 0)(2, MyApp_Conditional_4_Conditional_2_Template, 1, 0)(3, MyApp_Conditional_4_Conditional_3_Template, 1, 0); } if (rf & 2) { const $ctx_r2$ = $r3$.ɵɵnextContext(); $r3$.ɵɵconditional($ctx_r2$.innerVal === 0 ? 0 : $ctx_r2$.innerVal === 1 ? 1 : $ctx_r2$.innerVal === 2 ? 2 : 3); } } function MyApp_Conditional_5_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵtext(0, " three "); } } … function MyApp_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵelementStart(0, "div"); $r3$.ɵɵtext(1); $r3$.ɵɵtemplate(2, MyApp_Conditional_2_Template, 1, 0)(3, MyApp_Conditional_3_Template, 1, 0)(4, MyApp_Conditional_4_Template, 4, 1)(5, MyApp_Conditional_5_Template, 1, 0); $r3$.ɵɵelementEnd(); } if (rf & 2) { $r3$.ɵɵadvance(); $r3$.ɵɵtextInterpolate1(" ", ctx.message, " "); $r3$.ɵɵadvance(); $r3$.ɵɵconditional(ctx.val === 0 ? 2 : ctx.val === 1 ? 3 : ctx.val === 2 ? 4 : 5); } }
{ "end_byte": 1834, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/nested_if_template.js" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/basic_switch.ts_0_437
import {Component} from '@angular/core'; @Component({ template: ` <div> {{message}} @switch (value()) { @case (0) { case 0 } @case (1) { case 1 } @case (2) { case 2 } @default { default } } </div> `, standalone: false }) export class MyApp { message = 'hello'; value() { return 1; } }
{ "end_byte": 437, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/basic_switch.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/nested_switch_template.js_0_1555
function MyApp_Case_2_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵtext(0, " case 0 "); } } function MyApp_Case_3_Case_0_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵtext(0, " nested case 0 "); } } function MyApp_Case_3_Case_1_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵtext(0, " nested case 1 "); } } function MyApp_Case_3_Case_2_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵtext(0, " nested case 2 "); } } function MyApp_Case_3_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵtemplate(0, MyApp_Case_3_Case_0_Template, 1, 0)(1, MyApp_Case_3_Case_1_Template, 1, 0)(2, MyApp_Case_3_Case_2_Template, 1, 0); } if (rf & 2) { … const $ctx_r1$ = $r3$.ɵɵnextContext(); … $r3$.ɵɵconditional(($MyApp_Case_3_contFlowTmp$ = $ctx_r1$.nestedValue()) === 0 ? 0 : $MyApp_Case_3_contFlowTmp$ === 1 ? 1 : $MyApp_Case_3_contFlowTmp$ === 2 ? 2 : -1); } } function MyApp_Case_4_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵtext(0, " case 2 "); } } … function MyApp_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵelementStart(0, "div"); $r3$.ɵɵtext(1); $r3$.ɵɵtemplate(2, MyApp_Case_2_Template, 1, 0)(3, MyApp_Case_3_Template, 3, 1)(4, MyApp_Case_4_Template, 1, 0); $r3$.ɵɵelementEnd(); } if (rf & 2) { let $MyApp_contFlowTmp$; $r3$.ɵɵadvance(); $r3$.ɵɵtextInterpolate1(" ", ctx.message, " "); $r3$.ɵɵadvance(); $r3$.ɵɵconditional(($MyApp_contFlowTmp$ = ctx.value()) === 0 ? 2 : $MyApp_contFlowTmp$ === 1 ? 3 : $MyApp_contFlowTmp$ === 2 ? 4 : -1); } }
{ "end_byte": 1555, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/nested_switch_template.js" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/nested_for_template_variables_template.js_0_1082
function MyApp_For_3_For_2_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵtext(0); } if (rf & 2) { const $count_r7$ = ctx.$count; const $outerCount_r3$ = $r3$.ɵɵnextContext().$count; $r3$.ɵɵtextInterpolate2(" Outer: ", $outerCount_r3$, " Inner: ", $count_r7$, " "); } } function MyApp_For_3_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵtext(0); $r3$.ɵɵrepeaterCreate(1, MyApp_For_3_For_2_Template, 1, 2, null, null, $r3$.ɵɵrepeaterTrackByIdentity); } if (rf & 2) { const $item_r1$ = ctx.$implicit; $r3$.ɵɵtextInterpolate1(" ", $item_r1$.name, " "); $r3$.ɵɵadvance(); $r3$.ɵɵrepeater($item_r1$.subItems); } } … function MyApp_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵelementStart(0, "div"); $r3$.ɵɵtext(1); $r3$.ɵɵrepeaterCreate(2, MyApp_For_3_Template, 3, 1, null, null, $r3$.ɵɵrepeaterTrackByIdentity); $r3$.ɵɵelementEnd(); } if (rf & 2) { $r3$.ɵɵadvance(); $r3$.ɵɵtextInterpolate1(" ", ctx.message, " "); $r3$.ɵɵadvance(); $r3$.ɵɵrepeater(ctx.items); } }
{ "end_byte": 1082, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/nested_for_template_variables_template.js" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/for_template_variables_template.pipeline.js_0_875
function MyApp_For_3_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵtext(0); } if (rf & 2) { const $index_r2$ = ctx.$index; const $index_4_r2$ = ctx.$index; const $count_r3$ = ctx.$count; const $count_4_r2$ = ctx.$count; $r3$.ɵɵtextInterpolate6(" Index: ", $index_r2$, " First: ", $index_4_r2$ === 0, " Last: ", $index_4_r2$ === $count_4_r2$ - 1, " Even: ", $index_4_r2$ % 2 === 0, " Odd: ", $index_4_r2$ % 2 !== 0, " Count: ", $count_r3$, " "); } } … function MyApp_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵelementStart(0, "div"); $r3$.ɵɵtext(1); $r3$.ɵɵrepeaterCreate(2, MyApp_For_3_Template, 1, 6, null, null, $r3$.ɵɵrepeaterTrackByIdentity); $r3$.ɵɵelementEnd(); } if (rf & 2) { $r3$.ɵɵadvance(); $r3$.ɵɵtextInterpolate1(" ", ctx.message, " "); $r3$.ɵɵadvance(); $r3$.ɵɵrepeater(ctx.items); } }
{ "end_byte": 875, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/for_template_variables_template.pipeline.js" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/nested_for_listener_computed_template_variables.ts_0_1213
import {Component} from '@angular/core'; @Component({ template: ` @for (outer of items; track outer; let outerOdd = $odd, outerEven = $even, outerFirst = $first, outerLast = $last) { <button (click)="outerCb(outerOdd, outerEven, outerFirst, outerLast)"></button> @for (inner of items; track inner; let innerOdd = $odd, innerEven = $even, innerFirst = $first, innerLast = $last) { <button (click)="innerCb(innerOdd, innerEven, innerFirst, innerLast)"></button> <button (click)="outerCb(outerOdd, outerEven, outerFirst, outerLast)"></button> @for (innermost of items; track innermost; let innermostOdd = $odd, innermostEven = $even, innermostFirst = $first, innermostLast = $last) { <button (click)="innermostCb(innermostOdd, innermostEven, innermostFirst, innermostLast)"></button> <button (click)="innerCb(innerOdd, innerEven, innerFirst, innerLast)"></button> <button (click)="outerCb(outerOdd, outerEven, outerFirst, outerLast)"></button> } } } `, standalone: false }) export class MyApp { items = []; outerCb(...args: unknown[]) {} innerCb(...args: unknown[]) {} innermostCb(...args: unknown[]) {} }
{ "end_byte": 1213, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/nested_for_listener_computed_template_variables.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/for_template_variables_scope_template.pipeline.js_0_890
function MyApp_For_2_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵtext(0); } if (rf & 2) { const $index_r2$ = ctx.$index; const $index_2_r2$ = ctx.$index; const $count_r3$ = ctx.$count; const $count_2_r3$ = ctx.$count; $r3$.ɵɵtextInterpolate4(" ", $index_r2$, " ", $count_r3$, " ", $index_2_r2$ === 0, " ", $index_2_r2$ === $count_2_r3$ - 1, " "); } } … function MyApp_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵtext(0); $r3$.ɵɵrepeaterCreate(1, MyApp_For_2_Template, 1, 4, null, null, $r3$.ɵɵrepeaterTrackByIdentity); $r3$.ɵɵtext(3); } if (rf & 2) { $r3$.ɵɵtextInterpolate4(" ", ctx.$index, " ", ctx.$count, " ", ctx.$first, " ", ctx.$last, " "); $r3$.ɵɵadvance(); $r3$.ɵɵrepeater(ctx.items); $r3$.ɵɵadvance(2); $r3$.ɵɵtextInterpolate4(" ", ctx.$index, " ", ctx.$count, " ", ctx.$first, " ", ctx.$last, " "); } }
{ "end_byte": 890, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_control_flow/for_template_variables_scope_template.pipeline.js" }